Compare commits

...
6 Commits
Author SHA1 Message Date
sam a4d98786a1 chore(release): v1.41.2
deploy / gate (push) Failing after 3m35s
deploy / build-and-push (push) Skipped
deploy / dist-zip (push) Skipped
2026-09-25 01:58:54 +10:00
sam aa24551d98 fix(update): treat the runtime as the release version; stamp it in dist-zip
The update check still read the retired archie/v* tag stream, so a host on
1.41.1 was offered runtime 1.35.0, and the installer built the agent image
from that stale tag. Both now use the release's archied/v* tag. The dist-zip
build also stamps runtimeVersion, so /version stops reporting 'dev'.
2026-09-25 01:58:20 +10:00
sam cacf25039e test: remove events-page source-string test
deploy / gate (push) Failing after 3m49s
deploy / build-and-push (push) Skipped
deploy / dist-zip (push) Skipped
It asserted on text in the router, nav and Events page sources rather than
on behaviour.
2026-09-25 01:35:26 +10:00
sam 35dd7489dd test: remove layout-pinned route-registry and task-meta fixture tests
TestDashboardPagesRegistryCoversEveryRoute parsed ui/src/router/index.ts as
text, and TestTaskMetaPayloadMatchesFixture plus ui/test/task-meta-snapshot
pinned a formatted JSON fixture. They failed on formatting, not behaviour.
2026-09-25 01:32:20 +10:00
sam be1b3aa6a1 chore(release): v1.41.1
deploy / gate (push) Failing after 5m34s
deploy / build-and-push (push) Skipped
deploy / dist-zip (push) Skipped
2026-09-25 01:29:59 +10:00
sam 065606b2a5 fix(ci): make the gate tolerate formatting and give deploy a PG 18 client
The page-registry test parsed the route table one line per route and the
task-meta fixture was byte-compared, so the prettier reformat broke both.
The registry test now splits route objects and ignores comments; the
fixture compares compacted JSON. Also drops a stale router comment that
described the removed redirects, rebuilds ui/dist, regenerates the
contracts artifact, keeps prettier off generated output, and installs
postgresql-client-18 in deploy.yml's gate as quality.yml already does.
2026-09-25 01:29:23 +10:00
22 changed files with 189 additions and 50794 deletions

No files matched your search

+17 -1
View File
@@ -72,6 +72,22 @@ jobs:
- name: Install protobuf tools
run: bash tools/proto.sh install
# The backup/restore tests shell out to pg_dump/pg_restore against a
# postgres:18 testcontainer; the runner's stock client is older and
# refuses the server version.
- name: Install PostgreSQL 18 client
run: |
sudo install -d /usr/share/postgresql-common/pgdg
sudo curl --fail --silent --show-error --location \
https://www.postgresql.org/media/keys/ACCC4CF8.asc \
--output /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc
. /etc/os-release
echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt ${VERSION_CODENAME}-pgdg main" \
| sudo tee /etc/apt/sources.list.d/pgdg.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends postgresql-client-18
echo "/usr/lib/postgresql/18/bin" >> $GITHUB_PATH
- name: Ensure contract baseline ref
run: |
if ! git show-ref --verify --quiet refs/heads/main; then
@@ -305,7 +321,7 @@ jobs:
# ran on with a dead Telegram bot and no error anywhere
# (archie-core-1c01). TestDistZipShipsEveryHostCommand fails if this
# list and the copy list below stop matching the commands in cmd/.
ldflags="-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion=${{ steps.version.outputs.version }} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary -X github.com/samcharles93/archie-core/internal/buildinfo.Version=${{ steps.version.outputs.version }}"
ldflags="-X github.com/samcharles93/archie-core/internal/app/archied.gatewayVersion=${{ steps.version.outputs.version }} -X github.com/samcharles93/archie-core/internal/app/archied.runtimeVersion=${{ steps.version.outputs.version }} -X github.com/samcharles93/archie-core/internal/installtype.buildType=binary -X github.com/samcharles93/archie-core/internal/buildinfo.Version=${{ steps.version.outputs.version }} -X github.com/samcharles93/archie-core/internal/buildinfo.Runtime=${{ steps.version.outputs.version }}"
mkdir -p dist
for cmd in archied archie-gateway archie-state-store archie-ui archie-messaging archie-playbooks; do
go build -ldflags "$ldflags" -o "dist/$cmd" "./cmd/$cmd"
+4
View File
@@ -0,0 +1,4 @@
# Generated output: only its generator writes it, and the gate byte-checks it.
docs/data/generated/
internal/contracts/
ui/dist/
+20
View File
@@ -5,6 +5,26 @@ release's per-component sections are labelled beneath its heading.
## [Unreleased]
## [1.41.2] - 2026-09-25
### archied
- **`/update` no longer offers an old runtime.** The runtime has shipped under
the release version since the version streams merged, but the update check
still read the retired runtime tags, so a current host was offered runtime
1.35.0 as an update. Do not approve that offer on 1.41.1; update to 1.41.2
instead.
- **`/version` reports the runtime version.** Binaries from the release zip
showed `Runtime: dev`.
## [1.41.1] - 2026-09-25
### archied
- **First published build of 1.41.0.** The 1.41.0 tag produced no release
artifacts; 1.41.1 carries everything listed under 1.41.0 below, including
the PostgreSQL 18 requirement and the removed config keys.
## [1.41.0] - 2026-09-25
### archied
+29 -6
View File
@@ -137,7 +137,14 @@
"type": "integer"
}
},
"required": ["version", "task_id", "attempt", "stage", "status", "usage"],
"required": [
"version",
"task_id",
"attempt",
"stage",
"status",
"usage"
],
"type": "object"
},
"Budget": {
@@ -196,7 +203,9 @@
"type": "object"
}
},
"required": ["name"],
"required": [
"name"
],
"type": "object"
},
"Command": {
@@ -216,7 +225,10 @@
"type": "string"
}
},
"required": ["name", "argv"],
"required": [
"name",
"argv"
],
"type": "object"
},
"Gate": {
@@ -284,7 +296,10 @@
"type": "integer"
}
},
"required": ["type", "file_id"],
"required": [
"type",
"file_id"
],
"type": "object"
},
"MessageEvent": {
@@ -343,7 +358,12 @@
"type": "string"
}
},
"required": ["type", "channel_id", "platform", "sender_id"],
"required": [
"type",
"channel_id",
"platform",
"sender_id"
],
"type": "object"
},
"PluginSpec": {
@@ -357,7 +377,10 @@
"type": "string"
}
},
"required": ["name", "src"],
"required": [
"name",
"src"
],
"type": "object"
},
"Protection": {
+57 -57
View File
@@ -10,13 +10,13 @@
"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. Authorisation 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 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
"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/",
@@ -28,7 +28,7 @@
"url": "/dev/architecture/configuration/",
"title": "Configuration",
"section": "Architecture",
"body": "# Configuration\n\n**Status:** Approved; existing-type assignment is ongoing \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Ownership\n\nConfiguration has two separate responsibilities:\n\n1. `internal/infrastructure/configuration` loads files, environment variables,\n secret references, overlays, and compatibility representations.\n2. Each domain and plugin owns the typed runtime settings required for its\n behaviour.\n\n`internal/app` translates external input into those settings, validates\ncross-capability combinations, and supplies each component only its own\nsettings.\n\nThe following are prohibited:\n\n- passing complete application configuration into a domain;\n- making a domain depend on TOML, YAML, environment-variable names, secret\n references, or a configuration library;\n- defining a central runtime configuration type imported across the system;\n- placing plugin options in an unrelated global configuration model.\n\n## Private input document\n\n`internal/infrastructure/configuration` MAY use a complete decoded document\nwhile discovering files, decoding sections, and applying overlays. It is an\ninput-boundary DTO only.\n\nThe document:\n\n- remains private to the configuration infrastructure;\n- is composed from separately defined feature sections;\n- is immediately translated by application composition;\n- is never returned as the application's runtime model;\n- is never passed through runtime components.\n\nExternal DTOs and domain runtime settings are separate types.\n\nPlugins supply external configuration definitions through a narrow extension\ncontract. The core loader MUST NOT gain a field or recognised filename for every\nplugin.\n\nInvalid configuration input MUST NOT replace active valid settings or terminate\nunaffected capabilities. Configuration changes use the candidate validation,\npromotion, audit, and recovery requirements in\n[safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/).\n\n## Dissolution of `internal/config`\n\n`internal/config` has no target location. It MUST be dissolved and MUST NOT\nsurvive as a shared package, configuration domain, or renamed global model.\n\nIts loading behaviour moves to `internal/infrastructure/configuration`. Existing\ntypes and methods are reassigned by behaviour. Repository execution policy,\ndispatch policy, retry policy, ecosystem defaults, tool policy, memory settings,\nprovider settings, and channel settings move to their\nrespective owners.\n\n## Repository settings\n\nThe existing `config.Repo` MUST NOT move intact into a repository domain or\nshared settings package. A managed repository is an application association:\n\n- work intake owns which repository references an identity monitors;\n- task execution owns gates, preflight, test protection, ecosystem behaviour,\n and change limits;\n- task lifecycle owns retry behaviour;\n- scheduling owns concurrency policy;\n- workspace management owns base branch and persistent-storage requirements.\n\nApplication composition correlates these settings by repository reference. No\ndomain receives a universal repository profile.\n\n## Documentation\n\nGenerated configuration reference describes external sections and their owning\ncapabilities. It MUST NOT establish a global Go configuration structure as the\npublic contract.\n\n## Value classification rule\n\nEvery value that controls behaviour MUST have an explicit owner and MUST be\nclassified as exactly one of:\n\n1. **Invariant** — changing it changes the meaning of the program, a wire\n protocol, or a domain concept. It may be a Go constant.\n2. **Runtime setting** — an operator, identity, domain, plugin, or deployment\n may legitimately choose a different value. It is typed configuration owned by\n the affected capability.\n3. **Policy value** — it expresses what is allowed, limited, routed, retried,\n protected, or gated. Its typed definition belongs to the owning domain and it\n is evaluated through the policy system.\n4. **Derived value** — it is computed from other settings and is not\n independently mutable.\n5. **Runtime state** — it changes as the application operates, such as the\n active model for a conversation. It is changed by a domain command and is not\n configuration merely because it can be changed.\n\nAn unclassified behavioural literal is a defect.\n\n`const` MUST NOT be used merely because a value currently has one default.\nConstants are reserved for actual invariants: enum discriminants, protocol\nversions, fixed compatibility tokens, and values whose alteration would change\nthe program's semantics rather than configure an installation.\n\nIn Go, a constant is a compile-time value and does not represent mutable runtime\nstorage. It generally has no address that can be observed or changed.\nArchitecturally, a constant therefore asserts that the value cannot change for\nthe lifetiLine truncated
"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/",
@@ -46,13 +46,13 @@
"url": "/dev/architecture/generated-documentation/",
"title": "Generated Documentation",
"section": "Architecture",
"body": "# Generated Documentation\n\n**Status:** Data generation lives here; rendering and publishing live in the external Astro website\n**Date:** 2026-07-28 (revised 2026-09-25)\n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie's documentation-generation approach is:\n\n- production Go code, registries, configuration, and CLI behaviour remain the\n source of truth for published contracts;\n- a repository-local Go generator extracts and normalises documentation data;\n- the generator writes deterministic JSON/data files and protocol schemas;\n- the external Astro website consumes generated data and serves the public\n documentation at `offloaded.dev/docs/`.\n\nHugo is not part of the target architecture.\n\nThe documentation system is rooted at:\n\n```text\ntools/\n go.mod\n go.sum\n docsgen/\n main.go\ndocs/\n data/generated/\n public/schemas/\n *.md\n```\n\n### Rendering and publishing — external Astro website\n\nSuperseded 2026-09-12. The repository previously carried a VitePress site\n(`docs/.vitepress/config.mts`, `docs/package.json`, a 1620-line\n`docs/pnpm-lock.yaml`, `docs/pnpm-workspace.yaml`) built and deployed to GitHub\nPages by `.github/workflows/docs.yml`. It was removed as an unnecessary build\nstep: the published site was never stood up, and the Pages target is not\nconfigured.\n\nThe Astro website is maintained outside this repository. This repository owns\nthe Markdown source and generated JSON artifacts; it does not build, preview, or\ndeploy the site. The external site owns page rendering, navigation, and\npublishing.\n\nThe current boundaries are:\n\n| Concern | Owner |\n| --- | --- |\n| Reference-page rendering and publishing | External Astro website |\n| Documentation source and generated data | This repository |\n| Generated-data drift detection | `task docs:check`, `task docs:artifact:check`, and `task news:check` |\n| Navigation data | `docs/data/generated/docs.json` and `dev-docs.json` |\n\nChanges to an artifact contract must be coordinated with the external Astro\nconsumer. This repository does not validate the website's rendered links or\nroutes.\n\n## Single source of truth\n\nEvery published capability has one authoritative machine-readable definition\nowned by its domain or application boundary. Generated documentation derives\nfrom those definitions.\n\nGenerated reference includes:\n\n- domain commands and events;\n- Messages and typed message content;\n- Agent and Workflow contracts;\n- WorkflowSteps and Workflow plugin capability contracts;\n- policies and their typed inputs and outcomes;\n- tools and capabilities;\n- CLI commands, arguments, flags, defaults, and help;\n- runtime settings, types, defaults, validation, and secret metadata;\n- public worker and transport contracts;\n- indexes of registered functionality;\n- deprecation information.\n\nHandwritten documents contain:\n\n- architecture decisions and rationale;\n- tutorials and operational guides;\n- examples and walkthroughs;\n- migration guidance;\n- conceptual explanations.\n\nHandwritten documents link to generated reference rather than copying\nauthoritative tables.\n\n## Target generation architecture\n\n`tools/docsgen` is Archie's documentation extractor and normalizer. It produces\nstructured documentation data and protocol specifications. It does not own\npage layout and MUST NOT generate Markdown pages or fragments.\n\nThe generator is divided internally into reusable stages:\n\n```text\nload registries and types\n -\u003e normalize documentation model\n -\u003e validate ownership and identifiers\n -\u003e serialize data and protocol artifacts\n -\u003e compare or write output\n```\n\nThe normalised documentation model prevents each output renderer from\nindependently interpreting Go types. It contains stable documentation IDs,\nowners, names, descriptions, source references, versions, deprecations, fields,\ndefaults, validation, secret classifications, and relationships.\n\nInitial generator targets:\n\n```text\ndocsgen data\ndocsgen asyncapi\ndocsgen all\ndocsgen check\n```\n\n- `data` writes the normalised JSON reference data.\n- `asyncapi` writes protocol schemas and envelopes.\n- `all` generates every committed artifact.\n- `check` generates into a temporary directory and fails on drift.\n\nThe command may use subcommands or an equivalent explicit `--target` flag. It\nMUST retain one normalisation and validation path.\n\n## Target output\n\nDuring adaptation, `docs` remains the staging site. Generated outputs live in\na visibly owned subtree:\n\n```text\ndocs/\n data/\n 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
"body": "# Generated Documentation\n\n**Status:** Data generation lives here; rendering and publishing live in the external Astro website\n**Date:** 2026-07-28 (revised 2026-09-25)\n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie's documentation-generation approach is:\n\n- production Go code, registries, configuration, and CLI behaviour remain the\n source of truth for published contracts;\n- a repository-local Go generator extracts and normalises documentation data;\n- the generator writes deterministic JSON/data files and protocol schemas;\n- the external Astro website consumes generated data and serves the public\n documentation at `offloaded.dev/docs/`.\n\nHugo is not part of the target architecture.\n\nThe documentation system is rooted at:\n\n```text\ntools/\n go.mod\n go.sum\n docsgen/\n main.go\ndocs/\n data/generated/\n public/schemas/\n *.md\n```\n\n### Rendering and publishing — external Astro website\n\nSuperseded 2026-09-12. The repository previously carried a VitePress site\n(`docs/.vitepress/config.mts`, `docs/package.json`, a 1620-line\n`docs/pnpm-lock.yaml`, `docs/pnpm-workspace.yaml`) built and deployed to GitHub\nPages by `.github/workflows/docs.yml`. It was removed as an unnecessary build\nstep: the published site was never stood up, and the Pages target is not\nconfigured.\n\nThe Astro website is maintained outside this repository. This repository owns\nthe Markdown source and generated JSON artifacts; it does not build, preview, or\ndeploy the site. The external site owns page rendering, navigation, and\npublishing.\n\nThe current boundaries are:\n\n| Concern | Owner |\n| --------------------------------------- | -------------------------------------------------------------------- |\n| Reference-page rendering and publishing | External Astro website |\n| Documentation source and generated data | This repository |\n| Generated-data drift detection | `task docs:check`, `task docs:artifact:check`, and `task news:check` |\n| Navigation data | `docs/data/generated/docs.json` and `dev-docs.json` |\n\nChanges to an artifact contract must be coordinated with the external Astro\nconsumer. This repository does not validate the website's rendered links or\nroutes.\n\n## Single source of truth\n\nEvery published capability has one authoritative machine-readable definition\nowned by its domain or application boundary. Generated documentation derives\nfrom those definitions.\n\nGenerated reference includes:\n\n- domain commands and events;\n- Messages and typed message content;\n- Agent and Workflow contracts;\n- WorkflowSteps and Workflow plugin capability contracts;\n- policies and their typed inputs and outcomes;\n- tools and capabilities;\n- CLI commands, arguments, flags, defaults, and help;\n- runtime settings, types, defaults, validation, and secret metadata;\n- public worker and transport contracts;\n- indexes of registered functionality;\n- deprecation information.\n\nHandwritten documents contain:\n\n- architecture decisions and rationale;\n- tutorials and operational guides;\n- examples and walkthroughs;\n- migration guidance;\n- conceptual explanations.\n\nHandwritten documents link to generated reference rather than copying\nauthoritative tables.\n\n## Target generation architecture\n\n`tools/docsgen` is Archie's documentation extractor and normalizer. It produces\nstructured documentation data and protocol specifications. It does not own\npage layout and MUST NOT generate Markdown pages or fragments.\n\nThe generator is divided internally into reusable stages:\n\n```text\nload registries and types\n -\u003e normalize documentation model\n -\u003e validate ownership and identifiers\n -\u003e serialize data and protocol artifacts\n -\u003e compare or write output\n```\n\nThe normalised documentation model prevents each output renderer from\nindependently interpreting Go types. It contains stable documentation IDs,\nowners, names, descriptions, source references, versions, deprecations, fields,\ndefaults, validation, secret classifications, and relationships.\n\nInitial generator targets:\n\n```text\ndocsgen data\ndocsgen asyncapi\ndocsgen all\ndocsgen check\n```\n\n- `data` writes the normalised JSON reference data.\n- `asyncapi` writes protocol schemas and envelopes.\n- `all` generates every committed artifact.\n- `check` generates into a temporary directory and fails on drift.\n\nThe command may use subcommands or an equivalent explicit `--target` flag. It\nMUST retain one normalisation and validation path.\n\n## Target output\n\nDuring adaptation, `docs` remains the staging site. Generated outputs live in\na visibly owned subtree:\n\n```text\ndocs/\n data/\n geLine truncated
},
{
"url": "/dev/architecture/identity/",
"title": "Identity",
"section": "Architecture",
"body": "# Identity\n\n**Status:** Approved foundation; lifecycle details are deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nIdentity answers which persistent actor owns or performed an action. It supplies\nstable cross-domain attribution and lifecycle semantics.\n\nIdentity kinds include:\n\n- the Archie system identity, such as `System` or `archied`;\n- agent or bot identities;\n- service-account identities;\n- future user identities.\n\nA user is another kind of identity rather than a separate foundation concept.\n\n## Ownership\n\n`internal/domain/identity` owns:\n\n- immutable canonical `IdentityID` values;\n- identity kind;\n- lifecycle state;\n- ownership and attribution semantics;\n- identity-related commands and events.\n\nDomains may record an identity reference on their own state and events when\nownership or attribution is required. They MUST NOT receive a complete\nper-identity application configuration bundle.\n\nPersona and communication style are separate from identity.\n\nEvery Agent has its own immutable acting `IdentityID`. Agent actions use that\nidentity for ownership and attribution in the same way an organisation records\nwhich user accessed a resource, changed a permission, or performed another\nauditable action.\n\nAgent and Identity remain separate aggregates. Identity supplies the stable\nactor reference; Agent owns assistant behaviour, memory, specialisation,\nconversations, and capability context.\n\nAgent identities MUST NOT be shared between Agents. Automated WorkflowExecutions\nMAY eventually act through a dedicated service-account identity when a specific\nunattended automation requires it. Such use is an explicit execution decision\nand audit principal, not the default for Agents or a substitute for recording\nthe initiating user when one exists.\n\nA Workflow is owned by an IdentityID and executes as its owner by default.\nFuture delegated execution MAY explicitly assign a different `RunAsIdentityID`,\nincluding a user or service-account identity. Ownership, effective execution\nidentity, initiating identity, and delegation provenance remain distinct audit\nfacts.\n\n## Canonical identity\n\nEvery identity has an immutable `IdentityID`. It is the only value used for\ncross-domain ownership, attribution, routing, persistence, commands, and events.\n\nIdentity kind is explicit:\n\n- system;\n- bot;\n- service account;\n- user.\n\nDisplay names are mutable and MUST NOT be used as identifiers. Forge usernames,\nchannel bot names, Git authors, provider account names, and other external\nidentifiers are bindings associated with an identity rather than identity\nitself.\n\n`System` is represented by a real identity and `IdentityID`. The empty string\nMUST NOT retain special meaning as a legacy system identity.\n\nConfiguration refers to identities by `IdentityID` and supplies external\nbindings and capability settings separately. Renaming an identity or changing an\nexternal account MUST NOT change ownership or historical attribution.\n\nSecret-bearing channel bindings remain configuration concerns rather than\nidentity data. In particular, `[chat.telegram].token` is a\n`secret.SecretRef` resolved by the application through the configured secret\nregistry. It does not change the identity that owns or performs a chat action.\n\n## Persistence\n\nIdentity records are durable domain state. The Identity domain's repository is\nthe source of truth; infrastructure implements its persistence contract.\n\nConfiguration MAY bootstrap a missing identity through an explicit, audited\ncreation operation and MAY propose runtime capability bindings for an existing\n`IdentityID`. Configuration is not the identity registry.\n\nOmitting an identity from configuration stops assembling the omitted runtime\ncapabilities. It MUST NOT delete the identity record, erase history, or make\nhistorical references unresolvable.\n\nDisabling or retiring an identity requires an explicit Identity-domain command.\nRetired identities remain resolvable for historical attribution. A failed\nexternal binding affects capability availability without destroying or silently\nreplacing the identity.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or reLine truncated
"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/",
@@ -64,13 +64,13 @@
"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/",
"title": "Task Observability",
"section": "Architecture",
"body": "# Task Observability\n\n**Status:** Implemented. The per-run detail surface was added on 2026-09-18 and\nis described below.\n**Date:** 2026-08-09 (revised 2026-09-18)\n\n## Historical problem\n\narchied's own daemon logging (`internal/logging/`) was already solid: a\nrotating file sink, a live `Feed` the dashboard subscribes to, and a reader\nthe `/api/logs` endpoint serves from. Before this implementation, none of\nthat reached inside a task.\n\nA task's actual work happens in a task-scoped `archie-agent` container,\ndispatched as one complete workflow over NATS.\nBefore this design was implemented, five things destroyed the evidence of what\nthat container did:\n\n1. **Worker startup** constructed an stderr-only logger and never replaced its\n handler after discovering a dedicated boot task, so runtime records could\n not leave the container.\n2. **`internal/container/pool.go`** creates every task container with\n `AutoRemove: true`. The container — and its stderr — is gone at exit,\n success or failure alike.\n3. **`internal/domain/workflow/implement.go`, `StageBaselineGate`** captures\n `go build`/`go vet`/`go test` output via `cmd.CombinedOutput()`, then\n clips it to 200 characters into a `Warn` log line and discards the rest.\n The eventual park reason is built from `res.Status` alone — the actual\n compiler error is never persisted anywhere a human or Archie's own chat\n tools can read it back.\n4. **`agentexec.Result`** (`internal/agentexec/protocol.go`) carries only\n `Summary`/`Detail` — no step-by-step transcript (tool calls, durations,\n errors). There is no transcript to recover even in principle.\n5. **`agentexec.SubjectForSystem`** is documented as the return channel for\n exactly this — *\"log dumps, health, and PII warnings... the daemon reads\n these for observability and never forwards them\"* — but has no publisher\n and no consumer anywhere in the codebase except a subject-format\n assertion in `nats_test.go`. The designed return path was never wired.\n\nThe practical consequence: a task parks with\n`stage baseline: baseline red -- go build ./... fails and builder could not\nauto-fix (status: parked)` and there is no way — not from the dashboard, not\nfrom Telegram chat, not by SSH'ing into the deployment host — to see *why*\n`go build` failed. The container that knew is already gone.\n\nThis matters beyond debugging convenience: supported deployments can combine\na resident daemon with ephemeral Docker containers that run unattended for\nweeks between operator logins, and the system is\nintended to be usable by people other than the original operator. A system\nthat is only debuggable by an operator who happens to be watching `docker ps`\nin real time does not meet that bar.\n\n## Decision: NATS is the sole autonomous handoff\n\nThe agent image must reach NATS in every deployment, because the broker is the\nonly autonomous task handoff and the only channel carrying task results back\nto the daemon. `archied` has no workflow runner or host fallback. A container\nthat dies before establishing a NATS connection is a distinct, narrower\nfailure (connectivity/config) from the one this document addresses (a connected\ncontainer's own output being unrecoverable), and is out of scope here.\n\n## Implemented design\n\nThe key property: **logs leave the container while it is alive**, so its\ndeath at `AutoRemove` no longer matters. Persistence happens in the daemon\nprocess, which already owns durable state.\n\n### Sink: extend `internal/logging`, not a new package\n\n`internal/logging` already owns its on-disk format end to end per\n`organisation.md` (\"a package owns its own format end to end\"). Add a\ntask-scoped writer producing the same `logging.Entry` JSONL shape at\n`\u003cstate_dir\u003e/logs/tasks/\u003ctask_id\u003e/attempt-\u003cn\u003e.jsonl`. `logging.Tail`,\n`logging.Query`, and `logging.Components` operate on this unchanged;\n`internal/webui/api_logs.go` stays transport-only, as it does today.\n\n### Agent side: make the designed subject real\n\n`internal/app/agentworker` replaces the stderr-only `slog.Handler` with one\nthat tees to stderr (kept for container-level operator debugging when a\nshell is attached) and publishes each record to\n`agentexec.SubjectForSystem(taskID)`, which already exists for this purpose.\nThe application layer obtains only a narrow publisher from\n`internal/infrastructure/agenttransport/nats`; raw core-NATS types remain in\ninfrastructure. `internal/infrastructure/agentboot.TaskID` reads the task ID\nfrom `\u003cworktree\u003e/.git/task.json` per the container/pool.go trap documented in\n`CLAUDE.md`. Publishing is fire-and-forget: log shipping must never block or\nfail the run it is reporting on.\n\n### Daemon side\n\n`cmd/archied/main.go` registers `subscribeSystemLogs` once at startup on\n`agentexec.SubjectSystemWildcard`. It demultiplexes by task ID, appends to that task's\nsink, and pLine truncated
"body": "# Task Observability\n\n**Status:** Implemented. The per-run detail surface was added on 2026-09-18 and\nis described below.\n**Date:** 2026-08-09 (revised 2026-09-18)\n\n## Historical problem\n\narchied's own daemon logging (`internal/logging/`) was already solid: a\nrotating file sink, a live `Feed` the dashboard subscribes to, and a reader\nthe `/api/logs` endpoint serves from. Before this implementation, none of\nthat reached inside a task.\n\nA task's actual work happens in a task-scoped `archie-agent` container,\ndispatched as one complete workflow over NATS.\nBefore this design was implemented, five things destroyed the evidence of what\nthat container did:\n\n1. **Worker startup** constructed an stderr-only logger and never replaced its\n handler after discovering a dedicated boot task, so runtime records could\n not leave the container.\n2. **`internal/container/pool.go`** creates every task container with\n `AutoRemove: true`. The container — and its stderr — is gone at exit,\n success or failure alike.\n3. **`internal/domain/workflow/implement.go`, `StageBaselineGate`** captures\n `go build`/`go vet`/`go test` output via `cmd.CombinedOutput()`, then\n clips it to 200 characters into a `Warn` log line and discards the rest.\n The eventual park reason is built from `res.Status` alone — the actual\n compiler error is never persisted anywhere a human or Archie's own chat\n tools can read it back.\n4. **`agentexec.Result`** (`internal/agentexec/protocol.go`) carries only\n `Summary`/`Detail` — no step-by-step transcript (tool calls, durations,\n errors). There is no transcript to recover even in principle.\n5. **`agentexec.SubjectForSystem`** is documented as the return channel for\n exactly this — _\"log dumps, health, and PII warnings... the daemon reads\n these for observability and never forwards them\"_ — but has no publisher\n and no consumer anywhere in the codebase except a subject-format\n assertion in `nats_test.go`. The designed return path was never wired.\n\nThe practical consequence: a task parks with\n`stage baseline: baseline red -- go build ./... fails and builder could not\nauto-fix (status: parked)` and there is no way — not from the dashboard, not\nfrom Telegram chat, not by SSH'ing into the deployment host — to see _why_\n`go build` failed. The container that knew is already gone.\n\nThis matters beyond debugging convenience: supported deployments can combine\na resident daemon with ephemeral Docker containers that run unattended for\nweeks between operator logins, and the system is\nintended to be usable by people other than the original operator. A system\nthat is only debuggable by an operator who happens to be watching `docker ps`\nin real time does not meet that bar.\n\n## Decision: NATS is the sole autonomous handoff\n\nThe agent image must reach NATS in every deployment, because the broker is the\nonly autonomous task handoff and the only channel carrying task results back\nto the daemon. `archied` has no workflow runner or host fallback. A container\nthat dies before establishing a NATS connection is a distinct, narrower\nfailure (connectivity/config) from the one this document addresses (a connected\ncontainer's own output being unrecoverable), and is out of scope here.\n\n## Implemented design\n\nThe key property: **logs leave the container while it is alive**, so its\ndeath at `AutoRemove` no longer matters. Persistence happens in the daemon\nprocess, which already owns durable state.\n\n### Sink: extend `internal/logging`, not a new package\n\n`internal/logging` already owns its on-disk format end to end per\n`organisation.md` (\"a package owns its own format end to end\"). Add a\ntask-scoped writer producing the same `logging.Entry` JSONL shape at\n`\u003cstate_dir\u003e/logs/tasks/\u003ctask_id\u003e/attempt-\u003cn\u003e.jsonl`. `logging.Tail`,\n`logging.Query`, and `logging.Components` operate on this unchanged;\n`internal/webui/api_logs.go` stays transport-only, as it does today.\n\n### Agent side: make the designed subject real\n\n`internal/app/agentworker` replaces the stderr-only `slog.Handler` with one\nthat tees to stderr (kept for container-level operator debugging when a\nshell is attached) and publishes each record to\n`agentexec.SubjectForSystem(taskID)`, which already exists for this purpose.\nThe application layer obtains only a narrow publisher from\n`internal/infrastructure/agenttransport/nats`; raw core-NATS types remain in\ninfrastructure. `internal/infrastructure/agentboot.TaskID` reads the task ID\nfrom `\u003cworktree\u003e/.git/task.json` per the container/pool.go trap documented in\n`CLAUDE.md`. Publishing is fire-and-forget: log shipping must never block or\nfail the run it is reporting on.\n\n### Daemon side\n\n`cmd/archied/main.go` registers `subscribeSystemLogs` once at startup on\n`agentexec.SubjectSystemWildcard`. It demultiplexes by task ID, appends to that task's\nsink, and pLine truncated
},
{
"url": "/dev/architecture/organisation/",
@@ -82,7 +82,7 @@
"url": "/dev/architecture/package-review/",
"title": "Domain and Feature Review Procedure",
"section": "Architecture",
"body": "# Domain and Feature Review Procedure\n\n**Status:** Active \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchitecture work proceeds one domain or feature at a time. Before any design\nquestion, the selected area is researched across its complete live\nimplementation, consumers, tests, state, configuration, and runtime wiring.\n\nExisting packages are evidence, not the unit that drives the interview.\nPlacement follows behaviour and ownership, not the existing directory name.\n\nNo restructuring implementation begins until the relevant package decisions\nare agreed and recorded in the focused domain or requirement document.\n\n## Required research\n\nBefore design questions, the current-state report MUST identify:\n\n- entry points and runtime composition;\n- state, persistence, and lifecycle;\n- public and internal contracts;\n- commands, events, and policy enforcement;\n- configuration and defaults;\n- all consumers and cross-domain interactions;\n- process and infrastructure boundaries;\n- tests, failure behaviour, and known invariants;\n- duplicated or conflicting implementations;\n- documentation that disagrees with live code.\n\nDiscoverable facts MUST be investigated rather than presented to the user as\ndesign questions.\n\n## Required decisions\n\nEach package review records:\n\n| Decision | Required result |\n|---|---|\n| Owned behaviour | The cohesive job the code performs |\n| Domain ownership | The owner of the behaviour and vocabulary |\n| Final location | Its target path |\n| Public contracts | The smallest interfaces, commands, and events exposed |\n| Required services | Domain-defined interfaces implemented by infrastructure |\n| State ownership | The owner of each mutable record and transition |\n| Dependencies | Allowed imports and dependencies to remove |\n| Duplication | Code to consolidate, delete, or keep separate |\n| Plugin status | Core domain, shared contract, infrastructure, plugin, or extra |\n| Process boundary | In-process, or the concrete reason for isolation |\n| Configuration | Settings owned by the domain or plugin |\n| Policy | Definitions, evaluators, consequences, and shared mechanics used |\n| Documentation | Authoritative definitions and generated reference |\n| Migration constraints | Behaviour and data that must remain correct |\n\n## Interview method\n\nFor every selected domain or feature:\n\n1. Declare the single area under review.\n2. Complete the current-state research.\n3. Explain actual behaviour in plain technical language.\n4. Separate facts from design decisions and concerns.\n5. Resolve obvious consequences directly and ask only questions whose answer\n materially changes behaviour or structure.\n6. Record each confirmed decision in its focused document.\n7. Complete that area's handoff before selecting another.\n8. Keep unrelated domains outside the implementation scope.\n"
"body": "# Domain and Feature Review Procedure\n\n**Status:** Active \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchitecture work proceeds one domain or feature at a time. Before any design\nquestion, the selected area is researched across its complete live\nimplementation, consumers, tests, state, configuration, and runtime wiring.\n\nExisting packages are evidence, not the unit that drives the interview.\nPlacement follows behaviour and ownership, not the existing directory name.\n\nNo restructuring implementation begins until the relevant package decisions\nare agreed and recorded in the focused domain or requirement document.\n\n## Required research\n\nBefore design questions, the current-state report MUST identify:\n\n- entry points and runtime composition;\n- state, persistence, and lifecycle;\n- public and internal contracts;\n- commands, events, and policy enforcement;\n- configuration and defaults;\n- all consumers and cross-domain interactions;\n- process and infrastructure boundaries;\n- tests, failure behaviour, and known invariants;\n- duplicated or conflicting implementations;\n- documentation that disagrees with live code.\n\nDiscoverable facts MUST be investigated rather than presented to the user as\ndesign questions.\n\n## Required decisions\n\nEach package review records:\n\n| Decision | Required result |\n| --------------------- | ---------------------------------------------------------------- |\n| Owned behaviour | The cohesive job the code performs |\n| Domain ownership | The owner of the behaviour and vocabulary |\n| Final location | Its target path |\n| Public contracts | The smallest interfaces, commands, and events exposed |\n| Required services | Domain-defined interfaces implemented by infrastructure |\n| State ownership | The owner of each mutable record and transition |\n| Dependencies | Allowed imports and dependencies to remove |\n| Duplication | Code to consolidate, delete, or keep separate |\n| Plugin status | Core domain, shared contract, infrastructure, plugin, or extra |\n| Process boundary | In-process, or the concrete reason for isolation |\n| Configuration | Settings owned by the domain or plugin |\n| Policy | Definitions, evaluators, consequences, and shared mechanics used |\n| Documentation | Authoritative definitions and generated reference |\n| Migration constraints | Behaviour and data that must remain correct |\n\n## Interview method\n\nFor every selected domain or feature:\n\n1. Declare the single area under review.\n2. Complete the current-state research.\n3. Explain actual behaviour in plain technical language.\n4. Separate facts from design decisions and concerns.\n5. Resolve obvious consequences directly and ask only questions whose answer\n materially changes behaviour or structure.\n6. Record each confirmed decision in its focused document.\n7. Complete that area's handoff before selecting another.\n8. Keep unrelated domains outside the implementation scope.\n"
},
{
"url": "/dev/architecture/plugins-and-extensions/",
@@ -100,13 +100,13 @@
"url": "/dev/architecture/safe-change-and-recovery/",
"title": "Safe Change and Recovery",
"section": "Architecture",
"body": "# Safe Change and Recovery\n\n**Status:** Requirements approved; mechanics are under design. Database-backed settings are implemented through the control plane (2026-09): see the degrade/recovery section below, which records a gap rather than a solution. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.\n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie is built and improved by agents as well as humans. The architecture MUST\nmake a change easy to locate, understand, test, audit, extend, and reverse\nwithout requiring its author to understand unrelated parts of the application.\n\nSeparation of concerns is therefore an operational safety boundary, not only a\ncode-organisation preference.\n\n## Required outcomes\n\n- An agent can improve a focused feature without receiving authority over\n unrelated domains.\n- Every event, function, action, setting, and policy has an identifiable owner\n and provenance.\n- Source and runtime changes pass deterministic checks outside the actor making\n the change.\n- A rejected or unhealthy candidate cannot replace the last known working\n version.\n- Invalid user configuration does not terminate an otherwise healthy\n application.\n- Configuration and service failures are observable, attributed, and eligible\n for bounded remediation or rollback.\n- The application continues serving unaffected capabilities when one\n capability is misconfigured or unhealthy.\n- Recovery failure is reported and contained rather than hidden in an\n unbounded retry loop.\n\n## Source changes\n\nAgent-authored source changes occur through the task-execution boundary in an\nisolated workspace. The agent does not directly mutate the running\ninstallation.\n\nPromotion is controlled by deterministic repository-owned policy, including\ntests, generated-reference drift checks, protected paths, change scope, and\nother required gates. The actor proposing a change cannot waive these checks.\n\nRepository and domain separation SHOULD allow a task to load and modify only\nthe governing requirements and code for its declared scope.\n\n## Runtime changes\n\nConfiguration and other runtime changes are proposed as candidates rather than\nmutating the active state in place.\n\nThe affected domain owns:\n\n- the command describing the semantic change;\n- validation of its typed settings;\n- health signals that demonstrate correct operation;\n- domain-specific remediation and rollback consequences.\n\nShared policy supplies consistent evaluation, evidence, and audit mechanics.\nIdentity supplies actor attribution. Infrastructure supplies external\nconfiguration storage, service control, and other operational adapters.\n\n## Runtime change protocol\n\nLast-known-good preservation and candidate promotion are the universal runtime\nchange protocol.\n\n1. An identity proposes an immutable candidate version.\n2. Infrastructure parses it without changing active state.\n3. Each affected domain validates its typed settings.\n4. Shared policy evaluates cross-cutting constraints.\n5. Each affected capability prepares the candidate without destroying its\n active instance.\n6. Capability-specific health checks prove the candidate works.\n7. Runtime supervision atomically promotes the candidate.\n8. A bounded observation period watches for delayed failure.\n9. Failure restores the last-known-good version and records the reason,\n evidence, actor, and involved versions.\n10. Repeated remediation failure stops retrying, isolates the capability, and\n reports the fault.\n\nThe affected domain owns the semantic change command, typed validation, health\nsignals, and remediation consequences. Shared runtime supervision owns the\npromotion transaction. Infrastructure performs storage and service-control\noperations.\n\nThe protocol's exact Go contracts, storage model, atomicity boundary, and\nobservation rules require a focused runtime-supervision design pass.\n\n## Failure isolation\n\nInvalid input MUST leave the active valid configuration unchanged and produce a\ndiagnostic record.\n\nA capability that cannot start or reload SHOULD fail independently where its\nabsence does not violate a declared application invariant. Unaffected\ncapabilities continue operating.\n\nRemediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT\nsilently oscillate between versions or retry forever.\n\n## Database settings: degrade paths and recovery (2026-09)\n\nThe control plane owns runtime-tunable settings and stores them in the State\nStore's PostgreSQL database.\nThis replaced a dashboard overlay store that degraded to file config on any\nfailure and had three documented ways back. The replacement has none, and the\nposture is the opposite: **the daemon fails closed.**\n\n### Degrade paths\n\n| Failure | Boot behaviour | Where the operator sees it |\n| --- | -Line truncated
"body": "# Safe Change and Recovery\n\n**Status:** Requirements approved; mechanics are under design. Database-backed settings are implemented through the control plane (2026-09): see the degrade/recovery section below, which records a gap rather than a solution. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.\n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie is built and improved by agents as well as humans. The architecture MUST\nmake a change easy to locate, understand, test, audit, extend, and reverse\nwithout requiring its author to understand unrelated parts of the application.\n\nSeparation of concerns is therefore an operational safety boundary, not only a\ncode-organisation preference.\n\n## Required outcomes\n\n- An agent can improve a focused feature without receiving authority over\n unrelated domains.\n- Every event, function, action, setting, and policy has an identifiable owner\n and provenance.\n- Source and runtime changes pass deterministic checks outside the actor making\n the change.\n- A rejected or unhealthy candidate cannot replace the last known working\n version.\n- Invalid user configuration does not terminate an otherwise healthy\n application.\n- Configuration and service failures are observable, attributed, and eligible\n for bounded remediation or rollback.\n- The application continues serving unaffected capabilities when one\n capability is misconfigured or unhealthy.\n- Recovery failure is reported and contained rather than hidden in an\n unbounded retry loop.\n\n## Source changes\n\nAgent-authored source changes occur through the task-execution boundary in an\nisolated workspace. The agent does not directly mutate the running\ninstallation.\n\nPromotion is controlled by deterministic repository-owned policy, including\ntests, generated-reference drift checks, protected paths, change scope, and\nother required gates. The actor proposing a change cannot waive these checks.\n\nRepository and domain separation SHOULD allow a task to load and modify only\nthe governing requirements and code for its declared scope.\n\n## Runtime changes\n\nConfiguration and other runtime changes are proposed as candidates rather than\nmutating the active state in place.\n\nThe affected domain owns:\n\n- the command describing the semantic change;\n- validation of its typed settings;\n- health signals that demonstrate correct operation;\n- domain-specific remediation and rollback consequences.\n\nShared policy supplies consistent evaluation, evidence, and audit mechanics.\nIdentity supplies actor attribution. Infrastructure supplies external\nconfiguration storage, service control, and other operational adapters.\n\n## Runtime change protocol\n\nLast-known-good preservation and candidate promotion are the universal runtime\nchange protocol.\n\n1. An identity proposes an immutable candidate version.\n2. Infrastructure parses it without changing active state.\n3. Each affected domain validates its typed settings.\n4. Shared policy evaluates cross-cutting constraints.\n5. Each affected capability prepares the candidate without destroying its\n active instance.\n6. Capability-specific health checks prove the candidate works.\n7. Runtime supervision atomically promotes the candidate.\n8. A bounded observation period watches for delayed failure.\n9. Failure restores the last-known-good version and records the reason,\n evidence, actor, and involved versions.\n10. Repeated remediation failure stops retrying, isolates the capability, and\n reports the fault.\n\nThe affected domain owns the semantic change command, typed validation, health\nsignals, and remediation consequences. Shared runtime supervision owns the\npromotion transaction. Infrastructure performs storage and service-control\noperations.\n\nThe protocol's exact Go contracts, storage model, atomicity boundary, and\nobservation rules require a focused runtime-supervision design pass.\n\n## Failure isolation\n\nInvalid input MUST leave the active valid configuration unchanged and produce a\ndiagnostic record.\n\nA capability that cannot start or reload SHOULD fail independently where its\nabsence does not violate a declared application invariant. Unaffected\ncapabilities continue operating.\n\nRemediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT\nsilently oscillate between versions or retry forever.\n\n## Database settings: degrade paths and recovery (2026-09)\n\nThe control plane owns runtime-tunable settings and stores them in the State\nStore's PostgreSQL database.\nThis replaced a dashboard overlay store that degraded to file config on any\nfailure and had three documented ways back. The replacement has none, and the\nposture is the opposite: **the daemon fails closed.**\n\n### Degrade paths\n\n| Failure Line truncated
},
{
"url": "/dev/development/",
"title": "Development guides",
"section": "Development",
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| --- | --- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` also adds linter-tool lines to `go.sum`\n (bead 1e37); restore `go.sum` before committing unless you changed a\n dependency.\n- A change to `docs/prds/` or `docs/architecture/` carries the regenerated\n `docs/data/generated/dev-docs.json`, and PRD edits follow\n `docs/prds/RULES.md` and pass `task docs:prds`.\n"
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| ---------------------------------------------- | -------------------------------------------------------------------------------- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` also adds linter-tool lines to `go.sum`\n (bead 1e37); restore `go.sum` before committing unless you changed a\n dependency.\n- A change to `docs/prds/` or `docs/architecture/` carries the regenerated\n `docs/data/generated/dev-docs.json`, and PRD edits follow\n `docs/prds/RULES.md` and pass `task docs:prds`.\n"
},
{
"url": "/dev/development/agent/",
@@ -160,7 +160,7 @@
"url": "/dev/prds/01-project-management/",
"title": "Architecture Decision Index",
"section": "PRDs",
"body": "# Architecture Decision Index\n\n**Status:** Approved \n**Date:** 2026-07-28 \n**Beads issue:** `archie-core-5d7`\n\n## Purpose\n\nThis file is the navigation point for Archie's target architecture. It is\ndeliberately short. Architectural decisions are separated by domain or\nrequirement so an implementation task can load only the rules governing its\nscope.\n\nImplementers MUST read the decision document for the domain or requirement they\nare changing. They MUST NOT infer permission to change neighbouring domains from\na broader restructuring objective.\n\n## Global invariants\n\n- Organise code around cohesive application responsibilities, not generic\n technical mechanisms.\n- Domains own their behaviour, vocabulary, state, commands, events, policy\n implementations, runtime settings, and required service contracts.\n- Domains do not depend on infrastructure or manipulate another domain.\n- `internal/app` owns composition; `cmd/*` remains thin.\n- Cross-domain work uses an explicitly owned command, event, or approved shared\n contract.\n- Process boundaries are deployment choices and do not determine source-code\n ownership.\n- Existing package names and boundaries have no presumption of survival.\n\nThe words **MUST**, **MUST NOT**, **SHOULD**, and **MAY** are normative.\n\n## Decision documents\n\n| Scope | Authoritative document |\n| --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |\n| Repository layout, domains, composition, deployments, and optional material | [architecture/organisation.md](/dev/architecture/organisation/) |\n| Dependency direction, domain contracts, infrastructure, commands, events, and wire contracts | [architecture/dependencies-and-contracts.md](/dev/architecture/dependencies-and-contracts/) |\n| External configuration, runtime settings, and dissolution of `internal/config` | [architecture/configuration.md](/dev/architecture/configuration/) |\n| Persistent actor identity, ownership, lifecycle, and attribution | [architecture/identity.md](/dev/architecture/identity/) |\n| Agent definitions, workflows, workflow executions, tools, and worker boundaries | [architecture/agent-system.md](/dev/architecture/agent-system/) |\n| Personal-assistant interactions, messaging channels, and optional promotion into durable work | [architecture/messaging-and-work-intake.md](/dev/architecture/messaging-and-work-intake/) |\n| Shared policy evaluation and domain-owned policy semantics | [architecture/policy.md](/dev/architecture/policy/) |\n| Safe source/configuration changes, health supervision, and recovery | [architecture/safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/) |\n| Plugin framework, plugin implementations, and extension isolation | [architecture/plugins-and-extensions.md](/dev/architecture/plugins-and-extensions/) |\n| Generated references, deprecations, and changelog generation | [architecture/generated-documentation.md](/dev/architecture/generated-documentation/) |\n| Remaining package destinations, data migrations, runtime cutover, and completion criteria | [architecture/migration-decisions.md](/dev/architecture/migration-decisions/) |\n| Domain/feature research, design interview, and required handoff | [architecture/package-review.md](/dev/architecture/package-review/) |\n\n## Deferred decisions\n\nThe remaining package-placement, data-migration, shared-mechanics, process-\nboundary, and cutover decisions are maintained in\n[architecture/migration-decisions.md](/dev/architecture/migration-decisions/).\n\nEach decision is made in its focused document after code-grounded review.\n"
"body": "# Architecture Decision Index\n\n**Status:** Approved \n**Date:** 2026-07-28 \n**Beads issue:** `archie-core-5d7`\n\n## Purpose\n\nThis file is the navigation point for Archie's target architecture. It is\ndeliberately short. Architectural decisions are separated by domain or\nrequirement so an implementation task can load only the rules governing its\nscope.\n\nImplementers MUST read the decision document for the domain or requirement they\nare changing. They MUST NOT infer permission to change neighbouring domains from\na broader restructuring objective.\n\n## Global invariants\n\n- Organise code around cohesive application responsibilities, not generic\n technical mechanisms.\n- Domains own their behaviour, vocabulary, state, commands, events, policy\n implementations, runtime settings, and required service contracts.\n- Domains do not depend on infrastructure or manipulate another domain.\n- `internal/app` owns composition; `cmd/*` remains thin.\n- Cross-domain work uses an explicitly owned command, event, or approved shared\n contract.\n- Process boundaries are deployment choices and do not determine source-code\n ownership.\n- Existing package names and boundaries have no presumption of survival.\n\nThe words **MUST**, **MUST NOT**, **SHOULD**, and **MAY** are normative.\n\n## Decision documents\n\n| Scope | Authoritative document |\n| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |\n| Repository layout, domains, composition, deployments, and optional material | [architecture/organisation.md](/dev/architecture/organisation/) |\n| Dependency direction, domain contracts, infrastructure, commands, events, and wire contracts | [architecture/dependencies-and-contracts.md](/dev/architecture/dependencies-and-contracts/) |\n| External configuration, runtime settings, and dissolution of `internal/config` | [architecture/configuration.md](/dev/architecture/configuration/) |\n| Persistent actor identity, ownership, lifecycle, and attribution | [architecture/identity.md](/dev/architecture/identity/) |\n| Agent definitions, workflows, workflow executions, tools, and worker boundaries | [architecture/agent-system.md](/dev/architecture/agent-system/) |\n| Personal-assistant interactions, messaging channels, and optional promotion into durable work | [architecture/messaging-and-work-intake.md](/dev/architecture/messaging-and-work-intake/) |\n| Shared policy evaluation and domain-owned policy semantics | [architecture/policy.md](/dev/architecture/policy/) |\n| Safe source/configuration changes, health supervision, and recovery | [architecture/safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/) |\n| Plugin framework, plugin implementations, and extension isolation | [architecture/plugins-and-extensions.md](/dev/architecture/plugins-and-extensions/) |\n| Generated references, deprecations, and changelog generation | [architecture/generated-documentation.md](/dev/architecture/generated-documentation/) |\n| Remaining package destinations, data migrations, runtime cutover, and completion criteria | [architecture/migration-decisions.md](/dev/architecture/migration-decisions/) |\n| Domain/feature research, design interview, and required handoff | [architecture/package-review.md](/dev/architecture/package-review/) |\n\n## Deferred decisions\n\nThe remaining package-placement, data-migration, shared-mechanics, process-\nboundary, and cutover decisions are maintained in\n[architecture/migration-decisions.md](/dev/architecture/migration-decisions/).\n\nEach decision is made in its focused document after code-grounded review.\n"
},
{
"url": "/dev/prds/RULES/",
@@ -178,19 +178,19 @@
"url": "/dev/prds/adversarial-self-review/",
"title": "Adversarial self-review stage -- decision",
"section": "PRDs",
"body": "# Adversarial self-review stage -- decision\n\n**Status:** Finalised\n**Authority:** `docs/architecture/adversarial-review.md` describes the stage and is authoritative. This PRD remains the design-decision record.\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-h019.1`, blocks `h019.2/.3/.4/.5`\n\n\u003e **Section 1 is superseded by the decision below.**\n\u003e The original execution mechanism assumed daemon-owned in-process execution\n\u003e and a daemon-side second `Pool.Acquire`; `archie-core-q15y` removed both\n\u003e call sites, leaving one open question: how a fresh reviewer receives an\n\u003e isolated snapshot from inside the task-scoped worker, without a host\n\u003e executor or a nested container lifecycle. Section 1 below now answers it\n\u003e with `agent.Subagent`. Sections 2-5 were never invalidated and still hold;\n\u003e section 3's contract shipped as `archie-core-h019.2`.\n\nAnswers the five questions in `h019.1`'s description against the actual\nimplement workflow, not designed from scratch: the gate pattern, the\ncontainer pool, and the workflow engine's `Outcome` mechanism already answer\nmost of this.\n\n## 1. Where it runs: `agent.Subagent`, inside the task worker\n\nThe implement workflow's stage list\n(`internal/domain/workflow/implement.go`) already has the right slot:\nafter `StageDiffCap()`, before `StageOpenPR()` -- gates\nhave passed, the diff is final, and nothing has told the forge about this\nchange yet.\n\n**The reviewer is an `agent.Subagent` run, not a second container.** ai-sdk\n`v0.1.22` (already the pinned version) added `agent/subagent.go`: a nested,\nsynchronous `core.GenerateText` call in the same process, with its own model,\nsystem prompt, toolset and step budget. That is what makes this feature\nbuildable at all after `q15y` -- the reviewer runs inside the task-scoped\n`archie-agent` worker that is already executing the workflow, so there is no\nhost executor, no second `Pool.Acquire`, and no nested container lifecycle.\n\n**Two isolations are needed, and Subagent only provides one of them.**\n\n*Conversation isolation is structural, and free.* `Subagent.Run`\n(`agent/subagent.go`) calls `GenerateText` with `Prompt` set and\n`Messages` never populated. The implementer's history has no code path into\nthe nested run; only the prompt string crosses, and only text comes back.\nThis is the literal form of \"environmental enforcement over prompt rules\":\nthe reviewer is not told to ignore the implementer's reasoning, because\nnothing hands it any. `h019.3`'s required test asserts this as a construction\nfact.\n\n*Workspace isolation is still ours to build.* A sub-agent shares the parent's\nprocess, working directory and credentials. So the `.git`-free snapshot from\nthe original decision survives unchanged and is load-bearing: export the\nreviewed commit (`git archive \u003ccommit\u003e | tar -x`) into a fresh scratch\ndirectory beside, not inside, the task worktree, and write `diff.patch` (the\ndiff already computed for `StageYaegiGate`'s `Trees.Diff()`) and `issue.md`\n(the originating issue's title and body, nothing else) alongside it. Stripping\n`.git` is what makes commit messages, branch name and reflog -- the actual\nchannel a multi-commit implementer's reasoning leaks through -- structurally\nunreachable rather than merely undisclosed.\n\n`Subagent.Tools` therefore takes a **distinct read-only toolset rooted at the\nsnapshot**. Never the worker's own toolset: it carries the `worktreerpc`\npublication grant, so a reviewer holding it could push the branch it exists to\nblock.\n\n**Call `Run()`, not `Tool()`.** `Tool()` would register delegation as a tool\nthe *implementer's* model may choose to invoke -- self-certification by the\nimplementer, which is the exact failure this feature exists to prevent. The\nstage calls `Run()` unconditionally. That also sidesteps both of `Tool()`'s\ndocumented footguns: the parent's two-step minimum and the recursion risk of\npassing a toolset back to itself.\n\n**Findings return through a closure, not the return value.** `Run` yields only\nfinal text, so section 3's structured contract cannot ride the return. Because\nthe sub-agent is in-process, the capture tool's Go implementation appends\ndirectly to a `[]workflow.ReviewFinding` the stage owns. This preserves the\n\"cannot end its turn without calling a typed tool\" property, and it defeats\n`Subagent`'s documented \"no partial results on failure\" limitation: findings\nalready captured survive an error return, so **the stage reads the captured\nslice even when `Run` returns an error**. A reviewer that logged three defects\nand then hit its step limit still yields those three.\n\n## 2. What it's given, and what it must never be given\n\n**Given:** the clean file-content snapshot (so the reviewer can read whole\nfiles -- follow an import, check interface satisfaction, see a call site --\nnot just diff hunks, which the manual-read checklist in CLAUDE.md rLine truncated
"body": "# Adversarial self-review stage -- decision\n\n**Status:** Finalised\n**Authority:** `docs/architecture/adversarial-review.md` describes the stage and is authoritative. This PRD remains the design-decision record.\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-h019.1`, blocks `h019.2/.3/.4/.5`\n\n\u003e **Section 1 is superseded by the decision below.**\n\u003e The original execution mechanism assumed daemon-owned in-process execution\n\u003e and a daemon-side second `Pool.Acquire`; `archie-core-q15y` removed both\n\u003e call sites, leaving one open question: how a fresh reviewer receives an\n\u003e isolated snapshot from inside the task-scoped worker, without a host\n\u003e executor or a nested container lifecycle. Section 1 below now answers it\n\u003e with `agent.Subagent`. Sections 2-5 were never invalidated and still hold;\n\u003e section 3's contract shipped as `archie-core-h019.2`.\n\nAnswers the five questions in `h019.1`'s description against the actual\nimplement workflow, not designed from scratch: the gate pattern, the\ncontainer pool, and the workflow engine's `Outcome` mechanism already answer\nmost of this.\n\n## 1. Where it runs: `agent.Subagent`, inside the task worker\n\nThe implement workflow's stage list\n(`internal/domain/workflow/implement.go`) already has the right slot:\nafter `StageDiffCap()`, before `StageOpenPR()` -- gates\nhave passed, the diff is final, and nothing has told the forge about this\nchange yet.\n\n**The reviewer is an `agent.Subagent` run, not a second container.** ai-sdk\n`v0.1.22` (already the pinned version) added `agent/subagent.go`: a nested,\nsynchronous `core.GenerateText` call in the same process, with its own model,\nsystem prompt, toolset and step budget. That is what makes this feature\nbuildable at all after `q15y` -- the reviewer runs inside the task-scoped\n`archie-agent` worker that is already executing the workflow, so there is no\nhost executor, no second `Pool.Acquire`, and no nested container lifecycle.\n\n**Two isolations are needed, and Subagent only provides one of them.**\n\n_Conversation isolation is structural, and free._ `Subagent.Run`\n(`agent/subagent.go`) calls `GenerateText` with `Prompt` set and\n`Messages` never populated. The implementer's history has no code path into\nthe nested run; only the prompt string crosses, and only text comes back.\nThis is the literal form of \"environmental enforcement over prompt rules\":\nthe reviewer is not told to ignore the implementer's reasoning, because\nnothing hands it any. `h019.3`'s required test asserts this as a construction\nfact.\n\n_Workspace isolation is still ours to build._ A sub-agent shares the parent's\nprocess, working directory and credentials. So the `.git`-free snapshot from\nthe original decision survives unchanged and is load-bearing: export the\nreviewed commit (`git archive \u003ccommit\u003e | tar -x`) into a fresh scratch\ndirectory beside, not inside, the task worktree, and write `diff.patch` (the\ndiff already computed for `StageYaegiGate`'s `Trees.Diff()`) and `issue.md`\n(the originating issue's title and body, nothing else) alongside it. Stripping\n`.git` is what makes commit messages, branch name and reflog -- the actual\nchannel a multi-commit implementer's reasoning leaks through -- structurally\nunreachable rather than merely undisclosed.\n\n`Subagent.Tools` therefore takes a **distinct read-only toolset rooted at the\nsnapshot**. Never the worker's own toolset: it carries the `worktreerpc`\npublication grant, so a reviewer holding it could push the branch it exists to\nblock.\n\n**Call `Run()`, not `Tool()`.** `Tool()` would register delegation as a tool\nthe _implementer's_ model may choose to invoke -- self-certification by the\nimplementer, which is the exact failure this feature exists to prevent. The\nstage calls `Run()` unconditionally. That also sidesteps both of `Tool()`'s\ndocumented footguns: the parent's two-step minimum and the recursion risk of\npassing a toolset back to itself.\n\n**Findings return through a closure, not the return value.** `Run` yields only\nfinal text, so section 3's structured contract cannot ride the return. Because\nthe sub-agent is in-process, the capture tool's Go implementation appends\ndirectly to a `[]workflow.ReviewFinding` the stage owns. This preserves the\n\"cannot end its turn without calling a typed tool\" property, and it defeats\n`Subagent`'s documented \"no partial results on failure\" limitation: findings\nalready captured survive an error return, so **the stage reads the captured\nslice even when `Run` returns an error**. A reviewer that logged three defects\nand then hit its step limit still yields those three.\n\n## 2. What it's given, and what it must never be given\n\n**Given:** the clean file-content snapshot (so the reviewer can read whole\nfiles -- follow an import, check interface satisfaction, see a call site --\nnot just diff hunks, which the manual-read checklist in CLAUDE.md rLine truncated
},
{
"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/",
"title": "Artifact sender",
"section": "PRDs",
"body": "# Artifact sender\n\n**Status:** Approved\n**Revision:** 1\n**Authority:** this document\n\n## Purpose\n\narchie-core publishes artifacts — design documents, review reports, research briefs,\nrunnable pages — to the offloaded.dev collaborative editor. A person reads the\nartifact, comments on it, and the artifact page is the shared surface for iteration.\n\nThe receiving contract is owned by the editor: `POST /api/artifacts` with a bearer\nservice token, a closed field set, and server-side idempotency on `requestId` plus\nlast-write-wins on `sentAt`. This document owns only what archie-core sends.\n\n## Scope\n\nVersion one publishes one-way: archie-core sends, the editor receives. The first\nproducer is the pull-request adversarial review: a completed `ReviewReport` is\nrendered to markdown and published after the review completes.\n\nChat-surface tools (`create_artifact`, `update_artifact`), comment read-back, share\ntokens, and runnable-format producers (`html`, `react`, `vue`) are later slices. The\nreceiving contract already carries them; version one does not exercise them.\n\n## Configuration\n\n- New `[artifacts]` section: `base_url` (site origin), `token` (`SecretRef`) with\n `token_env` fallback naming `WORKSPACE_INGEST_TOKEN`.\n- An empty `base_url` disables the sender: no client is constructed, nothing is\n registered, and publishing degrades to a log line.\n- The token is runtime configuration. It is never baked at build time.\n\n## Sender\n\n- New package `internal/infrastructure/artifactsync` exposing one method,\n `Publish(ctx, Artifact) (string, error)`, where the string is the artifact URL.\n One-method injected seam, concrete client constructed by the boot path when the\n configuration resolves — the `crondelivery.Courier` posture.\n- The client POSTs the frozen contract body. Each publish sends the complete\n source: versions of record are full snapshots, never diffs.\n- A `503` response is retried three times with backoff. `401` and `400` are not\n retried; they are logged with the field reason the response names.\n- `requestId` is `artifact:\u003ctask-id\u003e:\u003cversion\u003e` when the producer is task-backed,\n otherwise `artifact:\u003cidentity\u003e:\u003csentAt-utc\u003e`. Sending the same `requestId` with\n an equal or older `sentAt` must be a server-side no-op, which makes sender-side\n retry safe.\n\n## Report rendering\n\n- `ReviewReport` gains a pure markdown renderer in `internal/domain/workflow`:\n the summary as the lede, one finding per subsection with file, line, verdict,\n level and the failure scenario, and the verified properties as a \"checked\n clean\" list. Findings carry their disposition when present.\n- The renderer performs no I/O and imports no infrastructure.\n\n## Attribution\n\n- `actor`: the producing identity. The reviewer publishes as `system:pr-reviewer`\n when no task identity resolves; otherwise the task's identity name.\n- `source`: the producing subsystem, `pr-review` for version one.\n- `task`: owner, repository and issue number from the task when one exists.\n\n## Failure behaviour\n\n- Publishing never fails the producing work. A failed publish is logged with its\n status and reason; the artifact is republished on the next production of the\n same artifact.\n- A successful publish records the artifact URL in the run report, so the PR\n description or task log links to the readable artifact.\n- The published URL is the editor deep link for the artifact, keyed on its\n immutable id. archie-core never mints share links; sharing is an\n account-holder decision made in the editor.\n\n## Verification\n\n- Client tests against a test server cover 201, 401, 400 with a field reason,\n and 503 retry behaviour.\n- The report renderer test covers a report with findings, checks, dispositions\n and a not-run status.\n- Configuration tests cover the disabled case, the `SecretRef` path and the\n `token_env` fallback."
"body": "# Artifact sender\n\n**Status:** Approved\n**Revision:** 1\n**Authority:** this document\n\n## Purpose\n\narchie-core publishes artifacts — design documents, review reports, research briefs,\nrunnable pages — to the offloaded.dev collaborative editor. A person reads the\nartifact, comments on it, and the artifact page is the shared surface for iteration.\n\nThe receiving contract is owned by the editor: `POST /api/artifacts` with a bearer\nservice token, a closed field set, and server-side idempotency on `requestId` plus\nlast-write-wins on `sentAt`. This document owns only what archie-core sends.\n\n## Scope\n\nVersion one publishes one-way: archie-core sends, the editor receives. The first\nproducer is the pull-request adversarial review: a completed `ReviewReport` is\nrendered to markdown and published after the review completes.\n\nChat-surface tools (`create_artifact`, `update_artifact`), comment read-back, share\ntokens, and runnable-format producers (`html`, `react`, `vue`) are later slices. The\nreceiving contract already carries them; version one does not exercise them.\n\n## Configuration\n\n- New `[artifacts]` section: `base_url` (site origin), `token` (`SecretRef`) with\n `token_env` fallback naming `WORKSPACE_INGEST_TOKEN`.\n- An empty `base_url` disables the sender: no client is constructed, nothing is\n registered, and publishing degrades to a log line.\n- The token is runtime configuration. It is never baked at build time.\n\n## Sender\n\n- New package `internal/infrastructure/artifactsync` exposing one method,\n `Publish(ctx, Artifact) (string, error)`, where the string is the artifact URL.\n One-method injected seam, concrete client constructed by the boot path when the\n configuration resolves — the `crondelivery.Courier` posture.\n- The client POSTs the frozen contract body. Each publish sends the complete\n source: versions of record are full snapshots, never diffs.\n- A `503` response is retried three times with backoff. `401` and `400` are not\n retried; they are logged with the field reason the response names.\n- `requestId` is `artifact:\u003ctask-id\u003e:\u003cversion\u003e` when the producer is task-backed,\n otherwise `artifact:\u003cidentity\u003e:\u003csentAt-utc\u003e`. Sending the same `requestId` with\n an equal or older `sentAt` must be a server-side no-op, which makes sender-side\n retry safe.\n\n## Report rendering\n\n- `ReviewReport` gains a pure markdown renderer in `internal/domain/workflow`:\n the summary as the lede, one finding per subsection with file, line, verdict,\n level and the failure scenario, and the verified properties as a \"checked\n clean\" list. Findings carry their disposition when present.\n- The renderer performs no I/O and imports no infrastructure.\n\n## Attribution\n\n- `actor`: the producing identity. The reviewer publishes as `system:pr-reviewer`\n when no task identity resolves; otherwise the task's identity name.\n- `source`: the producing subsystem, `pr-review` for version one.\n- `task`: owner, repository and issue number from the task when one exists.\n\n## Failure behaviour\n\n- Publishing never fails the producing work. A failed publish is logged with its\n status and reason; the artifact is republished on the next production of the\n same artifact.\n- A successful publish records the artifact URL in the run report, so the PR\n description or task log links to the readable artifact.\n- The published URL is the editor deep link for the artifact, keyed on its\n immutable id. archie-core never mints share links; sharing is an\n account-holder decision made in the editor.\n\n## Verification\n\n- Client tests against a test server cover 201, 401, 400 with a field reason,\n and 503 retry behaviour.\n- The report renderer test covers a report with findings, checks, dispositions\n and a not-run status.\n- Configuration tests cover the disabled case, the `SecretRef` path and the\n `token_env` fallback.\n"
},
{
"url": "/dev/prds/binding-secret-encryption/",
@@ -208,25 +208,25 @@
"url": "/dev/prds/code-graph-mcp/",
"title": "Code graph over MCP (`tools/codegraph`)",
"section": "PRDs",
"body": "# Code graph over MCP (`tools/codegraph`)\n\n**Status:** Draft\n**Supersedes:** `symbol-reference-index.md`, which scoped only the data layer.\n\n## The problem\n\nEstablishing what a change touches costs an agent eight to fifteen\ngreps, and the answers are wrong in specific ways. `grep -rn \"Register(\"`\ncannot separate `plugin.Registry.Register` from `captureintake.Receiver.Register`\nfrom `forgerpc.Server.Register`, all of which exist here. It also matches the\nsibling checkouts under `.worktrees/`, which are near-complete copies of the\nmodule, so every count is silently inflated.\n\nThat cost lands hardest in investigation, triage and the TDD loop, where the\nfirst question is always \"what does this touch\".\n\n## Decision: exact analysis, not semantic retrieval\n\nTools like Greptile parse with tree-sitter, summarise each node, embed the\nsummaries, and retrieve semantically. That design exists because they must\nserve any language. This repository is one Go module, and Go's type checker is\nground truth:\n\n| Question | Source of truth |\n| --- | --- |\n| Who references this symbol? | `go/packages` + `go/types`, resolved by identity |\n| What calls what? | `callgraph` RTA over SSA |\n| What imports what? | `go list -deps` |\n\nNo vector database, no embedding cost, no edges invented by a summary that\ndrifted from the code. For a single-language repository this is both cheaper\nand strictly more accurate. Copy the interface those tools expose, not their\narchitecture.\n\n**A code graph does not power a documentation chatbot.** It answers structural\nquestions about Go symbols. Answering \"how do I configure a second identity\"\nmeans retrieving prose from markdown, which needs chunking, embedding and\nsimilarity search over a different corpus entirely. That remains a separate\ncapability with its own design. Conflating the two would build one system that\ndoes neither well.\n\n## Interface: an MCP server\n\n`archied` already consumes MCP as a client (`internal/app/agentworker`\nstarts providers) and serves none. Exposing the graph over MCP reaches Claude\nCode, pi, codex and Archie's own agents through one surface, with no coupling\nto the daemon: it is configured like any other entry in `[[mcp_servers]]`.\n\nFour tools, each returning JSON with file:line citations:\n\n- `references(symbol)` — every reference site, classified `prod` / `test` /\n `generated` / `dynamic`\n- `callers(symbol, depth)` — inbound call edges\n- `callees(symbol, depth)` — outbound call edges\n- `blast_radius(file | symbol)` — the transitive neighbourhood a change reaches,\n which is the single call meant to replace the grep sequence\n\nDiagrams are deliberately not a tool. A model given an accurate subgraph writes\nits own Mermaid; a diagram endpoint would only fix the rendering of something\nthe model already has.\n\n## Decisions\n\n**Every answer declares what it could not see.** RTA over-approximates\ninterface dispatch, and reflection is invisible: every `reflect.ValueOf` entry\nin `wfextract`, `gateextract`, `pluginextract`, `secretextract` and\n`logextract` makes a symbol look reachable whether or not anything calls it.\nEach response carries a `dynamic_edges` field naming those boundaries. An agent\ntrusting a confident wrong graph is worse off than one that greps, so the graph\nstates its own limits rather than implying completeness.\n\n**Warm in memory, keyed on HEAD, never persisted to disk.** `deadcode` does\nwhole-program RTA in under seven seconds; this does less work. The server\nrebuilds when HEAD changes and refuses its cache outright when the tree is\ndirty. Nothing is written to disk, because a persisted index becomes a rendered\nview that outlives its evidence. That is the failure that made `STATUS.md`\nreport 90 of 91 findings re-verified while most statuses were 77 commits stale,\nand the same one that made `reachaudit` serve a previous tree's analysis from\n`/tmp` until its cache was keyed on HEAD.\n\n**`tools/codegraph`, not `internal/`.** It is developer tooling, not daemon\nruntime, so it belongs beside `docsgen`, `contractaudit` and `reachaudit` in\nthe `tools` module, which `task test:tools` already covers. Start as a single\nGo file; split only when it earns it.\n\n**No new dependency.** `golang.org/x/tools` is already in `go.sum` at v0.49.0.\n\n## How it is verified\n\nRed first. Table-driven tests against small fixture modules built in\n`t.TempDir()`, asserting the behaviour that distinguishes this from grep:\n\n1. Two methods spelled `Register` on different types resolve to two separate\n records, and a reference to one does not increment the other.\n2. A symbol referenced only from `_test.go` reports zero `prod` references.\n3. A symbol referenced only from a `reflect.ValueOf` table reports zero `prod`\n references and one `dynamic`, and names the table in `dynamic_edges`.\n4. A generated file's references land in `generated`, not `prod`.\n\nMutation-verify eachLine truncated
"body": "# Code graph over MCP (`tools/codegraph`)\n\n**Status:** Draft\n**Supersedes:** `symbol-reference-index.md`, which scoped only the data layer.\n\n## The problem\n\nEstablishing what a change touches costs an agent eight to fifteen\ngreps, and the answers are wrong in specific ways. `grep -rn \"Register(\"`\ncannot separate `plugin.Registry.Register` from `captureintake.Receiver.Register`\nfrom `forgerpc.Server.Register`, all of which exist here. It also matches the\nsibling checkouts under `.worktrees/`, which are near-complete copies of the\nmodule, so every count is silently inflated.\n\nThat cost lands hardest in investigation, triage and the TDD loop, where the\nfirst question is always \"what does this touch\".\n\n## Decision: exact analysis, not semantic retrieval\n\nTools like Greptile parse with tree-sitter, summarise each node, embed the\nsummaries, and retrieve semantically. That design exists because they must\nserve any language. This repository is one Go module, and Go's type checker is\nground truth:\n\n| Question | Source of truth |\n| --------------------------- | ------------------------------------------------ |\n| Who references this symbol? | `go/packages` + `go/types`, resolved by identity |\n| What calls what? | `callgraph` RTA over SSA |\n| What imports what? | `go list -deps` |\n\nNo vector database, no embedding cost, no edges invented by a summary that\ndrifted from the code. For a single-language repository this is both cheaper\nand strictly more accurate. Copy the interface those tools expose, not their\narchitecture.\n\n**A code graph does not power a documentation chatbot.** It answers structural\nquestions about Go symbols. Answering \"how do I configure a second identity\"\nmeans retrieving prose from markdown, which needs chunking, embedding and\nsimilarity search over a different corpus entirely. That remains a separate\ncapability with its own design. Conflating the two would build one system that\ndoes neither well.\n\n## Interface: an MCP server\n\n`archied` already consumes MCP as a client (`internal/app/agentworker`\nstarts providers) and serves none. Exposing the graph over MCP reaches Claude\nCode, pi, codex and Archie's own agents through one surface, with no coupling\nto the daemon: it is configured like any other entry in `[[mcp_servers]]`.\n\nFour tools, each returning JSON with file:line citations:\n\n- `references(symbol)` — every reference site, classified `prod` / `test` /\n `generated` / `dynamic`\n- `callers(symbol, depth)` — inbound call edges\n- `callees(symbol, depth)` — outbound call edges\n- `blast_radius(file | symbol)` — the transitive neighbourhood a change reaches,\n which is the single call meant to replace the grep sequence\n\nDiagrams are deliberately not a tool. A model given an accurate subgraph writes\nits own Mermaid; a diagram endpoint would only fix the rendering of something\nthe model already has.\n\n## Decisions\n\n**Every answer declares what it could not see.** RTA over-approximates\ninterface dispatch, and reflection is invisible: every `reflect.ValueOf` entry\nin `wfextract`, `gateextract`, `pluginextract`, `secretextract` and\n`logextract` makes a symbol look reachable whether or not anything calls it.\nEach response carries a `dynamic_edges` field naming those boundaries. An agent\ntrusting a confident wrong graph is worse off than one that greps, so the graph\nstates its own limits rather than implying completeness.\n\n**Warm in memory, keyed on HEAD, never persisted to disk.** `deadcode` does\nwhole-program RTA in under seven seconds; this does less work. The server\nrebuilds when HEAD changes and refuses its cache outright when the tree is\ndirty. Nothing is written to disk, because a persisted index becomes a rendered\nview that outlives its evidence. That is the failure that made `STATUS.md`\nreport 90 of 91 findings re-verified while most statuses were 77 commits stale,\nand the same one that made `reachaudit` serve a previous tree's analysis from\n`/tmp` until its cache was keyed on HEAD.\n\n**`tools/codegraph`, not `internal/`.** It is developer tooling, not daemon\nruntime, so it belongs beside `docsgen`, `contractaudit` and `reachaudit` in\nthe `tools` module, which `task test:tools` already covers. Start as a single\nGo file; split only when it earns it.\n\n**No new dependency.** `golang.org/x/tools` is already in `go.sum` at v0.49.0.\n\n## How it is verified\n\nRed first. Table-driven tests against small fixture modules built in\n`t.TempDir()`, asserting the behaviour that distinguishes this from grep:\n\n1. Two methods spelled `Register` on different types resolve to two separate\n records, and a reference to one does not increment the other.\n2. A symbol referenced only from `_test.go` reports zero `prod` references.\n3. A symbol referenced only from a `reflect.VLine truncated
},
{
"url": "/dev/prds/config-example-drift/",
"title": "Example-config and generated-config drift — decision",
"section": "PRDs",
"body": "# Example-config and generated-config drift — decision\n\n**Status:** Approved\n**Date:** 2026-09-15\n**Closes:** the checked-in-config half of audit findings `config-1` and\n`repo-root-deployment-2`; strengthens `doc-drift` findings generally.\n**Authority:** extends `docs/architecture/generated-documentation.md` and\n`docs/prds/config-schema.md`; does not replace either.\n\n## Question\n\nShould `config.example.toml` and `deployments/*.toml` be *generated*, so they\ncannot drift from the config code?\n\n## Decision\n\n**No — do not generate them. Gate them instead.** Neither file is a projection\nof the schema, and generating either would destroy the thing that makes it\nuseful. Three verified reasons, in order of weight:\n\n1. **`config.example.toml`'s value is its comments.** It documents **137 keys**\n (measured: active *and* commented-out), and those hand-written comments are\n the file's purpose — `docs/architecture/configuration.md` states outright\n that \"`config.example.toml` carries documentation users are meant to\n hand-edit\". TOML round-tripping does not preserve comments, which is exactly\n why `tomlwrite` does line-oriented edits rather than decode/encode. A\n generator would emit a correct file with the documentation deleted.\n2. **`docs/prds/config-schema.md` forbids building on `config.Config`.** That PRD\n rejects \"a reflection-based schema over `config.Config`\" because the struct is\n \"scheduled for dissolution\". A generator deriving the example from its struct\n tags would build on a foundation this repo has already decided to remove.\n3. **`docs/architecture/generated-documentation.md` prohibits it.** \"Adding\n another hardcoded type list to `docsgen` is prohibited\" — so any generator\n must consume a domain-owned registry, which does not exist for configuration\n yet. Creating one is the config-domain migration's job, not this change's.\n\nThe deployment profiles are also not a projection: they set **3-46 keys** against\nthe example's 137, and they are curated overlays (\"a complete config, not an\noverlay\", per their own headers), not near-duplicates. Generating them would add\nmachinery to remove duplication that largely is not there.\n\n## The gap that is real\n\n**Unknown config keys are silently ignored.** Verified at\n`internal/infrastructure/configuration/decode.go`:\n\n```go\nif _, err := toml.DecodeFile(path, target); err != nil {\n```\n\nThere is no `MetaData.Undecoded()` check, so a typo — `max_concurrancy = 4` —\nparses clean, validates clean, and does nothing. That is the same failure shape\nthis repo's audit found repeatedly: a setting that looks applied and is not. It\nis also detectable **without any hand-maintained list**, because `BurntSushi/toml`\nreports exactly which keys the target did not consume.\n\nNote the second, separate gap already admitted in writing:\n`generated-documentation.md` — \"`task check` does not run `docs:check`, so\ngenerated drift is ungated.\"\n\n## What to build\n\n**1. Unknown-key detection at the loader (behaviour).** Decode with metadata and\ncollect `Undecoded()`. Report it as a warning at startup listing the offending\nkeys, and expose it so tests can assert emptiness.\n\n**Deliberately a warning, not a fatal error.** `configuration.md`'s settled\nstartup policy is \"a missing credential disables a capability; only an invalid\nconfig stops the daemon\". A stray key is far more likely to be an operator typo\nin a file they are otherwise happy with than a reason to refuse to boot, and\n`[web]` is documented as landing in a *different* binary\n(`internal/app/archieui`), so a key unknown to one process is legitimately known\nto another. Failing closed here would break working deployments on upgrade.\n\n**2. A checked-in-config contract test (gate).** Load `config.example.toml` and\nevery `deployments/*.toml` through the real loader and assert `Undecoded()` is\nempty, with an explicit allowlist for keys another binary owns. This is the\nmechanism that would have caught a renamed key left behind in an example, and it\nneeds no inventory.\n\n**3. Gate generated data in `task check`.** Done. `task docs:check` runs in the\ngate, closing the admitted \"generated drift is ungated\" hole. The\ncheck mode did not exist when this was written; it was added for issue #855,\nwhich also made the check non-destructive so the gate can never rewrite the\nartifact it is judging.\n\n**4. Explicitly NOT now: a generated key inventory.** `configuration.md`'s\ncompletion criteria want \"generated documentation lists every external key,\ndefault, constraint, mutability class, owner\". That is a real target and it is\nthe config domain's, once a domain-owned registry exists — the prohibition above\nmeans it cannot be bootstrapped from a list inside `docsgen`. Recorded as\ndeferred, not rejected.\n\n## Non-goals\n\n- No generation of `config.example.toml` or `deployments/*.toml`.\n- No reflection-baLine truncated
"body": "# Example-config and generated-config drift — decision\n\n**Status:** Approved\n**Date:** 2026-09-15\n**Closes:** the checked-in-config half of audit findings `config-1` and\n`repo-root-deployment-2`; strengthens `doc-drift` findings generally.\n**Authority:** extends `docs/architecture/generated-documentation.md` and\n`docs/prds/config-schema.md`; does not replace either.\n\n## Question\n\nShould `config.example.toml` and `deployments/*.toml` be _generated_, so they\ncannot drift from the config code?\n\n## Decision\n\n**No — do not generate them. Gate them instead.** Neither file is a projection\nof the schema, and generating either would destroy the thing that makes it\nuseful. Three verified reasons, in order of weight:\n\n1. **`config.example.toml`'s value is its comments.** It documents **137 keys**\n (measured: active _and_ commented-out), and those hand-written comments are\n the file's purpose — `docs/architecture/configuration.md` states outright\n that \"`config.example.toml` carries documentation users are meant to\n hand-edit\". TOML round-tripping does not preserve comments, which is exactly\n why `tomlwrite` does line-oriented edits rather than decode/encode. A\n generator would emit a correct file with the documentation deleted.\n2. **`docs/prds/config-schema.md` forbids building on `config.Config`.** That PRD\n rejects \"a reflection-based schema over `config.Config`\" because the struct is\n \"scheduled for dissolution\". A generator deriving the example from its struct\n tags would build on a foundation this repo has already decided to remove.\n3. **`docs/architecture/generated-documentation.md` prohibits it.** \"Adding\n another hardcoded type list to `docsgen` is prohibited\" — so any generator\n must consume a domain-owned registry, which does not exist for configuration\n yet. Creating one is the config-domain migration's job, not this change's.\n\nThe deployment profiles are also not a projection: they set **3-46 keys** against\nthe example's 137, and they are curated overlays (\"a complete config, not an\noverlay\", per their own headers), not near-duplicates. Generating them would add\nmachinery to remove duplication that largely is not there.\n\n## The gap that is real\n\n**Unknown config keys are silently ignored.** Verified at\n`internal/infrastructure/configuration/decode.go`:\n\n```go\nif _, err := toml.DecodeFile(path, target); err != nil {\n```\n\nThere is no `MetaData.Undecoded()` check, so a typo — `max_concurrancy = 4` —\nparses clean, validates clean, and does nothing. That is the same failure shape\nthis repo's audit found repeatedly: a setting that looks applied and is not. It\nis also detectable **without any hand-maintained list**, because `BurntSushi/toml`\nreports exactly which keys the target did not consume.\n\nNote the second, separate gap already admitted in writing:\n`generated-documentation.md` — \"`task check` does not run `docs:check`, so\ngenerated drift is ungated.\"\n\n## What to build\n\n**1. Unknown-key detection at the loader (behaviour).** Decode with metadata and\ncollect `Undecoded()`. Report it as a warning at startup listing the offending\nkeys, and expose it so tests can assert emptiness.\n\n**Deliberately a warning, not a fatal error.** `configuration.md`'s settled\nstartup policy is \"a missing credential disables a capability; only an invalid\nconfig stops the daemon\". A stray key is far more likely to be an operator typo\nin a file they are otherwise happy with than a reason to refuse to boot, and\n`[web]` is documented as landing in a _different_ binary\n(`internal/app/archieui`), so a key unknown to one process is legitimately known\nto another. Failing closed here would break working deployments on upgrade.\n\n**2. A checked-in-config contract test (gate).** Load `config.example.toml` and\nevery `deployments/*.toml` through the real loader and assert `Undecoded()` is\nempty, with an explicit allowlist for keys another binary owns. This is the\nmechanism that would have caught a renamed key left behind in an example, and it\nneeds no inventory.\n\n**3. Gate generated data in `task check`.** Done. `task docs:check` runs in the\ngate, closing the admitted \"generated drift is ungated\" hole. The\ncheck mode did not exist when this was written; it was added for issue #855,\nwhich also made the check non-destructive so the gate can never rewrite the\nartifact it is judging.\n\n**4. Explicitly NOT now: a generated key inventory.** `configuration.md`'s\ncompletion criteria want \"generated documentation lists every external key,\ndefault, constraint, mutability class, owner\". That is a real target and it is\nthe config domain's, once a domain-owned registry exists — the prohibition above\nmeans it cannot be bootstrapped from a list inside `docsgen`. Recorded as\ndeferred, not rejected.\n\n## Non-goals\n\n- No generation of `config.example.toml` or `deployments/*.toml`.\n- No reflection-baLine truncated
},
{
"url": "/dev/prds/config-schema/",
"title": "Backend-owned configuration schema for the webui -- decision",
"section": "PRDs",
"body": "# Backend-owned configuration schema for the webui -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-b6ew` (epic), with children `.1`-`.5`\n\n## Decision\n\nThe dashboard's Configuration page keeps reading a secret-free,\nhand-picked view of `config.Config` -- that allowlist is a safety\nboundary and stays exactly as it is. What changes is who defines the\npage around it: `ui/src/settings/settings.js` and\n`config-row.js` hardcode every row's label, section, type, and\neditability by hand; after this, the backend attaches that metadata to\neach field it already allows through, and the frontend renders\nsections and fields generically from what the backend sends.\n\nThis is **not** a reflection-based schema over `config.Config`.\n`internal/config/config.go`'s own package doc states it is \"scheduled\nfor dissolution: its types and methods are to be reassigned to the\ndomains whose behaviour they describe\" -- building a generic\nschema-from-struct-tags mechanism over a struct on its way out would be\nbuilding on a foundation this repo has already decided to remove.\nInstead, every field already in `ConfigView` (`internal/webui/api_config.go`)\ngot there because someone deliberately vetted it as safe to show; the\nschema adds a hand-authored descriptor to that same deliberate act,\nnot a new mechanism that re-derives safety automatically.\n\n## Why now\n\nTask #6's investigation (`/9/26`) found the concrete failure this\nproduces: `Repo.AllowConcurrent` and `Repo.MaxRetries` already reach\n`GET /api/config` (`RepoView` in `api_config.go`), but the\nrepositories card renders a static read-only table that never shows\nthem, so the fix for \"why isn't a second agent running\" required an\nagent tracing Go source instead of a checkbox on the dashboard.\n`Repo.ReviewEnabled` is worse: it never reaches the API at all. Both\nare symptoms of the same root cause -- the frontend decides what a\nfield means and whether it's shown, and nothing keeps that in sync\nwith what the backend actually allows.\n\n## Shape\n\n```go\n// internal/webui/config_schema.go (new)\n\ntype ConfigFieldType string\n\nconst (\n FieldString ConfigFieldType = \"string\"\n FieldInt ConfigFieldType = \"int\"\n FieldBool ConfigFieldType = \"bool\"\n FieldDuration ConfigFieldType = \"duration\"\n FieldEnum ConfigFieldType = \"enum\"\n FieldStructured ConfigFieldType = \"structured\" // repositories, models, providers\n)\n\ntype ConfigField struct {\n Key string `json:\"key\"` // dotted path, matches UpdateConfig's key space\n Label string `json:\"label\"`\n Description string `json:\"description,omitempty\"`\n Type ConfigFieldType `json:\"type\"`\n Value any `json:\"value\"`\n Editable bool `json:\"editable\"`\n LockedReason string `json:\"locked_reason,omitempty\"`\n Overridden bool `json:\"overridden\"`\n Options []string `json:\"options,omitempty\"` // enum only\n RestartRequired bool `json:\"restart_required\"`\n}\n\ntype ConfigSection struct {\n ID string `json:\"id\"`\n Label string `json:\"label\"`\n Fields []ConfigField `json:\"fields\"`\n}\n```\n\n`handleConfig` builds `[]ConfigSection` from the existing per-field\nvalues it already assembles, plus `overlay.DeniedKeys` for\n`LockedReason` and the existing `Overridden` list -- both already\ncomputed just re-attached per field instead of returned as\nside-channel maps the frontend cross-references by key string.\n`Locked`/`Overridden`/`Reload`/`Provenance` stay as top-level\n`ConfigView` fields; they describe runtime state (what happened on\nthe last reload, which keys the overlay refuses), not the field\ncatalogue, and duplicating that logic per-field would be the same drift\nrisk this change exists to remove.\n\n`FieldStructured` fields (repositories, models, providers) carry\n`Value` as structured JSON and are rendered by dedicated\neditors, not the generic renderer -- see \"What this does not do\".\n\n## Sections\n\nMatches the cards the settings page already has: `identity`,\n`repositories`, `models`, `providers`, `budgets`, `storage`,\n`containers`, `web`. No new sections; this is metadata on existing\nrows, not new configuration surface.\n\n## Frontend\n\n`config-row.js`'s `row(label, value, opts)` becomes the renderer's\nprivate implementation detail, called generically:\n\n```js\nfor (const section of schema.sections) {\n const rows = section.fields\n .filter(f =\u003e f.type !== \"structured\")\n .map(f =\u003e 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
"body": "# Backend-owned configuration schema for the webui -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-b6ew` (epic), with children `.1`-`.5`\n\n## Decision\n\nThe dashboard's Configuration page keeps reading a secret-free,\nhand-picked view of `config.Config` -- that allowlist is a safety\nboundary and stays exactly as it is. What changes is who defines the\npage around it: `ui/src/settings/settings.js` and\n`config-row.js` hardcode every row's label, section, type, and\neditability by hand; after this, the backend attaches that metadata to\neach field it already allows through, and the frontend renders\nsections and fields generically from what the backend sends.\n\nThis is **not** a reflection-based schema over `config.Config`.\n`internal/config/config.go`'s own package doc states it is \"scheduled\nfor dissolution: its types and methods are to be reassigned to the\ndomains whose behaviour they describe\" -- building a generic\nschema-from-struct-tags mechanism over a struct on its way out would be\nbuilding on a foundation this repo has already decided to remove.\nInstead, every field already in `ConfigView` (`internal/webui/api_config.go`)\ngot there because someone deliberately vetted it as safe to show; the\nschema adds a hand-authored descriptor to that same deliberate act,\nnot a new mechanism that re-derives safety automatically.\n\n## Why now\n\nTask #6's investigation (`/9/26`) found the concrete failure this\nproduces: `Repo.AllowConcurrent` and `Repo.MaxRetries` already reach\n`GET /api/config` (`RepoView` in `api_config.go`), but the\nrepositories card renders a static read-only table that never shows\nthem, so the fix for \"why isn't a second agent running\" required an\nagent tracing Go source instead of a checkbox on the dashboard.\n`Repo.ReviewEnabled` is worse: it never reaches the API at all. Both\nare symptoms of the same root cause -- the frontend decides what a\nfield means and whether it's shown, and nothing keeps that in sync\nwith what the backend actually allows.\n\n## Shape\n\n```go\n// internal/webui/config_schema.go (new)\n\ntype ConfigFieldType string\n\nconst (\n FieldString ConfigFieldType = \"string\"\n FieldInt ConfigFieldType = \"int\"\n FieldBool ConfigFieldType = \"bool\"\n FieldDuration ConfigFieldType = \"duration\"\n FieldEnum ConfigFieldType = \"enum\"\n FieldStructured ConfigFieldType = \"structured\" // repositories, models, providers\n)\n\ntype ConfigField struct {\n Key string `json:\"key\"` // dotted path, matches UpdateConfig's key space\n Label string `json:\"label\"`\n Description string `json:\"description,omitempty\"`\n Type ConfigFieldType `json:\"type\"`\n Value any `json:\"value\"`\n Editable bool `json:\"editable\"`\n LockedReason string `json:\"locked_reason,omitempty\"`\n Overridden bool `json:\"overridden\"`\n Options []string `json:\"options,omitempty\"` // enum only\n RestartRequired bool `json:\"restart_required\"`\n}\n\ntype ConfigSection struct {\n ID string `json:\"id\"`\n Label string `json:\"label\"`\n Fields []ConfigField `json:\"fields\"`\n}\n```\n\n`handleConfig` builds `[]ConfigSection` from the existing per-field\nvalues it already assembles, plus `overlay.DeniedKeys` for\n`LockedReason` and the existing `Overridden` list -- both already\ncomputed just re-attached per field instead of returned as\nside-channel maps the frontend cross-references by key string.\n`Locked`/`Overridden`/`Reload`/`Provenance` stay as top-level\n`ConfigView` fields; they describe runtime state (what happened on\nthe last reload, which keys the overlay refuses), not the field\ncatalogue, and duplicating that logic per-field would be the same drift\nrisk this change exists to remove.\n\n`FieldStructured` fields (repositories, models, providers) carry\n`Value` as structured JSON and are rendered by dedicated\neditors, not the generic renderer -- see \"What this does not do\".\n\n## Sections\n\nMatches the cards the settings page already has: `identity`,\n`repositories`, `models`, `providers`, `budgets`, `storage`,\n`containers`, `web`. No new sections; this is metadata on existing\nrows, not new configuration surface.\n\n## Frontend\n\n`config-row.js`'s `row(label, value, opts)` becomes the renderer's\nprivate implementation detail, called generically:\n\n```js\nfor (const section of schema.sections) {\n const rows = section.fields\n .filter((f) =\u003e f.type !== \"structured\")\n .map((f) =\u003e\n row(f.label, f.value, {\n key: f.key,\n type: f.type,\n options: f.options,\n locked: f.locked_reason,\n overridden: f.overridden,\n restartRequired: f.restart_required,\n }),\n );\n // structured fLine truncated
},
{
"url": "/dev/prds/contract-conformance-audit/",
"title": "Contract conformance audit — decision",
"section": "PRDs",
"body": "# Contract conformance audit — decision\n\n**Status:** Finalised\n**Scope:** an **advisory** report, deliberately **not** part of `task check`.\n**Date:** 2026-09-15\n**Authority:** sibling to `archie-core-06ag` (standing reachability audit) and\n`docs/architecture/dependencies-and-contracts.md`. Replaces neither.\n**Open:** withdraw it, or rebuild it structurally. See \"Open decision\" — not to\nbe resolved by hardening the regexes.\n\n## Question\n\nDoes every declared contract surface have a consumer, or an explicit declaration\nthat it has none?\n\nReachability (`tools/reachaudit`) asks the complementary question — *is this code\nin a shipped binary?* — and cannot see a capability that is **reachable and\nunconsumed**. `ratelimit` was in the binary closure and called by nothing\n(`archie-core-6wxb`); reachability would not have found that.\n\n## Decision\n\nYes, as an advisory survey. `tools/contractaudit` classifies each subject of each\nsurface:\n\n| Classification | Meaning | Fails `--strict`? |\n| --- | --- | --- |\n| `CONSUMED` | a call site exercises it | no |\n| `DECLARED-UNCONSUMED` | allowlisted in `docs/contract-declarations.json`, with a reason and a tracker | no |\n| `UNDECLARED-UNCONSUMED` | nobody reaches it, nobody declared it | **yes** |\n| `STALE-DECLARATION` | an allowlist entry that is no longer true | **yes** |\n\nThere are **four** classes and **two** of them fail. The allowlist must match\nreality exactly, and it fails in both directions: a missing entry is a finding,\nand an entry that outlived its subject is a finding, because a stale allowlist is\nhow a check quietly stops checking anything.\n\n**Not gated.** `task contract` is advisory and `task check` does not run it,\nmatching `tools/reachaudit`. The surfaces are discovered by scanning source text,\nso a rename or a reformat elsewhere in the tree can change the output with nothing\nactually wrong. It has already produced 16 false \"unconsumed\" readings once, when\nthe dashboard's request helper was renamed. A check that can fail for reasons\nunrelated to what it measures must not be able to break a build.\n\n## Surfaces actually built — three, not five\n\n| Surface | Subjects | \"Consumed\" means |\n| --- | --- | --- |\n| `proto/state/v1` `StateStoreService` | **45 RPCs** | an adapter body calls `client.\u003cRpc\u003e(...)` |\n| `proto/gateway/v1` `ChatService` | **21 RPCs** | same |\n| `internal/webui` dashboard routes | **49 routes** | a path literal appears as a call argument under `ui/src` |\n\nConsumption for the gRPC surfaces is established by **scanning adapter source\ntext** for calls through the generated client, not by reflection. See the errata\nbelow: the first revision of this document claimed reflection, and the first\nimplementation did use it, but the shipped mechanism is a regex and the document\nwas not updated to match.\n\n## What this audit has actually found\n\n**Nothing actionable.** On the current tree it reports 0 undeclared and 0 stale.\nIts only allowlisted entries are two RPCs superseded by their streaming variants\n(`ListCaptures`, `ListUndispatchedCaptures`), which were already known from the\nsource comment on `staterpc.Client.ListCaptures`.\n\nEvery real defect found in the session that produced this tool was found by other\nmeans:\n\n- the three 415 refusals, by reading `authorizeTaskMutation` and reproducing the\n browser's exact headers against the real handler;\n- the dashboard client's duplicated request plumbing, by reading the module.\n\nRecorded plainly because a survey that has never found anything is evidence about\nthe survey, not about the tree.\n\n## Errata — claims in the first revision of this document that were false\n\n- **\"RPC coverage is derived by reflection over the exported client type.\"**\n It is not. `proto.go` regex-scans adapter bodies for `client.Method(` calls.\n The reflection version was replaced and the document was not updated. The unused\n `google.golang.org/grpc` family in `tools/go.mod` was residue from that\n iteration; `go mod tidy` removed it on 2026-09-15.\n- **Surface sizes of \"43 / 12 / 52\".** The real counts are 45 / 21 / 49.\n- **\"Three classifications, and the third is the only finding.\"** Four classes,\n two of which fail.\n- **\"Raw `fetch()` calls caused 401s to render as `refused`/`broken`.\"** Wrong.\n Every raw call site passed `res.status` to `ApiError`, so `classifyActionError`\n already mapped 401 to `session-expired`; the chat stream never classified at\n all. The real defect in that area was different (below).\n- **A five-surface \"Shape\" naming `surface.go`, `generated.go`,\n `declarations.go`, and `testdata/`.** None were written. The real files are\n `main.go`, `audit.go`, `proto.go`, `webui.go`.\n\n## The two gaps this was aimed at\n\n**1. `docsgen check` is documented and does not exist.** Closed by issue #855.\n(issue #855 / `archie-core-5gzx`). `tools/docsgen` now has a `check` subcommanLine truncated
"body": "# Contract conformance audit — decision\n\n**Status:** Finalised\n**Scope:** an **advisory** report, deliberately **not** part of `task check`.\n**Date:** 2026-09-15\n**Authority:** sibling to `archie-core-06ag` (standing reachability audit) and\n`docs/architecture/dependencies-and-contracts.md`. Replaces neither.\n**Open:** withdraw it, or rebuild it structurally. See \"Open decision\" — not to\nbe resolved by hardening the regexes.\n\n## Question\n\nDoes every declared contract surface have a consumer, or an explicit declaration\nthat it has none?\n\nReachability (`tools/reachaudit`) asks the complementary question — _is this code\nin a shipped binary?_ — and cannot see a capability that is **reachable and\nunconsumed**. `ratelimit` was in the binary closure and called by nothing\n(`archie-core-6wxb`); reachability would not have found that.\n\n## Decision\n\nYes, as an advisory survey. `tools/contractaudit` classifies each subject of each\nsurface:\n\n| Classification | Meaning | Fails `--strict`? |\n| ----------------------- | ----------------------------------------------------------------------------- | ----------------- |\n| `CONSUMED` | a call site exercises it | no |\n| `DECLARED-UNCONSUMED` | allowlisted in `docs/contract-declarations.json`, with a reason and a tracker | no |\n| `UNDECLARED-UNCONSUMED` | nobody reaches it, nobody declared it | **yes** |\n| `STALE-DECLARATION` | an allowlist entry that is no longer true | **yes** |\n\nThere are **four** classes and **two** of them fail. The allowlist must match\nreality exactly, and it fails in both directions: a missing entry is a finding,\nand an entry that outlived its subject is a finding, because a stale allowlist is\nhow a check quietly stops checking anything.\n\n**Not gated.** `task contract` is advisory and `task check` does not run it,\nmatching `tools/reachaudit`. The surfaces are discovered by scanning source text,\nso a rename or a reformat elsewhere in the tree can change the output with nothing\nactually wrong. It has already produced 16 false \"unconsumed\" readings once, when\nthe dashboard's request helper was renamed. A check that can fail for reasons\nunrelated to what it measures must not be able to break a build.\n\n## Surfaces actually built — three, not five\n\n| Surface | Subjects | \"Consumed\" means |\n| ------------------------------------ | ------------- | -------------------------------------------------------- |\n| `proto/state/v1` `StateStoreService` | **45 RPCs** | an adapter body calls `client.\u003cRpc\u003e(...)` |\n| `proto/gateway/v1` `ChatService` | **21 RPCs** | same |\n| `internal/webui` dashboard routes | **49 routes** | a path literal appears as a call argument under `ui/src` |\n\nConsumption for the gRPC surfaces is established by **scanning adapter source\ntext** for calls through the generated client, not by reflection. See the errata\nbelow: the first revision of this document claimed reflection, and the first\nimplementation did use it, but the shipped mechanism is a regex and the document\nwas not updated to match.\n\n## What this audit has actually found\n\n**Nothing actionable.** On the current tree it reports 0 undeclared and 0 stale.\nIts only allowlisted entries are two RPCs superseded by their streaming variants\n(`ListCaptures`, `ListUndispatchedCaptures`), which were already known from the\nsource comment on `staterpc.Client.ListCaptures`.\n\nEvery real defect found in the session that produced this tool was found by other\nmeans:\n\n- the three 415 refusals, by reading `authorizeTaskMutation` and reproducing the\n browser's exact headers against the real handler;\n- the dashboard client's duplicated request plumbing, by reading the module.\n\nRecorded plainly because a survey that has never found anything is evidence about\nthe survey, not about the tree.\n\n## Errata — claims in the first revision of this document that were false\n\n- **\"RPC coverage is derived by reflection over the exported client type.\"**\n It is not. `proto.go` regex-scans adapter bodies for `client.Method(` calls.\n The reflection version was replaced and the document was not updated. The unused\n `google.golang.org/grpc` family in `tools/go.mod` was residue from that\n iteration; `go mod tidy` removed it on 2026-09-15.\n- **Surface sizes of \"43 / 12 / 52\".** The real counts are 45 / 21 / 49.\n- **\"Three classifications, and the third is the only finding.\"** Four classes,\n two of which fail.\n- **\"Raw `fetch()` calls caused 401s to render as `refused`/`brokLine truncated
},
{
"url": "/dev/prds/control-plane-apply-status/",
@@ -238,13 +238,13 @@
"url": "/dev/prds/curator-sampler-wave1/",
"title": "Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision",
"section": "PRDs",
"body": "# Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision\n\n**Status:** Approved\n**Date:** 2026-09-05\n**Beads issue:** bead `archie-core-1786637500776-416-600a66e5` / GitHub #437\ncovers the embedding-backed follow-on strategy only. This PRD covers the\nprerequisite interface and the cheap strategies.\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n**Depends on:** nothing shipped (this is itself a prerequisite)\n**Blocks:** the embedding-backed surprisal strategy (GitHub #437), which\nimplements this same interface once the embeddings capability\n(`internal/domain/embedding`, this change) lands\n\n## Problem\n\nA future curator that reviews a large body of content (memories, sessions,\nskills) cannot always afford to run its agentic budget over every candidate\nevery pass. It needs to pick a bounded subset first. GitHub #437's acceptance\ncriteria requires that subset-picking to sit \"behind a `Sampler` interface\nthat wave 1 of the curator epic ships (cheap strategies: recency, random,\nall, staleness proxy)\" and that the embedding-backed strategy implement \"the\nsame interface\" later. No such interface, and none of the four cheap\nstrategies, exist anywhere in the codebase (bead 434e5bb9's closure\nwithout a linked PR was the tracker being wrong, not the code existing) --\nthis PRD is the one-page settled design for it, per this repo's Scope\nDiscipline rule.\n\n## Decision\n\nA `Sampler` is a pure, call-scoped selection function: given a fixed slice of\ncandidates and a request, it returns a subset. No lifecycle, no host access,\nno I/O for the four wave-1 strategies -- they are computation only, so they\nlive directly in `internal/domain/sampling` (a domain package, not\n`internal/infrastructure/*`) alongside the contract, the same way\n`curator/activity.go`'s pure ring buffer sits next to `curator/contract.go`\nrather than in an infrastructure package.\n\n```go\n// Package sampling is the curator sampler family: given a bounded set of\n// candidates, pick a subset to spend a curator pass's agentic budget on.\n// See docs/prds/curator-sampler-wave1.md.\npackage sampling\n\n// Candidate is one item eligible for sampling. It is deliberately narrow:\n// an opaque identifier, the timestamp the timestamp-based strategies score\n// against, and an open Metadata bag for whatever a future strategy needs\n// (e.g. the embedding-backed surprisal strategy's vector) without widening\n// this struct for every strategy that comes after wave 1.\ntype Candidate struct {\n ID string\n At time.Time\n Metadata map[string]any\n}\n\n// Request carries the knobs every strategy shares: a selection cap and a\n// deterministic seed. Both are optional -- Cap 0 means unlimited (the \"all\"\n// strategy relies on this), Seed 0 is a valid seed, not \"unset\".\ntype Request struct {\n Cap int\n Seed int64\n}\n\n// Sampler selects a subset of candidates to spend a curator pass's agentic\n// budget on. Every implementation -- the four here and the future\n// embedding-backed surprisal strategy (GitHub #437) -- must be\n// deterministic given the same candidates and Request: same inputs, same\n// output, every time. That is what makes a pass reproducible and testable,\n// and is GitHub #437's stated acceptance criterion for the strategy it\n// adds behind this same interface.\ntype Sampler interface {\n // Name identifies the strategy for logging/attribution (e.g.\n // \"recency\", \"random\", \"all\", \"staleness\", later \"surprisal\").\n Name() string\n // Sample selects from candidates per req. Implementations must not\n // mutate candidates or rely on anything but candidates and req --\n // determinism depends on that.\n Sample(ctx context.Context, candidates []Candidate, req Request) ([]Candidate, error)\n}\n```\n\n### The four wave-1 strategies\n\nAll four are `internal/domain/sampling` types constructed with `NewX(...)`,\neach implementing `Sampler`:\n\n- **`recency`** (`NewRecency()`): sorts candidates newest-`At`-first (stable\n sort, ties keep input order so output is deterministic even when two\n candidates share a timestamp), then truncates to `req.Cap` (0 = all).\n- **`staleness`** (`NewStaleness()`): the mirror of recency -- sorts oldest-\n `At`-first, then truncates to `req.Cap`. This is explicitly a *proxy*:\n \"hasn't been touched in the longest time\" using whatever timestamp the\n caller populated `Candidate.At` with (created, updated, or\n last-reviewed -- the caller's choice, not this package's), never the\n embedding-based surprisal calculation GitHub #437 owns.\n- **`all`** (`NewAll()`): no filtering. Returns candidates in input order,\n truncated to `req.Cap` (0 = every candidate). Input order is the only\n order this strategy has an opinion about, and preserving it is what makes\n it deterministic.\n- **`random`** (`NewRandom()`): a uniform-random subset, sized to\n `req.Cap` (0 = every canLine truncated
"body": "# Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision\n\n**Status:** Approved\n**Date:** 2026-09-05\n**Beads issue:** bead `archie-core-1786637500776-416-600a66e5` / GitHub #437\ncovers the embedding-backed follow-on strategy only. This PRD covers the\nprerequisite interface and the cheap strategies.\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n**Depends on:** nothing shipped (this is itself a prerequisite)\n**Blocks:** the embedding-backed surprisal strategy (GitHub #437), which\nimplements this same interface once the embeddings capability\n(`internal/domain/embedding`, this change) lands\n\n## Problem\n\nA future curator that reviews a large body of content (memories, sessions,\nskills) cannot always afford to run its agentic budget over every candidate\nevery pass. It needs to pick a bounded subset first. GitHub #437's acceptance\ncriteria requires that subset-picking to sit \"behind a `Sampler` interface\nthat wave 1 of the curator epic ships (cheap strategies: recency, random,\nall, staleness proxy)\" and that the embedding-backed strategy implement \"the\nsame interface\" later. No such interface, and none of the four cheap\nstrategies, exist anywhere in the codebase (bead 434e5bb9's closure\nwithout a linked PR was the tracker being wrong, not the code existing) --\nthis PRD is the one-page settled design for it, per this repo's Scope\nDiscipline rule.\n\n## Decision\n\nA `Sampler` is a pure, call-scoped selection function: given a fixed slice of\ncandidates and a request, it returns a subset. No lifecycle, no host access,\nno I/O for the four wave-1 strategies -- they are computation only, so they\nlive directly in `internal/domain/sampling` (a domain package, not\n`internal/infrastructure/*`) alongside the contract, the same way\n`curator/activity.go`'s pure ring buffer sits next to `curator/contract.go`\nrather than in an infrastructure package.\n\n```go\n// Package sampling is the curator sampler family: given a bounded set of\n// candidates, pick a subset to spend a curator pass's agentic budget on.\n// See docs/prds/curator-sampler-wave1.md.\npackage sampling\n\n// Candidate is one item eligible for sampling. It is deliberately narrow:\n// an opaque identifier, the timestamp the timestamp-based strategies score\n// against, and an open Metadata bag for whatever a future strategy needs\n// (e.g. the embedding-backed surprisal strategy's vector) without widening\n// this struct for every strategy that comes after wave 1.\ntype Candidate struct {\n ID string\n At time.Time\n Metadata map[string]any\n}\n\n// Request carries the knobs every strategy shares: a selection cap and a\n// deterministic seed. Both are optional -- Cap 0 means unlimited (the \"all\"\n// strategy relies on this), Seed 0 is a valid seed, not \"unset\".\ntype Request struct {\n Cap int\n Seed int64\n}\n\n// Sampler selects a subset of candidates to spend a curator pass's agentic\n// budget on. Every implementation -- the four here and the future\n// embedding-backed surprisal strategy (GitHub #437) -- must be\n// deterministic given the same candidates and Request: same inputs, same\n// output, every time. That is what makes a pass reproducible and testable,\n// and is GitHub #437's stated acceptance criterion for the strategy it\n// adds behind this same interface.\ntype Sampler interface {\n // Name identifies the strategy for logging/attribution (e.g.\n // \"recency\", \"random\", \"all\", \"staleness\", later \"surprisal\").\n Name() string\n // Sample selects from candidates per req. Implementations must not\n // mutate candidates or rely on anything but candidates and req --\n // determinism depends on that.\n Sample(ctx context.Context, candidates []Candidate, req Request) ([]Candidate, error)\n}\n```\n\n### The four wave-1 strategies\n\nAll four are `internal/domain/sampling` types constructed with `NewX(...)`,\neach implementing `Sampler`:\n\n- **`recency`** (`NewRecency()`): sorts candidates newest-`At`-first (stable\n sort, ties keep input order so output is deterministic even when two\n candidates share a timestamp), then truncates to `req.Cap` (0 = all).\n- **`staleness`** (`NewStaleness()`): the mirror of recency -- sorts oldest-\n `At`-first, then truncates to `req.Cap`. This is explicitly a _proxy_:\n \"hasn't been touched in the longest time\" using whatever timestamp the\n caller populated `Candidate.At` with (created, updated, or\n last-reviewed -- the caller's choice, not this package's), never the\n embedding-based surprisal calculation GitHub #437 owns.\n- **`all`** (`NewAll()`): no filtering. Returns candidates in input order,\n truncated to `req.Cap` (0 = every candidate). Input order is the only\n order this strategy has an opinion about, and preserving it is what makes\n it deterministic.\n- **`random`** (`NewRandom()`): a uniform-random subset, sized to\n `req.Cap` (0 = every canLine truncated
},
{
"url": "/dev/prds/dashboard-aware-chat-navigation/",
"title": "Dashboard-aware chat: Archie sees the page, and points the operator there",
"section": "PRDs",
"body": "# Dashboard-aware chat: Archie sees the page, and points the operator there\n\n**Status:** Approved\n**Date:** 2026-08-26\n**Compound:** the \"chat available on any page\" surface work (global chat presence)\n\n## Decision\n\nMake the web chat **dashboard-aware**: the agent is told which dashboard page\nthe operator has *open*, knows what each page is for, and can **point**\nthe operator to the relevant page with a **clickable destination chip** the UI\nrenders and follows - Option B (context + navigate), not just \"tell me in text.\"\n\nThree seams, each an existing extension point, one new tool and one message field:\n\n1. **Current page, into the prompt.** The browser sends its route with every\n chat message; the gateway threads it into the system prompt's runtime-metadata\n env block. Archie always knows where the operator is looking.\n2. **Page index.** A page_index tool lists the dashboard pages and what each one\n shows, so Archie knows what to point at - the agent \"has the map\".\n3. **Navigate.** A dashboard_navigate tool returns a structured path/label; the web\n UI renders it as a clickable chip that routes the operator there. This is the\n \"plenty of resources\" the requirement named.\n\nWe deliberately keep the agent's answer honest: the chip is *evidence* it can\nvalidly produce because dashboard_navigate is a real tool whose result is\nrendered, not a markdown link the model invents.\n\n## Why now\n\nThis is the natural next step of the \"chat on any page\" work, and the original\nrequest named it explicitly: *\"archie should be able to see what page you're on\ntoo. and point out where to go. so it needs plenty of resources.\"* The chat\nis a full-page route with no knowledge of the rest of the dashboard; the agent\ncannot see which page the operator is on and cannot reliably direct them anywhere.\nThe critique of the chat UI already identified \"chat is not available on any page\"\nas the largest structural gap (P1). This design is the capability that makes that\ngap worth closing.\n\n## Shape of the API\n\n### Message field (gateway.go)\n\nAdd Page to Message:\n\n```go\n// Page is the dashboard route the operator is on when they sent this message\n// (e.g. \"/tasks\", \"/logs\"). Empty for non-web channels, which have no page\n// context. It is per-message, not per-session: the operator navigates freely\n// while a conversation stays open.\nPage string\n```\n\n### Web request (api_chat.go)\n\nchatMessageRequest gains Page, decoded into Message.Page in decodeChatMessage.\n\n### System prompt config (prompt.go)\n\nSystemPromptConfig gains Page; BuildSystemPrompt passes it through to the template.\nThe env block of archie.md.tpl renders the current page when set.\n\n### Page index (dashboard_tools.go, new)\n\nA package-level registry mapping route to {Label, Description}. page_index returns\nthe list so the model knows what each page shows:\n\n```go\ntype DashboardPage struct {\n\tPath string // \"/tasks\"\n\tLabel string // \"Tasks\"\n\tDescription string // \"Issues Archie picked up, and where they stand.\"\n}\n```\n\n### Navigation tool (dashboard_tools.go)\n\ndashboard_navigate validates its path against the registry and returns the resolved\npath/label. Unknown path means a clear error, not a guess. The model must call the\ntool (not invent a link) to produce a chip, so the chip is honest.\n\n### Tool wiring (turn.go)\n\nextraTools already merges TaskTools + SessionTools. Add the dashboard tools alongside\nthem, gated on the channel being the web UI. The tool list is built from the same\nregistry the prompt's page line comes from, so the agent never points at a page it\nwas not told about.\n\n### Web UI (chat-render.js, chat-tools.js)\n\nA dashboard_navigate tool call renders as a **clickable chip**: an anchor with\nhref=\"/tasks\" and the label. The chip is a\nreal link that works from any page once the chat is a global presence. The chip is\nstyled as an action, not a code line, so it visibly invites a click.\n\n### Route transfer (chat.js)\n\nEach sendMessage includes the current location.hash route as page in the stream\nrequest body, so the backend gets the operator's live position.\n\n## What we deliberately do NOT do\n\n- **No navigation from a markdown link.** The model must use dashboard_navigate; a\n bare \"click here\" is not rendered as a trusted route.\n- **No full-page route hijack from the chat.** The chip sets location.hash.\n- **No page index for non-web channels.** Telegram/discord have no dashboard.\n- **No automatic history annotation.** Page is per-message from the browser.\n- **No change to the dangerous-action approval flow.** Separately tracked.\n\n## Acceptance criteria\n\n1. Chat messages from any page carry the current page to the agent's prompt.\n2. page_index returns every dashboard page with a plain-language description.\n3. dashboard_navigate renders a clickable chip that routes to the target page.\n4. dashboard_navLine truncated
"body": "# Dashboard-aware chat: Archie sees the page, and points the operator there\n\n**Status:** Approved\n**Date:** 2026-08-26\n**Compound:** the \"chat available on any page\" surface work (global chat presence)\n\n## Decision\n\nMake the web chat **dashboard-aware**: the agent is told which dashboard page\nthe operator has _open_, knows what each page is for, and can **point**\nthe operator to the relevant page with a **clickable destination chip** the UI\nrenders and follows - Option B (context + navigate), not just \"tell me in text.\"\n\nThree seams, each an existing extension point, one new tool and one message field:\n\n1. **Current page, into the prompt.** The browser sends its route with every\n chat message; the gateway threads it into the system prompt's runtime-metadata\n env block. Archie always knows where the operator is looking.\n2. **Page index.** A page_index tool lists the dashboard pages and what each one\n shows, so Archie knows what to point at - the agent \"has the map\".\n3. **Navigate.** A dashboard_navigate tool returns a structured path/label; the web\n UI renders it as a clickable chip that routes the operator there. This is the\n \"plenty of resources\" the requirement named.\n\nWe deliberately keep the agent's answer honest: the chip is _evidence_ it can\nvalidly produce because dashboard_navigate is a real tool whose result is\nrendered, not a markdown link the model invents.\n\n## Why now\n\nThis is the natural next step of the \"chat on any page\" work, and the original\nrequest named it explicitly: _\"archie should be able to see what page you're on\ntoo. and point out where to go. so it needs plenty of resources.\"_ The chat\nis a full-page route with no knowledge of the rest of the dashboard; the agent\ncannot see which page the operator is on and cannot reliably direct them anywhere.\nThe critique of the chat UI already identified \"chat is not available on any page\"\nas the largest structural gap (P1). This design is the capability that makes that\ngap worth closing.\n\n## Shape of the API\n\n### Message field (gateway.go)\n\nAdd Page to Message:\n\n```go\n// Page is the dashboard route the operator is on when they sent this message\n// (e.g. \"/tasks\", \"/logs\"). Empty for non-web channels, which have no page\n// context. It is per-message, not per-session: the operator navigates freely\n// while a conversation stays open.\nPage string\n```\n\n### Web request (api_chat.go)\n\nchatMessageRequest gains Page, decoded into Message.Page in decodeChatMessage.\n\n### System prompt config (prompt.go)\n\nSystemPromptConfig gains Page; BuildSystemPrompt passes it through to the template.\nThe env block of archie.md.tpl renders the current page when set.\n\n### Page index (dashboard_tools.go, new)\n\nA package-level registry mapping route to {Label, Description}. page_index returns\nthe list so the model knows what each page shows:\n\n```go\ntype DashboardPage struct {\n\tPath string // \"/tasks\"\n\tLabel string // \"Tasks\"\n\tDescription string // \"Issues Archie picked up, and where they stand.\"\n}\n```\n\n### Navigation tool (dashboard_tools.go)\n\ndashboard_navigate validates its path against the registry and returns the resolved\npath/label. Unknown path means a clear error, not a guess. The model must call the\ntool (not invent a link) to produce a chip, so the chip is honest.\n\n### Tool wiring (turn.go)\n\nextraTools already merges TaskTools + SessionTools. Add the dashboard tools alongside\nthem, gated on the channel being the web UI. The tool list is built from the same\nregistry the prompt's page line comes from, so the agent never points at a page it\nwas not told about.\n\n### Web UI (chat-render.js, chat-tools.js)\n\nA dashboard_navigate tool call renders as a **clickable chip**: an anchor with\nhref=\"/tasks\" and the label. The chip is a\nreal link that works from any page once the chat is a global presence. The chip is\nstyled as an action, not a code line, so it visibly invites a click.\n\n### Route transfer (chat.js)\n\nEach sendMessage includes the current location.hash route as page in the stream\nrequest body, so the backend gets the operator's live position.\n\n## What we deliberately do NOT do\n\n- **No navigation from a markdown link.** The model must use dashboard_navigate; a\n bare \"click here\" is not rendered as a trusted route.\n- **No full-page route hijack from the chat.** The chip sets location.hash.\n- **No page index for non-web channels.** Telegram/discord have no dashboard.\n- **No automatic history annotation.** Page is per-message from the browser.\n- **No change to the dangerous-action approval flow.** Separately tracked.\n\n## Acceptance criteria\n\n1. Chat messages from any page carry the current page to the agent's prompt.\n2. page_index returns every dashboard page with a plain-language description.\n3. dashboard_navigate renders a clickable chip that routes to the target page.\n4. dashboard_navLine truncated
},
{
"url": "/dev/prds/dashboard-live-state/",
@@ -256,7 +256,7 @@
"url": "/dev/prds/dashboard-navigation-groups/",
"title": "Dashboard navigation groups + Configuration split -- decision",
"section": "PRDs",
"body": "# Dashboard navigation groups + Configuration split -- decision\n\n**Status:** Approved\n**Date:** 2026-09-20\n**Beads issue:** `archie-core-ocfm`\n**Related:** `archie-core-gl96` (Logs absent from the nav -- subsumed here),\n`archie-core-ggqo` (Configuration's page width -- moot once it splits)\n\n## Problem\n\n`ui/src/main.jsx` declares eleven navigable routes in one flat bar. Three of\nthem (Skills, Curators, Channels) are capability-gated and hidden on the\nreference deployment, so the eight items normally visible are the best case,\nnot the worst: a composition that serves every section wraps the bar. Logs is\ndeclared but was never given a nav entry at all, reachable only from a\ndashboard link.\n\nThe labels compound it. \"Event inspector\", \"Field mappings\" and \"Playbook\nbindings\" are three long labels for three faces of one subject, and they sit\nbeside \"Dashboard\" and \"Tasks\" as though they were peers of equal weight.\n\nConfiguration is the other half. One route renders roughly ten sections --\nupdate status, work lifecycle, identity, budgets, storage, listen address,\nrepositories, models and providers, configuration sources, plus the operator\ncards rehomed in `archie-core-tf20` -- in a 4021px page with no in-page\nnavigation. There is no way to send someone to Repositories.\n\n## Decision\n\nFive top-level nav items. Dashboard is a link; the rest are dropdowns.\n\n| Group | Items |\n|---|---|\n| Dashboard | (link, `/`) |\n| Work | Tasks, Workflows |\n| Agent | Skills, Curators |\n| Events | Inspector, Mappings, Bindings |\n| System | Status, Logs, Appearance; **Settings:** Task settings, Models, Repositories, Channels, Advanced |\n\nItems are renamed because the group now carries the context: \"Event inspector\"\nbecomes \"Inspector\" under Events, and so on. A group renders only if at least\none of its children survives capability gating, and a group left with one\nchild still renders as a dropdown -- a bar whose shape changes per deployment\nis harder to learn than one with a predictable skeleton.\n\nThe System dropdown has two narratives. Status, Logs and Appearance describe\nthe running dashboard and sit first. A separator and visible **Settings** label\nintroduce Task settings, Models, Repositories, Channels and Advanced; those are\nconfiguration destinations, not awkward phrases such as \"System Models\" or\n\"System Advanced\".\n\n### Route map\n\nConfiguration dissolves into real routes. Anchors into one long page were\nrejected: they leave the 4021px page intact and a deep link lands the reader\nmid-scroll with no context above it.\n\n| Was | Becomes | Content |\n|---|---|---|\n| `/settings` | `/system/status` | Update status, configuration sources, daemon listen address |\n| -- | `/system/appearance` | Theme, and the density/motion preferences that follow it |\n| `/settings` | `/system/tasks` | Work lifecycle: statuses, operator actions, budgets |\n| `/settings` | `/system/models` | Model roles, providers |\n| `/settings` | `/system/repos` | Repositories and their per-repo gate overrides |\n| `/settings` | `/system/advanced` | Identity, storage and sandboxing, dangerous actions |\n| `/captures` | `/captures` | unchanged; label becomes \"Inspector\" |\n| `/mappings` | `/mappings` | unchanged; label becomes \"Mappings\" |\n| `/bindings` | `/bindings` | unchanged; label becomes \"Bindings\" |\n\n`/settings` is kept as a permanent redirect to `/system/status`. It is the URL\nin existing bookmarks, in `dashboardPages` (`internal/gateway/dashboard_tools.go`,\nwhich the chat agent navigates by), and in prior conversation history; breaking\nit to save one route entry is not a trade worth making.\n\n`dashboardPages` gains the new routes in the same change. That registry is\nguarded by `TestDashboardPagesRegistryCoversEveryRoute`, so a route added here\nand forgotten there fails the build -- which is how the deleted `/chat` entry\nwas caught.\n\n### Dropdown behaviour\n\nEach item carries a one-line description shown as a hover tooltip, using\nshadcn-vue's `Tooltip` rather than the `title` attribute, so it is keyboard\nreachable on focus and styled with the rest of the menu. Touch gets no tooltip,\nso no item may depend on one to be identifiable.\n\nThe menu is shadcn-vue's `DropdownMenu` (Reka UI underneath), which already\nsupplies the roving focus, ArrowDown/ArrowUp movement, Escape-closes-and-\nrestores-focus, and outside-pointerdown behaviour this would otherwise hand-\nroll. It opens on click, never on hover -- hover-opened menus on a control\nplane are a misclick away from a destructive page. The trigger keeps\n`aria-current` styling when any of its children is the active route, so the bar\nstill says where you are.\n\nThis section was written against the Preact dashboard; the decisions above\nsurvive the Vue migration unchanged, only the primitive supplying them\nchanged.\n\n### Scope boundaries\n\n- The daemon-backed configuration pages move sections between rLine truncated
"body": "# Dashboard navigation groups + Configuration split -- decision\n\n**Status:** Approved\n**Date:** 2026-09-20\n**Beads issue:** `archie-core-ocfm`\n**Related:** `archie-core-gl96` (Logs absent from the nav -- subsumed here),\n`archie-core-ggqo` (Configuration's page width -- moot once it splits)\n\n## Problem\n\n`ui/src/main.jsx` declares eleven navigable routes in one flat bar. Three of\nthem (Skills, Curators, Channels) are capability-gated and hidden on the\nreference deployment, so the eight items normally visible are the best case,\nnot the worst: a composition that serves every section wraps the bar. Logs is\ndeclared but was never given a nav entry at all, reachable only from a\ndashboard link.\n\nThe labels compound it. \"Event inspector\", \"Field mappings\" and \"Playbook\nbindings\" are three long labels for three faces of one subject, and they sit\nbeside \"Dashboard\" and \"Tasks\" as though they were peers of equal weight.\n\nConfiguration is the other half. One route renders roughly ten sections --\nupdate status, work lifecycle, identity, budgets, storage, listen address,\nrepositories, models and providers, configuration sources, plus the operator\ncards rehomed in `archie-core-tf20` -- in a 4021px page with no in-page\nnavigation. There is no way to send someone to Repositories.\n\n## Decision\n\nFive top-level nav items. Dashboard is a link; the rest are dropdowns.\n\n| Group | Items |\n| --------- | ----------------------------------------------------------------------------------------------- |\n| Dashboard | (link, `/`) |\n| Work | Tasks, Workflows |\n| Agent | Skills, Curators |\n| Events | Inspector, Mappings, Bindings |\n| System | Status, Logs, Appearance; **Settings:** Task settings, Models, Repositories, Channels, Advanced |\n\nItems are renamed because the group now carries the context: \"Event inspector\"\nbecomes \"Inspector\" under Events, and so on. A group renders only if at least\none of its children survives capability gating, and a group left with one\nchild still renders as a dropdown -- a bar whose shape changes per deployment\nis harder to learn than one with a predictable skeleton.\n\nThe System dropdown has two narratives. Status, Logs and Appearance describe\nthe running dashboard and sit first. A separator and visible **Settings** label\nintroduce Task settings, Models, Repositories, Channels and Advanced; those are\nconfiguration destinations, not awkward phrases such as \"System Models\" or\n\"System Advanced\".\n\n### Route map\n\nConfiguration dissolves into real routes. Anchors into one long page were\nrejected: they leave the 4021px page intact and a deep link lands the reader\nmid-scroll with no context above it.\n\n| Was | Becomes | Content |\n| ----------- | -------------------- | ----------------------------------------------------------- |\n| `/settings` | `/system/status` | Update status, configuration sources, daemon listen address |\n| -- | `/system/appearance` | Theme, and the density/motion preferences that follow it |\n| `/settings` | `/system/tasks` | Work lifecycle: statuses, operator actions, budgets |\n| `/settings` | `/system/models` | Model roles, providers |\n| `/settings` | `/system/repos` | Repositories and their per-repo gate overrides |\n| `/settings` | `/system/advanced` | Identity, storage and sandboxing, dangerous actions |\n| `/captures` | `/captures` | unchanged; label becomes \"Inspector\" |\n| `/mappings` | `/mappings` | unchanged; label becomes \"Mappings\" |\n| `/bindings` | `/bindings` | unchanged; label becomes \"Bindings\" |\n\n`/settings` is kept as a permanent redirect to `/system/status`. It is the URL\nin existing bookmarks, in `dashboardPages` (`internal/gateway/dashboard_tools.go`,\nwhich the chat agent navigates by), and in prior conversation history; breaking\nit to save one route entry is not a trade worth making.\n\n`dashboardPages` gains the new routes in the same change. That registry is\nguarded by `TestDashboardPagesRegistryCoversEveryRoute`, so a route added here\nand forgotten there fails the build -- which is how the deleted `/chat` entry\nwas caught.\n\n### Dropdown behaviour\n\nEach item carries a one-line description shown as a hover tooltip, using\nshadcn-vue's `Tooltip` rather than the `title` attribute, so it is kLine truncated
},
{
"url": "/dev/prds/dashboard-port-brief/",
@@ -268,61 +268,61 @@
"url": "/dev/prds/dashboard-vocabulary/",
"title": "One source for the dashboard's server vocabularies",
"section": "PRDs",
"body": "# One source for the dashboard's server vocabularies\n\n**Status:** Finalised\n\n## Problem\n\nThe dashboard kept its own copies of two vocabularies the daemon owns:\n\n- the changed-file statuses (`added`, `modified`, `deleted`, `renamed`,\n `typechange`), which are the `Change*` constants in\n `internal/domain/workflow/task`;\n- the schema stamp on a `config_captured` payload, `events.ConfigCapturedSchema`.\n\nNothing derived one side from the other, while `/api/task-meta` already served\nthe status and action vocabularies for exactly this reason.\n\n## Decision\n\n`GET /api/task-meta` also serves `change_statuses` (id and label) and\n`config_schema`. `buildTaskMeta` in `internal/webui/api_task_meta.go` takes the\nids from the `Change*` constants and the stamp from `events.ConfigCapturedSchema`.\n\nThe dashboard renders `ui/src/lib/task-meta-snapshot.ts` until the served\ncatalogue arrives, or when archied is unreachable. `loadTaskMeta` replaces only\nthe keys the payload carries, so a server without the new keys leaves the\nsnapshot in place. `changeStatusLabel` and `configSchema` in\n`ui/src/lib/task-meta.ts` are the only readers; an unknown status renders as\nits id.\n\n## Verification\n\n- `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- `TestTaskMetaChangeStatusesAreDeliberate` fails when a `Change*` constant is\n added without a label.\n\nA rename on one side therefore fails a test on the other.\n\n## Rejected\n\nDeleting `/api/task-meta` and accepting hand-copied constants. The endpoint is\nlive, and deleting it would still leave the two copies this document removes.\n"
},
{
"url": "/dev/prds/deep-research-capability/",
"title": "Deep research capability — design",
"section": "PRDs",
"body": "# Deep research capability — design\n\n**Status:** Draft\n**Date:** 2026-09-14\n**Scope:** A deep-research capability in archie-core: an orchestrator that\nspawns 1..N subagents to explore and research in parallel, collates their\nfindings, and returns one cited report. Grounded in web search and web fetch.\n**Beads issue:** none yet (this document is the input to it)\n**Depends on:** nothing shipped for slice 1; slice 2 depends on slice 1.\n\n## §0 Implementation status\n\nEvery claim in this document is mapped to what exists in the tree.\n\n| Claim | Status | Where it stands |\n|---|---|---|\n| `web_fetch` tool (URL → readable text) | **Implemented** | `internal/tools/webfetch/{tool.go,webfetch.go}`; registered in `internal/app/archied/bootstrap.go` `registerStandaloneTools`, disabled-by-config returns `nil` |\n| **Web search** (query → result list) | **Aspirational — zero code** | No search provider, no search tool, no config block anywhere in the tree or in `ai-sdk` v0.1.32 |\n| `agent.Subagent` — nested agent in a fresh context window | **Implemented** (dependency) | `github.com/samcharles93/ai-sdk@v0.1.32/agent/subagent.go`. Synchronous, non-streaming, own model/system/toolset, `MaxSteps` defaults to 10, nesting depth capped at 5, returns final text only |\n| Subagent used in production | **Implemented, one consumer** | `internal/app/agentworker/review.go` — the adversarial reviewer. That is the only non-test use of `Subagent` in the repo |\n| A **delegate/subagent tool** on the chat surface | **Aspirational — zero code** | No `subagent`/`delegate` tool name is registered anywhere |\n| **Fan-out orchestration** (N missions, one collator) | **Aspirational — zero code** | `agentloop`'s package doc states it runs *one* mission: \"orchestration across missions lives with the caller\". No caller does this yet |\n| Parallel-safe tool execution | **Aspirational — zero code** | The unreachable `internal/tools/dispatch.go` dispatch/gating engine (`ExecutionClass`, `DispatchSequential`/`DispatchConcurrent`/`ClassifyEntry`) was deleted as dead code (tools-core-1); live concurrency is ai-sdk's `GenerateOptions.MaxParallelToolCalls`, which archie-core never sets |\n| Per-result caps + spill-to-disk | **Implemented** | `internal/agentexec/toolset.go` `ToolLimits{MaxResultChars,SpillDir}`, applied in `toolExecute` via `tools.CapPayload` (`limit.go`); no **aggregate** turn cap by design (`toolset.go`). `config.ToolPolicy.SpillDir`; default cap 50k chars, spill dir deliberately not defaulted |\n| Tool guardrails (repeat-failure / no-progress) | **Implemented, not on the call path** | `internal/tools/guardrail.go` engine exists. Its only non-test caller is `dispatchOne` — which is itself unreachable — so **the chat path never consults it**, and the agent path only records per *stage* (`domain/workflow/agent.go`) |\n| Structured capture tools (model reports into a typed store, not prose) | **Implemented** | `internal/app/agentworker/review.go` `record_finding` / `record_checked` — `core.NewTypedTool` appending to a caller-owned slice. This is the pattern a research source ledger should reuse |\n| Curator engine (interval, declared tool set, lifecycle) | **Implemented, tools broken** | `internal/domain/curator`; a curator declaring tools is **refused** at registration (`registry.go`, no `ToolBuilder` implementation) and `curatorLLMRunner` (`internal/app/archied/main.go`) drops `ChatRequest.Tools`. Budgets are time+concurrency only (`runtime.go`) — **no token budget** |\n| Cron / scheduling + delivery router | **Implemented, wired into the daemon** | `internal/domain/scheduling` (ticker engine), `internal/infrastructure/cronstore` (schema v2, `Kind` discriminator), and `internal/infrastructure/crondelivery`; `internal/app/archied/scheduling.go` composes them and `main.go` starts the engine. |\n| Workflow engines (multi-stage, resumable) | **Implemented, worktree-bound** | `internal/domain/workflow` — every non-triage workflow opens with `StagePrepareWorktree()` and mounts `tc.Dir` into a container; the task persists after every stage (`workflow.go`). `triage.go` documents there is \"no cheaper directory-less classification primitive\" |\n| Long-running chat-initiated work with progress | **Partial** | Chat turns run **once, synchronously**, inline in the channel's turn runner (`internal/gateway/turn.go`). Chat can spawn a *workflow task* (`task_spawn`) which is asynchronous — but that path is worktree/PR-shaped |\n| **Operator-push delivery of an async result** | **Aspirational — zero code** | Nothing pushes a finished result to a chat. No channel subscribes to the event bus (Telegram only *publishes* `KindTurnCompleted`); `crondelivery.Courier` is the intended seam but has **no implementation and no caller**; `send_file` works only inside the live turn. The one out-of-band notification in the tree is feasibility's n8n webhook (`feasibility.go`) |\n| Citation storage / sourLine truncated
"body": "# Deep research capability — design\n\n**Status:** Draft\n**Date:** 2026-09-14\n**Scope:** A deep-research capability in archie-core: an orchestrator that\nspawns 1..N subagents to explore and research in parallel, collates their\nfindings, and returns one cited report. Grounded in web search and web fetch.\n**Beads issue:** none yet (this document is the input to it)\n**Depends on:** nothing shipped for slice 1; slice 2 depends on slice 1.\n\n## §0 Implementation status\n\nEvery claim in this document is mapped to what exists in the tree.\n\n| Claim | Status | Where it stands |\n| ---------------------------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `web_fetch` tool (URL → readable text) | **Implemented** | `internal/tools/webfetch/{tool.go,webfetch.go}`; registered in `internal/app/archied/bootstrap.go` `registerStandaloneTools`, disabled-by-config returns `nil` |\n| **Web search** (query → result list) | **Aspirational — zero code** | No search provider, no search tool, no config block anywhere in the tree or in `ai-sdk` v0.1.32 |\n| `agent.Subagent` — nested agent in a fresh context window | **Implemented** (dependency) | `github.com/samcharles93/ai-sdk@v0.1.32/agent/subagent.go`. Synchronous, non-streaming, own model/system/toolset, `MaxSteps` defaults to 10, nesting depth capped at 5, returns final text only |\n| Subagent used in production | **Implemented, one consumer** | `internal/app/agentworker/review.go` — the adversarial reviewer. That is the only non-test use of `Subagent` in the repo |\n| A **delegate/subagent tool** on the chat surface | **Aspirational — zero code** | No `subagent`/`delegate` tool name is registered anywhere |\n| **Fan-out orchestration** (N missions, one collator) | **Aspirational — zero code** | `agentloop`'s package doc states it runs _one_ mission: \"orchestration across missions lives with the caller\". No caller does this yet |\n| Parallel-safe tool execution | **Aspirational — zero code** | The unreachable `internal/tools/dispatch.go` dispatch/gating engine (`ExecutionClass`, `DispatchSequential`/`DispatchConcurrent`/`ClassifyEntry`) was deleted as dead code (tools-core-1); live concurrency is ai-sdk's `GenerateOptions.MaxParallelToolCalls`, which archie-core never sets |\n| Per-result caps + spill-to-disk | **Implemented** Line truncated
},
{
"url": "/dev/prds/dynamic-curators/",
"title": "Dynamically-defined curators -- decision",
"section": "PRDs",
"body": "# Dynamically-defined curators -- decision\n\n**Status:** Approved\n**Date:** 2026-09-12\n**GitHub epic:** [#789](https://github.com/samcharles93/archie-core/issues/789)\n**Parent epic (curator engine):** [#435](https://github.com/samcharles93/archie-core/issues/435) (closed)\n**Depends on:** nothing shipping; this resolves the open question that epic #435's\n\"registered and configured declaratively, not hardcoded\" criterion left open.\n\n## §0 Implementation status\n\nEvery claim in this document is mapped to what exists in the tree.\n\n| Claim | Status | Where it stands |\n|---|---|---|\n| Curator engine family: typed contract, owning registry, start/health/stop, narrow host access | **Implemented** | `internal/domain/curator/{contract,registry,runtime,registrar,activity,wake}.go` |\n| Curator declared shape (`Manifest`: interval, cooldown, on_input, tools, skills, memory engine, conversations, model) | **Implemented** | `internal/domain/curator/contract.go`; `Validate()` requires `Interval \u003e 0` |\n| Two reference curators run through the registry | **Implemented** | `internal/infrastructure/skillcurator`, `internal/infrastructure/sessioncurator` |\n| Curator definitions as persisted, API-editable data | **Aspirational -- zero code** | No table, no entity, no RPC, no config block |\n| Generic definition-driven engine that executes a declared tool set + free-form instructions | **Aspirational -- zero code** | Only the two code-registered curators exist |\n| `Registrar.Tools` (`ToolBuilder`) resolved and bound at registration | **Partial** | Interface declared (`registrar.go`); **no implementation anywhere**; `bootstrap.go` builds the `Registrar` with no `Tools` field |\n| A curator can declare tools at all | **Partial** | `Manifest.Tools` exists, but `registry.go` fails registration with `\"curator manifest: declares tools but the registrar has no ToolBuilder\"` |\n| Curator passes that actually reach a model with tools | **Cosmetic only** | `curator.ChatRequest` carries `Tools`/`MaxSteps`; `curatorLLMRunner` (`internal/app/archied/main.go`) drops both and returns `ChatResult{Text}` only |\n| Dynamic registration / removal (no restart) | **Aspirational -- zero code** | `Registry` has `Register`, no `Unregister`; `Runtime` has `Start`/`Nudge`/`Stop`, no `Add`/`Remove`; `Start()` snapshots membership |\n| Curator definition CRUD over REST | **Partial** | `GET /api/curators` read-only (`internal/webui/server.go`); no write routes |\n| Curator definition config | **Aspirational -- zero code** | No `[curator]` block in `internal/config/config.go` |\n| Store/API as definition authority | **Aspirational -- zero code** | No curator persistence of any kind |\n| No live-path defaults for interval/cooldown/tools/model/memory engine | **Partial** | `skillcurator.DefaultInterval` / `sessioncurator.DefaultInterval` are Go consts read at registration; `curator.NewRuntime(..., RuntimeConfig{})` uses code defaults for pass timeout and concurrency |\n| Idle curators are observable in logs | **Partial** | `runtime.go` logs nothing when `Check` reports not-due; the session-memory curator's hourly pass is the only curator activity ever logged |\n| Sampler family | **Implemented** | `internal/domain/sampling`, shipped; no curator consumes a `Sampler` yet |\n| Forge/issue reach from chat | **Implemented** (via `shell`) | No dedicated issue tool exists, but the chat agent's `shell` is unconfined (`chat.unrestricted_filesystem = true`), so `gh issue edit|comment|create|close` works. Dedicated tools (#161) are convenience, not a blocker |\n\n\u003e **Target state, not current state.** Everything below marked aspirational is\n\u003e design, not a description of the daemon as it runs.\n\n## Problem\n\nA curator exists only if a Go package implements `curator.CuratorEngine`\nand `bootstrap.go/1025` names it in a `Register` call. Nothing about a\ncurator is definable as data. Worse, no curator can declare a tool set at all:\nthe `ToolBuilder` interface has no implementation in the repo, so the registry\nrefuses (correctly, fail-closed) any curator that declares tools -- and the\ndaemon's model adapter drops the tools even if it were bound. The curator family\ntherefore has exactly one shape (cheap, tool-less maintenance pass) and its only\nextension point is compiling Go.\n\nSam's requirement is the opposite: *\"Curators should be dynamically created and\ndefined, in addition to being able to be defined in code/config/webui\"* and *\"No\nconfiguration should ever be hard-coded.\"* The motivating consumer is a\nproject/orchestrator curator -- declared as data, given forge issue tools, and\npointed at a repo to review, refine, and propose issues.\n\n## Decision\n\n**A curator definition is data: a persisted entity whose declared shape is\nexactly `curator.Manifest` plus identity, free-form instructions, and an enabled\nflag. One generic engine interprets any definition.** The shape is not a second\ninvention -- `MLine truncated
"body": "# Dynamically-defined curators -- decision\n\n**Status:** Approved\n**Date:** 2026-09-12\n**GitHub epic:** [#789](https://github.com/samcharles93/archie-core/issues/789)\n**Parent epic (curator engine):** [#435](https://github.com/samcharles93/archie-core/issues/435) (closed)\n**Depends on:** nothing shipping; this resolves the open question that epic #435's\n\"registered and configured declaratively, not hardcoded\" criterion left open.\n\n## §0 Implementation status\n\nEvery claim in this document is mapped to what exists in the tree.\n\n| Claim | Status | Where it stands |\n| --------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Curator engine family: typed contract, owning registry, start/health/stop, narrow host access | **Implemented** | `internal/domain/curator/{contract,registry,runtime,registrar,activity,wake}.go` |\n| Curator declared shape (`Manifest`: interval, cooldown, on_input, tools, skills, memory engine, conversations, model) | **Implemented** | `internal/domain/curator/contract.go`; `Validate()` requires `Interval \u003e 0` |\n| Two reference curators run through the registry | **Implemented** | `internal/infrastructure/skillcurator`, `internal/infrastructure/sessioncurator` |\n| Curator definitions as persisted, API-editable data | **Aspirational -- zero code** | No table, no entity, no RPC, no config block |\n| Generic definition-driven engine that executes a declared tool set + free-form instructions | **Aspirational -- zero code** | Only the two code-registered curators exist |\n| `Registrar.Tools` (`ToolBuilder`) resolved and bound at registration | **Partial** | Interface declared (`registrar.go`); **no implementation anywhere**; `bootstrap.go` builds the `Registrar` with no `Tools` field |\n| A curator can declare tools at all | **Partial** | `Manifest.Tools` exists, but `registry.go` fails registration with `\"curator manifest: declares tools but the registrar has no ToolBuilder\"` |\n| Curator passes that actually reach a model with tools | **Cosmetic only** | `curator.ChatRequest` carries `Tools`/`MaxSteps`; `curatorLLMRunner` (`internal/app/archied/main.go`) drops both and returns `ChatResult{Text}` only |\n| Dynamic registration / removal (no restart) | **Aspirational -- zero code** | `Registry` has `Register`, no `Unregister`; `Runtime` has `Start`/`Nudge`/`Stop`, no `Add`/`Remove`; `Start()` snapshots membership |\n| Curator definition CRUD over REST | **Partial** | `GET /api/curators` read-only (`internal/webui/server.go`); no write routes |\n| Curator definition config | **Aspirational -- zero code** | No `[curator]` block in `intLine truncated
},
{
"url": "/dev/prds/dynamic-workflow-triage/",
"title": "Dynamic workflow triage",
"section": "PRDs",
"body": "# Dynamic workflow triage\n\n**Status:** Finalised\n\nEpic: archie-core-enfj. Scope: give `workflow.Route()` a real, content-aware\nfallback instead of unconditionally defaulting every unlabelled task to the\nheaviest workflow.\n\n## Problem\n\n`Route()` (`internal/domain/workflow/workflow.go`) has exactly two real\nsignals: an explicit `t.Workflow`, and label matches via\n`workflowForLabels` (`routing.go`, `bug`→tdd, `feature`→feasibility,\nbootstrap→bootstrap). Anything else — which is every chat-spawned task,\nsince `task_spawn` rarely sets labels — falls straight through to\n`reg[\"implement\"]`, the full `prepare → baseline → plan → build →\ncommit-push → review → open-pr` pipeline, regardless of what the task\nactually asks for.\n\n`task_spawn`'s own tool schema overpromises: *\"workflow: … Omit to let the\ndaemon route it\"* (`internal/gateway/task_tools.go`) implies real\nrouting exists. It doesn't — \"route\" means \"check labels, then\ngive up and run the heaviest workflow anyway.\"\n\nConfirmed in production: a chat-spawned task whose\nentire content was \"this is just a test, close it when you receive it\" ran\nthe full `implement` pipeline end to end — 669,421 tokens, ~7 minutes —\nwhen nothing about the request needed a worktree-driven build at all. The\n`plan` stage's own LLM output *correctly* concluded no code change was\nneeded, but that conclusion arrives two expensive stages (`baseline`,\n`plan`) too late to save anything.\n\n## Decision\n\nAdd a **`triage` workflow**: cheap, classifies once, then either closes the\ntask immediately or hands off to the workflow the task actually needs.\n`Route()`'s final fallback (`reg[\"implement\"]`) becomes\n`reg[\"triage\"]` when a `triage` entry is registered, else the existing\n`implement` fallback — a two-line change, fully backward compatible when\n`triage` isn't wired up.\n\nTriage does **not** replace label-based routing. A labelled task\n(`bug`/`feature`/bootstrap) already has a free, reliable signal and goes\nstraight to its known workflow unchanged — spending a classification\ncall there would be pure waste. Triage only fires in the gap that\ndefaults to `implement` blindly: no explicit workflow, no label match.\n\n### Triage workflow shape\n\n```\nStagePrepareWorktree() -- still needed: AgentStage mounts tc.Dir into the\n agent container: internal/domain/workflow/agent.go:74\n passes tc.Dir straight through. No cheaper\n primitive exists in this codebase for a\n directory-less classification call.\nAgentStage \"classify\" -- ReadOnly, ONE cheap agent turn, no exploration\n tools required beyond what ReadOnly already\n grants. Mirrors feasibility.go's decideCaptureTools\n pattern: a structured capture tool, called\n exactly once, MaxCalls: 1.\n```\n\nMission: read the task's title/body/labels (already in `taskPromptBlock`)\nand decide, via a captured `decide` tool call:\n\n```json\n{\"needs_code_change\": bool, \"workflow\": \"implement\" | \"tdd\" | \"feasibility\", \"reasons\": \"...\"}\n```\n\n`needs_code_change: false` → close path: reuse `closeNoChangesIssue`\n(`steps.go`) directly — issue closed if forge-backed, task marked\n`StatusMerged`/`\"completed -- no changes required\"` otherwise. No baseline,\nno plan, no build, no commit, no PR. This is the actual fix for the\nproduction incident: a no-op request now costs one classification call\n(low thousands of tokens) instead of 669,421.\n\n`needs_code_change: true` → sets `tc.Task.Workflow` to the classifier's\nchosen workflow (`implement`/`tdd`/`feasibility`, defaulting to\n`implement` if the field is missing or unrecognised) and an Outcome that\nrequeues the task under it, the same requeue mechanism\n`chatTaskControllerAdapter.ApproveChatTask` already uses\n(`main.go`, `requeue(ctx, taskID, fromStatus, workflow)`). The task then\nre-enters `Route()` on its next claim with `t.Workflow` now set, and takes\nthe normal path for that workflow from there — triage never runs its\nclassification twice for the same task.\n\n### Non-goals (v1)\n\n- Full bug/feature intent classification quality — the classifier only\n needs to be *directionally* right; a wrong `tdd` vs `implement` call\n still produces a working PR, just via a slightly less-tailored pipeline.\n Tightening this is a follow-up, not a blocker.\n- Any change to label-based routing, `Route()`'s explicit-workflow branch,\n or `Bootstrap()`/`Feasibility()`/`TDD()` themselves.\n- Triage for forge-sourced (real GitHub issue) tasks with no labels —\n in scope structurally (same fallback branch), but the dominant case this\n fixes is chat-spawned tasks, which essentially never carry labels.\n\n## Testing\n\n- `workflow_test.go`: `Route()` picks `rLine truncated
"body": "# Dynamic workflow triage\n\n**Status:** Finalised\n\nEpic: archie-core-enfj. Scope: give `workflow.Route()` a real, content-aware\nfallback instead of unconditionally defaulting every unlabelled task to the\nheaviest workflow.\n\n## Problem\n\n`Route()` (`internal/domain/workflow/workflow.go`) has exactly two real\nsignals: an explicit `t.Workflow`, and label matches via\n`workflowForLabels` (`routing.go`, `bug`→tdd, `feature`→feasibility,\nbootstrap→bootstrap). Anything else — which is every chat-spawned task,\nsince `task_spawn` rarely sets labels — falls straight through to\n`reg[\"implement\"]`, the full `prepare → baseline → plan → build →\ncommit-push → review → open-pr` pipeline, regardless of what the task\nactually asks for.\n\n`task_spawn`'s own tool schema overpromises: _\"workflow: … Omit to let the\ndaemon route it\"_ (`internal/gateway/task_tools.go`) implies real\nrouting exists. It doesn't — \"route\" means \"check labels, then\ngive up and run the heaviest workflow anyway.\"\n\nConfirmed in production: a chat-spawned task whose\nentire content was \"this is just a test, close it when you receive it\" ran\nthe full `implement` pipeline end to end — 669,421 tokens, ~7 minutes —\nwhen nothing about the request needed a worktree-driven build at all. The\n`plan` stage's own LLM output _correctly_ concluded no code change was\nneeded, but that conclusion arrives two expensive stages (`baseline`,\n`plan`) too late to save anything.\n\n## Decision\n\nAdd a **`triage` workflow**: cheap, classifies once, then either closes the\ntask immediately or hands off to the workflow the task actually needs.\n`Route()`'s final fallback (`reg[\"implement\"]`) becomes\n`reg[\"triage\"]` when a `triage` entry is registered, else the existing\n`implement` fallback — a two-line change, fully backward compatible when\n`triage` isn't wired up.\n\nTriage does **not** replace label-based routing. A labelled task\n(`bug`/`feature`/bootstrap) already has a free, reliable signal and goes\nstraight to its known workflow unchanged — spending a classification\ncall there would be pure waste. Triage only fires in the gap that\ndefaults to `implement` blindly: no explicit workflow, no label match.\n\n### Triage workflow shape\n\n```\nStagePrepareWorktree() -- still needed: AgentStage mounts tc.Dir into the\n agent container: internal/domain/workflow/agent.go:74\n passes tc.Dir straight through. No cheaper\n primitive exists in this codebase for a\n directory-less classification call.\nAgentStage \"classify\" -- ReadOnly, ONE cheap agent turn, no exploration\n tools required beyond what ReadOnly already\n grants. Mirrors feasibility.go's decideCaptureTools\n pattern: a structured capture tool, called\n exactly once, MaxCalls: 1.\n```\n\nMission: read the task's title/body/labels (already in `taskPromptBlock`)\nand decide, via a captured `decide` tool call:\n\n```json\n{\"needs_code_change\": bool, \"workflow\": \"implement\" | \"tdd\" | \"feasibility\", \"reasons\": \"...\"}\n```\n\n`needs_code_change: false` → close path: reuse `closeNoChangesIssue`\n(`steps.go`) directly — issue closed if forge-backed, task marked\n`StatusMerged`/`\"completed -- no changes required\"` otherwise. No baseline,\nno plan, no build, no commit, no PR. This is the actual fix for the\nproduction incident: a no-op request now costs one classification call\n(low thousands of tokens) instead of 669,421.\n\n`needs_code_change: true` → sets `tc.Task.Workflow` to the classifier's\nchosen workflow (`implement`/`tdd`/`feasibility`, defaulting to\n`implement` if the field is missing or unrecognised) and an Outcome that\nrequeues the task under it, the same requeue mechanism\n`chatTaskControllerAdapter.ApproveChatTask` already uses\n(`main.go`, `requeue(ctx, taskID, fromStatus, workflow)`). The task then\nre-enters `Route()` on its next claim with `t.Workflow` now set, and takes\nthe normal path for that workflow from there — triage never runs its\nclassification twice for the same task.\n\n### Non-goals (v1)\n\n- Full bug/feature intent classification quality — the classifier only\n needs to be _directionally_ right; a wrong `tdd` vs `implement` call\n still produces a working PR, just via a slightly less-tailored pipeline.\n Tightening this is a follow-up, not a blocker.\n- Any change to label-based routing, `Route()`'s explicit-workflow branch,\n or `Bootstrap()`/`Feasibility()`/`TDD()` themselves.\n- Triage for forge-sourced (real GitHub issue) tasks with no labels —\n in scope structurally (same fallback branch), but the dominant case this\n fixes is chat-spawned tasks, which essentially never carry labels.\n\n## Testing\n\n- `workflow_test.go`: `Route()` picks `rLine truncated
},
{
"url": "/dev/prds/eda-playbook-engine/",
"title": "EDA playbook engine -- design",
"section": "PRDs",
"body": "# EDA playbook engine -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Beads epic:** `archie-core-t2db`\n\n## Problem\n\n\"Which workflow runs for which trigger\" is hardcoded Go: a literal\nlabel vocabulary (`workintake.labelKinds`) and a literal label-\u003eworkflow map\n(`workflow/routing.go`), extended only by adding a Go case or shipping a\nskill whose `metadata.archie.workflow` overrides one *named* built-in\nworkflow. Extending the system to a new trigger, a new action, or a new\nevent source means a feature branch, a code change in a hardcoded\npath, and new Go tests -- for every addition. That is the barrier this\ndocument exists to remove.\n\nThe goal: triggers, the actions they run, and the\nconditions that connect them should be **drop-in and load**, not **drop-in\nand touch application code**. Yaegi-evaluated Go is the unit of imperative\n\"do a thing\" logic; YAML playbooks are pure orchestration data -- no logic,\njust \"on this event, with this data, call these actions, in this order,\nunder these conditions.\" The daemon's event coordinator doesn't know what a\n`bugfix` or `image-gen` action does, it resolves the name against a\nregistry and pipes typed data through.\n\nThis is explicitly **not** scoped to code-generation workflows. A playbook\naction can be any registered capability -- run a codegen workflow, send a\nmessage on a channel, open something on a forge, generate an image -- so\nlong as it's implemented behind one of the typed engine families below.\n\n## Relationship to existing decisions\n\n- `docs/prds/event-sources-and-reactions.md` ruled\n that reactions in the two epics it covers are **producer-only** (no veto,\n no mutation of in-flight work) and explicitly rejected a single generic\n `Source` interface as \"the untyped-hook shape the plugin engine rule\n exists to prevent.\" **This document extends that scope**: playbooks can\n dispatch to multiple typed action kinds, not just \"produce a\n `TaskEnvelope`.\" It does not relitigate producer-only-ness (still no\n veto/mutation of in-flight work here) and it does not introduce one\n generic interface -- see \"Typed positions, not one generic hook\" below,\n which is how it stays compliant with the plugin engine rule instead of\n reopening that document's #4.\n- `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`\n governs every extension point\n introduced here. Every position below is a typed domain contract with an\n owning registry, not a generic callback map. This is a hard constraint,\n confirmed against the existing rule text before writing this doc.\n- Yaegi is already a proven in-process extension mechanism\n (`internal/plugin`, `internal/domain/workflow/wfeval/yaegi.go`,\n `internal/gate/gateeval/yaegi.go`, `internal/skill/plugin.go`) -- this\n design generalises its existing role, it does not introduce a new\n execution mechanism.\n- `internal/domain/workflow/skillbuild.BuildRegistry` already composes a\n `workflow.Registry` from a skills catalogue, plugin-defined overriding\n built-in. The playbook loader described here supersedes label routing\n specifically; it does not replace `skillbuild`'s workflow-composition role,\n it becomes an additional input the daemon composes at startup.\n- Webhook event intake is a separate design. This\n document defines the router each webhook-sourced event should be able to\n reach; it does not redesign webhook receipt itself.\n\n## Shape: four logic positions, each a typed engine family\n\nEvery entrypoint kind (mechanism, action, loop, schedule, route, trigger) is itself a schema emitter: defining a new kind produces the\ngenerated contract downstream tooling consumes. The kinds slot into a fixed\nhierarchy of logic positions:\n\n```\nWorkflow -\u003e Module -\u003e Channel (telegram/whatsapp/email/...)\n -\u003e Forge (GitHub/Gitea/GitLab/...)\n```\n\nEach position is its own typed engine family per the plugin engine rule:\nidentity + capability-specific operations, an owning `Registry`/`Manager`,\nexplicit lifecycle where the implementation owns resources, narrow host\naccess. Concretely:\n\n- **Workflow** -- already exists (`internal/domain/workflow`). A playbook\n action of kind `workflow` invokes a registered `workflow.Registry` entry\n by name, unchanged from the existing execution path.\n- **Module** -- the new general-purpose action position. A `Module` is a\n Yaegi-evaluated implementation of a generated interface (args in, typed\n result out) for one declared action kind (e.g. `image-gen`, `notify`,\n `open-pr-comment`). This is the position that makes actions \"not\n restricted to code-generation.\" Full design (schema-per-kind, the\n registry shape, the trust boundary, the recommended first slice):\n `docs/prds/module-position.md`.\n- **Channel** -- already exists as `channels.Channel` (telegram, email,\n webhook). A playbook action of kind `channel` sends througLine truncated
"body": "# EDA playbook engine -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Beads epic:** `archie-core-t2db`\n\n## Problem\n\n\"Which workflow runs for which trigger\" is hardcoded Go: a literal\nlabel vocabulary (`workintake.labelKinds`) and a literal label-\u003eworkflow map\n(`workflow/routing.go`), extended only by adding a Go case or shipping a\nskill whose `metadata.archie.workflow` overrides one _named_ built-in\nworkflow. Extending the system to a new trigger, a new action, or a new\nevent source means a feature branch, a code change in a hardcoded\npath, and new Go tests -- for every addition. That is the barrier this\ndocument exists to remove.\n\nThe goal: triggers, the actions they run, and the\nconditions that connect them should be **drop-in and load**, not **drop-in\nand touch application code**. Yaegi-evaluated Go is the unit of imperative\n\"do a thing\" logic; YAML playbooks are pure orchestration data -- no logic,\njust \"on this event, with this data, call these actions, in this order,\nunder these conditions.\" The daemon's event coordinator doesn't know what a\n`bugfix` or `image-gen` action does, it resolves the name against a\nregistry and pipes typed data through.\n\nThis is explicitly **not** scoped to code-generation workflows. A playbook\naction can be any registered capability -- run a codegen workflow, send a\nmessage on a channel, open something on a forge, generate an image -- so\nlong as it's implemented behind one of the typed engine families below.\n\n## Relationship to existing decisions\n\n- `docs/prds/event-sources-and-reactions.md` ruled\n that reactions in the two epics it covers are **producer-only** (no veto,\n no mutation of in-flight work) and explicitly rejected a single generic\n `Source` interface as \"the untyped-hook shape the plugin engine rule\n exists to prevent.\" **This document extends that scope**: playbooks can\n dispatch to multiple typed action kinds, not just \"produce a\n `TaskEnvelope`.\" It does not relitigate producer-only-ness (still no\n veto/mutation of in-flight work here) and it does not introduce one\n generic interface -- see \"Typed positions, not one generic hook\" below,\n which is how it stays compliant with the plugin engine rule instead of\n reopening that document's #4.\n- `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`\n governs every extension point\n introduced here. Every position below is a typed domain contract with an\n owning registry, not a generic callback map. This is a hard constraint,\n confirmed against the existing rule text before writing this doc.\n- Yaegi is already a proven in-process extension mechanism\n (`internal/plugin`, `internal/domain/workflow/wfeval/yaegi.go`,\n `internal/gate/gateeval/yaegi.go`, `internal/skill/plugin.go`) -- this\n design generalises its existing role, it does not introduce a new\n execution mechanism.\n- `internal/domain/workflow/skillbuild.BuildRegistry` already composes a\n `workflow.Registry` from a skills catalogue, plugin-defined overriding\n built-in. The playbook loader described here supersedes label routing\n specifically; it does not replace `skillbuild`'s workflow-composition role,\n it becomes an additional input the daemon composes at startup.\n- Webhook event intake is a separate design. This\n document defines the router each webhook-sourced event should be able to\n reach; it does not redesign webhook receipt itself.\n\n## Shape: four logic positions, each a typed engine family\n\nEvery entrypoint kind (mechanism, action, loop, schedule, route, trigger) is itself a schema emitter: defining a new kind produces the\ngenerated contract downstream tooling consumes. The kinds slot into a fixed\nhierarchy of logic positions:\n\n```\nWorkflow -\u003e Module -\u003e Channel (telegram/whatsapp/email/...)\n -\u003e Forge (GitHub/Gitea/GitLab/...)\n```\n\nEach position is its own typed engine family per the plugin engine rule:\nidentity + capability-specific operations, an owning `Registry`/`Manager`,\nexplicit lifecycle where the implementation owns resources, narrow host\naccess. Concretely:\n\n- **Workflow** -- already exists (`internal/domain/workflow`). A playbook\n action of kind `workflow` invokes a registered `workflow.Registry` entry\n by name, unchanged from the existing execution path.\n- **Module** -- the new general-purpose action position. A `Module` is a\n Yaegi-evaluated implementation of a generated interface (args in, typed\n result out) for one declared action kind (e.g. `image-gen`, `notify`,\n `open-pr-comment`). This is the position that makes actions \"not\n restricted to code-generation.\" Full design (schema-per-kind, the\n registry shape, the trust boundary, the recommended first slice):\n `docs/prds/module-position.md`.\n- **Channel** -- already exists as `channels.Channel` (telegram, email,\n webhook). A playbook action of kind `channel` sends througLine truncated
},
{
"url": "/dev/prds/embedded-nats/",
"title": "Embedded NATS execution -- decision",
"section": "PRDs",
"body": "# Embedded NATS execution -- decision\n\n**Status:** Finalised\n\n**Date:** 2026-08-24\n\n**Beads epic:** `archie-core-q15y`\n\nThis decision supersedes the position that embedded NATS was only a\ndistribution mechanism and could not be an agent-execution topology. That was\ntrue only because the embedded listener was unauthenticated loopback. It left a\nsecond production architecture in which `archied` ran autonomous workflows in\nits own process, weakening the isolation boundary that managed task containers\nexist to provide.\n\n## One execution architecture, two broker deployments\n\nEvery autonomous repository workflow is handed over as one complete task via\nNATS and runs in a task-scoped `archie-agent` container. `archied` remains a\nnative, long-lived orchestration and interactive-chat process; its operator\nconfigured host filesystem access is unchanged. It owns task admission,\nstate, forge and worktree operations, container lifecycle, and the broker when\nthe embedded deployment is selected. It does not run an autonomous model loop.\n\nNATS has two supported deployment shapes:\n\n| mode | meaning |\n| --- | --- |\n| `embedded` | `archied` owns an in-process JetStream server (default). |\n| `external` | `archied` and workers connect to the configured NATS URL. |\n\nBoth shapes have identical task semantics: one container and one full-task\nrequest per workflow. Broker placement must not select a different executor.\nThe legacy `agent` section and `containers.enabled` key remain decode-only\nmigration inputs. `nats.mode = \"off\"`, per-stage NATS, in-process execution,\nand subprocess execution are not production choices.\n\nSQLite remains authoritative for task state. NATS is the sole autonomous work\nhandoff. SQLite recovery may identify work that needs republishing, but it must\nnot cause `archied` to call `workflow.Run` locally.\n\n## Embedded reachability and authentication\n\nAn embedded listener uses a cryptographically random bearer token generated for\neach daemon start. The token exists only in process memory and the environment\nof managed worker containers; it is never written to config or logs.\n\nFor a native daemon with managed containers, startup resolves the Docker bridge\nthe workers will join. The listener binds only to that bridge's host gateway\naddress on a random port. Both the native daemon and workers use that same\nreachable endpoint, and every client supplies the generated token. Binding a\nDocker bridge address keeps the listener off ordinary LAN interfaces without\npublishing a host port. A configured user bridge is respected; otherwise the\nDocker default bridge is used. A network without a usable local IPv4 gateway is\na startup error for autonomous execution.\n\nIf Docker is unavailable, interactive chat may still start and embedded NATS\nmay remain loopback-only, but autonomous tasks park with an explicit container\ncapability failure. They never fall back to host execution.\n\n## Ownership and lifecycle\n\n- `internal/infrastructure/eventbus/nats` owns the authenticated embedded\n server and exposes its runtime endpoint, not the server implementation.\n- `internal/container` resolves the worker bridge and gateway and owns task\n container lifecycle.\n- `internal/app` composition selects embedded or external broker deployment,\n freezes the connected runtime endpoint for worker environments, and wires the\n full-task handoff.\n- `cmd/archied` remains process input only as the domain migration reaches this\n composition path.\n\nThe daemon starts the embedded server before its client, closes clients before\nthe server, and keeps JetStream data beneath the daemon data directory. NATS URL\nand token are startup-built values: a reload cannot send new workers to a broker\ndifferent from the one the daemon is using.\n"
"body": "# Embedded NATS execution -- decision\n\n**Status:** Finalised\n\n**Date:** 2026-08-24\n\n**Beads epic:** `archie-core-q15y`\n\nThis decision supersedes the position that embedded NATS was only a\ndistribution mechanism and could not be an agent-execution topology. That was\ntrue only because the embedded listener was unauthenticated loopback. It left a\nsecond production architecture in which `archied` ran autonomous workflows in\nits own process, weakening the isolation boundary that managed task containers\nexist to provide.\n\n## One execution architecture, two broker deployments\n\nEvery autonomous repository workflow is handed over as one complete task via\nNATS and runs in a task-scoped `archie-agent` container. `archied` remains a\nnative, long-lived orchestration and interactive-chat process; its operator\nconfigured host filesystem access is unchanged. It owns task admission,\nstate, forge and worktree operations, container lifecycle, and the broker when\nthe embedded deployment is selected. It does not run an autonomous model loop.\n\nNATS has two supported deployment shapes:\n\n| mode | meaning |\n| ---------- | --------------------------------------------------------- |\n| `embedded` | `archied` owns an in-process JetStream server (default). |\n| `external` | `archied` and workers connect to the configured NATS URL. |\n\nBoth shapes have identical task semantics: one container and one full-task\nrequest per workflow. Broker placement must not select a different executor.\nThe legacy `agent` section and `containers.enabled` key remain decode-only\nmigration inputs. `nats.mode = \"off\"`, per-stage NATS, in-process execution,\nand subprocess execution are not production choices.\n\nSQLite remains authoritative for task state. NATS is the sole autonomous work\nhandoff. SQLite recovery may identify work that needs republishing, but it must\nnot cause `archied` to call `workflow.Run` locally.\n\n## Embedded reachability and authentication\n\nAn embedded listener uses a cryptographically random bearer token generated for\neach daemon start. The token exists only in process memory and the environment\nof managed worker containers; it is never written to config or logs.\n\nFor a native daemon with managed containers, startup resolves the Docker bridge\nthe workers will join. The listener binds only to that bridge's host gateway\naddress on a random port. Both the native daemon and workers use that same\nreachable endpoint, and every client supplies the generated token. Binding a\nDocker bridge address keeps the listener off ordinary LAN interfaces without\npublishing a host port. A configured user bridge is respected; otherwise the\nDocker default bridge is used. A network without a usable local IPv4 gateway is\na startup error for autonomous execution.\n\nIf Docker is unavailable, interactive chat may still start and embedded NATS\nmay remain loopback-only, but autonomous tasks park with an explicit container\ncapability failure. They never fall back to host execution.\n\n## Ownership and lifecycle\n\n- `internal/infrastructure/eventbus/nats` owns the authenticated embedded\n server and exposes its runtime endpoint, not the server implementation.\n- `internal/container` resolves the worker bridge and gateway and owns task\n container lifecycle.\n- `internal/app` composition selects embedded or external broker deployment,\n freezes the connected runtime endpoint for worker environments, and wires the\n full-task handoff.\n- `cmd/archied` remains process input only as the domain migration reaches this\n composition path.\n\nThe daemon starts the embedded server before its client, closes clients before\nthe server, and keeps JetStream data beneath the daemon data directory. NATS URL\nand token are startup-built values: a reload cannot send new workers to a broker\ndifferent from the one the daemon is using.\n"
},
{
"url": "/dev/prds/event-automation/",
"title": "Event automation: identified events, typed parameters, purpose-built agents",
"section": "PRDs",
"body": "# Event automation: identified events, typed parameters, purpose-built agents\n\n**Status:** Approved\n**Date:** 2026-09-23\n**Parent:** epic `archie-core-t2db`\n\n## Why this exists\n\nArchie is an event-driven automation system. Any system that can send a\nwebhook (a forge, an error tracker, a firewall, a monitoring stack) should be\nable to start an agent built for that job. The shape this replaces cannot:\n\n- A binding matches only the URL segment an event was posted to, and a source\n may have one binding. Two kinds of event from one sender cannot go to\n different workflows.\n- A mapping is a list of JSON paths written against one example payload.\n Nothing recognises what kind of event arrived.\n- Mapped values reach the task only as `key=value` lines in its body text.\n- Every task needs a repository and runs in a git worktree.\n- Every agent runs the same image with the same forwarded keys.\n\n## The model\n\n```\nsource ─▶ event type ─▶ mapping ─▶ binding ─▶ workflow ─▶ agent profile\n (identified) (params) (+ filter, (inputs, (image, tools)\n repo) profile)\n```\n\n### Sources\n\nA source is the endpoint one sender posts to. Its path is a generated UUIDv7\n(`/webhooks/capture/0199…`), so an endpoint cannot be guessed or collide. The\noperator may replace it with a custom path for a sender that cannot use that\nformat; a custom path must be unique and URL-safe, and is refused otherwise.\nA source owns the signing setting:\n\n- **Signed** (default). Archie generates the secret. Only events with a valid\n `X-Hub-Signature-256` or `X-Signature-256` HMAC are dispatched.\n- **Unsigned.** The operator turns signing off for a sender that cannot sign.\n The source and every event from it are marked unsigned in the inspector,\n the binding list and the task timeline. Turning signing off needs the same\n approval as arming a binding.\n\nUnauthenticated events on a signed source are captured and never\ndispatched.\n\n### Event types\n\nAn event type is a named kind of event from one source, such as\n`github / pull_request.opened` or `firewall / blocked_connection`. It is\ndefined by a match rule:\n\n- header equality (`X-GitHub-Event = pull_request`), and\n- payload conditions (`action = \"opened\"`, or a path being present).\n\nAn event type can be created two ways:\n\n- **From an example payload.** The operator pastes a payload (and optionally\n its headers), and archie converts it to the type's schema. No event needs to\n have arrived.\n- **From captures.** Archie proposes types from what has arrived, as below.\n\nEither way, archie infers the schema, not the operator:\n\n- Each capture gets a structural signature: the set of JSON paths with their\n value types, plus the headers that look like discriminators (`*-Event`,\n `*-Type`, `Content-Type`).\n- Captures from one source that share a signature are grouped. The inspector\n shows each group as a proposed event type, with its inferred schema, its\n number of events and a sample, until the operator names it or dismisses it.\n- The proposed match rule is the set of discriminators that separates the\n group from its siblings. The operator can edit it before saving.\n- A capture that matches no named type is shown as unidentified. It is never\n dispatched.\n\nTwo event types on one source whose rules can match the same event are\nrefused when the second one is saved.\n\n### Mappings\n\nA mapping belongs to an event type. It maps payload paths to named, typed\nparameters, and it is checked against the type's inferred schema, so a path\nthe type does not have is refused when the mapping is saved. Any number of\nbindings may reuse one mapping.\n\nEach mapping shows how many events it has matched, with the time of the most\nrecent, so an operator can see which mappings are live and which have never\nfired.\n\n### Workflows declare inputs\n\nA workflow definition declares its inputs:\n\n```yaml\nid: firewall-investigate\ninputs:\n src_ip: { type: string, required: true }\n severity: { type: string }\nrepository: none # none | optional | required\nprofile: network-investigator\nsteps: ...\n```\n\n- `repository: none` runs the agent in a scratch workspace with no clone.\n `required`, the default, gives the agent a worktree of the task's\n repository. `optional` gives it a worktree when the binding names a\n repository and a scratch workspace when it does not.\n- A workflow whose `repository` is not `required` may use only steps that need\n no repository. `agent.run` is one: it runs one agent mission and finishes\n the task as done, with no pull request.\n- The declared inputs reach the agent as structured data in the task brief\n and in the agent's context. They are not body text.\n- A workflow may declare `outputs`, the structured result it returns when it\n finishes.\n\n### Workflows call workflows\n\nA workflow step can call another woLine truncated
"body": "# Event automation: identified events, typed parameters, purpose-built agents\n\n**Status:** Approved\n**Date:** 2026-09-23\n**Parent:** epic `archie-core-t2db`\n\n## Why this exists\n\nArchie is an event-driven automation system. Any system that can send a\nwebhook (a forge, an error tracker, a firewall, a monitoring stack) should be\nable to start an agent built for that job. The shape this replaces cannot:\n\n- A binding matches only the URL segment an event was posted to, and a source\n may have one binding. Two kinds of event from one sender cannot go to\n different workflows.\n- A mapping is a list of JSON paths written against one example payload.\n Nothing recognises what kind of event arrived.\n- Mapped values reach the task only as `key=value` lines in its body text.\n- Every task needs a repository and runs in a git worktree.\n- Every agent runs the same image with the same forwarded keys.\n\n## The model\n\n```\nsource ─▶ event type ─▶ mapping ─▶ binding ─▶ workflow ─▶ agent profile\n (identified) (params) (+ filter, (inputs, (image, tools)\n repo) profile)\n```\n\n### Sources\n\nA source is the endpoint one sender posts to. Its path is a generated UUIDv7\n(`/webhooks/capture/0199…`), so an endpoint cannot be guessed or collide. The\noperator may replace it with a custom path for a sender that cannot use that\nformat; a custom path must be unique and URL-safe, and is refused otherwise.\nA source owns the signing setting:\n\n- **Signed** (default). Archie generates the secret. Only events with a valid\n `X-Hub-Signature-256` or `X-Signature-256` HMAC are dispatched.\n- **Unsigned.** The operator turns signing off for a sender that cannot sign.\n The source and every event from it are marked unsigned in the inspector,\n the binding list and the task timeline. Turning signing off needs the same\n approval as arming a binding.\n\nUnauthenticated events on a signed source are captured and never\ndispatched.\n\n### Event types\n\nAn event type is a named kind of event from one source, such as\n`github / pull_request.opened` or `firewall / blocked_connection`. It is\ndefined by a match rule:\n\n- header equality (`X-GitHub-Event = pull_request`), and\n- payload conditions (`action = \"opened\"`, or a path being present).\n\nAn event type can be created two ways:\n\n- **From an example payload.** The operator pastes a payload (and optionally\n its headers), and archie converts it to the type's schema. No event needs to\n have arrived.\n- **From captures.** Archie proposes types from what has arrived, as below.\n\nEither way, archie infers the schema, not the operator:\n\n- Each capture gets a structural signature: the set of JSON paths with their\n value types, plus the headers that look like discriminators (`*-Event`,\n `*-Type`, `Content-Type`).\n- Captures from one source that share a signature are grouped. The inspector\n shows each group as a proposed event type, with its inferred schema, its\n number of events and a sample, until the operator names it or dismisses it.\n- The proposed match rule is the set of discriminators that separates the\n group from its siblings. The operator can edit it before saving.\n- A capture that matches no named type is shown as unidentified. It is never\n dispatched.\n\nTwo event types on one source whose rules can match the same event are\nrefused when the second one is saved.\n\n### Mappings\n\nA mapping belongs to an event type. It maps payload paths to named, typed\nparameters, and it is checked against the type's inferred schema, so a path\nthe type does not have is refused when the mapping is saved. Any number of\nbindings may reuse one mapping.\n\nEach mapping shows how many events it has matched, with the time of the most\nrecent, so an operator can see which mappings are live and which have never\nfired.\n\n### Workflows declare inputs\n\nA workflow definition declares its inputs:\n\n```yaml\nid: firewall-investigate\ninputs:\n src_ip: { type: string, required: true }\n severity: { type: string }\nrepository: none # none | optional | required\nprofile: network-investigator\nsteps: ...\n```\n\n- `repository: none` runs the agent in a scratch workspace with no clone.\n `required`, the default, gives the agent a worktree of the task's\n repository. `optional` gives it a worktree when the binding names a\n repository and a scratch workspace when it does not.\n- A workflow whose `repository` is not `required` may use only steps that need\n no repository. `agent.run` is one: it runs one agent mission and finishes\n the task as done, with no pull request.\n- The declared inputs reach the agent as structured data in the task brief\n and in the agent's context. They are not body text.\n- A workflow may declare `outputs`, the structured result it returns when it\n finishes.\n\n### Workflows call workflows\n\nA workflow step can call another workflow.Line truncated
},
{
"url": "/dev/prds/event-capture-storage/",
"title": "Event capture storage -- decision",
"section": "PRDs",
"body": "# Event capture storage -- decision\n\n**Status:** Finalised\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.1`\n\n`webhook-intake-security.md` decided points 1-5 (auth split, approval gate,\nrate limits, blast radius, retention/redaction) and explicitly left the\nstorage mechanism open, forward-pointing at \"`7d5u.2`, embedded NATS.\" That\npointer predates `7d5u.3`'s 2026-08-22 narrowing, which assigned capture\nstorage to this bead by name and told it to decide NATS-vs-SQLite itself\nrather than inherit an answer. This document is that decision.\n\n## Decision: SQLite, not NATS JetStream\n\nCaptured events are stored in archied's existing SQLite database, in a new\n`captured_events` table following the same shape as `internal/store/events.go`\n(`internal/store`, `*Store`, SQL migrations inline in Go). No JetStream\nstream is introduced for capture.\n\n### Why\n\n**NATS availability does not make capture a broker concern.** NATS is now\nunconditional for autonomous workflow handoff, including embedded mode, but\ncapture is also used by deployments with no repository workflow configured.\nSQLite is guaranteed present because it backs daemon state, and keeps\ncapture inspection independent of broker retention and consumer lifecycle.\nThe original version of this decision cited optional NATS as an additional\nreason; that premise was superseded by `archie-core-q15y`, while the storage\nfit and independence arguments remain.\n\n**Capture's access pattern doesn't need what JetStream is for.** JetStream\nearns its complexity for reaction delivery (`7d5u.2`) because multiple\nindependent consumers need fan-out, at-least-once redelivery, and Ack/Nak\nsemantics -- exactly the trap `CLAUDE.md` documents about `WorkQueuePolicy`\nand overlapping consumers. Capture has exactly one writer (the HTTP handler)\nand one reader (a human via the dashboard inspector, `t2db.2`). There is no\ncompeting-consumer problem to solve and no redelivery semantics to get right,\nso JetStream's core value proposition doesn't apply here. A bounded SQL\ntable is a better fit on the merits, not merely as a fallback.\n\n**Reusing `7d5u.2`'s stream, once it exists, would still be wrong.** That\nstream is provisioned for fan-out reaction delivery with its own retention\npolicy decision. Capture's retention need -- age- and count-bounded, prune\non write, no replay -- is a different shape. Building a second stream just\nfor capture, gated on an unrelated bead landing first, would trade a small\namount of duplication now for a hard dependency on `7d5u.2`'s timeline that\nthis bead's own acceptance criteria say not to accrue by accident.\n\nThis does not foreclose NATS later. If cross-daemon capture sharing or\ndurable replay becomes a real requirement, that is a new decision made\nagainst a real need, not now against a speculative one.\n\n## Storage shape\n\n`captured_events` table (`internal/store/captures.go`, mirrors\n`internal/store/events.go`'s pattern):\n\n| column | type | notes |\n|-----------------|---------|-------------------------------------------------|\n| id | INTEGER | primary key, autoincrement |\n| received_at | TEXT | RFC3339Nano |\n| source | TEXT | opaque path segment chosen by the sender's operator |\n| remote_addr | TEXT | `RemoteAddr` at capture time |\n| content_type | TEXT | `Content-Type` header |\n| headers | TEXT | JSON, redacted |\n| body | TEXT | JSON, redacted (`webhookguard.RedactPayload`) |\n| authenticated | INTEGER | 0/1; always 0 until a source registers a secret (future: `t2db.4`) |\n\nIndexed on `(source, id)` for per-source listing and pruning, and `id` alone\nfor the global cap.\n\n## Disk-bound mechanics\n\nThree independent bounds, composed, per `webhook-intake-security.md` point 5\nand this bead's own \"capture cannot exhaust disk\" criterion:\n\n1. **Per-request size cap.** The HTTP handler reads the body through\n `http.MaxBytesReader` (256 KiB default, configurable). A single oversized\n POST is rejected (413) before redaction or storage sees it.\n2. **Per-remote-address rate limit.** `webhookguard.RateLimiter`, keyed by\n the request's remote address, applied before the body is even read.\n *Not* keyed by the `source` path segment: `RateLimiter`'s own doc comment\n states its bucket map assumes a bounded, operator-registered key space,\n never evicted. `source` is exactly the opposite here -- an unregistered,\n attacker-chosen URL segment, since capturing senders with no registration\n yet is this endpoint's entire purpose. Keying on it would let one sender\n bypass the limit by rotating the segment every request (a fresh key\n always starts with a full burst) and grow the bucket map without bounLine truncated
"body": "# Event capture storage -- decision\n\n**Status:** Finalised\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.1`\n\n`webhook-intake-security.md` decided points 1-5 (auth split, approval gate,\nrate limits, blast radius, retention/redaction) and explicitly left the\nstorage mechanism open, forward-pointing at \"`7d5u.2`, embedded NATS.\" That\npointer predates `7d5u.3`'s 2026-08-22 narrowing, which assigned capture\nstorage to this bead by name and told it to decide NATS-vs-SQLite itself\nrather than inherit an answer. This document is that decision.\n\n## Decision: SQLite, not NATS JetStream\n\nCaptured events are stored in archied's existing SQLite database, in a new\n`captured_events` table following the same shape as `internal/store/events.go`\n(`internal/store`, `*Store`, SQL migrations inline in Go). No JetStream\nstream is introduced for capture.\n\n### Why\n\n**NATS availability does not make capture a broker concern.** NATS is now\nunconditional for autonomous workflow handoff, including embedded mode, but\ncapture is also used by deployments with no repository workflow configured.\nSQLite is guaranteed present because it backs daemon state, and keeps\ncapture inspection independent of broker retention and consumer lifecycle.\nThe original version of this decision cited optional NATS as an additional\nreason; that premise was superseded by `archie-core-q15y`, while the storage\nfit and independence arguments remain.\n\n**Capture's access pattern doesn't need what JetStream is for.** JetStream\nearns its complexity for reaction delivery (`7d5u.2`) because multiple\nindependent consumers need fan-out, at-least-once redelivery, and Ack/Nak\nsemantics -- exactly the trap `CLAUDE.md` documents about `WorkQueuePolicy`\nand overlapping consumers. Capture has exactly one writer (the HTTP handler)\nand one reader (a human via the dashboard inspector, `t2db.2`). There is no\ncompeting-consumer problem to solve and no redelivery semantics to get right,\nso JetStream's core value proposition doesn't apply here. A bounded SQL\ntable is a better fit on the merits, not merely as a fallback.\n\n**Reusing `7d5u.2`'s stream, once it exists, would still be wrong.** That\nstream is provisioned for fan-out reaction delivery with its own retention\npolicy decision. Capture's retention need -- age- and count-bounded, prune\non write, no replay -- is a different shape. Building a second stream just\nfor capture, gated on an unrelated bead landing first, would trade a small\namount of duplication now for a hard dependency on `7d5u.2`'s timeline that\nthis bead's own acceptance criteria say not to accrue by accident.\n\nThis does not foreclose NATS later. If cross-daemon capture sharing or\ndurable replay becomes a real requirement, that is a new decision made\nagainst a real need, not now against a speculative one.\n\n## Storage shape\n\n`captured_events` table (`internal/store/captures.go`, mirrors\n`internal/store/events.go`'s pattern):\n\n| column | type | notes |\n| ------------- | ------- | ------------------------------------------------------------------ |\n| id | INTEGER | primary key, autoincrement |\n| received_at | TEXT | RFC3339Nano |\n| source | TEXT | opaque path segment chosen by the sender's operator |\n| remote_addr | TEXT | `RemoteAddr` at capture time |\n| content_type | TEXT | `Content-Type` header |\n| headers | TEXT | JSON, redacted |\n| body | TEXT | JSON, redacted (`webhookguard.RedactPayload`) |\n| authenticated | INTEGER | 0/1; always 0 until a source registers a secret (future: `t2db.4`) |\n\nIndexed on `(source, id)` for per-source listing and pruning, and `id` alone\nfor the global cap.\n\n## Disk-bound mechanics\n\nThree independent bounds, composed, per `webhook-intake-security.md` point 5\nand this bead's own \"capture cannot exhaust disk\" criterion:\n\n1. **Per-request size cap.** The HTTP handler reads the body through\n `http.MaxBytesReader` (256 KiB default, configurable). A single oversized\n POST is rejected (413) before redaction or storage sees it.\n2. **Per-remote-address rate limit.** `webhookguard.RateLimiter`, keyed by\n the request's remote address, applied before the body is even read.\n _Not_ keyed by the `source` path segment: `RateLimiter`'s own doc comment\n states its bucket map assumes a bounded, operator-registered key space,\n never evicted. `source` is exactly the opposite here -- an unregistered,\n attacker-chosen URL segment, since capturing senders with no registration\n yet is this endpoint's entire purpose. Keying on it would let one sendLine truncated
},
{
"url": "/dev/prds/event-sources-and-reactions/",
"title": "Event sources and reactions -- decision",
"section": "PRDs",
"body": "# Event sources and reactions -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-7d5u.1`, blocks `7d5u.2/.3/.4/.5`\n\nAnswers the four questions in `7d5u.1`'s description. Investigated against\nthe actual tree, not designed from scratch: three mechanisms already in this\ncodebase answer most of this, and the job here is picking the right one for\neach question and saying which packages change.\n\n## 1. In-process typed families, not out-of-process dispatch\n\nArchie has no out-of-process extension mechanism. The plugin engine\nrule (`docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`,\nmechanically checked by\n`internal/plugin/architecture_test.go`) keeps every capability family\nin-process behind a narrow typed registrar; NATS RPC exists for\ndaemon\u003c-\u003eagentexec, a different actor with a different trust boundary (task\nexecution, not third-party extension code), not a precedent for generic\nplugin dispatch. Neither epic's near-term payoff -- react to a labelled\nissue, bind a captured webhook to a workflow -- needs extension code in\nanother language or process. Building out-of-process dispatch now would be\ndesigning for a requirement neither epic states.\n\n`docs/architecture/plugins-and-extensions.md` does **not** need amending.\nThe line that looked like a blanket ban on hooks (`archie-core-7d5u`'s notes\nrecord the correction) is scoped to Workflow semantics specifically, and\nnothing decided here touches Workflow's ownership of its own contracts.\n\n## 2. Reaction delivery: `internal/eventbus`'s contract, a NEW stream\n\n`internal/eventbus.Publisher`/`Consumer` already has everything a reaction\nneeds: `PublishUnique(subject, idempotencyKey, payload)` for at-least-once\nwithout duplicate enqueue, `Ack`/`Nak` with \"a handler returning an error\ncauses redelivery.\" Do not design new delivery semantics; use this contract.\n\n**Do not reuse the existing `nats.Client` as-is.** `Config.StreamName` and\n`Config.Subjects` are already composition-supplied (\"the bus must not know\nwhich subjects belong to which domain,\" `config.go`), but the\nretention policy is not parameterised: `New` hardcodes\n`Retention: jetstream.WorkQueuePolicy` (`client.go`), the competing-consumer\npolicy correct for `ARCHIE_TASKS` task distribution -- one message, claimed by\nexactly one consumer -- and wrong for reactions. Two independent reactions\nboth wanting to see the same event under `WorkQueuePolicy` hit exactly the\ntrap `CLAUDE.md` already documents: overlapping filter subjects on a\nwork-queue stream mean the second consumer silently gets nothing. Reactions\nneed fan-out, not claim-once, so the client needs retention made a `Config`\nfield (defaulting to `WorkQueuePolicy` so `ARCHIE_TASKS` is\nunaffected), and a second stream (`ARCHIE_REACTIONS` or similar) configured\nunder a fan-out-capable policy, alongside the existing task-distribution\nstream -- not instead of it.\n\nThis is where `7d5u.2`'s embedded-vs-external axis attaches: whichever NATS\ninstance backs `ARCHIE_TASKS` also backs the reaction stream. NATS is not\noptional as a technology -- the choice is only\nwhether it runs as an external server or embedded in-process\n(`github.com/nats-io/nats-server/v2` is already a direct, test-proven\ndependency, just never wired into production startup). `7d5u.2` wires that;\nthis document does not re-decide it.\n\n## 3. Reactions in these two epics are producer-only\n\nNo veto, no mutation of in-flight work. Two existing shapes cover everything\neither epic actually needs, and neither is a hook that can block something\nelse:\n\n- **Cheap wake, no payload.** `internal/domain/curator/wake.go`'s\n `WakeOnPrimaryInput` subscribes to the lossy `events.Bus` and nudges a\n runtime to check sooner; a dropped event only delays a check-in, never\n loses work, because the trigger decision is a deterministic state read at\n pass time, not the event payload. Model any \"check something sooner\"\n reaction on this, unchanged.\n- **Produce new work, real payload.** `daemon.go`'s existing `pollNATS` -\u003e\n `publishTask` path is already exactly a reaction that observes forge state\n and produces a `workintake.TaskEnvelope`. A webhook source is a second\n producer into the same path, not a new capability -- see question 4.\n\nA reaction that can veto or mutate an *in-flight* task (block a PR from\nopening, alter a running stage) is a different, harder problem with its own\nordering and failure semantics, and belongs to `archie-core-h019` (adversarial\nself-review) if and when that epic needs one -- not here. Do not build a\ngeneral block-capable hook mechanism for either epic; nothing in their stated\nscope requires it, and it would duplicate whatever h019 eventually needs.\n\n## 4. No single generic intake interface; each domain keeps its own\n\nA `Source` interface generic enough to cover a forge issue, a chat message,\nand a cron tick wouldLine truncated
"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 centre",
"section": "PRDs",
"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
"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/",
@@ -334,37 +334,37 @@
"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/",
"title": "Inline review -- decision",
"section": "PRDs",
"body": "# Inline review -- decision\n\n**Status:** Finalised\n**Beads issue:** `archie-core-q9au`\n**Builds on:** `archie-core-h019` (adversarial self-review), `docs/architecture/adversarial-review.md`\n\n## Problem\n\nFindings reach the operator only as a flat list in the PR body\n(`renderPRReviewSection`, h019.6): `` - `file.go` (confirmed, error): \u003cdefect\u003e\n— \u003cscenario\u003e ``. That is a report *about* the code, not a review *of* it. A real\nreviewer anchors each finding to the line it is about, so the author sees it in\ncontext — and, when the fix is mechanical, attaches the replacement so it can be\napplied in one click.\n\nBoth halves are missing:\n\n- **No line-anchored comment.** `forge.Forge.Comment` posts to the PR\n *conversation* (`Issues.CreateComment`); nothing creates a review comment at\n `path` + `line`.\n- **No suggested fix.** `ReviewFinding` carries `File`/`Line`/`Defect`/\n `FailureScenario`/`Verdict`/`Level`/`Category` — no replacement code, so even\n an anchored comment could only describe the fix, not offer it.\n\n## Decisions\n\n### 1. A narrow, type-asserted write surface\n\nThe set of comments travels in one call, so a forge that can only carry them on\na submitted review needs one request rather than one per finding:\n\n```go\ntype ReviewCommentWriter interface {\n CreateReviewComments(ctx context.Context, owner, repo string, number int,\n comments []InlineReviewComment) error\n}\n```\n\nType-asserted like `PullRequestReader`/`PullRequestReviewReader`, so a forge\nthat cannot do it is skipped rather than faked. The stage reaches it through\n`workflow.Forger`, whose production implementation is `forgerpc.Client` — the\nworker holds no forge credentials, so the daemon's forgerpc server type-asserts\n`forge.ReviewCommentWriter` and answers an incapable forge with an error the\nbest-effort stage logs.\n\nThe comment's line is anchored to the pull request's **current head revision**,\nresolved inside each implementation rather than passed in by the caller: it is\nthe revision the comments are attached to, and the caller that produced the line\nnumbers holds no forge credentials to read it. The caller does pass the revision\nthose line numbers were **measured on** (`TaskContext.ReviewedHeadSHA`,\nrecorded when `StageOpenPR` opens the pull request), and the implementation\nposts only while the head it read still matches it — see §4.\n\nPer-forge reality, verified against the SDKs:\n\n- **GitHub** — direct: `PullRequests.CreateComment` with\n `{Body, Path, Line, Side: \"RIGHT\", CommitID}`.\n- **Gitea** — no direct inline-comment call. Inline comments ride on a submitted\n review (`CreatePullReview` with `Comments` and a `COMMENT` state). The Gitea\n implementation therefore submits a single `COMMENT`-state review carrying the\n findings, or the capability is simply absent (the type assertion skips it).\n Decided: implement Gitea as a `COMMENT`-state review; do not block the feature\n on it.\n\n### 2. `Suggestion`, and only on confirmed findings\n\n`ReviewFinding` gains an optional `Suggestion string` — the replacement text for\nthe anchored line, rendered as a fenced `suggestion` block (GitHub's one-click\n\"Commit suggestion\").\n\n**Only `confirmed` findings may carry one.** A wrong suggestion is a\none-click path to breaking code a reviewer then has to notice; `confirmed` is by\ndefinition the verdict the reviewer traced and can state the failure for. A\n`plausible` finding is a worry, and a worry gets a sentence, not a patch. This is\nthe h019.5 calibration rule reused, not a new one.\n\n`Suggestion` replaces the anchored line exactly, and is only rendered when\n`Verdict == confirmed`. Single-line only in this cut;\nmulti-line (GitHub's `StartLine`/`StartSide`) is a follow-up, because a\nmulti-line suggestion that is off by one line silently corrupts the file. The\nrule is enforced in `ReviewFinding.Validate` — an embedded newline is rejected\nthere, so the `record_finding` tool refuses it with feedback the model can act\non, rather than the renderer silently posting a fence that applies only its\nfirst line.\n\n### 3. Which findings are posted inline\n\nOnly findings that are **line-anchored** (`Line \u003e 0`). A whole-file finding\n(`Line == 0`, e.g. \"README.md is stale\") has no line to attach to and stays in\nthe PR-body list. The body section keeps listing everything, so it remains the\ncomplete record and the fallback.\n\nFindings that block never reach this path: a surviving blocking finding parks\nthe task before `StageOpenPR`, so there is no PR to comment on. Inline comments\nare the non-blocking, line-anchored subset — which is exactly the set that would\notherwise be a body-only list the author has to map back to lines by hand.\n\n### 4. A best-effort stage after `StageOpenPR`\n\nNew `StagePostReviewComments`, after `StageOpenPR`:\n\n1. Read the report stashed by `StageReview` (`tc.ReviewReport`, h019.6).\Line truncated
"body": "# Inline review -- decision\n\n**Status:** Finalised\n**Beads issue:** `archie-core-q9au`\n**Builds on:** `archie-core-h019` (adversarial self-review), `docs/architecture/adversarial-review.md`\n\n## Problem\n\nFindings reach the operator only as a flat list in the PR body\n(`renderPRReviewSection`, h019.6): ``- `file.go` (confirmed, error): \u003cdefect\u003e\n— \u003cscenario\u003e``. That is a report _about_ the code, not a review _of_ it. A real\nreviewer anchors each finding to the line it is about, so the author sees it in\ncontext — and, when the fix is mechanical, attaches the replacement so it can be\napplied in one click.\n\nBoth halves are missing:\n\n- **No line-anchored comment.** `forge.Forge.Comment` posts to the PR\n _conversation_ (`Issues.CreateComment`); nothing creates a review comment at\n `path` + `line`.\n- **No suggested fix.** `ReviewFinding` carries `File`/`Line`/`Defect`/\n `FailureScenario`/`Verdict`/`Level`/`Category` — no replacement code, so even\n an anchored comment could only describe the fix, not offer it.\n\n## Decisions\n\n### 1. A narrow, type-asserted write surface\n\nThe set of comments travels in one call, so a forge that can only carry them on\na submitted review needs one request rather than one per finding:\n\n```go\ntype ReviewCommentWriter interface {\n CreateReviewComments(ctx context.Context, owner, repo string, number int,\n comments []InlineReviewComment) error\n}\n```\n\nType-asserted like `PullRequestReader`/`PullRequestReviewReader`, so a forge\nthat cannot do it is skipped rather than faked. The stage reaches it through\n`workflow.Forger`, whose production implementation is `forgerpc.Client` — the\nworker holds no forge credentials, so the daemon's forgerpc server type-asserts\n`forge.ReviewCommentWriter` and answers an incapable forge with an error the\nbest-effort stage logs.\n\nThe comment's line is anchored to the pull request's **current head revision**,\nresolved inside each implementation rather than passed in by the caller: it is\nthe revision the comments are attached to, and the caller that produced the line\nnumbers holds no forge credentials to read it. The caller does pass the revision\nthose line numbers were **measured on** (`TaskContext.ReviewedHeadSHA`,\nrecorded when `StageOpenPR` opens the pull request), and the implementation\nposts only while the head it read still matches it — see §4.\n\nPer-forge reality, verified against the SDKs:\n\n- **GitHub** — direct: `PullRequests.CreateComment` with\n `{Body, Path, Line, Side: \"RIGHT\", CommitID}`.\n- **Gitea** — no direct inline-comment call. Inline comments ride on a submitted\n review (`CreatePullReview` with `Comments` and a `COMMENT` state). The Gitea\n implementation therefore submits a single `COMMENT`-state review carrying the\n findings, or the capability is simply absent (the type assertion skips it).\n Decided: implement Gitea as a `COMMENT`-state review; do not block the feature\n on it.\n\n### 2. `Suggestion`, and only on confirmed findings\n\n`ReviewFinding` gains an optional `Suggestion string` — the replacement text for\nthe anchored line, rendered as a fenced `suggestion` block (GitHub's one-click\n\"Commit suggestion\").\n\n**Only `confirmed` findings may carry one.** A wrong suggestion is a\none-click path to breaking code a reviewer then has to notice; `confirmed` is by\ndefinition the verdict the reviewer traced and can state the failure for. A\n`plausible` finding is a worry, and a worry gets a sentence, not a patch. This is\nthe h019.5 calibration rule reused, not a new one.\n\n`Suggestion` replaces the anchored line exactly, and is only rendered when\n`Verdict == confirmed`. Single-line only in this cut;\nmulti-line (GitHub's `StartLine`/`StartSide`) is a follow-up, because a\nmulti-line suggestion that is off by one line silently corrupts the file. The\nrule is enforced in `ReviewFinding.Validate` — an embedded newline is rejected\nthere, so the `record_finding` tool refuses it with feedback the model can act\non, rather than the renderer silently posting a fence that applies only its\nfirst line.\n\n### 3. Which findings are posted inline\n\nOnly findings that are **line-anchored** (`Line \u003e 0`). A whole-file finding\n(`Line == 0`, e.g. \"README.md is stale\") has no line to attach to and stays in\nthe PR-body list. The body section keeps listing everything, so it remains the\ncomplete record and the fallback.\n\nFindings that block never reach this path: a surviving blocking finding parks\nthe task before `StageOpenPR`, so there is no PR to comment on. Inline comments\nare the non-blocking, line-anchored subset — which is exactly the set that would\notherwise be a body-only list the author has to map back to lines by hand.\n\n### 4. A best-effort stage after `StageOpenPR`\n\nNew `StagePostReviewComments`, after `StageOpenPR`:\n\n1. Read the report stashed by `StageReview` (`tc.ReviewReport`, h019.6).\n2Line truncated
},
{
"url": "/dev/prds/mcp-tool-completion/",
"title": "MCP client and tool-guardrail completion",
"section": "PRDs",
"body": "# MCP client and tool-guardrail completion\n\n**Status:** Approved\n\nEpic: `archie-core-1786637493439-140-2cee2e9b` / GitHub `#161` (\"[EPIC] Tools:\ncentral registry, MCP client, guardrails\").\n\nThis document is scoped to five sub-features of that epic: MCP\nserver-initiated sampling, the per-server parallel-tool-calls flag, sandboxed\nMCP tool servers, a Firecracker sandbox backend, and sequential dispatch with\nper-result previews.\n\nOut of scope, and not to be touched: the central registry\n(`internal/tools/registry.go`), all three MCP transports (stdio/HTTP/SSE,\n`internal/tools/mcp/transport*.go`), reconnect-with-backoff\n(`transport.go`), guardrail loop detection\n(`internal/tools/guardrail.go`), idempotent/mutating classification\n(`internal/tools/classification.go`), concurrent tool dispatch (`#183`), and\nprogressive disclosure wiring (`internal/app/archied`). These are settled and\nproduction-wired.\n\n## Problem\n\n`bd search \"MCP client\"` shows five closed transport beads and one open:\nserver-initiated sampling (`#151`). `internal/tools/mcp/client.go`\nholds a single `callMu *sync.Mutex` that serialises every `tools/call`\nregardless of server — `ParallelToolCalls` does not exist on the `MCPServer`\nconfig struct (`internal/config/config.go`), confirming `#177` is a\nreal gap, not a stale bead. `#178` (wire MCP tool servers for the chat agent,\nsandboxed) and `#179` (Firecracker substrate) have no corresponding code —\nMCP servers run as whatever the config's `Command`/`Args` launches,\nunsandboxed. `#182` (sequential tool dispatch with per-result previews) is\nopen; concurrent dispatch (`#183`) is closed, so there are two dispatch paths\nand this PRD decides how they coexist.\n\n## Design\n\nSub-features are independent; there is no new shared type this document\nintroduces. Each section below stands alone.\n\n## MCP server-initiated sampling (`#151`)\n\n**Decision.** Implement as a callback on `mcp.Client`, not a second\ntransport. The MCP spec's `sampling/createMessage` request flows server→client\nover the same connection each transport already maintains\n(`transport.go`'s stdio/HTTP/SSE all multiplex request and response frames).\nAdd a `SamplingHandler func(context.Context, SamplingRequest) (SamplingResult, error)`\nfield to the client's config struct next to the existing transport fields,\ndefaulting to nil (server sampling requests get a JSON-RPC \"not supported\"\nerror when unset — never a silent drop).\n\n**Call site.** `internal/tools/mcp/client.go` — add the handler field and a\ndispatch branch in whatever function demuxes incoming server\nmessages by method name (the same switch that already routes\n`notifications/*`). Wire a concrete handler in\n`internal/app/archied/main.go` that routes the sampling request through the\nsame chat-model call path `chatGenerateOptions` already uses, so a\nserver-initiated sample gets the daemon's configured model, not a second\nprovider client.\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
"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 commenLine truncated
},
{
"url": "/dev/prds/memory-engine-unification/",
"title": "Memory engine unification: four scopes, CRUD, and one write path -- decision",
"section": "PRDs",
"body": "# Memory engine unification: four scopes, CRUD, and one write path -- decision\n\n**Status:** Approved\n**Date:** 2026-09-16\n**Findings:** `memory-4` and its dependants in the adversarial sweep\n(`.local/issue-tracker`); the real defect is the split described below, for\nwhich `memory-4` is a symptom\n**Supersedes:** the draft `memory-turn-context.md` (its synchronous-read\nargument survives and is reused; its `Manager` method and consumer-owned port do\nnot)\n**Settles:** four open items in `docs/architecture/migration-decisions.md#5`\n(listed at the end)\n\n## Problem\n\nThere are **two live memory stores for one assistant**, split by which component\nwrites them, and the chat turn reads neither.\n\n| Family | Written by | Root | Format |\n|---|---|---|---|\n| `internal/memory` (`Manager`, `builtin.Provider`) | the chat agent's `memory_edit` tool via `memorytoolprovider` (`bootstrap.go`) | `\u003cworkDir\u003e/memory` | `MEMORY.md` / `USER.md` |\n| `internal/domain/memory` + `internal/infrastructure/memory` | the session curator (`sessioncurator.go`) | `\u003cworkDir\u003e/memory-engine` | identity-keyed blocks |\n\nThey share no code, no format and no scope vocabulary. Neither reaches a prompt:\n`Manager.SystemPromptBlock` (`internal/memory/manager.go`) has no production\ncaller anywhere, so the agent can write memory through a tool and never read it\nback.\n\nThree further defects fall out of the same split:\n\n1. **The engine's contract is not CRUD.** `Store` is `Write`/`Query`/`List`/\n `Forget` — create, read, delete, and **no Update**. The retired file provider\n *does* have `handleAdd`/`handleReplace`/`handleRemove`, so the family being\n deleted is operationally richer than its replacement.\n2. **There is no scope model.** The contract carries one opaque `Identity\n string`, and the curator fills it with a **session id** (`sessioncurator.go`)\n — which is none of the four scopes `docs/architecture/agent-system.md`\n requires, and stops meaning anything when the session ends.\n3. **The chat turn has no user identity on half the channels.** Telegram and\n email populate `SenderID` with a person; the dashboard populates it with\n nothing, and a webhook populates it with nothing either — a route path names\n a source, not a person, so `webhook.go` leaves `SenderID` empty and carries\n the route in `Inbound.BudgetKey` for rate limiting. `sender_id` is persisted\n (`session_store_postgres.go`), so whatever a channel puts there reaches the\n consumers that read it.\n\n`agent-system.md` says the write-scope selection and cross-scope sharing\nrules \"require a focused memory design decision\". This is that decision.\n\n## Decision\n\n### 1. One engine, addressed by four typed scopes\n\n`internal/domain/memory` is the only memory engine. `Observation.Identity`,\n`Query.Identity`, `Record.Identity` and `List(identity)` are deleted, not\nextended: a field whose meaning depends on the caller cannot carry a scope.\n\n```go\ntype ScopeKind string\n\nconst (\n ScopeGlobal ScopeKind = \"global\" // shared across the application\n ScopeAgent ScopeKind = \"agent\" // private to one Agent\n ScopeUser ScopeKind = \"user\" // one user, across their Agents\n ScopeAgentUser ScopeKind = \"agent-user\" // one Agent's relationship with one user\n)\n\ntype Scope struct {\n Kind ScopeKind\n Agent AgentID // required for ScopeAgent, ScopeAgentUser\n User IdentityID // required for ScopeUser, ScopeAgentUser\n}\n\nfunc (s Scope) Validate() error // rejects a component present where it is not required\nfunc (s Scope) Key() string // canonical, collision-free storage key\n```\n\n`AgentID` and `IdentityID` are opaque. This package never resolves or\ncanonicalises them.\n\nA turn's resolved identity is one value:\n\n```go\ntype Subject struct {\n AgentID AgentID\n UserID IdentityID // \"\" when the channel carries no per-person identity\n}\n\nfunc (s Subject) Scopes() []Scope // readable, most specific first\nfunc (s Subject) WritableScopes() []Scope // never includes ScopeGlobal\n```\n\n**Access control is naming a scope, and nothing else.** The read path names\nexactly the scopes of the resolved `Subject`; the engine never unions beyond what\nit is handed and applies no policy of its own. An engine that enforced policy\nwould need to know about channels, sessions and bindings, and every backend would\nreimplement it. \"Agent-wide is private to its owning Agent by default\"\n(`agent-system.md`) falls out mechanically, because `ScopeAgent{a}` and\n`ScopeAgent{b}` are different storage keys.\n\n`ScopeGlobal` is never model-writable. Writing it is an operator action; nothing\nproduces one yet, but the contract models it because the read set includes it.\n\n### 2. CRUD, with revisions retained\n\n```go\ntype Store interface {\n Create(ctx context.Context, in NewRecord) (Record, error)\n Get(ctx context.ContexLine truncated
"body": "# Memory engine unification: four scopes, CRUD, and one write path -- decision\n\n**Status:** Approved\n**Date:** 2026-09-16\n**Findings:** `memory-4` and its dependants in the adversarial sweep\n(`.local/issue-tracker`); the real defect is the split described below, for\nwhich `memory-4` is a symptom\n**Supersedes:** the draft `memory-turn-context.md` (its synchronous-read\nargument survives and is reused; its `Manager` method and consumer-owned port do\nnot)\n**Settles:** four open items in `docs/architecture/migration-decisions.md#5`\n(listed at the end)\n\n## Problem\n\nThere are **two live memory stores for one assistant**, split by which component\nwrites them, and the chat turn reads neither.\n\n| Family | Written by | Root | Format |\n| ----------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------- | ----------------------- |\n| `internal/memory` (`Manager`, `builtin.Provider`) | the chat agent's `memory_edit` tool via `memorytoolprovider` (`bootstrap.go`) | `\u003cworkDir\u003e/memory` | `MEMORY.md` / `USER.md` |\n| `internal/domain/memory` + `internal/infrastructure/memory` | the session curator (`sessioncurator.go`) | `\u003cworkDir\u003e/memory-engine` | identity-keyed blocks |\n\nThey share no code, no format and no scope vocabulary. Neither reaches a prompt:\n`Manager.SystemPromptBlock` (`internal/memory/manager.go`) has no production\ncaller anywhere, so the agent can write memory through a tool and never read it\nback.\n\nThree further defects fall out of the same split:\n\n1. **The engine's contract is not CRUD.** `Store` is `Write`/`Query`/`List`/\n `Forget` — create, read, delete, and **no Update**. The retired file provider\n _does_ have `handleAdd`/`handleReplace`/`handleRemove`, so the family being\n deleted is operationally richer than its replacement.\n2. **There is no scope model.** The contract carries one opaque `Identity\nstring`, and the curator fills it with a **session id** (`sessioncurator.go`)\n — which is none of the four scopes `docs/architecture/agent-system.md`\n requires, and stops meaning anything when the session ends.\n3. **The chat turn has no user identity on half the channels.** Telegram and\n email populate `SenderID` with a person; the dashboard populates it with\n nothing, and a webhook populates it with nothing either — a route path names\n a source, not a person, so `webhook.go` leaves `SenderID` empty and carries\n the route in `Inbound.BudgetKey` for rate limiting. `sender_id` is persisted\n (`session_store_postgres.go`), so whatever a channel puts there reaches the\n consumers that read it.\n\n`agent-system.md` says the write-scope selection and cross-scope sharing\nrules \"require a focused memory design decision\". This is that decision.\n\n## Decision\n\n### 1. One engine, addressed by four typed scopes\n\n`internal/domain/memory` is the only memory engine. `Observation.Identity`,\n`Query.Identity`, `Record.Identity` and `List(identity)` are deleted, not\nextended: a field whose meaning depends on the caller cannot carry a scope.\n\n```go\ntype ScopeKind string\n\nconst (\n ScopeGlobal ScopeKind = \"global\" // shared across the application\n ScopeAgent ScopeKind = \"agent\" // private to one Agent\n ScopeUser ScopeKind = \"user\" // one user, across their Agents\n ScopeAgentUser ScopeKind = \"agent-user\" // one Agent's relationship with one user\n)\n\ntype Scope struct {\n Kind ScopeKind\n Agent AgentID // required for ScopeAgent, ScopeAgentUser\n User IdentityID // required for ScopeUser, ScopeAgentUser\n}\n\nfunc (s Scope) Validate() error // rejects a component present where it is not required\nfunc (s Scope) Key() string // canonical, collision-free storage key\n```\n\n`AgentID` and `IdentityID` are opaque. This package never resolves or\ncanonicalises them.\n\nA turn's resolved identity is one value:\n\n```go\ntype Subject struct {\n AgentID AgentID\n UserID IdentityID // \"\" when the channel carries no per-person identity\n}\n\nfunc (s Subject) Scopes() []Scope // readable, most specific first\nfunc (s Subject) WritableScopes() []Scope // never includes ScopeGlobal\n```\n\n**Access control is naming a scope, and nothing else.** The read path names\nexactly the scopes of the resolved `Subject`; the engine never unions beyond what\nit is handed and applies no policy of its own. An engine that enforced policy\nwould need to know about channels, sessions and bindings, and every backend would\nreimplement it. \"Agent-wide is private to its owning Agent by default\"\n(`agent-system.md`) falls out mechanically, because `SLine truncated
},
{
"url": "/dev/prds/messaging-service-boundary/",
"title": "Messaging Service boundary and transport design",
"section": "PRDs",
"body": "# Messaging Service boundary and transport design\n\n**Status:** Approved\n**Revision:** 1 \n**Date:** 2026-09-19 \n**Beads issue:** `archie-core-8cda.6.1` \n**Parent:** [`service-decomposition.md`](/dev/prds/service-decomposition/) \n**Prerequisites:** Gateway contract extraction (Phase 1), State Store extraction (Phase 2), UI extraction (Phase 3)\n\nThis document is the authoritative specification for Phase 4: Messaging Service extraction. It fixes the process boundary, configuration ownership, client contracts, security posture, readiness behaviour, channel invariants, and deletion criteria required by `archie-core-8cda.6` and its child tasks.\n\n## Decision\n\nThe Messaging Service (`cmd/archie-messaging`, composed via `internal/app/archiemessaging`) owns external channel connections (Telegram, email, webhook) and dispatches inbound messages and commands to the standalone Gateway Service over gRPC via `messaging.ChatContract`.\n\nIt is a peer service to the UI Service and the daemon:\n- 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
"body": "# Messaging Service boundary and transport design\n\n**Status:** Approved\n**Revision:** 1 \n**Date:** 2026-09-19 \n**Beads issue:** `archie-core-8cda.6.1` \n**Parent:** [`service-decomposition.md`](/dev/prds/service-decomposition/) \n**Prerequisites:** Gateway contract extraction (Phase 1), State Store extraction (Phase 2), UI extraction (Phase 3)\n\nThis document is the authoritative specification for Phase 4: Messaging Service extraction. It fixes the process boundary, configuration ownership, client contracts, security posture, readiness behaviour, channel invariants, and deletion criteria required by `archie-core-8cda.6` and its child tasks.\n\n## Decision\n\nThe Messaging Service (`cmd/archie-messaging`, composed via `internal/app/archiemessaging`) owns external channel connections (Telegram, email, webhook) and dispatches inbound messages and commands to the standalone Gateway Service over gRPC via `messaging.ChatContract`.\n\nIt is a peer service to the UI Service and the daemon:\n\n- It serves external chat participants across configured communication platforms.\n- It consumes Gateway's `messaging.ChatContract` exclusively for chat turn execution, streaming, session queries, cancellation, persona selection, and task control actions.\n- It holds no direct database connections, owns no LLM execution or model provider credentials, and has no dependency on the daemon runtime or the UI HTTP server.\n\n## Boundary and Ownership\n\n| Concern | Messaging Service owns | Messaging Service consumes | Messaging Service must not own or link |\n| ---------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------ |\n| **Channel transports** | Telegram bot long-polling, Email IMAP/SMTP loops, Inbound Webhook HTTP listener | Gateway `ChatContract` | Direct LLM providers, model runtimes, tokenizer libraries |\n| **Turn dispatch** | Inbound message packaging, typing indicators, live streaming updates | `ChatContract.Route`, `ChatContract.Stream` | `gateway.Router`, `runtime.Runtime`, agent prompt builders |\n| **Sessions \u0026 History** | Platform-to-session key mapping, conversation thread ID translation | `ChatContract.GetSession`, `RecentMessages`, `RecentTurns` | store implementations, `SessionStore` database handles |\n| **Control \u0026 Actions** | Platform command parsing (`/status`, `/tasks`, `/cancel`, `/stop`, `/persona`) | `ChatContract.Snapshot`, `ApplyTaskAction`, `Cancel`, `SetPersona` | `daemon.Daemon`, workflow execution engine, worktree operations |\n| **Task Approvals** | Channel interactive keyboards, approval callbacks | `ChatContract.ApplyTaskAction` | Direct task status mutations, forge comment posters |\n| **Configuration** | Platform bot tokens, allowed sender/user IDs, webhook listen ports | `[chat.*]` channel configs, Gateway target/token | `config.Holder`, forge tokens, repo configs, agent container specs |\n| **Readiness** | Messaging process liveness, channel connectivity, Gateway probe | Gateway `ChatContract.Snapshot` | Internal daemon subsystem probes |\n\n## Target Service Shape\n\n1. **Binary entry point**: `cmd/archie-messaging/main.go` parses CLI flags (`-config`, `-config-overlay`, `-gateway-target`, `-gateway-token`) and hands execution to `internal/app/archiemessaging.Run`.\n2. **Application composition**: `internal/app/archiemessaging/` wires:\n - Config loading scoped strictly to `[chat.*]` and `[services.gateway]`.\n - Secret resolution for channel credentials (e.g. Telegram bot token).\n - Gateway gRPC client (`internal/infrastructure/gatewayrpc.Client`).\n - Channel lifecycle managers (`internal/channels/status`).\n - Channel instances (`internal/channels/telegram`, `email`, `webhook`).\n3. **Turn and Stream Execution**:\n - Channels adapt inbound platform messages to `messaging.Inbound`.\n - Streaming channels (Telegram) consume `ChatContract.Stream(ctx, inbound)` which returns `\u003c-chan messaging.ChatEvent`, mapping `started`, `delta`, `tool`, `media`, `done`, and `error` events directly to live message frames.\n - Non-streaming channels (email, synchronous webhooks) consume `ChatContract.Route(ctx, inbound)`.\n\n## Load-Bearing Channel Invariants\n\nThe Messaging Service preserves existing invariants defined in `AGENTS.md` and channel documentation:\n\n1. **Telegram long-polliLine truncated
},
{
"url": "/dev/prds/module-position/",
"title": "Module position -- design",
"section": "PRDs",
"body": "# Module position -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n\n## Problem\n\n`eda-playbook-engine.md` names four logic positions a playbook action can\ntarget: Workflow, Module, Channel, Forge. Workflow (`t2db.9`/`.10`/`.11`)\nand the standalone lint tool (`t2db.12`) are shipped. Module -- the\nposition that makes an action \"not restricted to code-generation\" -- has\nnot started, because it needs a schema-generation mechanism the parent\ndoc deliberately deferred: \"This document does not attempt to design the\nfull generator.\" This is that design.\n\n## Do not invent a new mechanism -- generalise the one used three times\n\nYaegi-interpreted extension code with a fixed, resolved-by-name exported\nfunction already exists in this codebase for three surfaces, and all three\nfollow the identical shape:\n\n| Surface | Fixed signature | Export path | Symbol table |\n|---|---|---|---|\n| Custom gate (`internal/gate/gateeval`) | `func(gate.GateContext) []gate.Finding` | `\"gate.Check\"` | `gateextract.Symbols` |\n| Workflow stage plugin (`skillbuild`) | stage-specific | skill-declared | `wfextract.Symbols` |\n| Skill plugin (`internal/skill/plugin.go`) | `func(string) string` | `\"main.Run\"` | none (stdlib only) |\n\nEach is: read a `.go` file -\u003e `yaegiutil.New` with that surface's symbol\ntable -\u003e `yaegiutil.Resolve[T](i, src, exportPath)` -\u003e call the resolved\nfunction wrapped in `yaegiutil.Safe` for panic recovery. **Module is a\nfourth instance of this same shape**, parameterised by action kind instead\nof hardcoded to one fixed signature. No new interpreter construction, no\nnew panic-recovery mechanism, no new symbol-table generation tool --\n`go generate ... yaegi extract` is already how `wfextract`/`gateextract`\nare produced that way (see their `//go:generate` directives), and Module\nschema generation reuses that exact command.\n\n## No generic `Module` interface -- one typed contract per action kind\n\nThe plugin engine rule's invariant 1 requires \"real capability-specific\noperations,\" and invariant 5 forbids adding capability methods to a\ngeneric interface. A single `Module` interface with `Run(args any) (any,\nerror)` would be exactly the untyped hook the rule (and\n`event-sources-and-reactions.md`'s rejection of a generic `Source`\ninterface) exists to prevent -- restating the mistake the whole EDA\ndocument was written to move away from (`wfextract`'s hardcoded\n`reflect.ValueOf(workflow.Implement)` table is what a closed, un-typed-per-\ncase system already looks like in this repo).\n\nInstead, **each action kind is its own tiny package with its own\ngenerated contract**, exactly like `gate.GateContext`/`gate.Finding` are\none hand-written Go file that `gateextract` turns into a Yaegi symbol\ntable:\n\n```go\n// internal/domain/eda/module/notify/types.go (hand-written, the schema source)\npackage notify\n\n// SchemaVersion is independent of a playbook's own workflow_version, per\n// eda-playbook-engine.md's schema-versioning point.\nconst SchemaVersion = 1\n\ntype Args struct {\n Channel string\n Message string\n}\n\ntype Result struct {\n Delivered bool\n}\n\n//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name notifyextract github.com/samcharles93/archie-core/internal/domain/eda/module/notify\n```\n\nA Yaegi module implementing this kind exports a fixed function name\nagainst these generated types, resolved the same way `gate.Check` is:\n\n```go\n// operator's notify.go, interpreted at load\npackage notify\n\nfunc Run(a notify.Args) notify.Result { ... }\n```\n\n`internal/domain/eda/module/notify` is the schema; `notifyextract.Symbols`\nis its generated Yaegi bridge; the operator's file is the implementation.\nThis is the same three-way split `internal/gate` / `gateextract` /\n`.archie/gate.go` already has.\n\n## The registry: `ModuleRegistry`, keyed by kind, not a service locator\n\nPer invariant 2 (owning family manager) and invariant 4 (narrow host\naccess): a `ModuleRegistry` in `internal/domain/eda/module` maps a kind\nname (`\"notify\"`, `\"image-gen\"`) to a resolved, type-erased invoker --\nthe same `map[string]reflect.Value`-shaped erasure `wfextract.Symbols`\nalready uses to bridge Yaegi and Go, not a new pattern and not exposed as\nthe plugin's contract with the daemon (the plugin still writes and is\nchecked against a fully typed `func(Args) Result`; the registry's\ninternal storage is the only place erasure appears, exactly as it already\ndoes inside `wfextract`).\n\n```go\ntype ModuleRegistry struct {\n // kind -\u003e (validate args against generated schema, invoke, marshal result)\n}\n\nfunc (r *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 *MoLine truncated
},
{
"url": "/dev/prds/multi-action-playbooks/",
@@ -382,55 +382,55 @@
"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. **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"
"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,\nBaseSHA, 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,\nbaseRef)` 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/",
"title": "Orgs, workspaces and access control",
"section": "PRDs",
"body": "# Orgs, workspaces and access control\n\n**Status:** Approved\n**Date:** 2026-09-24\n**Parent:** `docs/prds/event-automation.md`, epic `archie-core-t2db`\n\n## Why this exists\n\nArchie has no tenant boundary and no access control: one operator, one shared\ntoken, and no org on any record. The event automation design needs orgs to own\nsources, bindings, workflows and agents, and an agent's reach must be decided\nby the policies over it, never by the event that started it.\n\n## Concepts\n\n- **Org.** The tenant boundary. An instance admin creates an org and adds its\n first owner. An owner or admin adds further members by the sign-in\n provider's subject or email.\n- **Workspace.** A division of an org, named freely (`networking-prd`,\n `service-desk-dev`), with an optional `environment` attribute (any string)\n that policies can test. Sources, event types, mappings, bindings and runs\n belong to a workspace.\n- **Identity.** Every principal is an identity (`internal/domain/identity`):\n - a person is an identity of kind `user`, bound to the sign-in provider\n through the existing subject binding;\n - an agent is an identity of kind `bot` or `service_account`, assigned to\n one org and granted access, secrets and permissions the way a user is.\n\n Signing in and verifying credentials stay separate from identity; identity\n is who acts. Memberships, roles, grants and audit records all reference the\n identity ID.\n- **Instance admin.** Operates the installation: orgs, the sign-in provider,\n instance policies. Instance admins see an org's resources only as members\n of it.\n\n## What belongs where\n\n| Level | Owns |\n|---|---|\n| Instance | the shipped workflow catalogue, instance policies |\n| Org | members, identities and their grants, secrets, agent profiles, workspaces, org workflows and their enabled state |\n| Workspace | sources, event types, mappings, bindings, runs, captures, run events and logs, chat sessions, memory |\n\nEvery owned record carries its `org_id`, and workspace records also carry their\n`workspace_id`. An identity, secret or profile is used in a workspace only\nafter the org grants it to that workspace.\n\nA secret is granted to an identity. An agent profile holds the container\nimage, tools and network access, and no secrets; this supersedes the secret\nreferences in `event-automation.md`'s agent profiles.\n\nA workflow names the identity it runs as. A workflow called by another runs\nas its own identity, and the caller's identity must be permitted `run` on it.\n\n## Access decisions\n\n### Where it lives\n\n- `internal/domain/access` owns the policy schema, the action list, how\n principals and resources are turned into policy entities, and the\n `Authorizer` contract.\n- The Cedar implementation, using `github.com/cedar-policy/cedar-go`, lives in\n `internal/infrastructure/access`; `internal/app` wires it.\n- Exactly two places call the `Authorizer`: the dashboard and API request\n path, and dispatch. Every other service verifies a credential and never\n evaluates policy.\n\n### The model\n\n- **Principal:** an identity, with its memberships, roles and grants.\n- **Resource:** the record acted on, with its workspace and org as parents,\n its type, owner and state.\n- **Action:** one of `read`, `create`, `update`, `delete`, `approve`, `run`,\n `read_logs`, `read_secret`, `manage_members`, `manage_identities`,\n `manage_policies`.\n- **Context:** the event's signature result, the address it came from, the\n time, and the run and step when the principal is an agent.\n\n### The policy chain\n\n```\ninstance (+ network rules) ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object\n```\n\n- **Instance** policies hold across every org. They include network rules:\n which addresses may deliver events to any source on the instance.\n- **Object** policies attach to one object (an event source, a secret, an\n identity, a binding, a workflow): \"only `soc-responder` may read this\n secret\", \"this source accepts events only from 10.20.0.0/16\".\n- A request is allowed only if every level with policies for it permits it. A\n lower level narrows and never widens; a forbid at any level wins; with no\n permit the request is denied.\n- The shipped role policies mean the org level always has policies, so an\n object or workspace policy alone can never grant access.\n- Archie ships an instance policy, which no org can remove, forbidding any\n principal to act on a resource outside the orgs it belongs to.\n\n### Storing and changing policies\n\n- Policies are stored in the State Store per level, versioned, and every\n change is an audit event naming who made it.\n- A policy is checked against the current schema when it is saved, and every\n stored policy is checked again when archie starts. An invalid org, workspace\n or object policy makes its level deny everything and is reported as a health\n issue naming the policy and the errLine truncated
"body": "# Orgs, workspaces and access control\n\n**Status:** Approved\n**Date:** 2026-09-24\n**Parent:** `docs/prds/event-automation.md`, epic `archie-core-t2db`\n\n## Why this exists\n\nArchie has no tenant boundary and no access control: one operator, one shared\ntoken, and no org on any record. The event automation design needs orgs to own\nsources, bindings, workflows and agents, and an agent's reach must be decided\nby the policies over it, never by the event that started it.\n\n## Concepts\n\n- **Org.** The tenant boundary. An instance admin creates an org and adds its\n first owner. An owner or admin adds further members by the sign-in\n provider's subject or email.\n- **Workspace.** A division of an org, named freely (`networking-prd`,\n `service-desk-dev`), with an optional `environment` attribute (any string)\n that policies can test. Sources, event types, mappings, bindings and runs\n belong to a workspace.\n- **Identity.** Every principal is an identity (`internal/domain/identity`):\n - a person is an identity of kind `user`, bound to the sign-in provider\n through the existing subject binding;\n - an agent is an identity of kind `bot` or `service_account`, assigned to\n one org and granted access, secrets and permissions the way a user is.\n\n Signing in and verifying credentials stay separate from identity; identity\n is who acts. Memberships, roles, grants and audit records all reference the\n identity ID.\n\n- **Instance admin.** Operates the installation: orgs, the sign-in provider,\n instance policies. Instance admins see an org's resources only as members\n of it.\n\n## What belongs where\n\n| Level | Owns |\n| --------- | ---------------------------------------------------------------------------------------------------------------- |\n| Instance | the shipped workflow catalogue, instance policies |\n| Org | members, identities and their grants, secrets, agent profiles, workspaces, org workflows and their enabled state |\n| Workspace | sources, event types, mappings, bindings, runs, captures, run events and logs, chat sessions, memory |\n\nEvery owned record carries its `org_id`, and workspace records also carry their\n`workspace_id`. An identity, secret or profile is used in a workspace only\nafter the org grants it to that workspace.\n\nA secret is granted to an identity. An agent profile holds the container\nimage, tools and network access, and no secrets; this supersedes the secret\nreferences in `event-automation.md`'s agent profiles.\n\nA workflow names the identity it runs as. A workflow called by another runs\nas its own identity, and the caller's identity must be permitted `run` on it.\n\n## Access decisions\n\n### Where it lives\n\n- `internal/domain/access` owns the policy schema, the action list, how\n principals and resources are turned into policy entities, and the\n `Authorizer` contract.\n- The Cedar implementation, using `github.com/cedar-policy/cedar-go`, lives in\n `internal/infrastructure/access`; `internal/app` wires it.\n- Exactly two places call the `Authorizer`: the dashboard and API request\n path, and dispatch. Every other service verifies a credential and never\n evaluates policy.\n\n### The model\n\n- **Principal:** an identity, with its memberships, roles and grants.\n- **Resource:** the record acted on, with its workspace and org as parents,\n its type, owner and state.\n- **Action:** one of `read`, `create`, `update`, `delete`, `approve`, `run`,\n `read_logs`, `read_secret`, `manage_members`, `manage_identities`,\n `manage_policies`.\n- **Context:** the event's signature result, the address it came from, the\n time, and the run and step when the principal is an agent.\n\n### The policy chain\n\n```\ninstance (+ network rules) ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object\n```\n\n- **Instance** policies hold across every org. They include network rules:\n which addresses may deliver events to any source on the instance.\n- **Object** policies attach to one object (an event source, a secret, an\n identity, a binding, a workflow): \"only `soc-responder` may read this\n secret\", \"this source accepts events only from 10.20.0.0/16\".\n- A request is allowed only if every level with policies for it permits it. A\n lower level narrows and never widens; a forbid at any level wins; with no\n permit the request is denied.\n- The shipped role policies mean the org level always has policies, so an\n object or workspace policy alone can never grant access.\n- Archie ships an instance policy, which no org can remove, forbidding any\n principal to act on a resource outside the orgs it belongs to.\n\n### Storing and changing policies\n\n- Policies are stored in the State Store per level, versioned, and every\n changeLine truncated
},
{
"url": "/dev/prds/payload-field-mapping/",
"title": "Payload field mapping -- decision",
"section": "PRDs",
"body": "# Payload field mapping -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.3`, depends on `t2db.1`, blocks `t2db.4`\n\nAnswers what a \"mapping\" is, where it lives, and what \"resolve against a\nreal event\" means precisely enough to implement. `t2db.4` (binding: matcher\n+ mapping + workflow) is out of scope -- this bead ships the mapping\nconcept and its preview only, as a standalone entity `t2db.4` will later\nreference by ID.\n\n## Decision: a new `internal/domain/mapping` package, SQLite storage\n\n\u003e Storage superseded: every store now lives in PostgreSQL behind\n\u003e `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`\n\u003e (`docs/prds/state-store-contract.md`). SQLite names below describe the\n\u003e original design.\n\n`internal/domain/mapping` owns the mapping vocabulary and the pure\nresolve/preview rule; `internal/store` persists it (mirrors\n`captures.go`'s shape exactly -- inline schema const, narrow store\ninterface, `*store.Store` implementation); `internal/webui/api_mapping.go`\nis the transport. This follows `docs/prds/event-capture-storage.md`'s own\nplacement precedent: `internal/store` is where this daemon's persistence\nalready lives, not `internal/infrastructure` (that layer holds\ncross-domain services -- config, eventbus, modelcatalog -- not this\ndaemon's primary store).\n\n### Why a domain package and not just a store table\n\nResolving a path against a payload and deciding \"missing vs null vs\ntype-changed\" is a rule, not a query -- CLAUDE.md's domain layer owns\n\"language, state, rules, operations\" precisely so this logic is testable\nwithout a database and reusable by `t2db.4`'s runtime trigger path without\neither package importing the other's transport concerns.\n\n## Mapping shape\n\n```go\ntype Mapping struct {\n\tID int64\n\tName string\n\tSourceHint string // free-text label (e.g. \"sentry\"), organisational only -- not enforced against Capture.Source\n\tFields []Field\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\ntype Field struct {\n\tName string // the name the workflow receives\n\tPath string // dot/bracket path into the payload, see below\n\tType FieldType // expected type, checked at resolve time\n\tRequired bool // Required=false + missing is not a failure; Required=false + wrong type still is\n}\n\ntype FieldType string // \"string\" | \"number\" | \"bool\" | \"object\" | \"array\" | \"any\"\n```\n\n`SourceHint` is advisory only: an operator authors a mapping by clicking\nthrough one example capture, but the mapping is not pinned to that\ncapture's exact source string, because `t2db.4`'s matcher (not this bead)\ndecides which events a binding applies to. Pinning here would duplicate\nthat decision in the wrong layer.\n\n## Path syntax\n\nDot-separated keys with `[N]` for array indices: `data.items[0].id`. No\nwildcards, no filters, no external library -- the grammar is exactly what a\nclick-through UI needs to express (this key, then this key, then this\nindex), and every path in a mapping was generated by clicking a value in a\nreal payload, never hand-written against a spec. A hand-rolled parser\n(~30 lines: split on `.`, strip `[N]` suffixes) is less risk than a new\ndependency for a grammar this small.\n\n## Resolve semantics (the preview AND the future runtime path)\n\n```go\nfunc Resolve(fields []Field, payload []byte) (values map[string]any, failures []Failure)\n\ntype Failure struct {\n\tFieldName string\n\tPath string\n\tReason string // \"missing\" | \"null\" | \"type_mismatch\"\n}\n```\n\nDecode with `json.Decoder.UseNumber()` (matches `webhookguard.RedactPayload`'s\nexisting convention) so int/float distinction survives for type checking.\nWalk each field's path independently -- one field's failure does not stop\nresolution of the others, because the whole point of preview is showing\nthe operator every problem at once, not the first one.\n\n- Path segment doesn't exist, or indexes past an array's length -\u003e `missing`\n- Path resolves to JSON `null` -\u003e `null`\n- Path resolves to a value whose JSON type doesn't match `Field.Type`\n (`\"any\"` always matches) -\u003e `type_mismatch`\n- `Required: false` suppresses `missing` only, never `null` or\n `type_mismatch` -- a field that's present but the wrong shape is always\n worth surfacing, since silently coercing it is exactly the \"agent\n confabulates around a blank field\" failure this bead exists to prevent.\n\n**This is the same function both consumers use.** `t2db.3`'s preview calls\nit against an operator-picked capture and renders every result, pass or\nfail, in the UI -- that satisfies this bead's \"fail loudly\" acceptance\ncriterion, because at this stage the only runtime consumer of a mapping\n*is* the human previewing it. `t2db.4` will call the identical function\nwhen a live event triggers a binding and turn any non-emptyLine truncated
"body": "# Payload field mapping -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.3`, depends on `t2db.1`, blocks `t2db.4`\n\nAnswers what a \"mapping\" is, where it lives, and what \"resolve against a\nreal event\" means precisely enough to implement. `t2db.4` (binding: matcher\n\n- mapping + workflow) is out of scope -- this bead ships the mapping\n concept and its preview only, as a standalone entity `t2db.4` will later\n reference by ID.\n\n## Decision: a new `internal/domain/mapping` package, SQLite storage\n\n\u003e Storage superseded: every store now lives in PostgreSQL behind\n\u003e `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`\n\u003e (`docs/prds/state-store-contract.md`). SQLite names below describe the\n\u003e original design.\n\n`internal/domain/mapping` owns the mapping vocabulary and the pure\nresolve/preview rule; `internal/store` persists it (mirrors\n`captures.go`'s shape exactly -- inline schema const, narrow store\ninterface, `*store.Store` implementation); `internal/webui/api_mapping.go`\nis the transport. This follows `docs/prds/event-capture-storage.md`'s own\nplacement precedent: `internal/store` is where this daemon's persistence\nalready lives, not `internal/infrastructure` (that layer holds\ncross-domain services -- config, eventbus, modelcatalog -- not this\ndaemon's primary store).\n\n### Why a domain package and not just a store table\n\nResolving a path against a payload and deciding \"missing vs null vs\ntype-changed\" is a rule, not a query -- CLAUDE.md's domain layer owns\n\"language, state, rules, operations\" precisely so this logic is testable\nwithout a database and reusable by `t2db.4`'s runtime trigger path without\neither package importing the other's transport concerns.\n\n## Mapping shape\n\n```go\ntype Mapping struct {\n\tID int64\n\tName string\n\tSourceHint string // free-text label (e.g. \"sentry\"), organisational only -- not enforced against Capture.Source\n\tFields []Field\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\ntype Field struct {\n\tName string // the name the workflow receives\n\tPath string // dot/bracket path into the payload, see below\n\tType FieldType // expected type, checked at resolve time\n\tRequired bool // Required=false + missing is not a failure; Required=false + wrong type still is\n}\n\ntype FieldType string // \"string\" | \"number\" | \"bool\" | \"object\" | \"array\" | \"any\"\n```\n\n`SourceHint` is advisory only: an operator authors a mapping by clicking\nthrough one example capture, but the mapping is not pinned to that\ncapture's exact source string, because `t2db.4`'s matcher (not this bead)\ndecides which events a binding applies to. Pinning here would duplicate\nthat decision in the wrong layer.\n\n## Path syntax\n\nDot-separated keys with `[N]` for array indices: `data.items[0].id`. No\nwildcards, no filters, no external library -- the grammar is exactly what a\nclick-through UI needs to express (this key, then this key, then this\nindex), and every path in a mapping was generated by clicking a value in a\nreal payload, never hand-written against a spec. A hand-rolled parser\n(~30 lines: split on `.`, strip `[N]` suffixes) is less risk than a new\ndependency for a grammar this small.\n\n## Resolve semantics (the preview AND the future runtime path)\n\n```go\nfunc Resolve(fields []Field, payload []byte) (values map[string]any, failures []Failure)\n\ntype Failure struct {\n\tFieldName string\n\tPath string\n\tReason string // \"missing\" | \"null\" | \"type_mismatch\"\n}\n```\n\nDecode with `json.Decoder.UseNumber()` (matches `webhookguard.RedactPayload`'s\nexisting convention) so int/float distinction survives for type checking.\nWalk each field's path independently -- one field's failure does not stop\nresolution of the others, because the whole point of preview is showing\nthe operator every problem at once, not the first one.\n\n- Path segment doesn't exist, or indexes past an array's length -\u003e `missing`\n- Path resolves to JSON `null` -\u003e `null`\n- Path resolves to a value whose JSON type doesn't match `Field.Type`\n (`\"any\"` always matches) -\u003e `type_mismatch`\n- `Required: false` suppresses `missing` only, never `null` or\n `type_mismatch` -- a field that's present but the wrong shape is always\n worth surfacing, since silently coercing it is exactly the \"agent\n confabulates around a blank field\" failure this bead exists to prevent.\n\n**This is the same function both consumers use.** `t2db.3`'s preview calls\nit against an operator-picked capture and renders every result, pass or\nfail, in the UI -- that satisfies this bead's \"fail loudly\" acceptance\ncriterion, because at this stage the only runtime consumer of a mapping\n_is_ the human previewing it. `t2db.4` will call the identical function\nwhen a live event triggers a binding and turn any nonLine truncated
},
{
"url": "/dev/prds/playbook-expression-syntax/",
"title": "Playbook data-flow and condition syntax",
"section": "PRDs",
"body": "# Playbook data-flow and condition syntax\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.14` (expression environment).\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 Line truncated
},
{
"url": "/dev/prds/pr-review-remediation/",
"title": "PR review comment remediation -- decision",
"section": "PRDs",
"body": "# PR review comment remediation -- decision\n\n**Status:** Approved\n**Date:** 2026-09-10, amended and ratified 2026-09-19\n**Beads issue:** (filed as `archie-core-…`, parent: `archie-core-7d5u` event sources and typed reactions)\n\nAnswers: how archie reacts to review comments on a PR it opened, from a human\nor from another review bot, and remediates them. Built on two settled decisions — the 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/",
"title": "Progressive tool disclosure (bridge tools) — wiring",
"section": "PRDs",
"body": "# Progressive tool disclosure (bridge tools) — wiring\n\n**Status:** Finalised\n**Date:** 2026-08-15\n**Compound:** the \"keep the LLM tool schema small, give full access on demand\" work (issue #167)\n\n## Decision\n\nThe bridge-tool pattern is **implemented and tested** in\n`internal/tools/disclosure.go` (`tool_search`, `tool_describe`, `tool_call`\n+ `ContextPressureGate` + `DisclosureMode`, section 17.14/17.15) — but it is\n**never wired into the daemon**. `BridgeTools` and `ContextPressureGate` are\nreferenced only in `disclosure_test.go`. This task is therefore a **wiring**\ntask, not a feature build.\n\nWire the existing bridge into the per-chat-turn toolset:\n\n1. **Compose a per-turn registry** seeded from the base registry plus the\n per-turn extra tools, register the bridge tools into it, and hand it to both\n the bridge handlers and the `ContextPressureGate`.\n2. **Run the gate in `chatGenerateOptions`** (`internal/app/archied/main.go`)\n so it decides full-vs-bridge disclosure per turn, and build the\n `core.ToolSet` from the gate's filtered output.\n3. **Thread the model's context window** into the preparation seam so the gate\n has a real `ContextWindowSize` (it disables itself at 0, falling back to\n full disclosure).\n\n## Why the naive \"register extras into the base registry\" is wrong\n\n`BuildToolSetFrom` (`internal/agentexec/toolset.go`) documents the invariant:\n\n\u003e the task tools carry the calling gateway's identity, so there is one set of\n\u003e them per gateway and they **cannot live in the process-wide registry**.\n\nThis is confirmed by wiring: gateways are per-channel\n(`telegram_setup.go` build a `TurnRunner` per channel), and the extra\ntools (`task_*`, `session_*`, `dashboard_*`) close over that channel's identity\nvia `TurnRunnerConfig` (`turn.go`). Registering them into `b.toolReg` would\nlet channel A's session/identity-bound tools be invoked by channel B — a real\ncross-channel privilege bug. The bridge handlers iterate `reg.All()`\n(`disclosure.go`), so the extras must be discoverable; the fix is a\n**per-turn composed registry**, not a mutation of the process-wide one.\n\n## Shape of the change\n\n### 1. Per-turn composed registry + gate inside `chatGenerateOptions`\n\nReplace the current base-set + extra-set merge (`main.go`) with a single\ncomposed-registry pass:\n\n```go\n// new helper, in internal/tools/disclosure.go or the archied wiring package\nfunc ComposeForTurn(reg *tools.Registry, extra []tools.ToolEntry) (*tools.Registry, error) {\n composed := tools.NewRegistry()\n for _, e := range reg.All() {\n if err := composed.Register(e); err != nil { return nil, err }\n }\n for _, e := range extra {\n if err := composed.Register(e); err != nil { return nil, err }\n }\n if _, err := composed.RegisterBatch(tools.BridgeTools(composed)); err != nil {\n return nil, err\n }\n return composed, nil\n}\n```\n\n`chatGenerateOptions` then:\n\n```go\ncomposed, err := ComposeForTurn(registry, extra)\n// ...\ngate := tools.NewContextPressureGate(contextWindow)\ngate.SetAlwaysVisible(...) // e.g. session/session_resume, task/task_list\ndisclosed := gate.FilterTools(composed)\ntoolSet, err := agentexec.BuildToolSetFrom(disclosed, toolOpts)\n```\n\n`FilterTools` (`disclosure.go`) already returns `all` in full mode and\n`bridge + always-visible` in bridge mode, and `BuildToolSetFrom` re-applies\navailability/approval/schema rules, so the two layers compose cleanly.\n\n### 2. Thread context window through the preparation seam\n\n`ContextPressureGate` disables at `ContextWindowSize == 0`. The model context\nwindow is resolved in `TurnRunner.prepareTurn` (`turn.go`) but is not\npassed to `TurnModel.Prepare`. Extend the seam:\n\n```go\ntype TurnPrepareContext struct {\n Model string\n Extra []tools.ToolEntry\n ContextWindow int // model's context window in tokens; 0 = gate disabled\n}\n```\n\n`TurnModel.Prepare(ctx, context TurnPrepareContext)`; `prepareTurn` fills\n`ContextWindow` from `modelDetails.ContextWindow`. This touches one interface\n(`turn.go`), one production impl (`chat_turn_model.go`), and the test\nmock (`turn_test.go`).\n\n### 3. Bridge-handler parity note\n\n`bridgeCallHandler` calls `e.Handler` directly (`disclosure.go`), bypassing\n`toolExecute` — so a `tool_call` invocation does **not** apply `CapPayload` /\n`MaxResultSizeChars` spilling or `OnToolCall` reporting, and it pre-refuses\n`RequiresApproval` tools (`disclosure.go`). This is acceptable for the\nfirst wiring (the bridge is read-discover/describe plus a guarded call), but a\nlater hardening should route the invoked tool through the same\ncap/approval path the model's direct call uses. Recorded as a follow-up, not a\nblocker for this task.\n\n## Files touched\n\n- `internal/app/archied/main.go` — `chatGenerateOptions` composes + gates.\n- `internal/app/archied/chat_turn_model.go` — `PreLine truncated
"body": "# Progressive tool disclosure (bridge tools) — wiring\n\n**Status:** Finalised\n**Date:** 2026-08-15\n**Compound:** the \"keep the LLM tool schema small, give full access on demand\" work (issue #167)\n\n## Decision\n\nThe bridge-tool pattern is **implemented and tested** in\n`internal/tools/disclosure.go` (`tool_search`, `tool_describe`, `tool_call`\n\n- `ContextPressureGate` + `DisclosureMode`, section 17.14/17.15) — but it is\n **never wired into the daemon**. `BridgeTools` and `ContextPressureGate` are\n referenced only in `disclosure_test.go`. This task is therefore a **wiring**\n task, not a feature build.\n\nWire the existing bridge into the per-chat-turn toolset:\n\n1. **Compose a per-turn registry** seeded from the base registry plus the\n per-turn extra tools, register the bridge tools into it, and hand it to both\n the bridge handlers and the `ContextPressureGate`.\n2. **Run the gate in `chatGenerateOptions`** (`internal/app/archied/main.go`)\n so it decides full-vs-bridge disclosure per turn, and build the\n `core.ToolSet` from the gate's filtered output.\n3. **Thread the model's context window** into the preparation seam so the gate\n has a real `ContextWindowSize` (it disables itself at 0, falling back to\n full disclosure).\n\n## Why the naive \"register extras into the base registry\" is wrong\n\n`BuildToolSetFrom` (`internal/agentexec/toolset.go`) documents the invariant:\n\n\u003e the task tools carry the calling gateway's identity, so there is one set of\n\u003e them per gateway and they **cannot live in the process-wide registry**.\n\nThis is confirmed by wiring: gateways are per-channel\n(`telegram_setup.go` build a `TurnRunner` per channel), and the extra\ntools (`task_*`, `session_*`, `dashboard_*`) close over that channel's identity\nvia `TurnRunnerConfig` (`turn.go`). Registering them into `b.toolReg` would\nlet channel A's session/identity-bound tools be invoked by channel B — a real\ncross-channel privilege bug. The bridge handlers iterate `reg.All()`\n(`disclosure.go`), so the extras must be discoverable; the fix is a\n**per-turn composed registry**, not a mutation of the process-wide one.\n\n## Shape of the change\n\n### 1. Per-turn composed registry + gate inside `chatGenerateOptions`\n\nReplace the current base-set + extra-set merge (`main.go`) with a single\ncomposed-registry pass:\n\n```go\n// new helper, in internal/tools/disclosure.go or the archied wiring package\nfunc ComposeForTurn(reg *tools.Registry, extra []tools.ToolEntry) (*tools.Registry, error) {\n composed := tools.NewRegistry()\n for _, e := range reg.All() {\n if err := composed.Register(e); err != nil { return nil, err }\n }\n for _, e := range extra {\n if err := composed.Register(e); err != nil { return nil, err }\n }\n if _, err := composed.RegisterBatch(tools.BridgeTools(composed)); err != nil {\n return nil, err\n }\n return composed, nil\n}\n```\n\n`chatGenerateOptions` then:\n\n```go\ncomposed, err := ComposeForTurn(registry, extra)\n// ...\ngate := tools.NewContextPressureGate(contextWindow)\ngate.SetAlwaysVisible(...) // e.g. session/session_resume, task/task_list\ndisclosed := gate.FilterTools(composed)\ntoolSet, err := agentexec.BuildToolSetFrom(disclosed, toolOpts)\n```\n\n`FilterTools` (`disclosure.go`) already returns `all` in full mode and\n`bridge + always-visible` in bridge mode, and `BuildToolSetFrom` re-applies\navailability/approval/schema rules, so the two layers compose cleanly.\n\n### 2. Thread context window through the preparation seam\n\n`ContextPressureGate` disables at `ContextWindowSize == 0`. The model context\nwindow is resolved in `TurnRunner.prepareTurn` (`turn.go`) but is not\npassed to `TurnModel.Prepare`. Extend the seam:\n\n```go\ntype TurnPrepareContext struct {\n Model string\n Extra []tools.ToolEntry\n ContextWindow int // model's context window in tokens; 0 = gate disabled\n}\n```\n\n`TurnModel.Prepare(ctx, context TurnPrepareContext)`; `prepareTurn` fills\n`ContextWindow` from `modelDetails.ContextWindow`. This touches one interface\n(`turn.go`), one production impl (`chat_turn_model.go`), and the test\nmock (`turn_test.go`).\n\n### 3. Bridge-handler parity note\n\n`bridgeCallHandler` calls `e.Handler` directly (`disclosure.go`), bypassing\n`toolExecute` — so a `tool_call` invocation does **not** apply `CapPayload` /\n`MaxResultSizeChars` spilling or `OnToolCall` reporting, and it pre-refuses\n`RequiresApproval` tools (`disclosure.go`). This is acceptable for the\nfirst wiring (the bridge is read-discover/describe plus a guarded call), but a\nlater hardening should route the invoked tool through the same\ncap/approval path the model's direct call uses. Recorded as a follow-up, not a\nblocker for this task.\n\n## Files touched\n\n- `internal/app/archied/main.go` — `chatGenerateOptions` composes + gates.\n- `internal/app/archied/chat_turn_model.go` Line truncated
},
{
"url": "/dev/prds/public-and-dev-docs/",
"title": "Public and development documentation -- design",
"section": "PRDs",
"body": "# Public and development documentation -- design\n\n**Status:** Draft\n**Date:** 2026-09-22\n\n## Problem\n\nOne published set carries both kinds of document. A reader who wants to know\nwhat Archie is and how to point an event at it lands in a sidebar that also\nholds the repository organisation rules, the migration decision register, the\npackage review procedure and five PRDs. The PRDs are there for a reason that\nhas nothing to do with the reader: settled architecture cites them, and the\ngenerator refuses a link whose target it holds back, so publishing them was the\nonly way to keep those citations alive.\n\nMixing them is not an exposure problem. Every one of these documents can be\npublic. It is a navigation problem: a customer reading the site meets\ncontributor material with no signal that it is not for them.\n\n## Decision\n\nOne source tree, two published sets, two artifacts, two URL bases.\n\n| Set | Holds | Served under | Artifact |\n|---|---|---|---|\n| Public | `index.md`, `guides/` | `/docs/` | `docs/data/generated/docs.json` |\n| Development | `architecture/`, `prds/` | `/dev/` | `docs/data/generated/dev-docs.json` |\n\n`archive/`, `inspiration/`, `news/` and `github-token.md` stay out of both, for\nthe reasons the generator already records.\n\nThe two artifacts have the same shape. A renderer reads a second file and\nserves it under a second base; it needs no new field and no set discriminator,\nbecause the file a page arrived in is the set it belongs to.\n\n## Consequences the design depends on\n\n**Every PRD publishes.** Selective PRD publication existed to keep citations\nfrom settled architecture working. With both cited and citing documents in the\ndevelopment set, that pressure is gone, and the rule that produced it goes with\nit: `prds/` is a development tree, not a list of exceptions.\n\n**Cross-set links resolve.** A link from a public page to an architecture page\nrewrites to the development set's absolute path, and the reverse works the same\nway. Both sets are generated in one pass over one url map, so a link and its\ntarget cannot disagree about where the target lives. The generator's refusal\nstill fires, now only for a target genuinely in neither set.\n\n**Assets keep the public base.** `docs/public/` is one file set, referenced\nfrom either set, and serving one file under two paths would invent a second\nlocation for it.\n\n**The sidebar stays derived from the directory layout**, per set. A page added\nunder a directory appears without a second edit, which is the property the\ncurrent generator has and the reason its tree mirrors the tree on disk.\n\n## The public set is thin, and that is the honest state\n\nTwo pages: the landing page and the playbook guide. Nothing is lost by the\nsplit, because a reader was never served by the seventeen architecture pages\nnext to them. The pages a public site needs (installation, configuration\nreference, the event sources, the actions a playbook can run) are written into\n`guides/` and a `reference/` tree as they are written, and each lands in the\npublic set with no generator change.\n\n## Verification\n\n- `task docs:artifact` writes both files; `task docs:artifact:check` fails on a\n stale copy of either, without touching the tree.\n- A link from the public set to a development page, and a link the other way,\n each resolve to the other set's base path in the generated body.\n- A link to a page in neither set fails the generator, naming the file, the\n line and the target.\n- `docsgen` accounts for both artifacts, so neither tool reports the other's\n file as unowned.\n"
"body": "# Public and development documentation -- design\n\n**Status:** Draft\n**Date:** 2026-09-22\n\n## Problem\n\nOne published set carries both kinds of document. A reader who wants to know\nwhat Archie is and how to point an event at it lands in a sidebar that also\nholds the repository organisation rules, the migration decision register, the\npackage review procedure and five PRDs. The PRDs are there for a reason that\nhas nothing to do with the reader: settled architecture cites them, and the\ngenerator refuses a link whose target it holds back, so publishing them was the\nonly way to keep those citations alive.\n\nMixing them is not an exposure problem. Every one of these documents can be\npublic. It is a navigation problem: a customer reading the site meets\ncontributor material with no signal that it is not for them.\n\n## Decision\n\nOne source tree, two published sets, two artifacts, two URL bases.\n\n| Set | Holds | Served under | Artifact |\n| ----------- | ------------------------ | ------------ | ----------------------------------- |\n| Public | `index.md`, `guides/` | `/docs/` | `docs/data/generated/docs.json` |\n| Development | `architecture/`, `prds/` | `/dev/` | `docs/data/generated/dev-docs.json` |\n\n`archive/`, `inspiration/`, `news/` and `github-token.md` stay out of both, for\nthe reasons the generator already records.\n\nThe two artifacts have the same shape. A renderer reads a second file and\nserves it under a second base; it needs no new field and no set discriminator,\nbecause the file a page arrived in is the set it belongs to.\n\n## Consequences the design depends on\n\n**Every PRD publishes.** Selective PRD publication existed to keep citations\nfrom settled architecture working. With both cited and citing documents in the\ndevelopment set, that pressure is gone, and the rule that produced it goes with\nit: `prds/` is a development tree, not a list of exceptions.\n\n**Cross-set links resolve.** A link from a public page to an architecture page\nrewrites to the development set's absolute path, and the reverse works the same\nway. Both sets are generated in one pass over one url map, so a link and its\ntarget cannot disagree about where the target lives. The generator's refusal\nstill fires, now only for a target genuinely in neither set.\n\n**Assets keep the public base.** `docs/public/` is one file set, referenced\nfrom either set, and serving one file under two paths would invent a second\nlocation for it.\n\n**The sidebar stays derived from the directory layout**, per set. A page added\nunder a directory appears without a second edit, which is the property the\ncurrent generator has and the reason its tree mirrors the tree on disk.\n\n## The public set is thin, and that is the honest state\n\nTwo pages: the landing page and the playbook guide. Nothing is lost by the\nsplit, because a reader was never served by the seventeen architecture pages\nnext to them. The pages a public site needs (installation, configuration\nreference, the event sources, the actions a playbook can run) are written into\n`guides/` and a `reference/` tree as they are written, and each lands in the\npublic set with no generator change.\n\n## Verification\n\n- `task docs:artifact` writes both files; `task docs:artifact:check` fails on a\n stale copy of either, without touching the tree.\n- A link from the public set to a development page, and a link the other way,\n each resolve to the other set's base path in the generated body.\n- A link to a page in neither set fails the generator, naming the file, the\n line and the target.\n- `docsgen` accounts for both artifacts, so neither tool reports the other's\n file as unowned.\n"
},
{
"url": "/dev/prds/release-stream-and-commit-rules/",
"title": "One release stream, one page per version, and commit rules — decision",
"section": "PRDs",
"body": "# One release stream, one page per version, and commit rules — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** `RELEASING.md` for the process this changes, `AGENTS.md` for the\ncommit rules it enforces, and `tools/newsgen` for the artifact shape.\n\n**Supersedes:** `docs/prds/news-and-releases.md`, sections \"Source of truth\" and\n\"Two components\" — one changelog replaces two, and one page per version replaces\none page per component. Its remaining decisions stand.\n\n## Decision\n\n**A release is one version covering whatever changed.** One changelog holds every\nrelease section, one generated page holds every version's notes, and an operator\ncutting a release names one version.\n\n## One changelog\n\nEvery release section lives in `CHANGELOG.md`, newest first. `CHANGELOG.archied.md`\nand `CHANGELOG.archie.md` are deleted, and `CHANGELOG.md` stops being a pointer to\nthem. The changelog is the only source of release prose, and tags are not a source:\nCI and deployment check out shallow, so tags are absent from a site build while the\nchangelog is always present.\n\n### The merged history\n\nTwo version streams become one file, so a version that both components released\ncarries one heading and one date: **the newest date among that version's sections**,\nbecause a version's date is when the last part of it shipped. Where a component's own\ndate differs from it, that component's section label carries its own date, so the\nper-component fact survives the merge rather than being collapsed into the heading.\n\nThe merged history holds 65 versions: 33 that both components released, 31 only\n`archied`, and one only `archie`, from 64 and 34 sections respectively, so 98\npublished pages become 65. `## [Unreleased]` is not a release -- it carries no\nversion and gets no page -- but it stays at the top of the file, because it is\nthe one place unfinished work is recorded. Counting `##` headings rather than\nreleases overcounts by one.\n\nThis ambiguity is historical only. One version stream with one tag gives a version\nexactly one date, so the rule represents the merged past rather than a design that has\nto hold.\n\nThe merge is verified by content, not by the generator succeeding: the section count\nper source, the merged version set equal to the union of both sources with nothing\nextra, and every section title still present. A generator that agrees with the file it\njust wrote is evidence of nothing.\n\n## One version stream\n\n**`GATEWAY` and `RUNTIME` stop being release inputs.** `release:prepare` and\n`release:tag` take one version, and `tools/release.sh` loses the two flags.\n\nThey may stay as build-time stamps, because a binary must still report what it\ncontains. A release that must name three versions forces an operator to pass skip\nvalues for components that did not change, and that ceremony is what this decision\nremoves — along with the drift it allows, where two components' tags fall a release\napart.\n\n**Per-component detail stays, as sections inside the release.** A reader still needs\nto know whether `archied` or the agent changed; what goes away is the separate\nnumbers and the separate pages, not the information.\n\n**History is not re-tagged.** Existing tags keep their names, because tags are not a\nsource and nothing reads them to build a page. A future reader must not \"fix\" the\nunified changelog by rewriting tags to match it.\n\n## One release page per version\n\n`docs/news/\u003cversion\u003e.md` replaces `docs/news/\u003ccomponent\u003e/\u003cversion\u003e.md`, carrying the\nrelease's per-component sections inside it.\n\n**Every release URL already published keeps working.** `/news/archied/\u003cversion\u003e` and\n`/news/archie/\u003cversion\u003e` route to the unified page for that version. The generator\nemits the redirect table beside the pages so it cannot drift from them; if the\nrenderer needs the table in its own repository, that is a change in that repository\nrather than a hand-maintained list here.\n\n## The reviewer runs between prepare and tag\n\nRelease notes are prose, and the review agent exists to review prose. **`release:tag`\nrefuses to tag when the review has not been run for that version, or when it reports\nat the level.**\n\nThe invocation is verified rather than assumed. `tl rules --lint` reports `corpus ok`\nand exits 0. `tl review \u003cpath\u003e --deadline \u003cms\u003e --max-turns \u003cn\u003e` reports\n`0 findings (0 high, 0 medium) · 1/1 files reviewed · clean` and exits 0 on\n`docs/news/archied/1.36.0.md`.\n\n**`--fail-on` must be passed explicitly.** It defaults to `never`, so an invocation\nwithout it cannot refuse anything and the step would be decorative. `--fail-on high`\nis the level: a medium finding in a release note is worth acting on, and it should not\nstop a release on its own.\n\n**The rule is stated once.** It belongs in the reviewer's own rule set, which\n`tl rules --from-doc` can draft frLine truncated
"body": "# One release stream, one page per version, and commit rules — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** `RELEASING.md` for the process this changes, `AGENTS.md` for the\ncommit rules it enforces, and `tools/newsgen` for the artifact shape.\n\n**Supersedes:** `docs/prds/news-and-releases.md`, sections \"Source of truth\" and\n\"Two components\" — one changelog replaces two, and one page per version replaces\none page per component. Its remaining decisions stand.\n\n## Decision\n\n**A release is one version covering whatever changed.** One changelog holds every\nrelease section, one generated page holds every version's notes, and an operator\ncutting a release names one version.\n\n## One changelog\n\nEvery release section lives in `CHANGELOG.md`, newest first. `CHANGELOG.archied.md`\nand `CHANGELOG.archie.md` are deleted, and `CHANGELOG.md` stops being a pointer to\nthem. The changelog is the only source of release prose, and tags are not a source:\nCI and deployment check out shallow, so tags are absent from a site build while the\nchangelog is always present.\n\n### The merged history\n\nTwo version streams become one file, so a version that both components released\ncarries one heading and one date: **the newest date among that version's sections**,\nbecause a version's date is when the last part of it shipped. Where a component's own\ndate differs from it, that component's section label carries its own date, so the\nper-component fact survives the merge rather than being collapsed into the heading.\n\nThe merged history holds 65 versions: 33 that both components released, 31 only\n`archied`, and one only `archie`, from 64 and 34 sections respectively, so 98\npublished pages become 65. `## [Unreleased]` is not a release -- it carries no\nversion and gets no page -- but it stays at the top of the file, because it is\nthe one place unfinished work is recorded. Counting `##` headings rather than\nreleases overcounts by one.\n\nThis ambiguity is historical only. One version stream with one tag gives a version\nexactly one date, so the rule represents the merged past rather than a design that has\nto hold.\n\nThe merge is verified by content, not by the generator succeeding: the section count\nper source, the merged version set equal to the union of both sources with nothing\nextra, and every section title still present. A generator that agrees with the file it\njust wrote is evidence of nothing.\n\n## One version stream\n\n**`GATEWAY` and `RUNTIME` stop being release inputs.** `release:prepare` and\n`release:tag` take one version, and `tools/release.sh` loses the two flags.\n\nThey may stay as build-time stamps, because a binary must still report what it\ncontains. A release that must name three versions forces an operator to pass skip\nvalues for components that did not change, and that ceremony is what this decision\nremoves — along with the drift it allows, where two components' tags fall a release\napart.\n\n**Per-component detail stays, as sections inside the release.** A reader still needs\nto know whether `archied` or the agent changed; what goes away is the separate\nnumbers and the separate pages, not the information.\n\n**History is not re-tagged.** Existing tags keep their names, because tags are not a\nsource and nothing reads them to build a page. A future reader must not \"fix\" the\nunified changelog by rewriting tags to match it.\n\n## One release page per version\n\n`docs/news/\u003cversion\u003e.md` replaces `docs/news/\u003ccomponent\u003e/\u003cversion\u003e.md`, carrying the\nrelease's per-component sections inside it.\n\n**Every release URL already published keeps working.** `/news/archied/\u003cversion\u003e` and\n`/news/archie/\u003cversion\u003e` route to the unified page for that version. The generator\nemits the redirect table beside the pages so it cannot drift from them; if the\nrenderer needs the table in its own repository, that is a change in that repository\nrather than a hand-maintained list here.\n\n## The reviewer runs between prepare and tag\n\nRelease notes are prose, and the review agent exists to review prose. **`release:tag`\nrefuses to tag when the review has not been run for that version, or when it reports\nat the level.**\n\nThe invocation is verified rather than assumed. `tl rules --lint` reports `corpus ok`\nand exits 0. `tl review \u003cpath\u003e --deadline \u003cms\u003e --max-turns \u003cn\u003e` reports\n`0 findings (0 high, 0 medium) · 1/1 files reviewed · clean` and exits 0 on\n`docs/news/archied/1.36.0.md`.\n\n**`--fail-on` must be passed explicitly.** It defaults to `never`, so an invocation\nwithout it cannot refuse anything and the step would be decorative. `--fail-on high`\nis the level: a medium finding in a release note is worth acting on, and it should not\nstop a release on its own.\n\n**The rule is stated once.** It belongs in the reviewer's own rule set, which\n`tl rules --from-doc` can draft frLine truncated
},
{
"url": "/dev/prds/review-calibration/",
"title": "Review calibration -- decision",
"section": "PRDs",
"body": "# Review calibration -- decision\n\n**Status:** Draft\n**Beads issue:** `archie-core-h019.5` (parent `archie-core-h019`)\n\nDecides the half of calibration `docs/prds/adversarial-self-review.md` left\nopen: \"the adversarial-confirmation mechanism that keeps a finding from\nsurfacing on a single reviewer's say-so.\"\n\n## The problem, precisely\n\nThe shipped contract (`internal/domain/workflow/review_findings.go`, h019.2)\nalready makes only a **confirmed** error-level finding block\n(`Blocking() == Verdict == confirmed \u0026\u0026 Level == error`), and a zero-finding\nreview is already distinguishable from one that never ran (`ReviewStatus`).\nWhat is missing is the other half: a reviewer can report *nothing*\nand say only \"I found nothing\" in free text. The operator cannot tell \"I\nchecked the five things that matter and they are clean\" from \"I did not look.\"\nThat is the failure the epic names -- a findings surface that consumes attention\nwithout earning trust.\n\n## Decisions\n\n### 1. \"Checked and cleared\" becomes structured, not prose\n\n`ReviewReport` gains `Checked []ReviewCheck`:\n\n```go\ntype ReviewCheck struct {\n Property string // what was verified clean, e.g. \"nil-safety of Foo callers\"\n Evidence string // how it was verified, e.g. \"read all 4 callers; each nil-checks\"\n}\n```\n\n`Evidence` is required, for the same reason `ReviewFinding.FailureScenario` is:\na check without evidence is an assertion, and the whole point is to separate a\nverified property from an unexamined one. A zero-finding review is credible\nonly when it lists what it checked.\n\n### 2. Report checks through a typed tool, like findings\n\nThe reviewer calls a new capture tool `record_checked` (mirroring\n`record_finding`) once per property it verified clean. The same environmental\nargument as findings applies: the reviewer cannot end its turn having silently\nskipped the checklist. `ReviewReport.Summary` stays as the human overview.\n\n### 3. Style nits are out of contract\n\nA finding must describe wrong behaviour or a crash. Style, formatting, naming,\nand preference nits are explicitly out of contract -- they are the padding that\ntrains the operator to skim. Stated in the reviewer prompt and in the\n`ReviewFinding` type's own documentation. Not machine-enforced: deciding \"is\nthis a style nit\" from free text is unreliable, and a wrong rejection is worse\nthan a tolerated one. The category enum already has no style bucket; the rule\ncloses the gap that would otherwise let one hide under `other`.\n\n### 4. Surfacing\n\nThe PR-body findings section lists the cleared properties alongside findings,\nso \"ran and found nothing\" arrives with its evidence. (Park reasons keep\nrendering only blocking findings -- what a human needs to act on, not the full\nchecklist.)\n\n## What this does not decide\n\n- Adding a second, independent reviewer pass. The verdict distinction plus the\n recorded checks is the confirmation mechanism; a second model pass is a\n separate, heavier decision and nothing in `h019.5` requires it.\n- How many findings can survive before `MaxSteps` is exhausted (a budget\n question, already satisfied by the per-stage budget).\n\n## Packages this touches\n\n- `internal/domain/workflow` -- `ReviewCheck`, `ReviewReport.Checked`, validation.\n- `internal/app/agentworker` -- `record_checked` tool, prompt rules.\n- `internal/domain/workflow/review.go` -- render cleared properties on the PR body.\n"
"body": "# Review calibration -- decision\n\n**Status:** Draft\n**Beads issue:** `archie-core-h019.5` (parent `archie-core-h019`)\n\nDecides the half of calibration `docs/prds/adversarial-self-review.md` left\nopen: \"the adversarial-confirmation mechanism that keeps a finding from\nsurfacing on a single reviewer's say-so.\"\n\n## The problem, precisely\n\nThe shipped contract (`internal/domain/workflow/review_findings.go`, h019.2)\nalready makes only a **confirmed** error-level finding block\n(`Blocking() == Verdict == confirmed \u0026\u0026 Level == error`), and a zero-finding\nreview is already distinguishable from one that never ran (`ReviewStatus`).\nWhat is missing is the other half: a reviewer can report _nothing_\nand say only \"I found nothing\" in free text. The operator cannot tell \"I\nchecked the five things that matter and they are clean\" from \"I did not look.\"\nThat is the failure the epic names -- a findings surface that consumes attention\nwithout earning trust.\n\n## Decisions\n\n### 1. \"Checked and cleared\" becomes structured, not prose\n\n`ReviewReport` gains `Checked []ReviewCheck`:\n\n```go\ntype ReviewCheck struct {\n Property string // what was verified clean, e.g. \"nil-safety of Foo callers\"\n Evidence string // how it was verified, e.g. \"read all 4 callers; each nil-checks\"\n}\n```\n\n`Evidence` is required, for the same reason `ReviewFinding.FailureScenario` is:\na check without evidence is an assertion, and the whole point is to separate a\nverified property from an unexamined one. A zero-finding review is credible\nonly when it lists what it checked.\n\n### 2. Report checks through a typed tool, like findings\n\nThe reviewer calls a new capture tool `record_checked` (mirroring\n`record_finding`) once per property it verified clean. The same environmental\nargument as findings applies: the reviewer cannot end its turn having silently\nskipped the checklist. `ReviewReport.Summary` stays as the human overview.\n\n### 3. Style nits are out of contract\n\nA finding must describe wrong behaviour or a crash. Style, formatting, naming,\nand preference nits are explicitly out of contract -- they are the padding that\ntrains the operator to skim. Stated in the reviewer prompt and in the\n`ReviewFinding` type's own documentation. Not machine-enforced: deciding \"is\nthis a style nit\" from free text is unreliable, and a wrong rejection is worse\nthan a tolerated one. The category enum already has no style bucket; the rule\ncloses the gap that would otherwise let one hide under `other`.\n\n### 4. Surfacing\n\nThe PR-body findings section lists the cleared properties alongside findings,\nso \"ran and found nothing\" arrives with its evidence. (Park reasons keep\nrendering only blocking findings -- what a human needs to act on, not the full\nchecklist.)\n\n## What this does not decide\n\n- Adding a second, independent reviewer pass. The verdict distinction plus the\n recorded checks is the confirmation mechanism; a second model pass is a\n separate, heavier decision and nothing in `h019.5` requires it.\n- How many findings can survive before `MaxSteps` is exhausted (a budget\n question, already satisfied by the per-stage budget).\n\n## Packages this touches\n\n- `internal/domain/workflow` -- `ReviewCheck`, `ReviewReport.Checked`, validation.\n- `internal/app/agentworker` -- `record_checked` tool, prompt rules.\n- `internal/domain/workflow/review.go` -- render cleared properties on the PR body.\n"
},
{
"url": "/dev/prds/runtime-control-plane/",
@@ -442,19 +442,19 @@
"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 RHELine truncated
},
{
"url": "/dev/prds/service-registry/",
"title": "Service registry — one declaration per service",
"section": "PRDs",
"body": "# Service registry — one declaration per service\n\n**Status:** Draft\n**Supersedes:** `state-store-contract.md` §10's `State ServiceConnection`\nstruct-field instruction.\n\n**Base:** the `listen` field, `internal/app/archied/listen.go`, and the listen defaults cited\nbelow exist on `feat/attempt-attribution`, not on `main`. This design therefore lands on top of\nthat branch: `RegisterService`'s `listen` argument has nothing to carry without it.\n\n## Problem\n\nA service is already one Go type, `config.ServiceConnection`. What is duplicated is its\n**name**, in three layers:\n\n| Layer | Location | What is hard-coded |\n|---|---|---|\n| Declaration | `internal/config/services.go` | `Gateway` and `State` as struct fields |\n| Defaulting | `internal/infrastructure/configuration/defaults.go` | three `if cfg.Services.X.Y == \"\"` branches |\n| Consumption | `internal/app/archied/{bootstrap.go,state_store.go,gateway.go}`, `internal/app/archieui/config.go` | `cfg.Services.State` / `cfg.Services.Gateway` field access |\n\nAdding a service means editing all three. The drift this permits is already visible:\n`stateStoreResolvedToken` (`state_store_client.go`) and `gatewayResolvedToken`\n(`chat_service.go`) are byte-identical apart from the env var name, and\n`gateway.Target` is defaulted while `state.Target` is a startup error, with nothing\nstating that asymmetry in one place.\n\n`resolveServiceListen(service, flagValue, configured)` (`listen.go`) is already\nname-parameterised. It is the shape the rest should follow.\n\n## Decision\n\n**Key services by name, and carry per-service asymmetry as registration data.**\n\n### 1. Declaration collapses to a map\n\n```go\n// internal/config/services.go\ntype Services map[string]ServiceConnection\n```\n\n`ServiceConnection` is unchanged. The TOML shape is unchanged, so no deployment profile,\n`config.example.toml`, or `install.sh` edit is required. An unrecognised `[services.foo]`\ndecodes without a code edit, satisfying criterion 5.\n\n### 2. Registration is the single entry point\n\n```go\n// internal/config/servicespec.go\nfunc RegisterService(context, name, target, listen, tokenEnv string)\n```\n\nregistered once per service, at package init in `internal/config`:\n\n```go\nRegisterService(\"both\", \"gateway\", \"127.0.0.1:8585\", \"127.0.0.1:8585\", \"GATEWAY_TOKEN\")\nRegisterService(\"client\", \"state\", \"\", \"127.0.0.1:9090\", \"STATE_STORE_TOKEN\")\n```\n\nPositional, five strings, as the story specifies. Each argument is data the current code\nstates in prose or in a branch:\n\n- `context` is `client`, `server`, or `both`, and decides which fields must resolve\n non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with\n no default `listen`, panics at registration. Registrations come from this repository's\n own `init()`, never from operator input, so an invalid one is a programming error with\n no caller positioned to handle an error return. A documented-but-unread `Context` would\n be worse than no field at all.\n- `target` is the **default**, and an empty default means the operator must supply one.\n That single convention replaces the `state.target` required / `gateway.target` defaulted\n asymmetry with no branch: `state` registers `\"\"`, `gateway` registers an address.\n- `listen` is the default listen address, feeding the existing\n flag → `[services.\u003cname\u003e].listen` → default precedence unchanged.\n- `tokenEnv` names the fallback env var, replacing the two copied resolvers with one.\n\n### 3. Defaulting and consumption become loops and lookups\n\n`applyDefaults` iterates the registry instead of naming services. Consumers read\n`cfg.Services.Get(\"state\")`, returning a `ServiceConnection` plus the spec, so\n`stateStoreResolvedToken` and `gatewayResolvedToken` collapse into\n`Services.ResolvedToken(name, secrets)`.\n\n## Criteria satisfied\n\n1. Declared once, in the `RegisterService` call.\n2. No second location can contradict it; the map has no per-service fields to disagree with.\n3. Registration is the entry point, with the five fields a service has.\n4. A new service is one `RegisterService` line: no field, no default branch, no consumer edit.\n5. The set of services is registry data, not a struct definition.\n\n## Scope and risk\n\n- `state-store-contract.md` §10 must be revised in the same change, or the tree contradicts\n its own ratified authority. Its summary (`:7`) already says `[services.\u003cname\u003e]`.\n- A typo'd `[services.gatway]` is **reported** (`UnknownKeys = [services.gatway,\n services.gatway.target]`), because the struct form leaves it in `toml.MetaData.Undecoded()`.\n A map decodes any section, so preserving that is a requirement, not an optional extra:\n `unregisteredServiceKeys` asks the registry which names exist. This costs nothing in\n extensibility, because the answer comes from registration data rather than a fixed list.\n TheLine truncated
"body": "# Service registry — one declaration per service\n\n**Status:** Draft\n**Supersedes:** `state-store-contract.md` §10's `State ServiceConnection`\nstruct-field instruction.\n\n**Base:** the `listen` field, `internal/app/archied/listen.go`, and the listen defaults cited\nbelow exist on `feat/attempt-attribution`, not on `main`. This design therefore lands on top of\nthat branch: `RegisterService`'s `listen` argument has nothing to carry without it.\n\n## Problem\n\nA service is already one Go type, `config.ServiceConnection`. What is duplicated is its\n**name**, in three layers:\n\n| Layer | Location | What is hard-coded |\n| ----------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |\n| Declaration | `internal/config/services.go` | `Gateway` and `State` as struct fields |\n| Defaulting | `internal/infrastructure/configuration/defaults.go` | three `if cfg.Services.X.Y == \"\"` branches |\n| Consumption | `internal/app/archied/{bootstrap.go,state_store.go,gateway.go}`, `internal/app/archieui/config.go` | `cfg.Services.State` / `cfg.Services.Gateway` field access |\n\nAdding a service means editing all three. The drift this permits is already visible:\n`stateStoreResolvedToken` (`state_store_client.go`) and `gatewayResolvedToken`\n(`chat_service.go`) are byte-identical apart from the env var name, and\n`gateway.Target` is defaulted while `state.Target` is a startup error, with nothing\nstating that asymmetry in one place.\n\n`resolveServiceListen(service, flagValue, configured)` (`listen.go`) is already\nname-parameterised. It is the shape the rest should follow.\n\n## Decision\n\n**Key services by name, and carry per-service asymmetry as registration data.**\n\n### 1. Declaration collapses to a map\n\n```go\n// internal/config/services.go\ntype Services map[string]ServiceConnection\n```\n\n`ServiceConnection` is unchanged. The TOML shape is unchanged, so no deployment profile,\n`config.example.toml`, or `install.sh` edit is required. An unrecognised `[services.foo]`\ndecodes without a code edit, satisfying criterion 5.\n\n### 2. Registration is the single entry point\n\n```go\n// internal/config/servicespec.go\nfunc RegisterService(context, name, target, listen, tokenEnv string)\n```\n\nregistered once per service, at package init in `internal/config`:\n\n```go\nRegisterService(\"both\", \"gateway\", \"127.0.0.1:8585\", \"127.0.0.1:8585\", \"GATEWAY_TOKEN\")\nRegisterService(\"client\", \"state\", \"\", \"127.0.0.1:9090\", \"STATE_STORE_TOKEN\")\n```\n\nPositional, five strings, as the story specifies. Each argument is data the current code\nstates in prose or in a branch:\n\n- `context` is `client`, `server`, or `both`, and decides which fields must resolve\n non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with\n no default `listen`, panics at registration. Registrations come from this repository's\n own `init()`, never from operator input, so an invalid one is a programming error with\n no caller positioned to handle an error return. A documented-but-unread `Context` would\n be worse than no field at all.\n- `target` is the **default**, and an empty default means the operator must supply one.\n That single convention replaces the `state.target` required / `gateway.target` defaulted\n asymmetry with no branch: `state` registers `\"\"`, `gateway` registers an address.\n- `listen` is the default listen address, feeding the existing\n flag → `[services.\u003cname\u003e].listen` → default precedence unchanged.\n- `tokenEnv` names the fallback env var, replacing the two copied resolvers with one.\n\n### 3. Defaulting and consumption become loops and lookups\n\n`applyDefaults` iterates the registry instead of naming services. Consumers read\n`cfg.Services.Get(\"state\")`, returning a `ServiceConnection` plus the spec, so\n`stateStoreResolvedToken` and `gatewayResolvedToken` collapse into\n`Services.ResolvedToken(name, secrets)`.\n\n## Criteria satisfied\n\n1. Declared once, in the `RegisterService` call.\n2. No second location can contradict it; the map has no per-service fields to disagree with.\n3. Registration is the entry point, with the five fields a service has.\n4. A new service is one `RegisterService` line: no field, no default branch, no consumer edit.\n5. The set of services is registry data, not a struct definition.\n\n## Scope and risk\n\n- `state-store-contract.md` §10 must be revised in the same change, or the tree contradicts\n its own ratified authority. Its summary (`:7`) already says `[services.\u003cname\u003e]`.\nLine truncated
},
{
"url": "/dev/prds/session-memory-curator/",
@@ -466,49 +466,49 @@
"url": "/dev/prds/skill-curator/",
"title": "Skill curator (reference implementation) -- decision",
"section": "PRDs",
"body": "# Skill curator (reference implementation) -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-1786637499206`\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n\n## Decision\n\nThe skill curator's v1 scope is **mechanical validation and safe\nnormalisation only** -- it never rewrites skill prose, never deletes a\nskill, and never calls the model. Each pass:\n\n1. Lists every skill under one configured root.\n2. Reads each `SKILL.md` and attempts to parse its frontmatter\n (`internal/skill.Parse`).\n3. Records an `Action` for any structural problem: a parse failure, or a\n missing `name`/`description` in the frontmatter that parsed.\n4. Normalises trivial whitespace (trailing whitespace per line, exactly\n one trailing newline) and writes back **only** when normalisation\n actually changes the bytes, recording an `Action` for that write.\n\nNothing here needs judgement. \"Review, prune, and improve\" -- the epic's\nframing -- is real for v1 but deliberately narrow: review is structural\nvalidation, improve is whitespace normalisation, and prune is *reporting*\na problem, never removing a skill. `Manifest.Skills = true` still marks\nthis curator agentic (existing `agentic()` rule), so it receives model\naccess from the registrar -- unused but nothing about the contract\nor the runtime needs to change to let a later version reason about\ncontent quality using it.\n\n## Why this scope, not more\n\nAn autonomous process that rewrites or deletes a user's skill content\nis a real risk with no undo path (no draft/approval flow for\ncurator writes exists yet, unlike the workflow engine's PR-based review).\nThe epic's own stated purpose for this issue is proving the curator\ncontract holds for a second, structurally different consumer than the\nsession-memory curator (files-as-skills vs. observations-as-memory), not\nsolving \"what makes a skill good.\" Mechanical validation is real,\nuseful, safe to run unattended, and fully exercises\nList/Read/Write -- every method `curator.SkillStore` declares except\n`Delete`, which this curator's Pass never has a safe reason to call in\nv1 (kept implemented on the store adapter regardless, since the\ninterface requires it and a future consumer may).\n\n## Why `internal/skill` isn't `curator.SkillStore` directly\n\n`internal/skill.Discover` parses every `SKILL.md` under a root and\nreturns an error for the **whole** call if any one of them fails to\nparse -- the read side was built for \"load the catalogue to start the\ndaemon,\" where one bad skill failing the whole boot is arguably correct,\nnot for \"review each skill and report what's wrong with it\nindividually.\" A per-skill parse failure must become one `Action`, not\nabort the pass before any skill is reviewed. So\n`internal/infrastructure/skillcurator` gets its own thin store adapter\nthat lists raw directory names and reads/writes raw `SKILL.md` bytes\nper name; the skill curator itself calls `internal/skill.Parse` on each\none, isolated per skill.\n\n## Root scope\n\nOne root only, resolved the same way `loadWorkflows` already resolves\n`skillsBase` (`cfg.SkillsDir`, falling back to `cfg.WorkDir`) -- not\nevery root `skill.CatalogRoots`/`DefaultRoots` would read for a model\n(which layers a shared dir over the per-profile one). Write and Delete\nneed one unambiguous target; a curator that could write into a shared,\nmulti-tenant skills directory is a bigger decision than this issue\ncovers. The model still sees the full multi-root catalogue through the\nexisting read path -- this curator only maintains the local one.\n\n## Shape\n\n### `internal/infrastructure/skillcurator/store.go`\n\n```go\n// Store implements curator.SkillStore over one root directory's\n// .agents/skills/*/SKILL.md files, tolerating a per-skill parse failure\n// as the curator's problem to report rather than this store's problem\n// to abort on.\ntype Store struct { root string }\n\nfunc NewStore(root string) *Store\n\nfunc (s *Store) List(ctx context.Context) ([]curator.SkillRef, error)\nfunc (s *Store) Read(ctx context.Context, name string) (curator.Skill, error)\nfunc (s *Store) Write(ctx context.Context, sk curator.Skill) error\nfunc (s *Store) Delete(ctx context.Context, name string) error\n```\n\n`Read` best-effort parses frontmatter for `Skill.Description` (empty on\nparse failure -- not this method's job to report that; `Pass` does, via\nits own `skill.Parse` call on `Skill.Content`). `Write` rejects a name\nthat does not already exist as a directory (this store curates existing\nskills; creating a new one is out of scope). `Delete` removes the whole\nskill directory, matching \"delete a skill,\" not just `SKILL.md`.\n\n### `internal/infrastructure/skillcurator/skillcurator.go`\n\n```go\n// Curator implements domain/curator.CuratorEngine. See\n// docs/prds/skill-curator.md for what a pass does and why.\ntype Curator struct { /* unexported: registrar view, interval Line truncated
"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` (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
"body": "# State Store — contract boundary \u0026 transport (ratification)\n\n**Status:** Approved\n**Revision:** 2e\n**Date:** 2026-09-06\n\nThis is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalise\n`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)\nimplement against.\n**Beads milestone:** archie-core-8cda.4.1\n**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)\n\nThis document fixes the **contract boundary** and **transport** for the State Store service.\nIt does not redesign Archie's domain model, does not invent a second store, and does **not**\nsplit `archie.db`. It records method ownership, DTO/wire representation, error semantics,\nlimits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that\n`.4.2` and `.4.3` have exactly one authoritative surface to build against.\n\n\u003e **Storage superseded.** The store behind this contract is PostgreSQL:\n\u003e `internal/infrastructure/postgres` implements the producer-owned interfaces in\n\u003e `internal/domain/storecontract` and `workflow.Store`, over the database\n\u003e `database_url` names. `internal/store`, the SQLite file and the local adapter\n\u003e are gone; where this document says `archie.db`, `*store.Store` or\n\u003e `internal/store`, read the State Store's PostgreSQL database and\n\u003e `internal/infrastructure/postgres`. The contract, ownership split, error\n\u003e semantics and cutover rules stand.\n\n\u003e **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.\n4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in\n\u003e `internal/domain/workflow`, the six production workflow files import no `internal/store`\n\u003e symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of\n\u003e `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own\n\u003e service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.\n\n\u003e **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/\nmigration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\nStepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)\n\u003e **remains the authoritative, open document for the long-term Workflow migration.** This PRD\n\u003e does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface\n\u003e relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);\n\u003e the rest of §4 stays its own migration and stays open.\n\n---\n\n## 1. Decision (the invariant everything follows)\n\nArchie is composed such that a single **`archie-state-store`** service owns the one existing\nSQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is\nexactly one store, one file, one service. No database-per-service, no distributed\ntransactions, no second store abstraction.\n\nTwo adapter families satisfy the contract interfaces:\n\n- **Local adapter** — `*store.Store` (the in-process SQLite implementation).\n- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).\n\nEach adapter carries an explicit compile-time assertion against the contract interfaces it\nserves. Composition picks local vs. remote by the presence of `[services.state].target`\n(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet\nextracted), which is the PRD §3 posture; it differs from the gateway's remote-default only\nbecause the gateway is already a separate deployment and the State Store is not.\n\n\u003e **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**\n\u003e Ownership splits by the consumer's _layer_, per the dependency contract's rule #2\n\u003e (\"a domain defines the smallest interfaces required to perform its work\") and rule #7\n\u003e (\"database rows … MUST NOT leak into domain models\"):\n\u003e\n\u003e - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of\n\u003e store state. It defines its own **consumer-owned** narrow `Store` interface\n\u003e (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus\n\u003e `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the\n\u003e Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4\n\u003e (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion\n\u003e requires it.\n\u003e - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,\n\u003e `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay\n\u003e **producer-owned** in `internal/store`, because those consumers are application Line truncated
},
{
"url": "/dev/prds/status-health-surface/",
"title": "/status health surface",
"section": "PRDs",
"body": "# /status health surface\n\n**Status:** Finalised\n**Beads issue:** `archie-core-wp9s`\n\nA reported field must have a truthful source. `/status` reports broker\nconnectivity and the last chat-model call; the container pool, last poll and\nchannel state have no source in the process that answers the command, so they\nare left out rather than faked.\n\n## Background\n\n`archie-core-wp9s` (\"/status and /tasks have the wrong division of labour\")\nasked for two things: `/tasks` owning the live per-task work view, and\n`/status` owning daemon health -- \"broker connectivity, provider\nreachability, channel state, container pool, queue depth, last poll,\nversion\" -- with neither duplicating the other or static config available\nelsewhere (`/model` already lists active provider/model).\n\n## Phase 1\n\n- `/tasks`: new command, `gateway.ChatTaskSummary` extended with\n `Stage`/`Attempt`/`ParkReason`/`UpdatedAt` (all already persisted on\n `store.Task`, zero new instrumentation), sorted actionable-first.\n- `/status`: itemised per-status task counts replaced with one aggregate\n `Queue: N in flight (...)` line (running/waiting/parked only -- queued and\n terminal states excluded as not a health concern). Runtime\n (provider/model) is temporarily left in place; see \"Runtime (provider/model)\"\n under Phase 2's \"Truthful or absent\" for where that stands now.\n\nNot touched: `/agents` (`gateway.AgentReader`/`Router.Agents`) is a separate,\npre-existing command that already has the right shape for \"list active\nwork\" but is never wired to a real implementation in any composition-root\ncall site (`bootstrap.go`, `telegram_setup.go`) -- it always answers \"Agent\nlisting is not configured.\" in production. That is a standalone bug\n(`archie-core-mxls`), not folded into this work: deciding whether to wire\nit, repurpose it, or delete it in favour of `/tasks` is Sam's call, not\nsomething to resolve by implication here.\n\n## Phase 2 -- health checks, verified against the actual tree\n\nEach bullet below was checked against real code before being called cheap\nor not; nothing here is guessed. Both open questions were settled (see \"The two\ndecisions\"). The health section reports the broker connection and the last\nchat-model call; the three facts the answering process cannot see are covered\nunder \"Truthful or absent\".\n\n### Verified as cheap against the tree\n\n- **Broker connectivity.** `internal/infrastructure/eventbus/nats.Client`\n already exposes `CoreConn() (*nats.Conn, error)`\n (`client.go`). The underlying `nats.Conn` (nats.go) has its own\n `Status()`/`IsConnected()`. A `Client.Connected() bool` wrapper is a few\n lines.\n- **Container pool.** `container.Pool` already tracks `active int` under\n its own mutex (`pool.go`) but has no public accessor. A\n `Pool.Active() int` getter is a few lines.\n- **Last poll.** Nothing tracks this. The daemon's poll loop\n (`internal/daemon`) needs one `lastPollAt time.Time` field (atomic or\n mutex-guarded, matching the pool's own pattern) set at the top of each\n poll tick, with a getter.\n- **Queue depth.** Covered by Phase 1.\n\n### The two decisions\n\n- **Provider reachability is last-known outcome, never a live probe.** A chat\n command must not perform a blocking network call in its handler, and a probe\n reports the probe's reachability rather than the daemon's. `/status` therefore\n prints what actually happened -- the last chat-model call's model, age and\n error, or \"no calls attempted yet\" when there has been none. Implemented as\n `providerOutcomeRecorder`, written once in `sendChatTurn` (the single point\n every chat-model call in the process passes through) and read back by\n `newStatusHealth`. Nothing on this path dials a provider. The existing live\n model reachability check (`readiness.go`'s `modelReachProbe`) is unchanged and\n stays where it belongs: on `/health/detailed`, off the chat path.\n- **Channel state comes from the existing ChannelManager.** `/status` reads\n `status.Manager.Snapshot()` -- the same ledger the dashboard and the readiness\n probe already use -- rather than re-deriving channel health from each adapter.\n No method was added to the `Channel`/`Gateway` contract.\n\n### Phase 2\n\n- **Broker connectivity.** `internal/infrastructure/eventbus/nats.Client` gained\n `Connected() bool`, which reads the connection the process already holds. The\n standalone Gateway (which dials NATS itself for task actions) reports the same\n fact from that connection.\n- **Container pool.** `container.Pool.Active()` and `Pool.Cap()` read the pool's\n own counter and configured `max_concurrency` -- not a Docker listing, which\n would include containers this pool does not own. A cap of zero means\n unlimited, so `/status` renders the count alone rather than \"1/0 active\".\n- **Last poll.** `daemon.Daemon.LastPollAt()` reports when the most recent poll\n pass *began*; both poll paths (`poll` for sLine truncated
"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/",
"title": "task_logs pagination and bounded retrieval -- decision",
"section": "PRDs",
"body": "# task_logs pagination and bounded retrieval -- decision\n\n**Status:** Approved\n**Date:** 2026-08-26\n**Beads issue:** `archie-core-vq92`\n**Compounds with:** `archie-core-p1bl` (errors serialise as `{}`)\n\n## Decision\n\n`task_logs` becomes a *cursor-paginated, filterable* bounded read, not a\none-shot head-of-file window. The reader in `internal/logging` gains a\nsecond entry point (`Page`) that walks the file forward from a byte\noffset; the tool schema in `internal/gateway/task_tools.go` surfaces\nlevel, time-range and cursor parameters; the response carries an explicit\n\"more available\" signal so a model can either keep paging or hand the\nrest to `send_file` when the operator wants a complete archive.\n\nWe do NOT add an unbounded read path. A single response is still capped at\n`MaxTailLines` (2000) entries. What changes is that pagination makes the\ncap reachable in practice instead of silently terminal.\n\n## Why now\n\n`archie-core-vq92` is the right place to fix this: the chat tool is the\nuser-visible failure mode, but the same defect propagates to every caller\nof `internal/logging.Tail` (`internal/webui/api_logs.go` and the\n`chatTaskLogReaderAdapter` in `cmd/archied/main.go`). Patching the\nreader and the tool together is one change in two layers, not two\nchanges; CLAUDE.md's \"package owns its format end-to-end\" rule means the\nreader is the right place for cursor support regardless.\n\nThe compound with `p1bl` matters: a truncated window of uninformative\nerrors leaves an operator with nothing. Cursor pagination lets the model\nwalk the whole file when a level filter does not narrow enough, and the\nresponse's \"more available\" signal means it can honestly say \"I read N of\nM and stopped there\" instead of presenting the head as complete.\n\n## Shape of the API\n\n### Reader (`internal/logging`)\n\nAdd a second entry point next to `Tail`:\n\n```go\n// Page walks the log forward from cursor (a byte offset; 0 starts at\n// the beginning of the scanned window), applying the same filters as\n// Tail. PageResult.Cursor is the file offset just past the last line\n// the walk returned; pass it back as Cursor to continue, and stop when\n// MoreAvailable is false.\nfunc Page(path string, q Query, cursor int64) (PageResult, error)\n```\n\n`PageResult` carries `Entries`, `Truncated` (the existing meaning --\nolder entries exist that were not examined within `maxScanBytes`),\n`Cursor` (the byte offset the next page should resume from), and\n`MoreAvailable` (true iff the scan saw more matching entries beyond the\nreturned page within the same call).\n\n`Cursor` is a byte offset rather than an entry ID for two reasons.\nFirst, `TaskSink` writes JSONL through `slog.NewJSONHandler` directly --\nwithout routing through `FeedHandler` -- so the on-disk entries carry no\n`id` field and a per-task attempt monotonic counter would require\neither a sink-side change or a reader-side reconstruction that is\nbrittle against rotation. Second, the byte offset uniquely identifies\n\"the next unread position\" in a sequential scan, which is exactly what\nthe call pattern needs. A cursor that points at or past the file's\ncurrent size is treated as end-of-stream (empty page, `MoreAvailable`\nfalse).\n\nThe implementation is `readWindow` (reads the tail-most `maxScanBytes`\ninto a single in-memory buffer) plus `readLines` (clamps the cursor into\nthe window, drops a partial first line on the size-cap seek, then\ndelegates) plus `walkWindow` (walks the buffer line-by-line by exact\nslice offset). Offsets are into one contiguous buffer, so they are\ntrivially correct -- unlike an incremental reader over the file, whose\n`bufio.Reader` buffer-ahead would make its underlying file position\nunusable as a cursor.\n\n`Tail` is NOT a wrapper over `Page`: it keeps its legacy ring-buffer\nsemantics (newest `Limit` matches, oldest dropped, `Truncated` set on\nring overflow). They share `readWindow`/`walkWindow` but stay separate\nentry points precisely so Tail's established behaviour is unchanged.\n\n### `Query` gains two optional fields\n\n```go\nSince time.Time // inclusive lower bound on entry.Time\nUntil time.Time // inclusive upper bound on entry.Time\n```\n\n`Levels`, `Component`, `Contains`, `Limit` are unchanged. The existing\nfilter logic and tests move unchanged.\n\n### Tool schema (`internal/gateway/task_tools.go`)\n\n`ChatTaskLogQuery` gains three fields:\n\n- `Level []string` (forwarded to `Query.Levels`)\n- `Since time.Time` / `Until time.Time` (forwarded as `Query.Since/Until`)\n- `AfterID int64` (the cursor; 0 to start at the beginning)\n\n`ChatTaskLogResult` gains two fields:\n\n- `Cursor int64` -- highest ID in this page; pass back as `AfterID` to continue\n- `MoreAvailable bool` -- true iff the scan saw more matching entries that\n did not fit in this page\n\nThe tool description is updated to teach the model the pagination\nprotocol in one sentence: \"pass the previous `cursor` back as `Line truncated
"body": "# task_logs pagination and bounded retrieval -- decision\n\n**Status:** Approved\n**Date:** 2026-08-26\n**Beads issue:** `archie-core-vq92`\n**Compounds with:** `archie-core-p1bl` (errors serialise as `{}`)\n\n## Decision\n\n`task_logs` becomes a _cursor-paginated, filterable_ bounded read, not a\none-shot head-of-file window. The reader in `internal/logging` gains a\nsecond entry point (`Page`) that walks the file forward from a byte\noffset; the tool schema in `internal/gateway/task_tools.go` surfaces\nlevel, time-range and cursor parameters; the response carries an explicit\n\"more available\" signal so a model can either keep paging or hand the\nrest to `send_file` when the operator wants a complete archive.\n\nWe do NOT add an unbounded read path. A single response is still capped at\n`MaxTailLines` (2000) entries. What changes is that pagination makes the\ncap reachable in practice instead of silently terminal.\n\n## Why now\n\n`archie-core-vq92` is the right place to fix this: the chat tool is the\nuser-visible failure mode, but the same defect propagates to every caller\nof `internal/logging.Tail` (`internal/webui/api_logs.go` and the\n`chatTaskLogReaderAdapter` in `cmd/archied/main.go`). Patching the\nreader and the tool together is one change in two layers, not two\nchanges; CLAUDE.md's \"package owns its format end-to-end\" rule means the\nreader is the right place for cursor support regardless.\n\nThe compound with `p1bl` matters: a truncated window of uninformative\nerrors leaves an operator with nothing. Cursor pagination lets the model\nwalk the whole file when a level filter does not narrow enough, and the\nresponse's \"more available\" signal means it can honestly say \"I read N of\nM and stopped there\" instead of presenting the head as complete.\n\n## Shape of the API\n\n### Reader (`internal/logging`)\n\nAdd a second entry point next to `Tail`:\n\n```go\n// Page walks the log forward from cursor (a byte offset; 0 starts at\n// the beginning of the scanned window), applying the same filters as\n// Tail. PageResult.Cursor is the file offset just past the last line\n// the walk returned; pass it back as Cursor to continue, and stop when\n// MoreAvailable is false.\nfunc Page(path string, q Query, cursor int64) (PageResult, error)\n```\n\n`PageResult` carries `Entries`, `Truncated` (the existing meaning --\nolder entries exist that were not examined within `maxScanBytes`),\n`Cursor` (the byte offset the next page should resume from), and\n`MoreAvailable` (true iff the scan saw more matching entries beyond the\nreturned page within the same call).\n\n`Cursor` is a byte offset rather than an entry ID for two reasons.\nFirst, `TaskSink` writes JSONL through `slog.NewJSONHandler` directly --\nwithout routing through `FeedHandler` -- so the on-disk entries carry no\n`id` field and a per-task attempt monotonic counter would require\neither a sink-side change or a reader-side reconstruction that is\nbrittle against rotation. Second, the byte offset uniquely identifies\n\"the next unread position\" in a sequential scan, which is exactly what\nthe call pattern needs. A cursor that points at or past the file's\ncurrent size is treated as end-of-stream (empty page, `MoreAvailable`\nfalse).\n\nThe implementation is `readWindow` (reads the tail-most `maxScanBytes`\ninto a single in-memory buffer) plus `readLines` (clamps the cursor into\nthe window, drops a partial first line on the size-cap seek, then\ndelegates) plus `walkWindow` (walks the buffer line-by-line by exact\nslice offset). Offsets are into one contiguous buffer, so they are\ntrivially correct -- unlike an incremental reader over the file, whose\n`bufio.Reader` buffer-ahead would make its underlying file position\nunusable as a cursor.\n\n`Tail` is NOT a wrapper over `Page`: it keeps its legacy ring-buffer\nsemantics (newest `Limit` matches, oldest dropped, `Truncated` set on\nring overflow). They share `readWindow`/`walkWindow` but stay separate\nentry points precisely so Tail's established behaviour is unchanged.\n\n### `Query` gains two optional fields\n\n```go\nSince time.Time // inclusive lower bound on entry.Time\nUntil time.Time // inclusive upper bound on entry.Time\n```\n\n`Levels`, `Component`, `Contains`, `Limit` are unchanged. The existing\nfilter logic and tests move unchanged.\n\n### Tool schema (`internal/gateway/task_tools.go`)\n\n`ChatTaskLogQuery` gains three fields:\n\n- `Level []string` (forwarded to `Query.Levels`)\n- `Since time.Time` / `Until time.Time` (forwarded as `Query.Since/Until`)\n- `AfterID int64` (the cursor; 0 to start at the beginning)\n\n`ChatTaskLogResult` gains two fields:\n\n- `Cursor int64` -- highest ID in this page; pass back as `AfterID` to continue\n- `MoreAvailable bool` -- true iff the scan saw more matching entries that\n did not fit in this page\n\nThe tool description is updated to teach the model the pagination\nprotocol in one sentence: \"pass the previous `cursor` back as `Line truncated
},
{
"url": "/dev/prds/task-run-detail/",
"title": "Per-run task detail: attempts, stages, changes, config, debug",
"section": "PRDs",
"body": "# Per-run task detail: attempts, stages, changes, config, debug\n\n**Status:** Approved\n**Authority:** the surface contract itself is\n`docs/architecture/observability.md`.\n**Date:** 2026-09-18\n**Compounds with:** `docs/prds/task-logs-pagination.md` (a bounded read says\nwhat it does not show), `docs/prds/status-health-surface.md` (no surface that\nanswers something already answered elsewhere).\n\n## Decision\n\nA task gets one detail page that answers \"what did this run actually do?\" per\n**attempt**: an ordered stage rail, the change each commit/push produced, the\neffective configuration the attempt ran under, the attempt's log, and the raw\nrecord behind all of it.\n\nThe single organising idea is **attempt attribution**. The dashboard\nrenders a task's whole event stream as one flat timeline, so a retried task\nreads as one long run with two of everything. Every new panel is scoped to one\nattempt and says which one.\n\nThe second organising idea is **provenance, not re-derivation**. What a run\nproduced is captured at the producer, while the evidence exists, and persisted\ndurably. Nothing in this surface tries to reconstruct a past run from state\nthat has since moved on.\n\n## The requirement set\n\n| # | Requirement | Mechanism |\n| --- | --- | --- |\n| R1 | Per-attempt stage rail: stages with name, start, duration, terminal status and error, ordered within one attempt | `GET /api/tasks/{id}/attempts` reads the task's events and groups them by `attempt` |\n| R2 | Events carry an attempt, migrated safely and carried on the wire | `events.attempt` column + presence-gated migrator arm; `Event.attempt = 11` |\n| R3 | Changed files captured at commit/push, persisted per task, exposed, shown with repo/PR links | `changes_captured` durable event written by the commit/push steps; `GET /api/tasks/{id}/changes` |\n| R4 | The effective configuration an attempt ran under, secrets redacted, shown | `config_captured` durable event written once per attempt; read from the events response the page already holds |\n| R5 | Log pane filters by attempt, stage and level; absence stays distinct from an unreadable deployment | `logging.Query.Stage` + `ReadTaskLogRequest.stage = 9`; the pane keeps `disabled` and `found=false` apart |\n| R6 | Retry is reachable from the run view and produces a new attempt shown as a new run | Existing retry action, labelled as a NEW run whose confirm states the previous attempt's commits are discarded |\n| R7 | Raw JSON of the task record and its events for the selected attempt | `GET /api/tasks/{id}/debug` |\n| R8 | Deep-linkable, reload-safe per-task detail page that keeps existing URLs working | `/tasks/{id}` route beside the existing `/tasks?task=N` and `/tasks?status=...` |\n| R9 | Design polish: hierarchy, tokens, both themes, responsive rail, a11y, loading/empty/error states | UI lane; measured at 480px and 700px in both themes |\n| R10 | Documentation of record | This document plus `docs/architecture/observability.md` |\n| R11 | Red-first tests for every new behaviour, full gate, `task ui`, forced `go build ./...`, `go test -race` on touched packages | Per lane; the anti-cost-cutting requirement lives here |\n\n## Attempt attribution: a column, not a guess\n\n`events.Event.Attempt`, persisted as the `events.attempt` column\n(`internal/infrastructure/postgres/migrations/0001_state_store.sql`), is a real column,\n`NOT NULL DEFAULT 0`. It was chosen over segmenting the stream on `task_queued` /\n`task_retried` because a fold would have to guess which side of a boundary an\nevent belongs to when the daemon restarts mid-attempt, when `RecoverStale`\nrequeues, or when two attempts interleave across a crash. A guess rendered as\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\nstrucLine truncated
},
{
"url": "/dev/prds/task-run-master-detail/",
"title": "Task run detail as a master-detail split pane",
"section": "PRDs",
"body": "# Task run detail as a master-detail split pane\n\n**Status:** Approved\n**Authority:** the panel contracts stay as ratified in\n`docs/prds/task-run-detail.md`; this document changes only the run page's\narrangement of them.\n**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution, the\nlog stage filter, the per-panel honesty rules).\n\n## Decision\n\nThe run page's five tabs become two panes. The stage rail is the **master**,\nalways visible on the left. The four context panels — log, changed files,\nconfiguration, debug — are the **inspector** on the right, and their tab bar\nmoves into the inspector. The \"Stages\" tab stops existing.\n\nSelecting a stage switches the inspector to the log tab and sets the log\npane's stage filter to that stage. Changing the filter afterwards is the\noperator's choice and is not overridden; rail selection never touches the\nlevel filter. Clicking the selected stage again returns the filter to all\nstages. A stage with no name is rendered but not selectable.\n\nSwitching attempts resets the stage filter to all stages: a selection was\ncommanded on the attempt it was made on, and a different attempt presents a\ndifferent stage list. Changed files, configuration and debug stay\nattempt-scoped; a stage selection never scopes them.\n\n## What does not change\n\n- No new endpoint, RPC, table or configuration field. Every read is one the\n page already makes.\n- The URL contract: `tab` and `attempt` ride in the query string and survive\n a reload. Log filters are not part of the URL; a reload returns the log to\n all stages. `tab=stages` stays a valid URL and renders the log tab; the\n page never generates it again.\n- Attempt attribution, the log stage filter's coverage limit and every\n honesty rule in `task-run-detail.md` still apply: each pane states what it\n cannot show under that document's rendering rules.\n- The task header and the attempt selector sit above both panes.\n\n## Arrangement\n\n- Left pane: fixed-width rail (20rem) with the attempt's stage rows. Status,\n duration, error, the stage's agent report, the attempt's status badge and\n start time, and the attempt-attribution footnotes render in the rail.\n- Right pane: the inspector's tab bar plus the selected panel, filling the\n remaining width.\n- Below the shell's 900px frame breakpoint the rail stacks above the\n inspector; neither pane is hidden.\n- Keyboard: the rail keeps its list semantics and each stage row is a real\n button, so selection and deselection work without a pointer; the inspector\n keeps the WAI-ARIA tabs pattern the tab bar already provides.\n\n## Acceptance\n\n1. The rail is visible without opening any tab, and no \"Stages\" trigger exists.\n2. Clicking a stage opens the log filtered to that stage; clicking it again\n shows all stages.\n3. After a stage selection, a filter change made by the operator is kept, and\n the level filter survives the selection.\n4. Switching attempts resets the stage filter to all stages, and no rail row\n on the new attempt renders as selected unless the operator selected it\n there.\n5. `tab=stages` loads and renders the log tab.\n6. Every inspector tab and attempt deep-link survives a reload.\n7. A stage is selectable and deselectable by keyboard, and the selection\n mirrors the log pane's stage filter.\n8. Below 900px the rail stacks above the inspector.\n9. `task check` passes clean and `ui/dist` matches the sources."
"body": "# Task run detail as a master-detail split pane\n\n**Status:** Approved\n**Authority:** the panel contracts stay as ratified in\n`docs/prds/task-run-detail.md`; this document changes only the run page's\narrangement of them.\n**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution, the\nlog stage filter, the per-panel honesty rules).\n\n## Decision\n\nThe run page's five tabs become two panes. The stage rail is the **master**,\nalways visible on the left. The four context panels — log, changed files,\nconfiguration, debug — are the **inspector** on the right, and their tab bar\nmoves into the inspector. The \"Stages\" tab stops existing.\n\nSelecting a stage switches the inspector to the log tab and sets the log\npane's stage filter to that stage. Changing the filter afterwards is the\noperator's choice and is not overridden; rail selection never touches the\nlevel filter. Clicking the selected stage again returns the filter to all\nstages. A stage with no name is rendered but not selectable.\n\nSwitching attempts resets the stage filter to all stages: a selection was\ncommanded on the attempt it was made on, and a different attempt presents a\ndifferent stage list. Changed files, configuration and debug stay\nattempt-scoped; a stage selection never scopes them.\n\n## What does not change\n\n- No new endpoint, RPC, table or configuration field. Every read is one the\n page already makes.\n- The URL contract: `tab` and `attempt` ride in the query string and survive\n a reload. Log filters are not part of the URL; a reload returns the log to\n all stages. `tab=stages` stays a valid URL and renders the log tab; the\n page never generates it again.\n- Attempt attribution, the log stage filter's coverage limit and every\n honesty rule in `task-run-detail.md` still apply: each pane states what it\n cannot show under that document's rendering rules.\n- The task header and the attempt selector sit above both panes.\n\n## Arrangement\n\n- Left pane: fixed-width rail (20rem) with the attempt's stage rows. Status,\n duration, error, the stage's agent report, the attempt's status badge and\n start time, and the attempt-attribution footnotes render in the rail.\n- Right pane: the inspector's tab bar plus the selected panel, filling the\n remaining width.\n- Below the shell's 900px frame breakpoint the rail stacks above the\n inspector; neither pane is hidden.\n- Keyboard: the rail keeps its list semantics and each stage row is a real\n button, so selection and deselection work without a pointer; the inspector\n keeps the WAI-ARIA tabs pattern the tab bar already provides.\n\n## Acceptance\n\n1. The rail is visible without opening any tab, and no \"Stages\" trigger exists.\n2. Clicking a stage opens the log filtered to that stage; clicking it again\n shows all stages.\n3. After a stage selection, a filter change made by the operator is kept, and\n the level filter survives the selection.\n4. Switching attempts resets the stage filter to all stages, and no rail row\n on the new attempt renders as selected unless the operator selected it\n there.\n5. `tab=stages` loads and renders the log tab.\n6. Every inspector tab and attempt deep-link survives a reload.\n7. A stage is selectable and deselectable by keyboard, and the selection\n mirrors the log pane's stage filter.\n8. Below 900px the rail stacks above the inspector.\n9. `task check` passes clean and `ui/dist` matches the sources.\n"
},
{
"url": "/dev/prds/ui-service-boundary/",
"title": "UI Service boundary and configuration ownership",
"section": "PRDs",
"body": "# UI Service boundary and configuration ownership\n\n**Status:** Approved\n**Revision:** 1\n**Date:** 2026-09-07\n**Beads issue:** `archie-core-8cda.5.1`\n**Parent:** [`service-decomposition.md`](/dev/prds/service-decomposition/)\n**Prerequisites:** Gateway contract extraction and State Store contract ratification\n\nThis document is the authority for Phase 3 UI Service implementation. It fixes\nthe process boundary, configuration ownership, client contracts, security\nposture, readiness behaviour, and migration evidence required by\n`archie-core-8cda.5.2` and later UI extraction work.\n\n## Decision\n\nThe UI Service owns the operator-facing HTTP surface and the compiled SPA. It\nserves `ui/dist` and exposes UI-specific JSON DTOs for dashboard views and\nactions. It does not own conversations, task state, workflow execution,\nchannel lifecycle, forge access, or the daemon's runtime configuration.\n\nThe UI Service consumes two typed remote capabilities:\n\n- Gateway's `gateway.ChatContract` through the versioned Gateway gRPC\n contract, for chat snapshots, messages, turns, streaming, persona changes,\n cancellation, and Gateway task actions.\n- State Store's narrow read/write contracts through the versioned State Store\n gRPC contract, for task views, events, captures, mappings, bindings, and\n configuration data explicitly projected for the dashboard.\n\nThe UI process may compose local adapters during the migration seam, but the\nadapter implements the same wire-safe contract as the remote client. The\nproduction extraction cutover removes the in-process adapter in the same\nchange; a dual-live UI authority is not permitted.\n\n## Boundary and ownership\n\n| Concern | UI Service owns | UI Service may consume | UI Service must not own or receive |\n|---|---|---|---|\n| HTTP and SPA | routes, auth middleware, UI DTOs, assets, HTTP lifecycle | contract results and health snapshots | domain entities or infrastructure handles |\n| Chat | request validation and response projection | Gateway `ChatContract` | `gateway.Router`, `SessionStore`, turn runner, model/provider runtime |\n| Task dashboard | query/action DTOs and HTTP status mapping | State Store narrow contracts and explicitly ratified task-action contract | `*store.Store`, SQL connections, workflow registry, daemon pointer |\n| Configuration page | secret-free view and update request validation | a UI configuration contract owned by the configuration/application boundary | `config.Config`, `config.Holder`, secret registry, reload implementation |\n| Readiness | UI process liveness and dependency readiness aggregation | bounded health results from Gateway and State Store | direct probing of private databases or providers |\n\nEvery value crossing the process boundary is a versioned DTO or scalar contract\nvalue. `internal/webui` may retain temporary Go-side adapters while the\nmigration is in progress, but handlers must map Gateway/State Store values to\nUI-owned response types at the HTTP edge. A constructor accepting a concrete\nGateway, State Store, daemon, or `config.Holder` is not an approved final\nboundary.\n\nThe existing UI routes remain behaviourally compatible during extraction,\nincluding task actions, SSE event delivery, config views, chat streaming,\ncapture intake, mappings, bindings, update reporting, and health endpoints.\nCompatibility preserves status codes, authentication requirements, redaction,\npagination/limits, event ordering, and failure degradation unless a separately\nratified contract changes them.\n\nThe route families have these target owners. This is the required inventory for\nthe implementation children; a route without an owner is not eligible for\ncutover.\n\n| Route family | Target owner consumed by UI | Migration status |\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
"body": "# UI Service boundary and configuration ownership\n\n**Status:** Approved\n**Revision:** 1\n**Date:** 2026-09-07\n**Beads issue:** `archie-core-8cda.5.1`\n**Parent:** [`service-decomposition.md`](/dev/prds/service-decomposition/)\n**Prerequisites:** Gateway contract extraction and State Store contract ratification\n\nThis document is the authority for Phase 3 UI Service implementation. It fixes\nthe process boundary, configuration ownership, client contracts, security\nposture, readiness behaviour, and migration evidence required by\n`archie-core-8cda.5.2` and later UI extraction work.\n\n## Decision\n\nThe UI Service owns the operator-facing HTTP surface and the compiled SPA. It\nserves `ui/dist` and exposes UI-specific JSON DTOs for dashboard views and\nactions. It does not own conversations, task state, workflow execution,\nchannel lifecycle, forge access, or the daemon's runtime configuration.\n\nThe UI Service consumes two typed remote capabilities:\n\n- Gateway's `gateway.ChatContract` through the versioned Gateway gRPC\n contract, for chat snapshots, messages, turns, streaming, persona changes,\n cancellation, and Gateway task actions.\n- State Store's narrow read/write contracts through the versioned State Store\n gRPC contract, for task views, events, captures, mappings, bindings, and\n configuration data explicitly projected for the dashboard.\n\nThe UI process may compose local adapters during the migration seam, but the\nadapter implements the same wire-safe contract as the remote client. The\nproduction extraction cutover removes the in-process adapter in the same\nchange; a dual-live UI authority is not permitted.\n\n## Boundary and ownership\n\n| Concern | UI Service owns | UI Service may consume | UI Service must not own or receive |\n| ------------------ | -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| HTTP and SPA | routes, auth middleware, UI DTOs, assets, HTTP lifecycle | contract results and health snapshots | domain entities or infrastructure handles |\n| Chat | request validation and response projection | Gateway `ChatContract` | `gateway.Router`, `SessionStore`, turn runner, model/provider runtime |\n| Task dashboard | query/action DTOs and HTTP status mapping | State Store narrow contracts and explicitly ratified task-action contract | `*store.Store`, SQL connections, workflow registry, daemon pointer |\n| Configuration page | secret-free view and update request validation | a UI configuration contract owned by the configuration/application boundary | `config.Config`, `config.Holder`, secret registry, reload implementation |\n| Readiness | UI process liveness and dependency readiness aggregation | bounded health results from Gateway and State Store | direct probing of private databases or providers |\n\nEvery value crossing the process boundary is a versioned DTO or scalar contract\nvalue. `internal/webui` may retain temporary Go-side adapters while the\nmigration is in progress, but handlers must map Gateway/State Store values to\nUI-owned response types at the HTTP edge. A constructor accepting a concrete\nGateway, State Store, daemon, or `config.Holder` is not an approved final\nboundary.\n\nThe existing UI routes remain behaviourally compatible during extraction,\nincluding task actions, SSE event delivery, config views, chat streaming,\ncapture intake, mappings, bindings, update reporting, and health endpoints.\nCompatibility preserves status codes, authentication requirements, redaction,\npagination/limits, event ordering, and failure degradation unless a separately\nratified contract changes them.\n\nThe route families have these target owners. This is the required inventory for\nthe implementation children; a route without an owner is not eligible for\ncutover.\n\n| Route family | Target owner consumed by UI | Migration status Line truncated
},
{
"url": "/dev/prds/vue-migration-checklist/",
"title": "Preact → Vue 3 + shadcn-vue migration checklist",
"section": "PRDs",
"body": "# Preact → Vue 3 + shadcn-vue migration checklist\n\n**Status:** Approved\n**Date:** 2026-09-20\n**Bead:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation restructure)\n**Bootstrap commit:** `e18fb8b2`\n\nThe Preact dashboard was deleted, not ported incrementally. This is the list of\nwhat has to exist again, what must not be lost on the way, and the contracts\nthat break silently if missed.\n\nDeleted source is recoverable at `git show e18fb8b2^:ui/src/\u003cpath\u003e`. Every\nclaim below was cross-checked against that tree; where a number is a live\nmeasurement rather than something recoverable from git, it says so.\n\n## Invariants that outlive the framework\n\nThese are not features; they are things other processes depend on. Breaking one\ndoes not show up as a broken page.\n\n- [ ] **Embed contract.** `ui/embed.go` embeds a committed `ui/dist`. The build\n must keep unhashed `assets/index.{js,css}`: dist/ lives in git, and\n hashed names orphan a file on every rebuild.\n- [ ] **Route registry.** `internal/gateway/dashboard_tools.go` hand-copies the\n route table and `TestDashboardPagesRegistryCoversEveryRoute` parses\n `ui/src/router/index.ts` to hold them in step. The parser needs\n `const routes = [` on its own line, `path: \"...\"` on a single line per\n route, and `nav: false` on any entry the registry should skip. That guard\n caught a stale `/chat` entry earlier.\n- [ ] **Mutation headers.** Every POST/PATCH/DELETE must send **both**\n `X-Archie-CSRF: 1` and `Content-Type: application/json`. The server\n returns 403 without the first and 415 without the second\n (`internal/webui/api_tasks.go`, `authorizeTaskMutation`). GET sends\n neither. This is the single most likely thing to silently break every\n write after the port.\n- [x] **History routing.** `createWebHistory`, `base: \"/\"`. Legacy `#/path`\n links are rewritten by `src/legacy-hash-redirect.ts`. The chat navigate\n chip should emit `/tasks`; the Go side already stores bare paths.\n- [ ] **Capability gating.** `GET /api/capabilities`\n (`internal/webui/api_capabilities.go`) returns a `sections` map of ten\n booleans: chat, logs, skills, curators, channels, captures, mappings,\n bindings, and workflows/settings which are always true. A route whose\n section is false must be hidden, not rendered empty. **Fail open**: on a\n failed or null response hide nothing — the old client used a bare\n `.catch(() =\u003e {})` for exactly this. A page that says \"unavailable\" is\n recoverable; a nav entry that vanished is not.\n- [ ] **`LOG_LEVELS`** in `base/log-row.jsx` is a wire contract, not a display\n list: the CSV level filter is matched server-side by `splitCSV` in\n `internal/webui/api_tasks_logs.go`. A value mismatch breaks filtering\n with no error.\n- [ ] **SSE lifecycle.** Three streams, all `id: \u003cn\u003e\\ndata: \u003cjson\u003e\\n\\n` except\n chat which omits the id:\n `/events` (task lifecycle, `sse.go`, supports `?since=` and\n `Last-Event-ID` resume), `/api/logs/stream` (`api_logs.go`, same\n resume protocol), `/api/chat/stream` (`api_chat.go`, frames typed\n delta/tool/media/navigate). Each must be closed on unmount or the app\n leaks a connection per navigation. Preact used an `archie:teardown`\n event; Vue should use `onUnmounted`.\n\n\u003e **On tests.** Per Sam's call, the 43-file suite was not ported and tests\n\u003e return when there is behaviour worth pinning. Flagging one exception for when\n\u003e that moment comes: the deleted `ui/test/api-client.test.js` classified every\n\u003e API method as mutation/read/stream/url and asserted the right headers per\n\u003e class. It is the only cheap guard on the CSRF contract above. (It did **not**\n\u003e text-scan for a second `fetch()` — that check was deliberately removed\n\u003e upstream for testing the file's wording rather than its behaviour.)\n\n## Phase 1 — Foundation\n\n- [x] **Theme.** `css/tokens.css` was a complete two-theme semantic token set\n (`--fg-subtle`, `--accent`, `--ok/warn/danger`, surfaces, shadows). Mapped\n onto Tailwind v4's `@theme` in `src/style.css`; the second system was not\n kept.\n- [x] **`color-scheme`.** `[data-theme=\"dark\"] { color-scheme: dark }` and the\n light equivalent. Without it the UA paints light scrollbars and light\n native controls inside the dark app. Fixed; trivially lost.\n- [x] **Contrast values.** The violet palette moved these off the values pinned\n here, so they were recomputed against its own backgrounds instead of\n carried: `--fg-subtle` `#A99DBD` dark (7.67:1, AAA) / `#6E6577` light\n (4.87:1, AA), and `--fg-muted` `#B9AECB` / `#635B6B` (9.28:1 and 5.70:1).\n The invariant the pin existed for holds; the values are the palette's.\n- [x] **API client** (`base/api.jsx` → `src/lib/api.tLine truncated
"body": "# Preact → Vue 3 + shadcn-vue migration checklist\n\n**Status:** Approved\n**Date:** 2026-09-20\n**Bead:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation restructure)\n**Bootstrap commit:** `e18fb8b2`\n\nThe Preact dashboard was deleted, not ported incrementally. This is the list of\nwhat has to exist again, what must not be lost on the way, and the contracts\nthat break silently if missed.\n\nDeleted source is recoverable at `git show e18fb8b2^:ui/src/\u003cpath\u003e`. Every\nclaim below was cross-checked against that tree; where a number is a live\nmeasurement rather than something recoverable from git, it says so.\n\n## Invariants that outlive the framework\n\nThese are not features; they are things other processes depend on. Breaking one\ndoes not show up as a broken page.\n\n- [ ] **Embed contract.** `ui/embed.go` embeds a committed `ui/dist`. The build\n must keep unhashed `assets/index.{js,css}`: dist/ lives in git, and\n hashed names orphan a file on every rebuild.\n- [ ] **Route registry.** `internal/gateway/dashboard_tools.go` hand-copies the\n route table and `TestDashboardPagesRegistryCoversEveryRoute` parses\n `ui/src/router/index.ts` to hold them in step. The parser needs\n `const routes = [` on its own line, `path: \"...\"` on a single line per\n route, and `nav: false` on any entry the registry should skip. That guard\n caught a stale `/chat` entry earlier.\n- [ ] **Mutation headers.** Every POST/PATCH/DELETE must send **both**\n `X-Archie-CSRF: 1` and `Content-Type: application/json`. The server\n returns 403 without the first and 415 without the second\n (`internal/webui/api_tasks.go`, `authorizeTaskMutation`). GET sends\n neither. This is the single most likely thing to silently break every\n write after the port.\n- [x] **History routing.** `createWebHistory`, `base: \"/\"`. Legacy `#/path`\n links are rewritten by `src/legacy-hash-redirect.ts`. The chat navigate\n chip should emit `/tasks`; the Go side already stores bare paths.\n- [ ] **Capability gating.** `GET /api/capabilities`\n (`internal/webui/api_capabilities.go`) returns a `sections` map of ten\n booleans: chat, logs, skills, curators, channels, captures, mappings,\n bindings, and workflows/settings which are always true. A route whose\n section is false must be hidden, not rendered empty. **Fail open**: on a\n failed or null response hide nothing — the old client used a bare\n `.catch(() =\u003e {})` for exactly this. A page that says \"unavailable\" is\n recoverable; a nav entry that vanished is not.\n- [ ] **`LOG_LEVELS`** in `base/log-row.jsx` is a wire contract, not a display\n list: the CSV level filter is matched server-side by `splitCSV` in\n `internal/webui/api_tasks_logs.go`. A value mismatch breaks filtering\n with no error.\n- [ ] **SSE lifecycle.** Three streams, all `id: \u003cn\u003e\\ndata: \u003cjson\u003e\\n\\n` except\n chat which omits the id:\n `/events` (task lifecycle, `sse.go`, supports `?since=` and\n `Last-Event-ID` resume), `/api/logs/stream` (`api_logs.go`, same\n resume protocol), `/api/chat/stream` (`api_chat.go`, frames typed\n delta/tool/media/navigate). Each must be closed on unmount or the app\n leaks a connection per navigation. Preact used an `archie:teardown`\n event; Vue should use `onUnmounted`.\n\n\u003e **On tests.** Per Sam's call, the 43-file suite was not ported and tests\n\u003e return when there is behaviour worth pinning. Flagging one exception for when\n\u003e that moment comes: the deleted `ui/test/api-client.test.js` classified every\n\u003e API method as mutation/read/stream/url and asserted the right headers per\n\u003e class. It is the only cheap guard on the CSRF contract above. (It did **not**\n\u003e text-scan for a second `fetch()` — that check was deliberately removed\n\u003e upstream for testing the file's wording rather than its behaviour.)\n\n## Phase 1 — Foundation\n\n- [x] **Theme.** `css/tokens.css` was a complete two-theme semantic token set\n (`--fg-subtle`, `--accent`, `--ok/warn/danger`, surfaces, shadows). Mapped\n onto Tailwind v4's `@theme` in `src/style.css`; the second system was not\n kept.\n- [x] **`color-scheme`.** `[data-theme=\"dark\"] { color-scheme: dark }` and the\n light equivalent. Without it the UA paints light scrollbars and light\n native controls inside the dark app. Fixed; trivially lost.\n- [x] **Contrast values.** The violet palette moved these off the values pinned\n here, so they were recomputed against its own backgrounds instead of\n carried: `--fg-subtle` `#A99DBD` dark (7.67:1, AAA) / `#6E6577` light\n (4.87:1, AA), and `--fg-muted` `#B9AECB` / `#635B6B` (9.28:1 and 5.70:1).\n The invariant the pin existed for holds; the values are the palette's.\n- [x] **API client** (`base/api.jsx` → `src/lib/api.tLine truncated
},
{
"url": "/dev/prds/webhook-intake-security/",
+4
View File
@@ -53,6 +53,8 @@
"/news/archie/1.4.1/": "/news/1.4.1/",
"/news/archie/1.40.0/": "/news/1.40.0/",
"/news/archie/1.41.0/": "/news/1.41.0/",
"/news/archie/1.41.1/": "/news/1.41.1/",
"/news/archie/1.41.2/": "/news/1.41.2/",
"/news/archie/1.5.0/": "/news/1.5.0/",
"/news/archie/1.6.0/": "/news/1.6.0/",
"/news/archie/1.7.0/": "/news/1.7.0/",
@@ -123,6 +125,8 @@
"/news/archied/1.4.1/": "/news/1.4.1/",
"/news/archied/1.40.0/": "/news/1.40.0/",
"/news/archied/1.41.0/": "/news/1.41.0/",
"/news/archied/1.41.1/": "/news/1.41.1/",
"/news/archied/1.41.2/": "/news/1.41.2/",
"/news/archied/1.5.0/": "/news/1.5.0/",
"/news/archied/1.6.0/": "/news/1.6.0/",
"/news/archied/1.7.0/": "/news/1.7.0/",
+10
View File
@@ -1,4 +1,14 @@
[
{
"version": "1.41.2",
"date": "2026-09-25",
"body": "### archied\n\n- **`/update` no longer offers an old runtime.** The runtime has shipped under\n the release version since the version streams merged, but the update check\n still read the retired runtime tags, so a current host was offered runtime\n 1.35.0 as an update. Do not approve that offer on 1.41.1; update to 1.41.2\n instead.\n- **`/version` reports the runtime version.** Binaries from the release zip\n showed `Runtime: dev`."
},
{
"version": "1.41.1",
"date": "2026-09-25",
"body": "### archied\n\n- **First published build of 1.41.0.** The 1.41.0 tag produced no release\n artifacts; 1.41.1 carries everything listed under 1.41.0 below, including\n the PostgreSQL 18 requirement and the removed config keys."
},
{
"version": "1.41.0",
"date": "2026-09-25",
-5
View File
@@ -29,11 +29,6 @@ its id.
## Verification
- `TestTaskMetaPayloadMatchesFixture` requires the handler to serve
`internal/webui/testdata/task_meta.json` byte for byte. Regenerate it with
`go test ./internal/webui -run TestTaskMetaPayloadMatchesFixture -update`.
- `ui/test/task-meta-snapshot.test.ts` requires the snapshot to equal that
fixture.
- `TestTaskMetaChangeStatusesAreDeliberate` fails when a `Change*` constant is
added without a label.
-80
View File
@@ -2,10 +2,6 @@ package gateway
import (
"context"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
@@ -13,82 +9,6 @@ import (
// the signature, so a background context is safe and deterministic.
func quietContext() context.Context { return context.Background() }
// routePathRe matches one route entry's path in the dashboard's route table.
var routePathRe = regexp.MustCompile(`path:\s*"([^"]+)"`)
// dashboardRoutesFromSource reads the dashboard's route table out of the UI
// source.
//
// The page registry is what the agent is told the dashboard exposes, and it is
// a hand-copy of that table. Hand-copies drift: /memory stayed in the registry
// after the page was deleted, and /bindings and /curators were never added --
// so the agent offered the operator a route that no longer existed and was
// blind to two that did. Reading the table back is what turns the registry's
// "single source of truth" claim into something a test can hold.
func dashboardRoutesFromSource(t *testing.T) []string {
t.Helper()
path := filepath.Join("..", "..", "ui", "src", "router", "index.ts")
src, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
block := string(src)
start := strings.Index(block, "const routes = [")
if start < 0 {
t.Fatalf("%s: no routes table", path)
}
block = block[start:]
if end := strings.Index(block, "\n];"); end >= 0 {
block = block[:end]
}
// One route per line. A detail route (nav: false) is addressed by URL but is
// not a navigation entry, so the registry does not carry it.
var paths []string
for line := range strings.SplitSeq(block, "\n") {
match := routePathRe.FindStringSubmatch(line)
if match == nil || strings.Contains(line, "nav: false") {
continue
}
paths = append(paths, match[1])
}
if len(paths) == 0 {
t.Fatalf("%s: parsed no routes", path)
}
return paths
}
func TestDashboardPagesRegistryCoversEveryRoute(t *testing.T) {
pages := DashboardPages()
if len(pages) == 0 {
t.Fatal("DashboardPages() returned no pages")
}
seen := map[string]bool{}
for _, p := range pages {
if p.Path == "" || p.Label == "" || p.Description == "" {
t.Fatalf("page %#v is missing path/label/description", p)
}
if seen[p.Path] {
t.Fatalf("duplicate page path %q", p.Path)
}
seen[p.Path] = true
}
routes := dashboardRoutesFromSource(t)
inDashboard := map[string]bool{}
for _, route := range routes {
inDashboard[route] = true
if !seen[route] {
t.Errorf("route %q is a dashboard page the registry does not list, so the agent cannot point at it", route)
}
}
for _, p := range pages {
if !inDashboard[p.Path] {
t.Errorf("registry lists %q (%s), which is not a dashboard route: the agent would send the operator somewhere that does not exist", p.Path, p.Label)
}
}
}
func TestPageIndexToolReturnsEveryPage(t *testing.T) {
entry, ok := pageIndexTool()
if !ok {
+4 -2
View File
@@ -110,7 +110,9 @@ esac
if got, want := componentAvailable(snapshot, ComponentDaemon), "1.23.0"; got != want {
t.Errorf("daemon available = %q, want %q", got, want)
}
if got, want := componentAvailable(snapshot, ComponentAgent), "1.21.0"; got != want {
// One version covers every component; a stale archie/v* runtime tag must
// never be offered as an update.
if got, want := componentAvailable(snapshot, ComponentAgent), "1.23.0"; got != want {
t.Errorf("agent available = %q, want %q", got, want)
}
}
@@ -154,7 +156,7 @@ esac
if got, want := componentAvailable(snapshot, ComponentDaemon), "1.24.0"; got != want {
t.Errorf("daemon available = %q, want %q", got, want)
}
if got, want := componentAvailable(snapshot, ComponentAgent), "1.23.0"; got != want {
if got, want := componentAvailable(snapshot, ComponentAgent), "1.24.0"; got != want {
t.Errorf("agent available = %q, want %q", got, want)
}
if ref := componentReference(snapshot, ComponentDaemon); !strings.Contains(ref, "forge-api-tags") {
+17 -16
View File
@@ -81,32 +81,33 @@ func TestUpdateInstallBothComponentsBuildsDaemonAndManagedWorkerImage(t *testing
// releases are the norm. Each changed component must be built from its own
// approved tag; forcing both tags onto one commit refuses every update once
// the two components' newest releases diverge.
func TestUpdateInstallBuildsEachComponentFromItsOwnTag(t *testing.T) {
// One version covers every component, so the managed worker image is built
// from the release's own archied/v* tag -- never from a stale archie/v* tag.
func TestUpdateInstallBuildsTheAgentImageFromTheReleaseTag(t *testing.T) {
result, calls := runUpdateInstallScript(t, map[string]string{
"ARCHIE_UPDATE_DAEMON_PREVIOUS": "1.12.0",
"ARCHIE_UPDATE_DAEMON_VERSION": "1.13.0",
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.9.9",
"ARCHIE_UPDATE_AGENT_VERSION": "1.10.0",
"ARCHIE_UPDATE_AGENT_PREVIOUS": "1.12.0",
"ARCHIE_UPDATE_AGENT_VERSION": "1.13.0",
})
if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.10.0" {
t.Fatalf("installed = %#v, want both release versions", result.Installed)
if result.Installed[ComponentDaemon] != "1.13.0" || result.Installed[ComponentAgent] != "1.13.0" {
t.Fatalf("installed = %#v, want the release version for both", result.Installed)
}
// The derived fake commits differ per tag, so these assertions fail if
// either component is built from the other's release.
daemonCheckout := indexOfCallContaining(t, calls, "checkout --quiet --detach archied-v1.13.0")
agentCheckout := indexOfCallContaining(t, calls, "checkout --quiet --detach archie-v1.10.0")
assertCallAbsent(t, calls, "archie-v1.13.0")
daemonBuild := indexOfCallContaining(t, calls, "go build", "./cmd/archied")
agentImageBuild := indexOfCallContaining(t, calls, "docker build")
if daemonCheckout < 0 || agentCheckout < 0 || daemonBuild < 0 || agentImageBuild < 0 {
t.Fatalf("missing expected step: daemon checkout %d, daemon build %d, agent checkout %d, agent image build %d",
daemonCheckout, daemonBuild, agentCheckout, agentImageBuild)
lastCheckout := -1
for i, call := range calls {
if strings.Contains(call, "checkout --quiet --detach") && i < agentImageBuild {
lastCheckout = i
}
}
if daemonCheckout > daemonBuild {
t.Errorf("daemon binaries must be built from the daemon tag's commit; calls = %#v", calls)
if daemonBuild < 0 || agentImageBuild < 0 || lastCheckout < 0 {
t.Fatalf("missing expected step: daemon build %d, agent image build %d, checkout %d", daemonBuild, agentImageBuild, lastCheckout)
}
if agentCheckout > agentImageBuild {
t.Errorf("the managed worker image must be built from the agent tag's commit; calls = %#v", calls)
if !strings.Contains(calls[lastCheckout], "archied-v1.13.0") {
t.Errorf("image built after checking out %q, want the archied/v1.13.0 release; calls = %#v", calls[lastCheckout], calls)
}
}
-54
View File
@@ -1,24 +1,14 @@
package webui
import (
"bytes"
"encoding/json"
"flag"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
)
// updateTaskMetaFixture rewrites the committed payload fixture from the served
// handler. It is the same generated-artifact discipline the repo already uses
// for docs/data/generated/contracts.json (task docs:generate): the fixture is
// committed, the gate checks rather than regenerates, and the -update run is
// what blesses a deliberate vocabulary change.
var updateTaskMetaFixture = flag.Bool("update", false, "rewrite testdata/task_meta.json from the served /api/task-meta payload")
// The dashboard derives everything it can present from /api/task-meta. If the
// catalog is empty or malformed the frontend falls back to its own defaults and
// the whole point of the endpoint -- one server-held vocabulary -- is lost.
@@ -116,47 +106,3 @@ func TestTaskMetaChangeStatusesAreDeliberate(t *testing.T) {
labels[cs.Label] = cs.ID
}
}
// TestTaskMetaPayloadMatchesFixture pins the served payload byte-for-byte
// against the committed fixture, and the fixture against the dashboard's
// freeze-dried snapshot (ui/src/base/task-meta.jsx) via
// ui/test/task-meta-catalogue.test.js. Between the two, a one-sided rename of a
// status label, an action, a change status or the config schema fails a test on
// whichever side was not updated -- the property neither per-side literal test
// could provide.
//
// Regenerate with:
//
// go test ./internal/webui -run TestTaskMetaPayloadMatchesFixture -update
func TestTaskMetaPayloadMatchesFixture(t *testing.T) {
srv := newTestServer(t)
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/task-meta", nil)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, body %s", w.Code, w.Body)
}
served := w.Body.Bytes()
const fixture = "testdata/task_meta.json"
if *updateTaskMetaFixture {
if err := os.MkdirAll("testdata", 0o755); err != nil {
t.Fatalf("mkdir testdata: %v", err)
}
if err := os.WriteFile(fixture, served, 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
return
}
committed, err := os.ReadFile(fixture)
if err != nil {
t.Fatalf("read %s: %v\nrun: go test ./internal/webui -run TestTaskMetaPayloadMatchesFixture -update", fixture, err)
}
if !bytes.Equal(served, committed) {
t.Errorf("GET /api/task-meta no longer matches %s.\n"+
"The fixture pins the dashboard's freeze-dried snapshot (ui/src/base/task-meta.jsx);\n"+
"ui/test/task-meta-catalogue.test.js fails until both sides agree.\n"+
"regenerate with: go test ./internal/webui -run TestTaskMetaPayloadMatchesFixture -update", fixture)
}
}
-78
View File
@@ -1,78 +0,0 @@
{
"statuses": [
{ "id": "queued", "label": "Queued", "kind": "idle", "needs_you": false },
{ "id": "running", "label": "Working", "kind": "info", "needs_you": false },
{
"id": "waiting_human",
"label": "Waiting for you",
"kind": "warn",
"needs_you": true
},
{ "id": "pr_open", "label": "In review", "kind": "ok", "needs_you": false },
{ "id": "merged", "label": "Merged", "kind": "ok", "needs_you": false },
{ "id": "completed", "label": "Done", "kind": "ok", "needs_you": false },
{ "id": "parked", "label": "Parked", "kind": "warn", "needs_you": true },
{
"id": "dead",
"label": "Stopped (too many retries)",
"kind": "danger",
"needs_you": false
},
{
"id": "rejected",
"label": "Rejected",
"kind": "danger",
"needs_you": false
},
{
"id": "closed_wont_do",
"label": "Won't do",
"kind": "idle",
"needs_you": false
}
],
"actions": [
{
"id": "cancel",
"label": "Cancel",
"kind": "quiet",
"confirm": "Cancel \"{title}\"? This closes the forge issue."
},
{
"id": "stop",
"label": "Stop",
"kind": "primary",
"confirm": "Stop \"{title}\"? Recoverable work will remain parked."
},
{ "id": "approve", "label": "Approve", "kind": "primary", "confirm": "" },
{
"id": "reject",
"label": "Reject",
"kind": "quiet",
"confirm": "Reject \"{title}\"? This closes the forge issue."
},
{ "id": "retry", "label": "Retry", "kind": "primary", "confirm": "" },
{
"id": "abandon",
"label": "Abandon",
"kind": "quiet",
"confirm": "Abandon \"{title}\"? This closes the forge issue."
},
{
"id": "archive",
"label": "Archive",
"kind": "quiet",
"confirm": "Archive the local record for \"{title}\"?"
},
{ "id": "open_pr", "label": "Open PR", "kind": "link", "confirm": "" },
{ "id": "open_issue", "label": "Open issue", "kind": "link", "confirm": "" }
],
"change_statuses": [
{ "id": "added", "label": "Added" },
{ "id": "modified", "label": "Modified" },
{ "id": "deleted", "label": "Deleted" },
{ "id": "renamed", "label": "Renamed" },
{ "id": "typechange", "label": "Type changed" }
],
"config_schema": "archie/task-config@1"
}
+6 -5
View File
@@ -136,15 +136,16 @@ else
agent_installed="$(base "$(installed_for archie-agent || true)")"
fi
# One version covers every component (RELEASING.md): the runtime image a
# release publishes carries the release's own version, tagged archied/v*.
daemon_available="$(newest_tag_git archied || true)"
agent_available="$(newest_tag_git archie || true)"
tag_source="git-tags"
if [ -z "$daemon_available" ] && [ -z "$agent_available" ]; then
if [ -z "$daemon_available" ]; then
daemon_available="$(newest_tag_api archied || true)"
agent_available="$(newest_tag_api archie || true)"
tag_source="forge-api-tags"
fi
if [ -z "$daemon_available" ] && [ -z "$agent_available" ]; then
agent_available="$daemon_available"
if [ -z "$daemon_available" ]; then
# Neither source answered. Report the failure; do not exit 0 with two empty
# components, which the caller renders as "up to date".
echo "archie-update-check: could not resolve any release tag from ${SOURCE_URL} or ${API_BASE}/repos/${REPO_SLUG}/tags" >&2
@@ -154,7 +155,7 @@ fi
daemon_artifacts=""
[ -n "$daemon_available" ] && daemon_artifacts="$(artifact_state "archied/v${daemon_available}")"
agent_artifacts=""
[ -n "$agent_available" ] && agent_artifacts="$(artifact_state "archie/v${agent_available}")"
agent_artifacts="$daemon_artifacts"
reference_for() {
local component="$1" version="$2" artifacts="$3"
+1 -1
View File
@@ -181,7 +181,7 @@ if [[ ",$components," == *,daemon,* ]]; then
gw_commit="$(git -C "$source_dir" rev-parse --verify "refs/tags/archied/v$GW^{commit}")"
fi
if [[ ",$components," == *,agent,* ]]; then
rt_commit="$(git -C "$source_dir" rev-parse --verify "refs/tags/archie/v$RT^{commit}")"
rt_commit="$(git -C "$source_dir" rev-parse --verify "refs/tags/archied/v$RT^{commit}")"
fi
build_commit="$gw_commit"
[ -n "$build_commit" ] || build_commit="$rt_commit"
+1 -5599
View File
File diff suppressed because it is too large. Load diff
+15 -44760
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -33,7 +33,7 @@
})();
</script>
<script type="module" crossorigin src="/assets/index.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index.css" />
<link rel="stylesheet" crossorigin href="/assets/index.css">
</head>
<body>
<div id="app"></div>
+2 -4
View File
@@ -1,8 +1,6 @@
// The freeze-dried /api/task-meta catalog the dashboard renders before the
// served one arrives, or when archied is unreachable. It has no imports so the
// node test runner can compare it against the Go handler's committed fixture
// (internal/webui/testdata/task_meta.json); task-meta.ts replaces it with the
// live catalog.
// served one arrives, or when archied is unreachable; task-meta.ts replaces it
// with the live catalog.
/** A lifecycle status as the server describes it. */
export interface StatusMeta {
+1 -7
View File
@@ -17,9 +17,7 @@ import TaskDetailPage from "@/tasks/TaskDetailPage.vue";
import TasksPage from "@/tasks/TasksPage.vue";
import WorkflowsPage from "@/workflows/WorkflowsPage.vue";
// internal/gateway/dashboard_tools.go mirrors this table; its test parses this
// file, so keep one route per line with `path: "..."` on a single line, and
// `nav: false` on any entry the registry should skip.
// internal/gateway/dashboard_tools.go mirrors this table.
//
// meta:
// label the navigation label, short because its group carries the context
@@ -94,10 +92,6 @@ const routes = [
"Captured inbound events, how their fields map, and which workflow they start.",
},
},
// The three former destinations, kept as bookmarks rather than removed: a
// link, a bookmark or an agent that learned these URLs still lands somewhere
// that works. `nav: false` is what the page registry's test reads to skip
// them -- they are addressed by URL, not offered as destinations.
{
path: "/system/status",
name: "system-status",
-77
View File
@@ -1,77 +0,0 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
/**
* The Events surfaces are one page with three tabs, and the navigation entry is
* always live (Sam's call): the tabs behind it prune themselves per capability,
* so an operator on a composition that can only back some of them still reaches
* the ones it can. What must not come back is three sibling destinations.
*/
const router = await readFile(
new URL("../src/router/index.ts", import.meta.url),
"utf8",
);
const nav = await readFile(
new URL("../src/lib/nav.ts", import.meta.url),
"utf8",
);
const page = await readFile(
new URL("../src/events/EventsPage.vue", import.meta.url),
"utf8",
);
const registry = await readFile(
new URL("../../internal/gateway/dashboard_tools.go", import.meta.url),
"utf8",
);
test("the Events page is the tab host, and the old paths are gone", () => {
assert.match(page, /Tabs/, "the page composes tabs");
assert.match(
page,
/CapturesPage/,
"the Inspector tab is the captures surface",
);
assert.match(
page,
/BindingsPage/,
"the Bindings tab is the bindings surface",
);
assert.match(
page,
/MappingsPage/,
"the Mappings tab is the mappings surface",
);
for (const path of ["/captures", "/mappings", "/bindings"]) {
assert.ok(
!router.includes(`path: "${path}"`),
`${path} is routed again; the Events tabs replaced it`,
);
}
});
test("Events is one live navigation entry, not a group of three", () => {
const entry = nav.split("\n").find((l) => l.includes('"/events"'));
assert.ok(entry, "the navigation model does not reference /events");
assert.doesNotMatch(
nav,
/label:\s*"Events",\s*paths:/,
"Events is still a three-item group",
);
});
test("the page registry and the route table still agree", () => {
assert.match(
registry,
/Path: "\/events"/,
"the agent's page registry does not know /events",
);
for (const path of ["/captures", "/mappings", "/bindings"]) {
assert.doesNotMatch(
registry,
new RegExp(`Path: "${path}"`),
`${path} is still a registered page`,
);
}
});
-41
View File
@@ -1,41 +0,0 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import test from "node:test";
const snapshot = await import("../src/lib/task-meta-snapshot.ts");
// internal/webui/testdata/task_meta.json is the served /api/task-meta payload,
// pinned byte-for-byte by TestTaskMetaPayloadMatchesFixture. Comparing the
// first-paint snapshot against it means a one-sided rename of any vocabulary
// fails on whichever side was not updated.
const fixture = JSON.parse(
await readFile(
new URL("../../internal/webui/testdata/task_meta.json", import.meta.url),
"utf8",
),
);
// The server emits an unset optional field (needs_you, confirm) as its zero
// value; the snapshot omits it.
const dropZero = (rows: Record<string, unknown>[]) =>
rows.map((row) =>
Object.fromEntries(
Object.entries(row).filter(([, v]) => v !== false && v !== ""),
),
);
test("the status snapshot matches the served catalog", () => {
assert.deepEqual(snapshot.DEFAULT_STATUSES, dropZero(fixture.statuses));
});
test("the action snapshot matches the served catalog", () => {
assert.deepEqual(snapshot.DEFAULT_ACTIONS, dropZero(fixture.actions));
});
test("the change-status snapshot matches the served catalog", () => {
assert.deepEqual(snapshot.DEFAULT_CHANGE_STATUSES, fixture.change_statuses);
});
test("the config schema snapshot matches the served catalog", () => {
assert.equal(snapshot.DEFAULT_CONFIG_SCHEMA, fixture.config_schema);
});