diff --git a/.agents/skills/archie-agent-fleet/SKILL.md b/.agents/skills/archie-agent-fleet/SKILL.md deleted file mode 100644 index 25485a68e..000000000 --- a/.agents/skills/archie-agent-fleet/SKILL.md +++ /dev/null @@ -1,247 +0,0 @@ ---- -name: archie-agent-fleet -description: >- - Run a bounded fleet of coding agents across archie-core's backlog without - flooding review. Load when fanning work out into parallel lanes, waves, - worktrees or subagents on this repository; when a lane worktree dies with the - unknown-agent error for `cp-writer`; or when deciding what every lane call must - carry, which gate evidence to demand, and how a lane's scoped test command - should be shaped here. Carries archie-specific fleet facts only; the method - lives in the user-scope high-throughput-programming skill. ---- - -# Run an agent fleet on archie-core - -This skill carries the facts about _this repository_. It deliberately does not -restate the process. - -## Where the method lives - -The how is the user-scope skill `high-throughput-programming` at -`~/.agents/skills/high-throughput-programming/`: doctrine, pipeline shape, the -interview that scaffolds a run, the pi-subagents ceilings and traps, `scripts/`, -`templates/` and `references/`. Read its `INTERVIEW.md` before scaffolding a run; -never scaffold one from memory. - -**Precedence.** That skill is normative for method; this one is normative for -archie's facts. If they disagree about the process, it wins. If they disagree -about this repository — a path, an invariant, a gate — this one wins, because the -method skill is repository-agnostic by construction. - -Route runtime facts to `archie-run-and-operate`, toolchain facts to -`archie-build-and-env`, and dependency/boundary rules to -`archie-architecture-contract`. - -## Invariants every lane call must carry - -State these as facts to each lane, not as advice. Each one has cost a real run. - -| Invariant | Why it matters to a lane | -| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **The control plane fails closed.** A stored resource that will not validate stops `archied` starting, and nothing bypasses the control plane at boot. Resource history is the only in-band remedy, and it needs the State Store up. | A lane touching the boot path, a stored resource kind, or the recovery commands is a risk-routed lane for the operator's eyes, not a gate-and-merge lane. Evidence: `docs/architecture/safe-change-and-recovery.md` ("Database settings: degrade paths and recovery"). | -| **`internal/webui` must not reach `internal/domain/workflow`.** Go imports are atomic: one reference relinks the whole daemon runtime into the UI binary. | `cmd/archie-ui/architecture_test.go` measures the linked binary (`go list -deps .`), not the imports, and fails on anything under `internal/domain/workflow`. `internal/domain/workflow/task` is a named `gateExceptions` entry that must stay linked — it carries only contract and view types, and a stale exception fails the test in both directions. The same test's gate also excludes `internal/app/archied` from the UI binary, so a helper needed by both the daemon and the `cmd/` binaries belongs in `internal/infrastructure/configuration` (which already owns path resolution), never in `archied`. | -| **The task DB has one owner.** The task tables are served by the standalone `cmd/archie-state-store` process alone. No second listener, no in-process serving path in the daemon or Gateway. | `boot.openStateStore` (`internal/app/archied/state_store.go`) is the only place the task store is built, and it holds the `state-store` Postgres ownership lock for the process's life — a second State Store on the same database fails there rather than merely being discouraged. Offline maintenance belongs in subcommands of that binary, never a new `cmd/` entry (`docs/architecture/organisation.md#process-boundaries`). | -| **Never commit `.beads/`.** Bead state moves through Dolt; `issues.jsonl` and `interactions.jsonl` are local-only. | A lane that stages `.beads/` pollutes its diff. Closing a bead is not commit-worthy on its own. | -| **Generated assets are LAW.** `ui/dist/` and the schema outputs (`docs/data/generated/contracts.json`). | Incorporate them into the commit that shifted them. Never revert, regenerate away, or leave them out. | -| **Scratch goes to `/tmp` only.** Never the working tree. | `worktree.CommitAll` stages with go-git's `AddWithOptions{All: true}` (`internal/worktree/worktree.go:502`), which does **not** honour `.gitignore`. An untracked scratch file in a lane worktree is swept onto the task branch. The task brief lives in `.git/task.json` for exactly this reason. | -| **A config field must survive the control-plane round trip or it does nothing.** A field added to `MCPServer` (or any projected settings type) must be carried in three sites: `mcpServerSettings` and `seedTools` in `internal/app/controlplane/tool_settings.go`, and `runtimeToolConfigFrom` in `runtime_config.go`. | The control plane rebuilds the whole resource from that projection, so a field missing there is silently dropped whenever a control plane is configured: the setting parses, appears in the dashboard, and has no effect. `TestToolSettingsProjectionCarriesEveryMCPServerField` reflects over `MCPServer` and fails on an omitted field, in both directions (seed and layering) — but it covers that type only; every other mirrored type (`minimaxSettings`, ...) is still hand-mirrored. Adding the field to just `internal/config` is the `xrux`/`parallel_tool_calls` failure shape. | -| **Dependency direction is `cmd -> app -> {domain, infrastructure}`**, with infrastructure implementing domain contracts. | A lane that needs a new edge says so before writing it. The `internal/{logging,events,eventbus,policy,taskstate}` cross-cutting packages import zero internal packages. Source: `docs/architecture/organisation.md`. | - -## The canonical gate - -```bash -~/.agents/skills/high-throughput-programming/scripts/gate-evidence.sh \ - '' -``` - -Run it on the host, per lane. It executes the scoped tests, then a module-wide -build (`go build ./...`) and the linter (`golangci-lint run ./...`), and emits -JSON for the harness to use as the child's structured output. - -The two extra checks are required, not optional. `go test ./pkg/...` compiles -only that package, so a changed constructor signature or interface passes its own -lane and breaks the next package to merge. That shape has bitten twice here: one -lane changed a constructor's signature, passed its own gate, and failed three -packages the moment it merged; formatting and lint drifted the same way, and only -the repository gate saw it. Both failures are paid for inside the lane when the -gate runs the build and the linter, and at merge when it does not. - -Gate the **candidate** before `main` moves. Check the merge candidate out -detached — or gate the lane branch — and advance the ref only on a green result: -gating after a fast-forward lands the failure on the branch of record and leaves -only fix-forward or reset as exits. The lane brief must name the linter as well, -`golangci-lint run .//...` beside the scoped tests, because a scoped -test run cannot see a complexity or style limit and `task check` is where that -failure otherwise surfaces — once it is already merged. - -A copy of the script under `.pi/control-plane-run/` is that run's disposable -state and may lag the skill's version. The skill's copy is the one to trust. - -## Shape a lane's test command like this - -Name every package the change can reach, plus `go vet` on the same set: - -```bash -go test ./internal/app/controlplane/... ./internal/domain/applystatus/... -count=1 \ - && go vet ./internal/app/controlplane/... ./internal/domain/applystatus/... -``` - -Real examples, from the worked example's `lanes.json`: - -| Lane surface | Scoped command | -| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| CLI subcommands and the State Store contract | `go test ./cmd/... ./internal/infrastructure/staterpc/... -count=1 && go vet ./cmd/...` | -| Workflow registry and the agent worker | `go test ./internal/domain/workflow/... ./internal/app/agentworker/... -count=1 && go vet ./internal/domain/workflow/...` | -| Config decoding and daemon boot | `go test ./internal/infrastructure/configuration/... ./internal/app/archied/... -count=1 && go vet ./internal/infrastructure/configuration/... ./internal/app/archied/...` | - -`task check` is the _serial full gate_ — fmt, proto checks, `docs:check`, vet, -lint, build, `go test ./...`, the tools tests and the dashboard tests. The merge -train owns it. Never run it in a lane, and never two at once: it saturates the -host. - -"Never two at once" includes gates you did not start. More than one agent session -works in this checkout, so before the merge train gates, check who holds it: - -```bash -ps -ef | grep -E '[t]ask check|[t]ask ' | grep -v grep -``` - -A concurrent gate is not merely slow. Both runs regenerate -`docs/data/generated/contracts.json` and `ui/dist`, so a contended result is -worthless in either direction — neither run's verdict tells you anything about -the tree. Wait for the host to be quiet and bound the wait: still held after -about twenty minutes means report the contention rather than gate anyway. - -The train integrates **local** `main`. Nothing in the gate consults `origin`, and -the version stamp comes from `git describe --tags` against local tags, so -unpushed commits neither block nor invalidate a gate run — the remote can lag -and does, since the maintainer pushes when inclined. - -## The agent-discovery trap - -A lane worktree is a **sibling** of the repository (`/work/apps/cp-`), not a -directory inside it. pi discovers project-scope agents under `/.pi/agents/`, -so a child launched in a lane worktree does not see them and dies with -`Unknown agent: cp-writer`. - -Fix it once per worktree: - -```bash -mkdir -p /work/apps/cp-/.pi -ln -sfn /work/apps/archie-core/.pi/agents /work/apps/cp-/.pi/agents -``` - -`.pi/` is gitignored, so the worktree stays clean and the symlink cannot reach a -commit. This costs an hour to rediscover. - -## Peer sessions over intercom - -A fleet here can also run as **sibling sessions** coordinated over `intercom` — -a peer per lane — rather than pi-subagents children under one orchestrator. -These facts are peer-specific, and each has cost a real run. - -- **Name the channel in the brief.** A peer's knowledge of how to report lives in - its context, not its configuration. Write "report to over intercom" as - an instruction; a convention that is only assumed evaporates. -- **A compaction erases conventions, not just facts.** A peer that compacts - mid-task keeps its task state and loses its transport: it reverts to - addressing its operator, and the coordinator reads that as idleness or death. - **Peer silence is not evidence of either** — ask for a one-line ack over the - channel before concluding anything. Re-priming restores the channel; the - transport itself survives compaction intact. -- **Match the task's shape to the session's window, not its strength.** A sweep - over hundreds of items needs the largest window available; a bounded hard - artifact (a PRD, a conformance review, a design decision) belongs in a smaller, - reasoning-strong session. A wide task in a small window stalls the task — too - wide is not the same as too hard, and it is the coordinator's assignment error, - not the peer's failure. -- **Checkpoint at ~70%, never compact mid-task.** A terse ledger sent to the - coordinator before the window fills survives; one reconstructed afterwards - loses exactly the identifiers — bead IDs, exact counts — that made it worth - having. Instruct every long-running peer to report and stop there. -- **One writer per resource.** Exactly one session writes the tracker. Two - writers produce double-closes, contradictory verdicts, and counts nobody can - reconcile. When a sweep changes hands, the successor re-derives them rather - than inheriting the predecessor's ledger as fact. - -## Traps worth carrying - -- **`touch` does not invalidate a Task source.** Task hashes file _content_, so a - stale-binary probe has to change bytes. `task build` now tracks `ui/dist/**`, - the generated dashboard the binary embeds, which is why the merge train still - runs `task build --force` before the gate. -- **`GATEWAY_VERSION` and `RUNTIME_VERSION` come from `git describe`**, which no - file checksum can invalidate: an empty commit moves the stamp while `task -build` still reports the binary up to date, shipping the old value. Tracked as - `archie-core-pdq2`. -- **The lane gate cannot see `tools/` or the contract schema.** `tools/` is - a separate Go module that reaches `internal/` through `docsgen`, and - `docs/data/generated/contracts.json` is generated from wire types such as - `agentexec.Request`. A lane that adds an import to a package `tools/` - reaches, or changes a wire type, passes its own gate and fails - `task check` on a missing `tools/go.sum` entry or a stale schema. Such a - lane runs `go -C tools mod tidy` and `task docs:generate` and commits both. - Adding or editing a page under `docs/` — a PRD included — changes - `docs/data/generated/dev-docs.json`, which gains or loses a page: regenerate it - and commit it in the same commit, or `docs:artifact:check` fails. That failure - lands on `main`, not in the lane, if the ref moves first. -- **Untracked files in the shared checkout are other sessions'.** prdlint - scratch (`docs/prds/rules.jsonl`), editor state, and gate-written artifacts - appear and vanish under a lane. Never chase, add, stage or commit them: a - merge train's scope is its own lanes' files, and nothing else. - -## codegraph answers symbol questions cheaply - -The maintainer's `codegraph` MCP server indexes this repository. Prefer it to -grep or whole-file reading for "who calls X", "is this dead", "what does this -change touch": it enumerates call sites that a grep only summarises, and labels -each caller's confidence so interface fan-out is not mistaken for direct calls. - -- **`pr_impact `** lists changed symbols with per-symbol caller and - test counts. Read `interface_dispatch` and the inferred tests alongside - `test_count`: a method reached through an interface reports a low direct test - count while many indirect tests reach it, and the compact line alone invites - the wrong conclusion. -- **It is a derived cache.** `scip-go` and tree-sitter rebuild it, and a query - indexes the revisions it names, so a cold query is slow and losing the index - costs a rebuild rather than data. `list_repositories` reports the indexed - revision — compare it with the tree before trusting a default-revision answer. -- **Stagger heavy queries.** Concurrent sessions share one instance, and - **name-based** `symbol_context` is what locks: it returns `database is locked` - or times out, while the same symbol **by id** returns immediately. Query - serially and retry rather than assuming a hang. -- **Report problems one line at a time** in - `/work/apps/codegraph/data/feedback.jsonl` — one JSON object per line, keys - `date`, `repo`, `task`, `tools`, `helped`, `missed`, `wrong`, `slow`. A raw - newline inside a string makes the line invalid and breaks every reader; a - multi-line entry corrupted that file once. Validate, append, never rewrite. - -## Tracker conventions - -`bd` is the only tracker; no markdown TODO lists, no local trackers. - -```bash -bd show # before working an item — the brief may describe a tree that has moved -bd update --claim -bd close # after the work lands, not when it commits -``` - -Bead state moves through Dolt, never through git commits on this repository. The -Dolt remote is pushed explicitly (`bd dolt push`) and never assumed to be in sync. - -## Run artifacts are evidence, not documentation - -`.pi/control-plane-run/` holds a run's scaffold, lane plan, prompts, scripts and -gate output. It is gitignored and disposable. Treat it as run evidence only: a -fact worth keeping goes into this skill or `docs/`, not into a -run directory the next clean deletes. - -## Worked example - -`references/worked-example/` is the control-plane backlog run of September 2026, -committed verbatim: the filled orchestrator prompt, four lane briefs, three -sub-prompts, and the three agent definitions with their project invariants -inlined. Read it for the level of detail a good brief carries. - -Its scripts are the snapshot's, not the current ones. The user-scope skill's -`scripts/` and `templates/` are normative and win any disagreement. diff --git a/.agents/skills/archie-agent-fleet/agents/openai.yaml b/.agents/skills/archie-agent-fleet/agents/openai.yaml deleted file mode 100644 index c4585120c..000000000 --- a/.agents/skills/archie-agent-fleet/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Agent Fleet" - short_description: "Run bounded agent fleets on archie-core" - default_prompt: "Use $archie-agent-fleet to fan work out across lanes on this repository, carrying the fleet invariants, the gate evidence it needs, and the worktree agent-discovery fix." diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/00-orchestrator.md b/.agents/skills/archie-agent-fleet/references/worked-example/00-orchestrator.md deleted file mode 100644 index 687740e4b..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/00-orchestrator.md +++ /dev/null @@ -1,474 +0,0 @@ -# Mission: clear the archie-core control-plane backlog with a bounded high-throughput fleet - -> **Where this file's paths point.** This is the committed copy of a live run. -> Paths under `.pi/control-plane-run/` (sections 6, 9, 10) name that run's own -> disposable copies of `wave0.js`, `wave2.js`, `review.js` and -> `gate-evidence.sh`; they are gitignored run state and may lag the skill's -> normative versions in `~/.agents/skills/high-throughput-programming/`. The -> skill is the one to trust. Paths under `/work/apps/archie-core` and -> repo-relative source paths are unchanged. - -You are the orchestrator. You do not write production code yourself. You run -waves of subagents through the `subagent` tool, verify their work against git -evidence rather than their reports, and land finished slices on `main`. - -Repository: `/work/apps/archie-core`, branch `main`, working tree clean at -start. Gate: `task check`. Tracker: `bd`. Read `CLAUDE.md` and -`docs/architecture/organisation.md` before Wave 1. - ---- - -## 1. Hard rules - -1. **One top-level `subagent` call per wave.** Every child launches inside that - call's `workflowScript`. Never open a second top-level orchestration while a - wave is running. -2. **Read-only fans out wide. Writers do not.** Recon and review children are - cheap and parallel. Writer children are bounded by file overlap and by this - machine (16 cores), not by the spawn budget. -3. **At most one `task check` at a time, ever.** It compiles 117 Go packages, - runs the full test suite and the Node dashboard tests, and saturates the - machine. Writer children run package-scoped tests only. The full gate belongs - to the merge train in Wave 4, which is strictly serial. -4. **A worker's report is not evidence.** Accept a lane only on: the handoff - manifest path, `git -C status --short`, `git log --oneline`, and - `git diff --stat` against the lane's own base. A bead marked closed with no - commits means the work did not happen. -5. **No suppression.** Children may not add `//nolint`, `t.Skip`, build tags - that exclude a failing test, or delete an assertion to make a gate pass. Say - this in every writer and fix task. A child that suppresses gets its lane - reverted, not patched. -6. **Formatting is law.** Adopt `task fmt` output verbatim. Never revert a - linter or formatter diff. -7. **Zero patch stacking.** Two failed fixes on the same logic block means the - block gets rewritten, not patched a third time. This is a `CLAUDE.md` rule - and it applies to children. -8. **Do not push.** Commit gate-clean work to `main` in the captain checkout. - Sam pushes manually and does not always announce it, so never assume a commit - is local or remote without checking `git log origin/main..main`. -9. **No `.beads/` commits.** Bead state moves through Dolt. Closing a bead is - not commit-worthy on its own. -10. **Scratch stays out of the tree.** Children write scratch to `/tmp` only. - `.pi/` is gitignored; nothing else you create may land in a commit. -11. **Separation of duties.** No agent merges, closes or approves its own work. - Writers write, reviewers review, and you alone run the merge train. You do - not write production code; if you find yourself editing a lane's files, the - lane was scoped wrong. -12. **Every wave ends with an adversarial review pass** before the next wave - starts. Reviewers are read-only, parallel and cheap; a defect caught at the - end of the wave that produced it costs one lane, and the same defect caught - three waves later costs the tree. - ---- - -## 2. Ground truth: do not spend agents rediscovering this - -This came from the session that just ended. Treat it as fact. - -- `docs/prds/runtime-control-plane.md` is Approved and is the spec. Its resource - surface, YAML workflow definitions, identity-backed attribution and audit - trail are already built. -- **Restore is not its own command.** A revision carries its value, so restoring - replays it through the ordinary replace. Do not add a rollback RPC. -- **Dashboard writes attribute to `identity.SystemID`.** One shared bearer - token, no per-user session. `webAudit` in `internal/webui/api_identities.go` - is the only source. Named attribution needs a dashboard login first. -- **`internal/webui` must not link the workflow engine.** It decodes definitions - with the projection types in `internal/domain/workflow/task`. - `cmd/archie-ui`'s deletion gate fails if anything reaches - `internal/domain/workflow`. -- Shipped defaults ride `ResourceDescriptor.defaults_json`. The API is fixed at - four operations, so defaults get no REST route. -- `archie-messaging` fails closed when the State Store is unreachable. The - database is authoritative for channel settings. File config is not a fallback. -- **The control plane fails closed with no way back.** A stored value that will - not validate stops `archied` starting. Nothing bypasses the control plane at - boot. `docs/architecture/safe-change-and-recovery.md` records this posture. - Resource history is the only in-band remedy and needs the State Store up. -- **`task check` will not catch a field the server stopped sending.** Optional - chaining made a dead dashboard banner typecheck silently; - `delivery-snapshot.sh` scanned for a symbol its composition root no longer - calls. Both fixed in `85f0fd0b`. When a server-side field is deleted, grep the - dashboard and the snapshot scripts by name. Add this to every review task. -- **Reload re-reads the database layer and can fail.** `boot.runtimeConfig` is - the one layering call; the SIGHUP callback makes the same call over the - document it just resolved (`9af013eb`). A new database-owned layer goes in - `runtimeConfig` and nowhere else. -- **Apply status lives on the State Store contract, not the control plane.** - `PutApplyStatus`/`ListApplyStatus` are administrative, keyed on - `(process, kind)`, replaced in place, re-stamped every 30s, stale at 90s, and - a stale record renders as "Not reporting", never as current. `applystatus.New` - refuses a process name `Processes()` does not list. -- Five commits are local as of 2026-09-21: `731a9a06`, `1dd0d874`, `d9dd7885`, - `9accf112`, `d38e27fd`. `archie-core-pskb` is closed. There is no post-commit - hook; `core.hooksPath` is `.beads/hooks` and those are beads shims. - ---- - -## 3. The backlog - -Seven ready beads carry the `control-plane` label. Their real shape is what -decides the lanes, and it is not the same as their titles. - -| Bead | Title shape | Primary surface | -| ------------------ | -------------------------------------------------------- | ------------------------------------------------------------- | -| `archie-core-nwa0` | check a live replacement before switching to it | live apply path + apply-status surface | -| `archie-core-fwmp` | let plugins register workflow step types | `workflow.BuiltinStepRegistry()` and all five call sites | -| `archie-core-8szi` | registered steps covering the deleted `.archie` gate | `internal/domain/workflow/steps.go`, needs fwmp's answer | -| `archie-core-6zw0` | offline backup/restore/validate/rollback for `archie.db` | new `cmd/` binary + state-store infrastructure | -| `archie-core-i3qm` | stop TOML blocking State Store startup | `internal/app/archied/control_plane.go`, bootstrap validation | -| `archie-core-xrux` | `ApplyOverlayValues` is dead, confirm the file overlay | `internal/infrastructure/configuration/loader.go`, `apply.go` | -| `archie-core-eju6` | end-to-end restart test for a database-backed change | test only, proves the whole loop | - -Three couplings you already know about, and Wave 0 exists to find the rest: - -- **fwmp is the shared shape.** It changes the registry every call site - hardcodes (`app/agentworker/task_execution.go:319,:335`, - `app/controlplane/workflow_definitions.go:26,:33`, - `app/controlplane/client.go:41`) and the validating side and the executing - side must resolve it identically. 8szi has nothing to register against until - fwmp lands. These two are never concurrent writers. -- **xrux decides i3qm's blast radius.** xrux is an investigation with two - opposite outcomes: either the file overlay zeroes omitted map fields, in which - case `foldOverrides` moves there and it is a live bug, or it does not, in - which case `apply.go`, `apply_test.go` and `Loader.ApplyOverlay` are deleted. - Both land in the same package i3qm rewrites. One lane owns both, in that - order. `archie-core-xrux` is a trap, not a cleanup. Read the bead before - deleting `apply.go`. -- **eju6 proves the others.** It goes last, against everything merged. - ---- - -## 4. Models: resolve before Wave 0 - -Run `subagent({ action: "models" })` first and pick exact `provider/id` strings. -Bare ids resolve only when unique. Then print the table you resolved and use it. - -| Tier | Used by | Pick | -| ------ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Fast | recon, inventory, grep-shaped probes | cheapest capable, low or medium thinking. Default `ollama/deepseek-v4.1-flash:cloud`. | -| Strong | writers, integrator | best reasoning model authenticated here, high thinking. Prefer a `deepseek-v4-pro` class id if `models` lists one. | -| Review | reviewers, oracle | a **different family** from the writer that produced the diff. Model diversity catches different failure modes; it does not rescue an ambiguous prompt. | - -If a tier cannot be resolved, say so and fall back to the session default rather -than inventing an id. Provider 429s return from that model; do not kill a rate -limited child, it keeps its context and recovers. - ---- - -## 5. Concurrency: the numbers that actually bind - -Defaults in this install (`pi-subagents` 0.70.0) are not 64. - -- `globalConcurrencyLimit` defaults to **20** concurrent children per run. Set - it explicitly on each top-level call. -- `maxSubagentSpawnsPerRun` defaults to **64** cumulative admissions per run - tree, never refunded. Retries and fix passes spend it too. -- **Each wave is its own top-level run, so each wave gets its own budget.** This - is why the mission is split into waves rather than one giant script. -- `runs.lanes` is capped at 32 lanes, 16 stages per lane, 64 stages total. - -Per-wave dials: - -| Wave | Shape | `globalConcurrencyLimit` | `maxSubagentSpawnsPerRun` | -| -------------- | ------------------------------------------------------------------------ | ------------------------ | ------------------------- | -| 0 recon | `runs.all`, read-only | 32 | 64 | -| 0R audit | `review.js`, angles `claims` | 16 | 24 | -| 1 shape-first | one writer plus one probe | 2 | 8 | -| 1R review | `review.js`, full angle set, one target | 12 | 16 | -| 2 writer lanes | `runs.lanes`, one worktree each | 4 | 32 | -| 2R review | `review.js`, full angle set, four targets | 24 | 48 | -| 3 fix pass | `runs.lanes`, retained writers | 4 | 24 | -| 4 merge train | serial, one `task check` at a time | 1 | 8 | -| 4R post-merge | `review.js` on merged `main`, angles `boundary`, `deadfield`, `contract` | 8 | 12 | -| 5 eju6 | one lane, then its own review | 2 | 12 | - -Do not set a hard `toolBudget` or a tight `usageBudget` on any writer, fix -worker, or reviewer with edit authority: the default budget blocks read and -search tools rather than mutation tools, which leaves a half-written tree. Bound -writers with `timeoutMs` plus `checkpointBeforeDeadlineMs` instead. Hard caps -are fine on explicitly read-only children. - ---- - -## 5a. The constraint is review, not generation - -Generation is no longer the bottleneck and has not been for a while. The -measured evidence is consistent: agent-authored changes take far longer to reach -a first review, merge at a lower rate than human-authored ones, and raise more -issues per change; one randomized study found experienced developers 19% slower -with agent tooling while expecting to be faster. Feature-branch throughput rises -while main-branch throughput falls. Adding writer lanes past what review can -absorb does not raise throughput, it grows a queue, and queued work ages badly -because the tree moves underneath it. - -Act on that as follows. - -- **WIP is capped by review, not by cores.** Four writer lanes exist because - four is what the review pass and the merge train can absorb per cycle. Do not - raise it to use spare concurrency. -- **Put the judgement upstream.** Before a writer starts, its task must carry - intent, acceptance criteria and non-goals, so verification has an external - reference. "Does this do what it was supposed to do" is checkable; "does this - look right" is not, and fluent output passes a read-through scan regardless of - whether it is correct. -- **Spend the effort on the verifier, not the prompt.** A parallel fleet is only - as good as the check that decides whether its output is right. A better test - is worth more than a better instruction. -- **Every handoff carries evidence.** Intent, non-goals, files touched with a - reason each, alternatives rejected, commands actually run with pasted output, - the test that would fail first, and known limitations. A report that only - describes its own diff is not evidence. -- **Deterministic gates run before any reviewer looks.** `gate-evidence.sh` runs - the lane's tests on the host and emits JSON that becomes the child's - structured output, and it fails the lane on added `//nolint`, `t.Skip`, ignore - build tags, removed tests or removed assertions. Gate gaming is cheap to - detect and expensive to miss, so detect it mechanically rather than asking a - reviewer to notice. -- **Keep batches small.** Generation being cheap is a reason for smaller - changes, not bigger ones. A lane whose diff passes roughly 400 changed lines - gets split at a coherent boundary. -- **Route risk, do not review uniformly.** These surfaces get Sam's eyes before - merge, named explicitly in your report: the fail-closed boot path - (`boot.runtimeConfig`, bootstrap validation), the State Store wire contract - and its error sentinels, task-scoped grants and credentials, anything that - writes or migrates `archie.db`, and the release or CI surface. Everything else - merges on gate plus reviewer verdict, with a sample called out for him to - spot-check. -- **Watch the right numbers.** Report per wave: reviewer findings raised versus - accepted, lanes blocked by gate versus by review, rework passes per lane, and - wall-clock from lane start to merged. Lines written and beads closed measure - how fast the queue fills. - ---- - -## 6. Wave 0: recon fanout (read-only, wide) - -One top-level call, `async: true`, -`workflowScriptPath: ".pi/control-plane-run/wave0.js"`. - -Three probes per bead, plus four cross-cutting probes: 25 children, all -`cp-recon`, all read-only, all returning structured output. The probe text is -composed inside `wave0.js`; do not retype it. - -Per bead: - -- **spec** — extract the exact PRD clauses the bead must satisfy, with line - anchors, and the acceptance criteria the gate can actually check. -- **blast** — trace every call site, consumer and test of the symbols the bead - names. Return package paths and file paths, not prose. -- **tests** — inventory the tests that already cover this surface and name the - one test that would fail first if the change were wrong. - -Cross-cutting: - -- **overlap** — for all seven beads, the set of packages and files each one must - modify, in one table. -- **gate-cost** — time `task build` and - `go test ./internal/app/controlplane/...` and report wall-clock, so Wave 2 - timeouts are measured rather than guessed. -- **dead-field** — grep `ui/src/` and `scripts/delivery-snapshot.sh` for every - control-plane field name the server sends today, and flag any the server no - longer sends. This is the failure class `task check` cannot see. -- **contract-pairs** — find every place the validating side (State Store) and - the executing side (archie-agent) must agree on the same vocabulary, and name - the single test that would tie each pair together. - -Every probe returns `structuredOutput` matching the schema in `wave0.js`. Long -findings go to a file via `outputMode: "file-only"`; do not pull transcripts -into your context. - -**Do not let a recon child draw the conclusion.** A scout that measures -correctly can still land the wrong call, and its write-up reads confident either -way. Take their facts, make the call yourself. - ---- - -## 7. Checkpoint A: lane plan, then stop - -Build the conflict matrix from the `overlap` probe and the per-bead `blast` -results. Two beads may be concurrent writers only if their file sets are -disjoint. Directory names are not evidence of disjointness: check the imports. - -Then report to Sam, in under 30 lines: - -- the matrix, as bead by bead package intersections; -- the proposed lanes, and which beads you are deliberately serializing; -- any bead whose description no longer matches the tree, with the commit that - moved underneath it; -- the measured gate cost and the timeouts you derived from it; -- anything in Wave 0 that contradicts section 2. - -Wait for approval before Wave 1. This is the only mandatory stop. - ---- - -## 8. Wave 1: shape-first, serial - -Land the shared shape before anything forks against it. Five workers each adding -a field to one struct produced eight cleanup commits on this repo in July; the -merge cost scales with shared-file overlap, not worker count. - -Sub-prompts for both children are in `prompts/wave1.md`. - -1. **fwmp** alone: one `cp-writer`, `worktree: true`, red-green, gate - `go test ./internal/domain/workflow/... ./internal/app/controlplane/... ./internal/app/agentworker/...`. - Requirement: one contract test asserting the validating registry and the - executing registry resolve the same step vocabulary. Two sides that each pass - their own tests and disagree with each other is the exact failure this bead - exists to prevent. -2. Merge fwmp through the Wave 4 train immediately, before Wave 2 starts. Wave 2 - branches from the merged shape. -3. **xrux investigation** runs concurrently with fwmp, because it is read-only - until it has a verdict: one `cp-recon` writes a characterisation test in a - scratch worktree that answers the single question, does `Loader.overlayFile` - zero omitted fields of a map-valued entry. It returns the verdict and the - test, and nothing else. The verdict decides the i3qm lane's stages. - ---- - -## 9. Wave 2: bounded writer lanes - -One top-level call, `runs.lanes`, `worktree: true` on every writer stage, -`baseRef: "HEAD"` resolved after fwmp merged. Four lanes, concurrency 4. - -| Lane | Beads | Stages | -| ---------- | -------------- | ----------------------------------------------- | -| `live` | nwa0 | red, green, self-gate, challenge | -| `recovery` | 6zw0 | red, green, self-gate, challenge | -| `steps` | 8szi | red, green, self-gate, challenge | -| `config` | xrux then i3qm | verdict-apply, red, green, self-gate, challenge | - -Stage contract, enforced by `wave2.js` and the `cp-writer` agent definition: - -- **red**: write the failing table-driven test first, run it, and paste the - failure. Verify the failure comes from an assertion, not a compile error. A - test that cannot fail for an interesting reason is noise in the gate. -- **green**: minimal implementation that satisfies the failing test. -- **self-gate**: a typed `gate` pointed at - `.pi/control-plane-run/gate-evidence.sh`, which runs the lane's package-scoped - test command on the host and returns JSON that becomes the child's - `structuredOutput`: branch, sha, changed files, uncommitted files, test exit - and tail, plus the gate-gaming counters. Never `task check`. The evidence - comes from the host, so a child cannot report a pass it did not get. -- **challenge**: `resume: "previous"` against the same writer, with the - adversarial prompt built into `wave2.js`'s challenge stage. The writer still - holds the context; a fresh child pays for that context twice. Only resume a - child `children.list` reports as `resumable`; otherwise start a same-role - fallback and label it a fallback. - -Each lane's writer also returns the evidence handoff in `wave2.js`: intent, -non-goals, files with reasons, alternatives rejected, commands run with pasted -output, the test that would fail first, and known limitations. A lane whose diff -passes roughly 400 changed lines stops at a coherent boundary and reports what -remains rather than growing further. - -Every writer opens by printing `pwd`, `git branch --show-current` and -`git status --short`, and repeats that evidence in its final report. A worker -that finishes in the wrong checkout looks exactly like a worker that did -nothing. - -A failed stage blocks only its lane. Do not repair a lane by hand and do not -fall back to running the work yourself, `pi -ne`, or an external CLI: a child -launch or tooling failure is a lane infrastructure blocker, so report the exact -failure, the run status, and the worktree state, then retry through the same -path. - ---- - -## 10. Review after every wave - -`.pi/control-plane-run/review.js`, read-only `cp-reviewer` children on a -different model family from the producer, one child per angle per target. The -angles live in that script: `bead`, `invariant`, `contract`, `deadfield`, -`boundary`, `operator`, `tests`, `gaming`, `intent`, plus `claims` for auditing -recon findings. - -| After | Targets | Angles | -| ------ | ----------------------------- | ----------------------------------- | -| Wave 0 | the recon findings themselves | `claims` | -| Wave 1 | `cp/shape` | full set | -| Wave 2 | the four lane branches | full set | -| Wave 4 | merged `main` | `boundary`, `deadfield`, `contract` | -| Wave 5 | the eju6 branch | `tests`, `operator`, `intent` | - -The Wave 0 audit is the cheapest of these and catches the most: a recon child -that measures correctly can still carry a wrong conclusion into your lane plan, -and its write-up reads confident either way. Feed the audit the claims your lane -plan is about to rest on, and check the load-bearing ones before Checkpoint A, -not after. - -Reviewers label findings P0/P1/P2 by evidence, not by severity language, carry -`file:line` with a quoted proof, and end with one of `Merge verdict: BLOCK`, -`Merge verdict: OK`, `Merge verdict: OK with notes`. Prose is never parsed for -control flow: you decide the lane's fate from the findings. - -Fixes go back to that lane's retained writer, batched into one pass, not one -child per finding. Resume only a writer `children.list` reports as `resumable`; -otherwise start a same-role fallback and label it as a fallback. A second failed -fix on the same logic block means the lane is reverted and requeued, not patched -again. - -Count the pass as complete only when every angle returned. A missing angle is an -unreviewed axis, not a clean one. - ---- - -## 11. Wave 4: merge train, strictly serial - -The procedure, with the exact commands, is in `prompts/wave4-merge-train.md`. -One branch at a time, in dependency order, in the captain checkout at -`/work/apps/archie-core`. Per branch: - -1. `git merge-base --is-ancestor main `. A stale branch computed its - deletions against code that has since changed; rebase or re-derive, never - merge it as is. -2. Apply the lane's handoff patch. -3. `task check`, once, alone. Nothing else runs while it does. -4. On failure: one fix pass through the lane's writer with the real output. On a - second failure, revert the lane and requeue it; do not stack a third patch. -5. Commit with a conventional scope (`feat(controlplane): ...`, - `fix(config): ...`). Include generated assets under `ui/dist/` in the same - commit; they are LAW, never reverted or ignored. -6. `bd close `. Do not stage `.beads/`. -7. Verify it landed: `git log --oneline -1`, then `git branch --no-merged main`. - Done has three states: no commits, committed and unmerged, merged. Only the - third counts. - -Your own edits get the same gate as the children's. A coordinator `sed` broke -the build on this repo once and nobody else reviews your diffs. - ---- - -## 12. Wave 5: eju6 - -Sub-prompt in `prompts/wave5-eju6.md`. Last, against merged `main`. One lane: an -end-to-end test that drives a change through the API, restarts a process, and -asserts the change survived. Not a unit test, and not a rewrite of -`internal/app/controlplane/controlplane_test.go`, which covers seeding and -catalogue only. This is the proof the whole feature works across a restart, -which nothing currently provides. - -If it fails, that is a finding about the feature, not about the test. Report it -and stop rather than weakening the assertion. - ---- - -## 13. Final report - -- Beads closed, with the commit that closed each one. -- Beads deliberately not attempted, and why. -- `task check` result on final `main`, quoted, not summarised. -- Every branch still unmerged, and whether it holds work. -- Commits now local and unpushed (`git log --oneline origin/main..main`), stated - as fact without pushing. -- Anything you found that contradicts `docs/prds/runtime-control-plane.md` or - section 2 of this prompt, filed as a new bead. -- New beads for identified debt or follow-ups, filed via `bd`. -- The wave metrics: per wave, reviewer findings raised versus accepted, lanes - blocked by the gate versus by review, rework passes per lane, and wall-clock - from lane start to merged. Say which stage was the constraint in practice and - whether it matched the prediction that review would be. -- The risk-routed surfaces that changed and need Sam's eyes: the fail-closed - boot path, the State Store wire contract and error sentinels, grants and - credentials, anything touching `archie.db`, and the release or CI surface. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/ABOUT.md b/.agents/skills/archie-agent-fleet/references/worked-example/ABOUT.md deleted file mode 100644 index 21d0aa842..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/ABOUT.md +++ /dev/null @@ -1,43 +0,0 @@ -# Worked example: archie-core control plane, September 2026 - -A real run, frozen partway through, kept verbatim so the shapes can be read -rather than re-derived. It is repository-specific on purpose: the value is in -seeing how much project knowledge a good brief carries. - -**Its scripts are the snapshot's, not the current ones.** This directory was -captured mid-run, so the scripts in it predate fixes the skill's own lessons -describe — the typed-gate boolean trap, the post-fix re-gate and re-review, the -P2 handling, the build and lint checks in the gate. -`~/.agents/skills/high-throughput-programming/scripts/` and -`~/.agents/skills/high-throughput-programming/templates/` are normative; if this -directory disagrees with them, they win. Read the briefs, the lane plan and the -merge-train procedure here. Do not copy the scripts. - -The method this run followed lives in the user-scope skill -`~/.agents/skills/high-throughput-programming/`; it is normative for method. This -repository's `archie-agent-fleet` skill is normative for facts about archie-core. -A run in another repository uses that skill's `templates/` plus its own filled-in -briefs — none of the archie specifics here transfer. - -Seven tracker items, one shared shape, four lanes, a review pass after every -wave, a serial merge train. - -| File | Note | -| ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `00-orchestrator.md` | The filled orchestrator prompt. Section 2 is the project's ground truth, section 5a the review-is-the-constraint doctrine, section 10 the review cadence. | -| `lanes.json` | Lane briefs carrying intent, traps and `file:line` premises. Read one to see the level of detail a brief needs. | -| `prompts/wave1.md` | The shared shape, plus an investigation whose verdict gated another lane. | -| `prompts/wave4-merge-train.md` | The serial merge procedure with the project's own hazards in it. | -| `agents/` | The three agent definitions with project invariants inlined. | - -No scripts are copied here. This run's `wave0.js`, `wave2.js`, `review.js` and -`gate-evidence.sh` became `templates/recon.js`, `templates/lanes.js`, -`templates/review.js` and `scripts/gate-evidence.sh` in the user-scope skill; -those are normative, and this directory's stale copies were deleted so there is -exactly one of each to keep current. - -What this run's Wave 0 actually caught, which is the argument for recon before -fanout: three of the seven items had premises that no longer matched the tree, -including one whose target file did not exist under the name the item used, one -whose anchor had moved commits earlier, and one whose scope could not reach the -clause it cited. All three would have produced confidently wrong lanes. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/README.md b/.agents/skills/archie-agent-fleet/references/worked-example/README.md deleted file mode 100644 index 697d5ec50..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# Control-plane backlog run: how to drive it - -This is the committed copy of a real run. Its originals lived in -`/work/apps/archie-core/.pi/control-plane-run/`, which is gitignored, disposable -run state whose live copies may have moved on since. Nothing here is load -bearing at runtime. - -The method is not here. The pipeline shape, the concurrency ceilings, the -pi-subagents traps, and the `scripts/` and `templates/` this file names all live -in the user-scope skill `~/.agents/skills/high-throughput-programming/`, and that -skill is normative for method. This copy is normative only for what the run -looked like on this repository; the archie-specific facts themselves live in the -parent `archie-agent-fleet` skill. A run in another repository uses that skill's -`templates/` plus its own filled-in briefs. - -## Files - -| File | What it is | -| -------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `00-orchestrator.md` | The prompt you give pi. It owns the waves, the ceilings and the verification rules. | -| _(the scripts)_ | This run's `wave0.js`, `wave2.js`, `review.js` and `gate-evidence.sh` are **not copied here**: they live on as `templates/recon.js`, `templates/lanes.js`, `templates/review.js` and `scripts/gate-evidence.sh` under `~/.agents/skills/high-throughput-programming/`, which are normative. The snapshot's copies were stale, so they were deleted rather than duplicated. | -| `lanes.json` | Lane definitions: worktree paths, branches, beads, scoped test commands, briefs. Fill in the model id. | -| `prompts/wave1.md` | fwmp shape-first writer, and the xrux verdict probe. | -| `prompts/wave4-merge-train.md` | The serial merge procedure and the landing checks. | -| `prompts/wave5-eju6.md` | The end-to-end restart test. | -| `agents/cp-recon.md`, `agents/cp-writer.md`, `agents/cp-reviewer.md` | Project-scope agent definitions, as the run used them from `.pi/agents/`; these committed copies sit beside this file. | - -## Start it - -```fish -cd /work/apps/archie-core -pi "$(cat .pi/control-plane-run/00-orchestrator.md)" -``` - -The `.pi/control-plane-run/` path is the run's own state directory, not this -copy. Interactive is the right mode here: Checkpoint A after Wave 0 is a real -stop and wants you in the loop. `/subagents-fleet` opens the live inspector, -`/subagents-doctor` checks the install. - -## Before Wave 2 - -Create the durable worktrees yourself. Managed `worktree: true` children capture -a patch and then remove the worktree, which a resumed challenge stage cannot -edit, so the lanes use operator-created worktrees plus per-child `cwd`. - -```fish -for lane in live recovery steps config - git -C /work/apps/archie-core worktree add ../cp-$lane -b cp/$lane -end -``` - -A lane worktree is a **sibling** of the repository, so `.pi/agents/` inside the -repository is not discovered from it. Link it per worktree or the children fail -with `Unknown agent: cp-writer`: - -```fish -for lane in live recovery steps config - mkdir -p /work/apps/cp-$lane/.pi - ln -sfn /work/apps/archie-core/.pi/agents /work/apps/cp-$lane/.pi/agents -end -``` - -Then fill `model` in `lanes.json` from what `subagent({ action: "models" })` -resolves, and pass it as `args`. - -## Ceilings worth knowing before you tune anything - -This install is `pi-subagents` **0.70.0**, matching your clone except for four -doc files. Two 0.69/0.70 features are load bearing here: typed gates -(`gate: { command, output: "json" }` turns a host command's JSON stdout into the -child's `structuredOutput`) and `allowedAgents`, which can stop a reviewer -launching a writer if you want separation of duties enforced rather than -instructed. - -- `globalConcurrencyLimit` defaults to **20**, not 64. Set it per top-level call. -- `maxSubagentSpawnsPerRun` defaults to **64** cumulative admissions per run - tree, never refunded, so retries spend it. Each wave is a separate top-level - run precisely so each gets its own budget. -- `runs.lanes` caps at 32 lanes, 16 stages per lane, 64 stages total. -- `gate` is rejected on a retained `resume` item, which is why the challenge - stage runs its tests through `bash` instead. -- A typed gate cannot be combined with `outputSchema` on the same child, so the - writer stages carry the gate and the reviewers carry the schema. -- Host steps have no per-step `cwd`, which is why `gate-evidence.sh` takes the - worktree path as its first argument instead of relying on one. - -## Why the fleet is not 64 writers - -64 concurrent children is comfortable for read-only work and pointless for -writers here. Two limits bite first: - -1. **Overlap.** Merge cost scales with shared file overlap, not worker count. - Seven beads reduce to four genuinely disjoint lanes plus one shared shape - that has to land alone first. Five workers each adding a field to one struct - cost eight cleanup commits on this repo in July. -2. **The machine.** 16 cores, 117 Go packages, and `task check` also runs the - dashboard tests. One full gate saturates the host, so the gate is serialised - into the merge train and writers run package-scoped tests. - -The throughput comes from recon and review: 25 recon children, then a review -pass after every wave at up to 36 children, all read-only, all cheap, all -genuinely parallel. The writers stay at four because that is what the -repository's coupling and the review pass can absorb. The measured literature is -consistent that review, not generation, is where agent-heavy pipelines stall, so -spare concurrency goes into checking rather than into more lanes. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-recon.md b/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-recon.md deleted file mode 100644 index 816615515..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-recon.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -name: cp-recon -description: - Read-only recon on archie-core. Traces call sites, extracts spec clauses, - inventories tests. Returns citations, never conclusions. -tools: read, grep, find, ls, bash -excludeTools: write, edit -acceptanceRole: read-only -completionGuard: false -inheritProjectContext: true -inheritGlobalContext: false -inheritSkills: false -thinking: high -systemPromptMode: replace ---- - -You are a read-only investigator in the archie-core Go repository. You measure; -you do not decide. - -Rules: - -- Never edit, write, stage, commit, or run anything that mutates the tree. - `bash` is for `git log`, `grep`, `go list`, `bd show`, and timing commands - only. -- Every claim carries `file:line`. A claim without a citation is not a finding, - it is a guess. -- Report facts. The orchestrator draws the conclusion. Do not recommend a course - of action unless you were asked for one, and never close or reopen a bead. -- Grep first, then read only the lines that matter. Do not pull whole packages - into context. -- Directory and bead names are not evidence of coupling. Check the imports. -- `ARCHITECTURE.md` and `CLAUDE.md` are stale by construction in this repo. The - tree is the only evidence of current state; when a doc and the code disagree, - report both and say which file you read. -- If your task's premise is false, say so plainly as your first line instead of - answering the question you were asked. - -Finish with your structured output. Keep prose under 40 lines; long inventories -belong in your output file. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-reviewer.md b/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-reviewer.md deleted file mode 100644 index 96ba4f8dc..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-reviewer.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -name: cp-reviewer -description: - Read-only adversarial reviewer for one archie-core lane and one angle. - Evidence-labelled findings and a single merge verdict. -tools: read, grep, find, ls, bash -excludeTools: write, edit -acceptanceRole: read-only -completionGuard: false -inheritProjectContext: true -inheritGlobalContext: false -inheritSkills: false -thinking: high -systemPromptMode: replace ---- - -You review one lane of archie-core work from one angle. You did not write this -code and you do not fix it. - -Start from `git diff main..` and `git diff --stat main..`. -Review the diff, never the writer's transcript: the transcript costs context and -carries almost no signal. - -What you are looking for, in order: - -1. Behaviour the change dropped while keeping the shape. Refactors lose guards. - Read every new or changed doc comment: one that describes a silent fallback - is usually a confession. -2. A claim in the diff that the code does not support. -3. A test that restates an assignment or a constant instead of failing for an - interesting reason. -4. Two sides that must agree and have no test tying them together. - -Rules: - -- Read-only. Do not edit, stage, commit, or fix. Propose the fix in words. -- Every finding carries `file:line` and a quoted proof. -- Label by evidence, not by how bad it sounds: P0 breaks a user-reachable path - or an invariant, P1 is a real defect with a bounded blast radius, P2 is worth - fixing but not now. -- "No finding" is a valid and useful answer. Do not manufacture findings to look - thorough. -- `task check` passing is not evidence of correctness: it cannot see a field the - server stopped sending, because optional chaining makes a dead dashboard - binding typecheck. - -End with exactly one line: `Merge verdict: BLOCK`, `Merge verdict: OK`, or -`Merge verdict: OK with notes`. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-writer.md b/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-writer.md deleted file mode 100644 index c74461aab..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/agents/cp-writer.md +++ /dev/null @@ -1,55 +0,0 @@ ---- -name: cp-writer -description: - Implementation worker for archie-core lanes. Red-green TDD in an isolated - worktree, package-scoped gate, no suppression. -tools: read, write, edit, grep, find, ls, bash -acceptanceRole: writer -inheritProjectContext: true -inheritGlobalContext: false -inheritSkills: false -thinking: high -timeoutMs: 5400000 -systemPromptMode: replace ---- - -You implement one lane of work in the archie-core Go repository, inside your own -git worktree. - -Open every run by printing `pwd`, `git branch --show-current` and -`git status --short`, and repeat all three in your final report. A worker that -finishes in the wrong checkout looks exactly like one that did nothing. - -Method: - -1. Read the bead with `bd show `, then `CLAUDE.md` and - `docs/architecture/organisation.md`. -2. Red: write the failing table-driven test first. Run it. Paste the failure. - Confirm it fails on an assertion, not a compile error. A test that cannot - fail for an interesting reason is noise in the gate. -3. Green: the minimal implementation that satisfies the test. -4. Run your lane's scoped test command. Never run `task check`: it saturates the - machine and the merge train owns it. -5. Commit on your lane branch with a conventional-commit subject scoped by - package (`feat(controlplane): ...`). - -Hard rules: - -- Fix invalid state at the producer, not with a defensive check at the consumer. -- Never suppress: no `//nolint`, no `t.Skip`, no build tag that hides a failing - test, no deleted assertion. If a lint is wrong, leave it failing and say why. -- Adopt `task fmt` output verbatim. Never revert a formatter or linter diff. -- Two failed fixes on the same logic block means you rewrite the block, not - patch it a third time. Prefer a clean 20-line rewrite over a 5-line band-aid. -- Dependency flow is `cmd -> app -> {domain, infrastructure}`, with - infrastructure implementing domain contracts. Nothing in `internal/webui` may - reach `internal/domain/workflow`. -- Do not widen scope. Work not asked for is a finding to report, not work to do. -- Do not merge, do not push, do not touch `.beads/`, do not edit the main - checkout. -- Scratch files live in `/tmp`. Never in the working tree. -- If the bead describes a world the tree no longer has, stop and report that - instead of implementing it. - -Your final report states: the commit sha, changed files, the scoped test command -and its result, what you deliberately did not do, and any residual risk. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/lanes.json b/.agents/skills/archie-agent-fleet/references/worked-example/lanes.json deleted file mode 100644 index 27dbafb3d..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/lanes.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "model": "REPLACE_WITH_STRONG_TIER_ID", - "timeoutMs": 5400000, - "lanes": [ - { - "key": "live", - "dir": "/work/apps/cp-live", - "branch": "cp/live", - "beads": ["archie-core-nwa0"], - "test": "go test ./internal/app/controlplane/... ./internal/domain/applystatus/... -count=1 && go vet ./internal/app/controlplane/... ./internal/domain/applystatus/...", - "brief": "Wave 0 and its claims audit corrected this bead's premise, and the correction is the work. There is not one live apply path, there are two, and the PRD clause (Archie starts and checks a replacement before switching, and if the check fails the old one keeps running) applies to both. (1) workflow-execution-settings is applied on a watch (internal/app/archied/control_plane.go:94) and reports apply status at :118. (2) personas is also watched and applied live in the same process (internal/app/archied/gateway_runtime.go:37 watch, :79-86 apply) and reports NO apply status at all, so personas is the live-watched kind that widens this bead. Correction to the earlier version of this brief: workflow-definitions is not applied by a daemon watch, but do not read that as \"no watch anywhere\" -- the webui streams it at internal/webui/api_control_plane.go:139, which is a generic SSE passthrough for any kind. That is a read path, not a component-replacement path, so it does not widen nwa0. What the audit also established: the hard-coded nil at control_plane.go:118 is inert (no path in applyWorkflowExecutionSettings can fail), so do not build the bead around \"the report path cannot carry a rejection\"; that framing is wrong. Order of work: add the build-and-probe step to the live apply path, retain the previous component when the check fails, and report the failure through the apply-status surface. Decide explicitly whether personas gets the same treatment in this bead or a follow-up bead; if it is a follow-up, file the bead rather than half-wiring it. Do NOT fix the watch-reconnect defect opportunistically: it is filed separately as archie-core-yrmr, and a defect found by a review pass must not be silently repaired inside another lane. Apply status is on the State Store contract, not the control plane: PutApplyStatus/ListApplyStatus are administrative, keyed on (process, kind), replaced in place, re-stamped every 30s, stale at 90s, and a stale record renders as \"Not reporting\", never as current. applystatus.New refuses a process name Processes() does not list, deliberately: an invented name would read as a process that is not running, which the PRD blesses as legitimate, so the failure would be invisible." - }, - { - "key": "recovery", - "dir": "/work/apps/cp-recovery", - "branch": "cp/recovery", - "beads": ["archie-core-6zw0"], - "test": "go test ./cmd/... ./internal/infrastructure/staterpc/... -count=1 && go vet ./cmd/...", - "brief": "DECIDED: subcommands of cmd/archie-state-store (backup, restore, validate, rollback). Not a new binary. Sam's standing rule, restated 2026-09-21 and now recorded in docs/architecture/organisation.md#process-boundaries: a cmd/ entry is a process boundary, earned only when a surface fails independently of the rest of the fleet or when that process may need to run in more than one location (HA pair, NAT traversal, separate host). Operational commands over a surface an existing binary already owns are subcommands of it. Do not reopen this. Two premise corrections from Wave 0 that change the work. First, the file is /archie.db-tasks.sqlite (cmd/archie-state-store/main.go:290-292, asserted at main_test.go:435-439), not archie.db, so a command that operates on 'archie.db' by name operates on nothing. Second, part of this already exists in shell: scripts/archie-update-install:189 takes a sqlite3 .backup of the task database and describes it as the watchdog's only route back from a forward schema migration. That makes this bead partly consolidation. The subcommand becomes the one authoritative implementation and the install script calls it, rather than a Go path and a shell path that drift apart. Changing that script is in scope for this lane; the watchdog's refusal semantics (an update that cannot back up must not start) must survive the change unchanged. The command operates on the database file directly with the State Store stopped, refuses to run against a live store, and adds no rollback RPC: a revision carries its value and restoring replays it through the ordinary replace." - }, - { - "key": "steps", - "dir": "/work/apps/cp-steps", - "branch": "cp/steps", - "beads": ["archie-core-8szi"], - "test": "go test ./internal/domain/workflow/... ./internal/app/agentworker/... -count=1 && go vet ./internal/domain/workflow/...", - "brief": "internal/domain/workflow/steps.go:215 and :227 hard-error on legacy .archie/stages/*.go and .archie/gate.go and tell the operator to migrate to a registered YAML workflow step, but BuiltinStepRegistry() only exposes the six shipped workflows' own stages, so there is nothing to migrate to. Identify what the removed hooks actually did and land the equivalent as registered step types. This lane starts only after archie-core-fwmp has merged, and registers against the extension point fwmp created. Do not re-open the registry design." - }, - { - "key": "config", - "dir": "/work/apps/cp-config", - "branch": "cp/config", - "beads": ["archie-core-xrux", "archie-core-i3qm"], - "test": "go test ./internal/infrastructure/configuration/... ./internal/app/archied/... -count=1 && go vet ./internal/infrastructure/configuration/... ./internal/app/archied/...", - "brief": "Two beads in order, one package owner. First archie-core-xrux. The verdict is already measured with evidence (Wave 0R claims audit c6) and it is ZEROES: the -config-overlay file path silently drops every field a partial map-valued entry omits, which is exactly the archie-core-e2e2 hazard, and it is user-reachable because deployments/dev.toml is the documented -config-overlay argument and sets [services.state] target/listen, while the base config.toml is where [services.state].target_token lives -- so the overlay drops the token. The red stage is a committed characterization test through the production entry point (Loader.Resolve / -config-overlay) that loads a config with a populated map-valued entry, overlays a file setting one sibling key, and asserts the omitted keys survive; it fails today. Then move apply.go's foldOverrides (apply.go:60) onto the file overlay path (loader.go:161-194, decode at :176) so it passes. Do NOT delete apply.go, apply_test.go or Loader.ApplyOverlay: the hazard they were written for is live on that path. No dotted-path field merge is wanted beyond this guard, because the control plane replaces whole documents. Then archie-core-i3qm, whose anchor and scope the audit corrected. control_plane.go:13 is a blank line (the doc comment is :14-18); the calls moved to :20 (RuntimeConfig) and :27 (configuration.Validate) in 9accf112. More importantly the PRD clause names State Store startup, and state_store.go:75-104 never calls runtimeConfig: it reaches Loader.finalize via bootstrap.go:263 (the loader.Resolve call site, not finalize itself) and loader.go:341-346, where Validate runs. Scope correction: that file-only Validate runs before loadRuntimeConfig for ALL THREE binaries (main.go:358, gateway.go:61, state_store.go:78), so it is not state-store-specific; and a value that is valid alone but invalid only after the DB merge never blocks the state store at all, because it is imported unvalidated at state_store.go:104 and fails later in the daemon's loadRuntimeConfig (control_plane.go:27). Reduce the bootstrap document to the fields the PRD lists (database path, listen addresses, credentials, TLS, encryption-key references) and stop validating the migrated surface at startup, so a stale TOML value in a database-owned field cannot fail boot. boot.runtimeConfig is the one layering call and the SIGHUP callback makes the same call: if you add a database-owned layer, add it there and nowhere else." - } - ] -} diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave1.md b/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave1.md deleted file mode 100644 index 1a4dc6b41..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave1.md +++ /dev/null @@ -1,73 +0,0 @@ -# Wave 1 sub-prompt: shape first - -**One child. fwmp alone.** Nothing else runs until it merges, and Wave 2 -branches from the merged shape. - -xrux is no longer a Wave 1 probe. Its verdict is already measured with evidence -(Wave 0R claims audit c6) and the answer is **ZEROES**. Re-measuring buys -nothing, so the characterisation test is folded into the `config` lane's red -stage, where it is committed and the evidence lives in the tree rather than in a -transcript. See the `config` brief in `lanes.json`. - ---- - -## fwmp: the shared shape (cp-writer, worktree `/work/apps/cp-shape`, branch `cp/shape`) - -Gate: -`go test ./internal/domain/workflow/... ./internal/app/controlplane/... ./internal/app/agentworker/... -count=1` - -```text -Bead archie-core-fwmp. Run `bd show archie-core-fwmp` first. - -docs/prds/runtime-control-plane.md:95 says plugins can add step types. Today every -call site hardcodes workflow.BuiltinStepRegistry(): -internal/app/agentworker/task_execution.go:319 and :335, -internal/app/controlplane/workflow_definitions.go:26 and :33, and -internal/app/controlplane/client.go:41. The step vocabulary is closed to the six -shipped workflows. - -Verified by the Wave 0 claims audit, so treat as fact and do not re-derive: -- Those are exactly five non-test call sites, plus five test call sites. -- BuiltinStepRegistry() is defined at internal/domain/workflow/definition.go:149 and - is built only from legacyBuiltinWorkflows() (definition.go:181). -- StepRegistry is a plain `map[string]StepFactory` (definition.go:32). There is no - merge/widen function; BuiltinStepRegistry() is itself the only registration site. -- All five production call sites pass the identical function, so nothing diverges - today. The gap is the absence of a guard, not a live defect. - -Deliver: a registry assembled from the plugin set, resolved identically on both -sides. - -The load-bearing constraint is not the extension point, it is agreement. The -validating side is the State Store; the executing side is archie-agent. A -definition that validates and then fails to compile at run time is the failure -this bead exists to prevent, and it is exactly the failure two packages that each -pass their own tests produce. No test today ties the two sides: no test file -imports both internal/app/controlplane and internal/app/agentworker. Your change -is not done until one test asserts that both sides resolve the same step -vocabulary from the same plugin set. Write that test first and let it fail for the -right reason. - -Do NOT edit internal/domain/workflow/definition_test.go:8 -TestParseDefinitionRejectsUnsafeDefinitions. The audit established it is not an -obstacle: its pin is name-exact ("shell" at :11, implement.prepare's own factory at -:12), so a settings-bearing plugin step type under any other name passes it -unchanged. Adding a step type is archie-core-8szi's lane, not this one. - -Do NOT fix the workflow-version pin opportunistically. The audit found it is never -persisted over gRPC and its digest guard is dead in production; that is filed as -archie-core-zf8h and gets its own lane and Sam's eyes. Report it if you touch it, -do not repair it here. - -Before adding a plugin engine surface, satisfy -ARCHITECTURE.md#plugin-engine-rule-strict. - -This is the shape every other lane branches from, so it lands alone and it lands -first. Do not implement any step type; archie-core-8szi does that afterwards -against what you build. Do not widen scope to the .archie gate behaviour. - -Working contract: print pwd, git branch --show-current and git status --short -before editing and repeat them in your report. Red then green. Package-scoped -tests only, never `task check`. No //nolint, no t.Skip, no deleted assertions. -Adopt `task fmt` verbatim. Commit on cp/shape with a conventional subject. -``` diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave4-merge-train.md b/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave4-merge-train.md deleted file mode 100644 index 4ca14efa3..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave4-merge-train.md +++ /dev/null @@ -1,66 +0,0 @@ -# Wave 4: merge train - -Serial. You run this yourself in the captain checkout at -`/work/apps/archie-core`. No subagent owns `main`, and only one `task check` -exists at a time. - -Order: `cp/shape` (already merged in Wave 1), then `cp/config`, `cp/live`, -`cp/recovery`, `cp/steps`. Config goes early because it owns the bootstrap path -the others boot through. - -## Per branch - -```bash -BR=cp/live - -git -C /work/apps/archie-core status --short # must be clean -git merge-base --is-ancestor main $BR && echo "stale: rebase required" -git log --oneline main..$BR -git diff --stat main..$BR -``` - -A branch that predates a merge computed its deletions against code that has -since changed. On this repo a stale branch's diff deleted 460 lines of -`internal/config` that read as tidy relocation and would have reverted another -lane's decomposition. Rebase it or re-derive the work. Never merge a diff whose -deletions were computed against code that has moved. - -Then: - -1. `git merge --no-ff $BR` (or apply the lane's handoff patch if the lane ran in - a managed worktree). -2. `task build --force`, then `task check`, once, alone. Nothing else runs on - this machine while it does. The force-build is required until - archie-core-hhgw lands: `task build`'s sources are Go-only - (Taskfile.yml:325), so a ui/dist-only change does not retrigger it and a - stale embedded dashboard would ship (Wave 0R audit c10). -3. On failure: one fix pass back to that lane's retained writer with the real - output pasted in, not a summary. On a second failure, `git reset --hard` the - merge, requeue the lane, and move to the next branch. Do not stack a third - patch, and do not fix it yourself unless the fix is one line and obvious. -4. Commit generated assets in the same commit. `ui/dist/` and schema outputs are - LAW: never regenerated away, never reverted, never left out. -5. `bd close ` for each bead the branch delivered. Do not stage `.beads/`, - and never create a commit whose only content is beads bookkeeping. - -## Landing check, every time - -```bash -git log --oneline -3 -git branch --no-merged main -git log --oneline origin/main..main -``` - -Done has three states: no commits, committed and unmerged, merged. Only the -third counts. A closed bead is what a worker believed, not what landed. - -## Your own edits - -A coordinator `sed` rename on this repo once produced `&fakeStore{fakeStore{` in -six places and broke the build. Your edits get the same gate as the children's, -and nobody else reviews them. - -## Do not push - -Sam pushes manually and does not always announce it. Report what is unpushed as -fact. If `git log origin/main..main` is long, say how long; do not act on it. diff --git a/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave5-eju6.md b/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave5-eju6.md deleted file mode 100644 index 5b0192e55..000000000 --- a/.agents/skills/archie-agent-fleet/references/worked-example/prompts/wave5-eju6.md +++ /dev/null @@ -1,53 +0,0 @@ -# Wave 5: eju6, the end-to-end restart test - -One lane, one `cp-writer`, against merged `main`. This is the only bead that -proves the feature rather than adding to it, so it runs last and alone. - -Gate: `cd && go test ./internal/app/controlplane/... -count=1`, then -`task check` through the merge train as usual. - -```text -Bead archie-core-eju6. Run `bd show archie-core-eju6` first. - -docs/prds/runtime-control-plane.md ("First implementation") lists an end-to-end -restart test as a deliverable and there is none. -internal/app/controlplane/controlplane_test.go covers seeding and catalog only. -No test drives a change through the API, restarts a process, and asserts the -change survived. - -Deliver that test: a real end-to-end check, not a unit test, and not a rewrite -of the existing file. - -It must, in one test: - 1. write a settings change through the control-plane API, as the dashboard - would, attributing to identity.SystemID; - 2. observe the change land in the audit trail as an ordinary edit; - 3. restart the process that consumes it; - 4. assert the process came back on the stored value, not the file value; - 5. assert the apply-status row for that process reports the version it - applied, and that a record older than 90 seconds reads as "not reporting" - rather than as current. - -Facts you need and must not re-derive: - - boot.runtimeConfig is the single layering call, and the SIGHUP reload makes - the same call over the document it just resolved (9af013eb). A reload cannot - revert a database-owned setting to its file value, and that is the property - under test. - - Execution budgets arrive on a watch, not a resource query, so boot records - the last settings it applied and the reload re-applies them from there. - - PutApplyStatus/ListApplyStatus are administrative on the State Store - contract: a task-scoped grant is denied both by the deny-by-default arm of - authorizesTaskScopedCall. Your harness needs the administrative token. - - Rows are keyed on (process, kind) and replaced in place; every process - re-stamps every 30 seconds. - - The control plane fails closed: a stored value that will not validate stops - archied starting. - -If the test fails, that is a finding about the feature, not about the test. -Report the failure with the output and stop. Do not weaken an assertion, do not -add a retry loop to paper over a race, and do not mark it t.Skip. - -If a real end-to-end restart cannot be driven in-process, say so explicitly and -describe what harness it would need, rather than substituting a unit test that -asserts less and claims the bead. -``` diff --git a/.agents/skills/archie-architecture-contract/SKILL.md b/.agents/skills/archie-architecture-contract/SKILL.md deleted file mode 100644 index 831753e5b..000000000 --- a/.agents/skills/archie-architecture-contract/SKILL.md +++ /dev/null @@ -1,246 +0,0 @@ ---- -name: archie-architecture-contract -description: >- - Protect Archie's load-bearing architecture while placing, implementing, or - reviewing behaviour. Load this skill before changing daemon composition, - domains, workflows, task lifecycle, agent execution, messaging, work intake, - identity, memory, configuration, plugins, policies, persistence, NATS/RPC, - containers, or process boundaries; use it when deciding where new code - belongs, enforcing dependency direction, separating current runtime truth - from the approved target and open migration decisions, or ensuring every - behaviour has one authoritative path. Route proof of duplication, dead-code - disposition, production reachability, and maintainability to - archie-technical-accountability. ---- - -# Archie Architecture Contract - -Treat architecture as executable safety policy. Preserve one understandable -owner and one production path for each behaviour. - -## Read status before code - -| Label | Meaning | Authority | -| ------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | -| **CURRENT** | Behaviour present in live code and production composition as of 2026-09-18. | Code, tests, and `internal/app/archied` wiring (`cmd/archied/main.go` is a thin dispatcher) | -| **APPROVED TARGET** | Direction an implementation must approach, but which may not exist on disk. | `docs/prds/01-project-management.md` and documents whose status says approved | -| **OPEN** | A migration or API decision no implementer may invent locally. | `docs/architecture/migration-decisions.md` and documents marked in progress or under design | - -> **Do not implement target prose as though it describes current code.** -> Before treating a target package as available, prove that it exists and is -> used from a production entry point. As of 2026-09-18 `internal/domain/`, -> `internal/eventbus/`, `internal/infrastructure/`, and `internal/app/` exist; -> `internal/policy/` does not, and `internal/domain/{agent,identity}` remain -> APPROVED TARGET only. - -Resolve apparent disagreement in this order: - -1. Read live code and production composition for CURRENT behaviour. -2. Read `docs/prds/01-project-management.md` for APPROVED TARGET ownership. -3. Read the focused decision document for the selected behaviour. -4. Read `docs/architecture/migration-decisions.md` for OPEN work. -5. Stop and use `archie-architecture-planning-campaign` if a required semantic - decision remains open. - -Route to `archie-domain-reference` for glossary and -`archie-config-and-flags` for config enumeration. - -Two skills this document routes to are parked outside this checkout, under -`/work/apps/archie-skills-parked/`: `archie-technical-accountability` and -`archie-architecture-planning-campaign`. If your session has not loaded them, -treat each routing target as a manual escalation step rather than a live skill. -Also: `cmd/archied/main.go` is a thin dispatcher; the wiring lives in -`internal/app/archied/`. - -## Know the CURRENT system - -Do not simplify these facts into the target model: - -| Concern | CURRENT runtime truth on 2026-09-18 | Evidence | -| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | -| Composition | `cmd/archied/main.go` dispatches to `internal/app/archied.Run()`, which performs construction and wiring in `bootstrap.go`. | `cmd/archied/main.go`; `internal/app/archied/` | -| Durable work | `task.Task` combines forge/chat source data, workflow position, output, retry, identity, and PR state. | `internal/domain/workflow/task/task.go`; `internal/domain/storecontract/storecontract.go` | -| Workflow | `internal/domain/workflow` routes a `task.Task` into a `map[string]Workflow`, mutates a broad `TaskContext` through sequential stages. | `internal/domain/workflow/workflow.go` | -| Agent-stage boundary | Versioned `agentexec.Request`/`Result` carries one autonomous stage; validation correlates task, attempt, and stage. | `internal/agentexec/protocol.go` | -| Container handoff | `internal/taskrun` carries entire task plus `config.Repo` and `config.TaskConfig`; `internal/app/agentworker` owns routing and sequencing while its NATS adapter owns wire mechanics. | `internal/taskrun/taskrun.go`; `internal/app/agentworker/`; `internal/infrastructure/agenttransport/nats/` | -| Git ownership | Daemon-owned worktree operations clone, commit, push, diff, and clean up. | `internal/worktree/`; `internal/domain/workflow/steps.go`; `docs/architecture/agent-system.md` | -| Enforcement | Gates, read-only/protected paths, TDD inverted test gates, and diff caps are represented outside prompt prose. | `internal/gate/`; `internal/domain/workflow/{agent,tdd,steps}.go` | -| Configuration | `internal/config.Config`, `IdentityConfig`, `Repo`, and task snapshots mix input decoding with runtime concerns. Decoding itself lives in `internal/infrastructure/configuration`. | `internal/config/config.go`; `internal/infrastructure/configuration/` | -| Identity | Configured names and bot usernames act as process-local identity keys. There is no durable Identity domain. | `internal/daemon/daemon.go`; `internal/domain/storecontract/storecontract.go`; `internal/gateway/session.go` | -| Messaging | `internal/gateway` contains both the `Message` struct flow and richer `MessageEvent`; channel routing and task control are mixed with conversational behaviour. | `internal/gateway/{gateway,messageevent,tasks}.go`; `internal/channels/` | -| Plugins | `plugin.Plugin` exposes only `Name` and `Version`; current loading interprets operator-installed Go files with Yaegi. | `internal/plugin/plugin.go` | -| Processes | Agent modes include in-process, subprocess, and NATS. Optional containers add a distinct boundary with known gaps. | `internal/config/config.go`; `internal/app/archied/`; `docs/architecture/organisation.md` | - -### Interpret the current lifecycle honestly - -Use these CURRENT status values: - -```text -queued, running, waiting_human, pr_open, merged, -parked, dead, rejected, closed_wont_do -``` - -The intended flow includes queue/claim, workflow stages, human wait/resume, PR -reconciliation, parking/retry/exhaustion, and crash recovery. Read -`internal/domain/workflow/task/task.go`, `internal/daemon/daemon.go`, and -`internal/domain/workflow/workflow.go` before changing a transition. - -`Store.Transition(ctx, taskID, from, to, detail)` now guards on `from` -(`WHERE id=? AND status=?`, returning `store.ErrStaleTransition` on mismatch) -and runs the status update plus the transition-history insert in one -transaction (`internal/infrastructure/postgres/store.go`). The sentinel crosses the State Store -gRPC boundary via `mapError`/`unmapError` in -`internal/infrastructure/staterpc/values.go`; its canonical message string is -part of the wire contract. Earlier non-atomic behaviour is the settled fix, -not an open design. - -## Preserve the load-bearing invariants - -| Invariant | Required action | Status and source | -| ----------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| The model never runs git | Keep clone, branch, commit, push, diff, and cleanup in deterministic workspace/worktree steps. | CURRENT: `docs/architecture/agent-system.md`; `internal/worktree/` | -| Deterministic constraints outrank prompts | Enforce gates, protected paths, read-only stages, test protection, and change caps outside model instructions. | CURRENT: `docs/architecture/agent-system.md`; `internal/gate/`; `internal/domain/workflow/` | -| Agent execution is a data boundary | Send bounded, versioned input; validate correlated output before applying it. | CURRENT foundation: `internal/agentexec/protocol.go`; `docs/architecture/agent-system.md` | -| Every workflow ends explicitly | Preserve terminal outcome or visible park. Preserve crash recovery of interrupted `running` work. | CURRENT: `internal/domain/workflow/workflow.go`; `internal/infrastructure/postgres/store.go` | -| Generic plugins stay metadata-only | Keep `plugin.Plugin` at `Name()`/`Version()`. Behaviour on typed capability interface with owning `Registry`/`Manager`. | CURRENT-enforced rule: `internal/plugin/architecture_test.go` | -| Capability engines own lifecycle | Give resource-owning engines explicit start/health/stop semantics and failure isolation. | APPROVED rule: `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict` | -| Trust is explicit | Treat trusted operator-installed in-process code, repository code, out-of-process integrations, and container-isolated code as different trust classes. | APPROVED rule: `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict` | -| Infrastructure stays replaceable | Keep forge, persistence, workspace, transport, container, and model details behind behaviour-owned contracts. | APPROVED TARGET: `docs/architecture/dependencies-and-contracts.md` | -| Same-repository execution serialises by default | Preserve default unless explicit scheduling policy permits concurrency. | CURRENT: `internal/config/config.go`; `internal/daemon/daemon.go` | - -Run the mechanical plugin guard after changing any plugin or `*Engine` -interface: - -```bash -go test ./internal/plugin -count=1 -``` - -## Apply the APPROVED TARGET - -Apply ownership rules to migration plans and new seams. Not CURRENT until -production wiring proves the cutover. - -### Keep dependency direction inward - -```text -domain and shared application contracts <- infrastructure implementations - ^ - | - application composition -``` - -1. Put cohesive behaviour, vocabulary, state, commands, events, policies, - runtime settings, and required service interfaces with its owning domain. -2. Make infrastructure implement domain-required interfaces and translate - external representations. -3. Let only `internal/app` choose concrete implementations and connect domains. -4. Keep `cmd/*` limited to process input and invoking composition. -5. Use an owned command, event, or approved shared contract across domains. -6. Never let one domain mutate another domain's state or call its internals. - -Sources: `docs/architecture/organisation.md`, -`docs/architecture/dependencies-and-contracts.md`. - -### Separate interaction, admission, assistance, and execution - -```text -channel-neutral Message -> Agent turn -> optional proposed work --> Work Intake -> AcceptedWorkRequest -> Workflow selects version -> WorkflowExecution -``` - -- **Messaging** owns canonical messages, conversations, branches, channel correlation, delivery. -- **Agent** owns persistent assistant, continuity, specialisation, memory. -- **Work Intake** owns admission, validation, routing, accepted-work-request handoff. -- **Workflow** owns versioned definitions, steps, executions, attempts, outcomes. - -Do not equate external issue/message with WorkflowExecution; do not let Work -Intake create one directly. - -Sources: `docs/architecture/migration-decisions.md`, -`docs/architecture/agent-system.md`, `docs/architecture/messaging-and-work-intake.md`. - -### Separate identity, Agent, conversation, and memory - -Use immutable `IdentityID` for target attribution. Keep Identity separate from -Agent. Four fixed memory scopes: - -| Scope | Visibility | -| ----------------------- | ------------------------------------------ | -| Global shared | Shared across Archie | -| Agent-wide | One Agent across users; private by default | -| User-wide | One user across authorised Agents | -| Agent-user relationship | Exactly one Agent and one user | - -Do not use conversation branching as a fifth memory scope. - -Sources: `docs/architecture/identity.md`, `docs/architecture/agent-system.md`, -`docs/architecture/migration-decisions.md`. - -### Dissolve global runtime configuration - -Treat `internal/config` as migration source inventory: - -- move file/env/overlay/secret decoding to `internal/infrastructure/configuration`; -- let each domain or plugin own typed runtime settings; -- translate external DTOs in `internal/app`; -- never pass complete application config into a domain; -- classify each behavioural value as invariant, runtime setting, policy value, - derived value, or runtime state. - -Source: `docs/architecture/configuration.md`. - -## Place new behaviour deliberately - -| Behaviour | Target owner/location | Decision gate | -| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -| Persistent actor lifecycle and attribution | `internal/domain/identity` | Do not mix authentication/access policy into Identity. | -| Persistent assistant behaviour and continuity | `internal/domain/agent` | Keep model/provider replaceable; do not fold Workflow into Agent. | -| Workflow definitions, steps, executions, attempts, outcomes | `internal/domain/workflow` | Preserve version ownership and one authoritative lifecycle. | -| Canonical messages, conversations, branches, delivery | `internal/domain/messaging` | Keep platform IDs as external correlation. | -| Admission and deterministic routing of proposed durable work | `internal/domain/workintake` | Emit an accepted request; do not construct execution state. | -| Generic plugin identity/discovery/compatibility/lifecycle | `internal/domain/plugin` | Keep generic contract metadata-only. | -| Capability-specific plugin behaviour | Owning domain's typed registry/manager | Never add behaviour to `plugin.Plugin`. | -| Broker-neutral publication/subscription mechanics | `internal/eventbus` | Keep message meaning and schemas with their domain. | -| Shared policy evaluation/evidence mechanics | No current package. `internal/policy` was the planned location; as of 2026-09-18 policy lives inside playbook bindings (`playbooks/`, `internal/domain/eda/playbook`) and `internal/gate/`. | Keep policy vocabulary, evaluators, and consequences with consuming domain. | -| NATS, PostgreSQL, forge, config decoding, external SDK adapters | `internal/infrastructure/` | Implement a narrow owner-defined contract; translate at boundary. | -| Construction, cross-domain connection, startup/shutdown | `internal/app/archied` or `internal/app/agentworker` | Keep `cmd/*` thin; define health and shutdown order. | -| Deploy assembly | `deployments/` | Do not move application behaviour into deployment files. | -| Unreviewed memory/tools/workspace/gate/storage/web/RPC/scheduling | **OPEN** | Run `archie-architecture-planning-campaign`. | - -## Confront known weak points - -| Weak point on 2026-09-18 | Required response | -| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | -| `TaskContext` is a mutable service bag with config, services, policy, scratch state. | Design narrow step inputs and staged removal. | -| Workflow lifecycle split across store, daemon, workflow, gateway, worker. | Trace every writer and reader before changing status. | -| State changes and transition history were non-atomic and `from` was advisory — **settled** in `internal/infrastructure/postgres`: `Transition` guards on the current status and writes status plus history in one transaction. | Keep every status writer behind `Transition`; do not reintroduce a raw `UPDATE tasks SET status`. | -| In-process and container paths put orchestration on different sides of process boundary. | Decide which path survives before extending both. | -| Identity uses strings; task uniqueness/NATS dedup omit identity. | Don't promise multi-identity ownership until canonical IDs migrate. | -| Container RPC uses root forge/worktree, not task owner's identity. | Known trust/correctness defect — not identity-isolated. | -| Missing `task.json` makes `archie-agent` join shared queue. | Fail closed before treating as isolated. | -| Subprocess uses daemon user and host access. | Not a security boundary. | -| Gateway formerly duplicated lifecycle strings, competing message contracts. | No third contract or direct lifecycle mutation path; status constants live in `internal/domain/workflow`. | -| Global config and `IdentityConfig` combine unrelated owners. | Don't rename global structure or add `Extra` map. | -| Memory has fixed scope requirements but OPEN final placement/migration. | Preserve scope isolation; focused design before moving. | -| Tests can make unused/duplicate code appear legitimate. | Prove production reachability from composition. | - -## Control every architecture-affecting change - -| Class | Action | -| ------------------------ | ------------------------------------------------------------------------------------------ | -| Current-path repair | Stay inside current owner, preserve invariants. | -| Migration slice | Record current/target owner, contracts, compatibility adapter, cutover, deletion criteria. | -| New/changed architecture | Stop; run `archie-architecture-planning-campaign` until approved. | - -Trace with evidence: - -```bash -rg -n '||' cmd internal -go list -deps ./cmd/archied | rg 'github.com/samcharles93/archie-core/internal/' -gopls references path/to/file.go:: -``` - -Use `gopls references` or another AST-aware reference query when interfaces, -embedding, generated symbols, or same-named methods make text search ambiguous. -Trace from `cmd/archied/main.go` into `internal/app/archied.Run()`; the wiring -itself is in `internal/app/archied/bootstrap.go`. diff --git a/.agents/skills/archie-architecture-contract/agents/openai.yaml b/.agents/skills/archie-architecture-contract/agents/openai.yaml deleted file mode 100644 index 1048ff3d5..000000000 --- a/.agents/skills/archie-architecture-contract/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Architecture Contract" - short_description: "Protect Archie load-bearing architecture decisions" - default_prompt: "Use $archie-architecture-contract to place and review this change without violating current or target architecture." diff --git a/.agents/skills/archie-build-and-env/SKILL.md b/.agents/skills/archie-build-and-env/SKILL.md deleted file mode 100644 index 22d47ebef..000000000 --- a/.agents/skills/archie-build-and-env/SKILL.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -name: archie-build-and-env -description: Recreate, inspect, and troubleshoot Archie Core's development, build, test, documentation, and container toolchains. Use when onboarding a checkout; diagnosing Go, Task, golangci-lint, gofumpt, Docker/Compose, NATS, GPG, cache, temporary-directory, listener, or network failures; comparing local work with repository automation; or proving which build surfaces a command actually covers. Load this before running task check in an unfamiliar or restricted environment because that gate rewrites files and omits several independent surfaces. ---- - -# Build and verify the Archie environment - -Recreate the environment as independently verified surfaces. Do not turn a -passing root-module command into a claim that the tools module, documentation -site, race detector, linter, or container images also passed. - -All volatile observations are snapshots from **2026-09-18** (HEAD `2e1e1549`). - -## Name the surfaces - -| Term | Meaning here | -| ------------------ | ----------------------------------------------------------------------------------------------------------------- | -| Repository root | Directory containing `go.mod`, `Taskfile.yml`, and `CLAUDE.md`. | -| Runtime module | Root Go module `github.com/samcharles93/archie-core`. | -| Tools module | Independent nested Go module under `tools/`. | -| Docs | Markdown and generated JSON under `docs/`; an external Astro website renders and deploys the generated artifacts. | -| Cold cache | Dependency cache not yet containing required modules/packages. | -| Restricted sandbox | May allow file reads but deny loopback listeners, container engine, or writes to default caches. | - -No root `README*` or `CONTRIBUTING*` file exists. Begin with: - -```bash -sed -n '1,240p' CLAUDE.md -ls docs/architecture/ -task --list -``` - -## Inventory requirements before installing anything - -```bash -go version -go env GOTOOLCHAIN GOVERSION GOOS GOARCH CGO_ENABLED GOTMPDIR GOCACHE GOMODCACHE -task --version; golangci-lint version; gofumpt -version -node --version; npm --version # UI only; docs need no Node toolchain -docker --version; docker compose version -git --version; gpg --version -``` - -Classify a missing command as an environment prerequisite. Bootstrap (verified -2026-09-19): Go ≥ 1.27.0, Task ≥ 3.x, gofumpt v0.11.0, golangci-lint 2.13.2, -Node 24.x for the `ui/` frontend. - -`task fmt` runs `go fix` and then `golangci-lint fmt`; `task lint` uses the -same binary and `.golangci.yml`, so its gofumpt, goimports, and gci rules have -one owner and the writer converges the checker. Standalone `gofumpt` remains -only for generated protobuf contracts in `tools/proto.sh`. - -The three Yaegi secret-engine examples carry `//go:build ignore`. goimports -cannot type-check them and deletes a genuinely used `internal/secret` import, -so `.golangci.yml` excludes those exact files from the formatter set. Their -runtime loading remains covered by `internal/secret/engines_test.go`. - -| Surface | Repository declaration | Installed snapshot | Interpretation | -| ------------- | ----------------------------------------------------- | --------------------------------------- | ------------------------------------------------------- | -| Runtime Go | `go 1.27.0` in `go.mod` | Go 1.27.0, linux/amd64 | Requires at least declared Go level. | -| Tools Go | `go 1.27.0` in `tools/go.mod` | Same Go 1.27.0 binary | Toolchain must satisfy both modules. | -| Task | Taskfile schema `version: "3"` | Task 3.48.0 | Installed version is environment fact. | -| gofumpt | Generated protobuf formatting; pinned in `Dockerfile` | v0.11.0 | Not the ordinary source formatter. | -| golangci-lint | v2 config in `.golangci.yml`; pinned in `Dockerfile` | 2.13.2 | Owns ordinary formatting and lint checks. | -| Node | `ui/` frontend build | 26.9.0 / npm 11.19.1 | No `engines`/`packageManager` field. Docs need no Node. | -| Containers | Compose commands in `Taskfile.yml` | Podman-backed, unusable in this sandbox | Verify CLI, Compose plugin, daemon/socket separately. | - -## Prepare writable caches in a restricted sandbox - -```bash -go env GOTMPDIR GOCACHE GOMODCACHE GOPATH -df -T /tmp -``` - -If any default is read-only: - -```bash -export ARCHIE_GOTMPDIR=/tmp/archie-core-gotmp -export ARCHIE_GOCACHE=/tmp/archie-core-gocache -export ARCHIE_GOMODCACHE=/tmp/archie-core-gomodcache -export ARCHIE_GOPATH=/tmp/archie-core-gopath -export ARCHIE_LINT_CACHE=/tmp/archie-core-golangci -mkdir -p "$ARCHIE_GOTMPDIR" "$ARCHIE_GOCACHE" "$ARCHIE_GOMODCACHE" \ - "$ARCHIE_GOPATH" "$ARCHIE_LINT_CACHE" -``` - -Prefix Go commands: - -```bash -env GOTMPDIR="$ARCHIE_GOTMPDIR" GOCACHE="$ARCHIE_GOCACHE" \ - GOMODCACHE="$ARCHIE_GOMODCACHE" GOPATH="$ARCHIE_GOPATH" \ - go test ./internal/config/... -count=1 -``` - -Populate cold cache only with network authorised: - -```bash -env ... go mod download; env ... go -C tools mod download -``` - -## Recreate the root Go surface - -```bash -test -f go.mod && test -f cmd/archied/main.go && test -f cmd/archie-agent/main.go -go list -m -go build -o /tmp/archie-core-archied ./cmd/archied -go build -o /tmp/archie-core-agent ./cmd/archie-agent -go test ./internal/config/... -count=1 -go vet ./... -golangci-lint run ./... -``` - -## Understand exactly what Task runs - -| Task | Exact effect | -| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -| `task fmt` | `go fix ./...`, then `golangci-lint fmt` — both may rewrite source. | -| `task vet` | `go vet ./...` in the runtime module. | -| `task lint` | `golangci-lint run ./...`. | -| `task build` | Builds both commands into `bin/`. | -| `task test` | `go test -short ./...` in the runtime module, test cache on. `task test:full` is the uncached run including wall-clock-bound tests. | -| `task check` | `fmt` + `proto:lint` + `proto:check` + `docs:check` + `vet` + `lint` + `build` + `test` + `test:tools` + `test:ui`. | -| `task clean` | Recursively removes `bin/`; destructive. | -| `task docker-build` | `docker compose build agent` only. | - -`task check` is the definitive gate but omits race tests, `task vuln`, and -`task docker-build`. Its docs step, `docs:check`, verifies committed generated -data and never renders anything: there is still no documentation build. - -Two of its steps check committed artifacts rather than the build, so both fail -on work that is correct but unstaged, and both read as a broken generator: - -- `proto:check` regenerates, then runs `git diff --exit-code -- internal/contracts` - and rejects untracked files there. After any `.proto` edit, - `git add internal/contracts proto` before the gate. The failure prints the - regenerated diff, which looks like generation produced something unexpected. -- `ui:check` compares `ui/dist` against a fresh build of `ui/src` and fails when - they differ. `task check` never rebuilds the bundle: run `task ui` after any - `ui/src` change and commit the result with that change. - -Run only in an authorised writable worktree. For a read-only ordinary-source -preview, use `golangci-lint fmt --diff`. - -## Verify the tools module separately - -No `go.work`. Root `go test ./...` does not enter `tools/`. - -```text -module github.com/samcharles93/archie-core/tools -replace github.com/samcharles93/archie-core => ../ -``` - -```bash -go -C tools test -mod=readonly ./... -count=1 -``` - -`-mod=readonly` is mandatory on every `go -C tools` command. The `replace` -forces the tools build list to satisfy the root module's requirements, so a -root dependency bump leaves tools stale, and a writable command repairs -`tools/go.mod` and `tools/go.sum` in place, dirtying the tree with an -unrelated diff. Pass the flag explicitly: a global `GOFLAGS=-mod=mod` in -`go env` beats the toolchain default. A failure here means run -`go -C tools mod tidy` and commit that on its own. `task check` runs this via -`task test:tools`. - -Generate documentation to temp file: - -```bash -go -C tools run -mod=readonly ./docsgen --repo-root .. --out /tmp/archie-core-contracts.json -cmp --silent docs/data/generated/contracts.json /tmp/archie-core-contracts.json -``` - -2026-09-18 run wrote 11 schemas. The committed output was stale since -`4b340d2b` and was regenerated the same day; `cmp` now passes. `task docs:check` -now runs inside `task check`, so this drift fails the gate instead of waiting to -be found by hand. `docsgen all` does not exist yet. - -Prefer the task over the raw commands: - -```bash -task docs:check # non-destructive; fails loudly and names the Go type -task docs:generate # rewrites the committed artifact; review the diff -``` - -## Documentation needs no build - -`docs/` is Markdown read directly in the repository, an editor, or the forge's -file view. Nothing builds, renders, or publishes it. - -The VitePress site (`docs/.vitepress/`, `docs/package.json`, the pnpm lockfile), -its landing page, and `.github/workflows/docs.yml` were removed on 2026-09-12 as -an unnecessary build step. Git no longer tracks any `docs/node_modules` entries. - -Do not `pnpm install` under `docs/`; it has no package manifest. See -`docs/architecture/generated-documentation.md`, "Rendering and publishing". - -Commit `4cb0577` cleaned up accidentally committed `.gotmp`; `.gotmp/` now ignored. - -## Treat container setup as a networked, privileged surface - -```bash -test -e .dockerignore || echo ".dockerignore is absent" -rg -n '^(FROM|[[:space:]]*image:)|@latest|:latest|setup_24.x' \ - Dockerfile Dockerfile.archied docker-compose.yml -``` - -`.dockerignore` exists (421 bytes) and excludes `.git`, `.task`, `.claude`, -`.codex`, `.crew`, `.agents`, `.references`, `bin/`, `dist/`, `docs/`, -`node_modules/`, root-built `archied`/`archie-agent`, and local config. Both -Dockerfiles still run `COPY . .` on top of it. Floating inputs: Go builder tags -omit patch/digest; Ubuntu base images omit digests; agent installs multiple -`@latest` Go tools; Node from moving `setup_24.x` channel. - -`task docker-build` needs registry/network and functioning Compose. -`task docker-up` starts the Compose-managed NATS service and binds ports -4222/8222. The host daemon and its Docker-socket access are outside Compose. - -## Separate environment failures from code failures - -| Signature | Classify and branch | -| ------------------------------------------------------------------- | ------------------------------------------------------------ | -| `go: creating work dir: mkdir /work/tmp/...: read-only file system` | Set task-specific `GOTMPDIR`. | -| `open .../.cache/go-build/...: read-only file system` | Set writable `GOCACHE`. | -| `open .../pkg/mod/cache/...tmp: read-only file system` | Set writable `GOMODCACHE` and `GOPATH`. | -| `listen ...: socket: operation not permitted` | Re-run on host with loopback sockets. | -| `Unable to start NATS Server in Go Routine` after ~10s | Test whether local listeners permitted. | -| `cannot auto-sign commit` | Ambient `commit.gpgSign=true`; fixtures set `gpgsign=false`. | -| `EAI_AGAIN` for `registry.npmjs.org` | Dependency retrieval failed. | -| `Podman configuration ... read-only file system` | Container backend cannot initialise. | -| `TestRunWrapsExternalCommand ... Run() = "\n"` | Focused code failure in `internal/skillscript`. | - -For hermetic test diagnosis: - -```bash -env GIT_CONFIG_GLOBAL=/dev/null go test ./internal/worktree/... ./internal/worktreerpc/... -count=1 -``` - -## Use the complete validation matrix - -| Evidence | Command | Current snapshot | -| --------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | -| Focused Go behaviour | `go test ./pkg/... -run '^TestName$' -count=1 -v` | Use first. | -| Root unit/integration suite | `go test ./... -count=1` | Restricted sandbox fails listener-dependent packages. | -| Root race suite | `go test -race ./... -count=1` | Not run by `task check`. | -| Vet | `go vet ./...` | Passed on 2026-09-18. | -| Lint | `golangci-lint run ./...` | Not re-run on 2026-09-18; a focused `--enable-only=dupl ./internal/...` run reported 0 issues. Re-run before quoting a total. | -| Build | `go build -o /tmp/... ./cmd/archied` and `cmd/archie-agent` | Both passed on 2026-09-18. | -| Tools tests | `go -C tools test -mod=readonly ./... -count=1` | Passed on 2026-09-18. | -| Generated contract parity | Temp docsgen output + `cmp --silent` | Passed for 11 schemas on 2026-09-18, after regenerating a file stale since `4b340d2b`. | -| Container build | `task docker-build` | Not verified in restricted environment. | -| Repository gate | `task check` | See `archie-diagnostics-and-tooling` for the dated snapshot. | diff --git a/.agents/skills/archie-build-and-env/agents/openai.yaml b/.agents/skills/archie-build-and-env/agents/openai.yaml deleted file mode 100644 index 971323ae0..000000000 --- a/.agents/skills/archie-build-and-env/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Build and Environment" - short_description: "Recreate and verify the Archie toolchain" - default_prompt: "Use $archie-build-and-env to recreate a clean Archie development environment and verify every build surface." diff --git a/.agents/skills/archie-codebase-discovery/SKILL.md b/.agents/skills/archie-codebase-discovery/SKILL.md deleted file mode 100644 index 9b2dea956..000000000 --- a/.agents/skills/archie-codebase-discovery/SKILL.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -name: archie-codebase-discovery -description: "Trace Archie behaviour and blast radius through Go source, types, state, persistence, transports, consumers, tests, configuration, production composition, and target architecture. Load before changing or planning a non-trivial feature, refactor, config field, interface, persistence path, workflow, channel, plugin, or agent execution path; also load to investigate duplicate behaviour, hidden dead code, constructor bypasses, package dependencies, decoded-but-unwired configuration, or uncertainty about what a symbol actually affects." ---- - -# Discover the Archie codebase - -Use evidence from the current checkout to explain a behaviour before changing it. -Volatile tool facts below were verified on **2026-09-18**. - -**Composition roots**: `cmd/archied/main.go` (thin dispatcher) → -`internal/app/archied.Run()`, and `internal/app/agentworker` (invoked by -`cmd/archie-agent/main.go`). Do not treat `cmd/*` as the wiring site. -**Production wiring**: a path selected by a shipped entrypoint — not a -constructor, decoder, or passing unit test. **State owner**: component with -authority to validate and persist a state transition. - -## Establish a reproducible baseline - -```sh -go version; go env GOMOD GOWORK GOOS GOARCH -gopls version; golangci-lint version; staticcheck -version -``` - -As of 2026-09-18: Go 1.27.0, gopls 0.23.0, golangci-lint 2.13.2, -staticcheck 2026.2.1. Use `gopls call_hierarchy` (no `go tool callgraph`; -`go tool` lists only asm, cgo, compile, cover, fix, link, preprofile, vet). - -Writable caches when defaults are read-only: - -```sh -export GOCACHE="${TMPDIR:-/tmp}/archie-discovery-gocache" -export GOLANGCI_LINT_CACHE="${TMPDIR:-/tmp}/archie-discovery-lint" -export GOTMPDIR="${TMPDIR:-/tmp}" -export GOPROXY=off GOFLAGS=-mod=readonly -``` - -Module boundaries (root and `tools/` are separate): - -```sh -find . -name go.mod -not -path './.git/*' -not -path './node_modules/*' -go list -m -f '{{.Path}} {{.GoVersion}}' -go -C tools list -mod=readonly -m -f '{{.Path}} {{.GoVersion}}' -``` - -## Build the behaviour trace - -Write: behaviour, observable input, expected output, state that may change, modes. - -| Step | Find | Required evidence | -| ---: | ------------------- | ------------------------------------------------------------------------ | -| 1 | Entrypoint | `main`, handler, poller, RPC subject, or tool registration | -| 2 | Construction | Constructor and every direct struct literal | -| 3 | Contract | Interface, wire type, command, event, or public method crossed | -| 4 | Implementation | All type-valid implementations, selected per mode | -| 5 | State owner | Function validating transition, owning concurrency/transaction rules | -| 6 | Persistence | Store adapter, schema/key/document, serialisation, reload/recovery | -| 7 | Event/transport | Publish/send and subscribe/receive, subject/framing, timeout, retry, ack | -| 8 | Consumer | Callers and downstream readers | -| 9 | Tests | Unit, integration, contract, architecture, production-composition | -| 10 | Configuration | Decode, default, validation, normalisation, composition-root consumption | -| 11 | Target architecture | Current-to-target mapping in `docs/prds/`; label gaps | - -Start at these verified anchors: - -| Concern | Current anchor | -| --------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| Resident daemon | `cmd/archied/main.go` → `internal/app/archied.Run()` (`internal/app/archied/main.go`) → `daemon.Daemon` | -| Sandboxed worker | `cmd/archie-agent/main.go` → `internal/app/agentworker/`; NATS boundary in `internal/infrastructure/agenttransport/nats/` | -| Task orchestration | `internal/daemon/daemon.go`, `internal/domain/workflow/` | -| Task contracts | `internal/domain/storecontract/storecontract.go` (`TaskStore`) | -| Production task persistence | `internal/infrastructure/postgres/`; built in `internal/app/archied/state_store.go` | -| RPC split | `internal/{taskrun,natsrpc,forgerpc,worktreerpc}/` plus `internal/infrastructure/staterpc/` (gRPC State Store) | -| Chat and channels | `internal/gateway/`, `internal/channels/` | -| Configuration | `internal/config/`, `internal/infrastructure/configuration/`, `config.example.toml`, `deployments/*.toml` | -| Target map | `docs/prds/01-project-management.md` and linked `docs/architecture/*.md` | - -## Use syntax, type, and call evidence - -### Map packages before reading files - -```sh -go list -f '{{.ImportPath}}|go={{join .GoFiles ","}}|tests={{join .TestGoFiles ","}}' ./internal/infrastructure/postgres -go list -json ./internal/infrastructure/postgres -.agents/skills/archie-codebase-discovery/scripts/package-edges.sh ./internal/... -``` - -### Resolve symbols with gopls - -1-indexed `file:line:column`: - -```sh -gopls symbols internal/domain/storecontract/storecontract.go -gopls definition cmd/archied/main.go:27:14 -gopls references -d internal/domain/storecontract/storecontract.go:33:2 -gopls implementation internal/domain/storecontract/storecontract.go:33:2 -gopls call_hierarchy internal/domain/storecontract/storecontract.go:33:2 -go doc ./internal/domain/storecontract.TaskStore -go test ./internal/infrastructure/postgres -list '.' -``` - -### Generate AST candidates for construction - -```sh -.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.sh Daemon . -.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.sh -tests Task . -``` - -Confirms candidates with `gopls definition` or `gopls references`. Pass -`-tests` to expose test-only construction. - -## Run focused discovery recipes - -### Find duplicate behaviour paths - -```sh -golangci-lint run --enable-only=dupl ./internal/... -rg -n 'Transition\(|PublishTask\(|ClaimNext\(|StatusWaitingHuman' cmd internal -``` - -Trace each candidate to entrypoint and state owner. `dupl` finds similar syntax, -not two different implementations of one responsibility. - -### Find unused-but-compiled code - -```sh -staticcheck -checks=U1000 ./internal/... -``` - -For every suspect: `gopls references -d`; search init, reflection/Yaegi, tags, -RPC subjects, plugin manifests, string dispatch; check build tags/OS files; -search both composition roots. `U1000` does not prove exported/reflection/wire -targets are dead. - -### Find interface implementations - -```sh -gopls implementation -rg -n 'var _ .*=' --glob '*.go' cmd internal -``` - -Trace which implementation the composition root selects for each mode. - -### Find struct-field consumers - -`gopls references -d` on field declaration, not common name. Trace assignments -and reads separately. Follow `ForTask`/`ToConfig` copies. Check JSON/TOML/YAML -tags. Compare production and `_test.go` references. - -### Detect constructor bypasses - -Run `scan-go-type-syntax.sh Type .`. Inspect struct literals outside owning -package. Compare validation/defaulting in constructors with direct literals. -Use `gopls references` on constructor and type. - -### Prove package dependency direction - -```sh -.agents/skills/archie-codebase-discovery/scripts/package-edges.sh ./internal/... -go list -deps -json -``` - -### Find decoded-but-unused configuration - -Prove: `file/key → decoder → default → validation → normalisation/copy → -composition-root read → concrete component → observable behaviour`. - -```sh -rg -n 'toml:"|yaml:"|json:"' internal/config -rg -n 'Resolve|Overlay|Dir|finalize|ForTask|ToConfig' internal/infrastructure/configuration internal/app/archied -gopls references -d -``` - -Decoding lives in `internal/infrastructure/configuration`, not `internal/config`. -`configuration.New(log)` returns a `Loader`; the composition root in -`internal/app/archied/bootstrap.go` calls `Loader.Resolve` (with `Loader.Overlay` -and `Loader.Dir` for overlay/`conf.d` inputs). There is no `config.Load` or -`config.LoadDir`. - -### Prove production composition - -1. Start at `internal/app/archied/main.go` (`Run`), entered from - `cmd/archied/main.go`. -2. Record config condition per branch. -3. Follow concrete construction into `daemon.Daemon` and gateway start. -4. For container/NATS behaviour, trace `cmd/archie-agent/main.go` into - `internal/app/agentworker` and `internal/infrastructure/agenttransport/nats`. -5. Trace both sides of every RPC/transport and error/timeout paths. -6. Read contract/architecture tests. -7. Confirm deploy inputs in Compose and CI. - -### Trace persistence - -Treat `internal/domain/storecontract` as the application contract and -`internal/infrastructure/postgres` as the production adapter behind it; the -schema is `internal/infrastructure/postgres/migrations/` and the queries are -sqlc-generated from `queries/`. - -```sh -gopls implementation internal/domain/storecontract/storecontract.go:33:2 -rg -n 'CREATE TABLE|CREATE INDEX' internal/infrastructure/postgres/migrations -``` - -## Reject false confidence - -| Weak evidence | Why it fails | Required correction | -| ---------------------------- | ---------------------------------------------------------------------- | ----------------------------------------------------- | -| One `rg` result | Misses interface dispatch, aliases, generated registration, reflection | Use gopls, AST candidates, package edges, composition | -| Green unit test | May bypass config, lifecycle, transport | Add composition/contract/integration evidence | -| Fake client and server agree | Both mirror same wrong framing/subject/state assumption | Compare independent spec or real boundary fixture | -| High coverage | Does not establish ownership, maintainability, mode selection | Trace authority and production selection | -| Constructor exists | Does not prove callers use it | Find struct literals and type-aware references | -| Config field decodes | Does not prove executable reads it | Complete config-to-observable chain | -| Target PRD says it | Not necessarily current code | Cite current implementation and label gap | - -## Produce the discovery handoff - -1. **Behaviour trace:** path:line, symbol, current responsibility per traversal step. -2. **Mode matrix:** mode/config branch → concrete implementation → state store - → transport → consumer. -3. **State and authority:** owner, copies, persistence, transition rules, recovery. -4. **Blast radius:** callers, consumers, tests, config, deploy wiring, docs, - compatibility paths. -5. **Duplication/deprecation ledger:** each candidate, live/dead evidence, - replacement, objective removal gate. -6. **Current-to-target gap:** current fact, target PRD, migration implication. -7. **Unknowns:** exact command, output/blocker, next evidence needed. - -Do not propose implementation until the trace answers: what entrypoint selects -this path, which component owns state, which parallel/older path the feature -replaces, which production modes and persisted data must remain compatible, -which evidence would falsify current understanding. diff --git a/.agents/skills/archie-codebase-discovery/agents/openai.yaml b/.agents/skills/archie-codebase-discovery/agents/openai.yaml deleted file mode 100644 index 2957f7f74..000000000 --- a/.agents/skills/archie-codebase-discovery/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Codebase Discovery" - short_description: "Trace Archie behavior from entrypoint to production" - default_prompt: "Use $archie-codebase-discovery to trace this behavior through production wiring before proposing a change." diff --git a/.agents/skills/archie-codebase-discovery/scripts/package-edges.sh b/.agents/skills/archie-codebase-discovery/scripts/package-edges.sh deleted file mode 100755 index e2e833674..000000000 --- a/.agents/skills/archie-codebase-discovery/scripts/package-edges.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/bin/sh -set -eu - -if [ "$#" -gt 1 ]; then - printf '%s\n' "usage: $0 [go-package-pattern]" >&2 - exit 2 -fi - -command -v go >/dev/null 2>&1 || { - printf '%s\n' "error: go is required" >&2 - exit 127 -} - -pattern=${1:-./...} -cache_root=${ARCHIE_DISCOVERY_CACHE:-"${TMPDIR:-/tmp}/archie-codebase-discovery"} -mkdir -p "$cache_root/go-build" "$cache_root/tmp" - -export GOCACHE="$cache_root/go-build" -export GOTMPDIR="$cache_root/tmp" -export GOPROXY=off -export GOFLAGS=-mod=readonly - -module_path=$(go list -m -f '{{.Path}}') - -go list -f '{{.ImportPath}}{{range .Imports}}{{printf "\t%s" .}}{{end}}' "$pattern" | - awk -F ' ' -v module="$module_path" ' - { - from = $1 - for (i = 2; i <= NF; i++) { - if ($i == module || index($i, module "/") == 1) { - printf "%s -> %s\n", from, $i - } - } - } - ' | - LC_ALL=C sort -u diff --git a/.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.go b/.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.go deleted file mode 100644 index 6e562e2bc..000000000 --- a/.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.go +++ /dev/null @@ -1,176 +0,0 @@ -// Command scan-go-type-syntax reports syntax-level construction candidates for -// a named Go type. It deliberately uses only the standard library and never -// writes to the inspected tree. -package main - -import ( - "bufio" - "flag" - "fmt" - "go/ast" - "go/parser" - "go/token" - "io/fs" - "os" - "path/filepath" - "sort" - "strings" -) - -type finding struct { - path string - line int - column int - kind string - detail string -} - -func main() { - includeTests := flag.Bool("tests", false, "include *_test.go files") - flag.Usage = func() { - fmt.Fprintf(flag.CommandLine.Output(), "usage: %s [-tests] TypeName [root]\n", os.Args[0]) - flag.PrintDefaults() - } - flag.Parse() - if flag.NArg() < 1 || flag.NArg() > 2 { - flag.Usage() - os.Exit(2) - } - - typeName := flag.Arg(0) - root := "." - if flag.NArg() == 2 { - root = flag.Arg(1) - } - if !token.IsIdentifier(typeName) { - fmt.Fprintf(os.Stderr, "error: %q is not a Go identifier\n", typeName) - os.Exit(2) - } - - results, err := scan(root, typeName, *includeTests) - if err != nil { - fmt.Fprintf(os.Stderr, "error: %v\n", err) - os.Exit(1) - } - - out := bufio.NewWriter(os.Stdout) - defer out.Flush() - fmt.Fprintln(out, "kind\tlocation\tdetail") - for _, result := range results { - fmt.Fprintf(out, "%s\t%s:%d:%d\t%s\n", - result.kind, result.path, result.line, result.column, result.detail) - } -} - -func scan(root, typeName string, includeTests bool) ([]finding, error) { - fset := token.NewFileSet() - var results []finding - - err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if entry.IsDir() { - if path == root { - return nil - } - name := entry.Name() - if strings.HasPrefix(name, ".") || name == "node_modules" || - name == "vendor" || name == "bin" { - return filepath.SkipDir - } - return nil - } - if filepath.Ext(path) != ".go" { - return nil - } - if !includeTests && strings.HasSuffix(path, "_test.go") { - return nil - } - - file, err := parser.ParseFile(fset, path, nil, 0) - if err != nil { - return fmt.Errorf("parse %s: %w", path, err) - } - - ast.Inspect(file, func(node ast.Node) bool { - switch node := node.(type) { - case *ast.TypeSpec: - if node.Name.Name == typeName { - results = appendFinding(results, fset, node.Name.Pos(), - path, "declaration", "type "+node.Name.Name) - } - case *ast.CompositeLit: - if matchesType(node.Type, typeName) { - results = appendFinding(results, fset, node.Type.Pos(), - path, "literal", "direct composite literal of "+typeName) - } - case *ast.FuncDecl: - if returnsType(node.Type.Results, typeName) { - results = appendFinding(results, fset, node.Name.Pos(), - path, "returns-type", "func "+node.Name.Name) - } - } - return true - }) - return nil - }) - if err != nil { - return nil, err - } - - sort.Slice(results, func(i, j int) bool { - left, right := results[i], results[j] - if left.path != right.path { - return left.path < right.path - } - if left.line != right.line { - return left.line < right.line - } - if left.column != right.column { - return left.column < right.column - } - return left.kind < right.kind - }) - return results, nil -} - -func appendFinding(results []finding, fset *token.FileSet, pos token.Pos, path, kind, detail string) []finding { - position := fset.Position(pos) - return append(results, finding{ - path: filepath.ToSlash(path), - line: position.Line, - column: position.Column, - kind: kind, - detail: detail, - }) -} - -func returnsType(fields *ast.FieldList, typeName string) bool { - if fields == nil { - return false - } - for _, field := range fields.List { - if matchesType(field.Type, typeName) { - return true - } - } - return false -} - -func matchesType(expr ast.Expr, typeName string) bool { - switch expr := expr.(type) { - case *ast.Ident: - return expr.Name == typeName - case *ast.SelectorExpr: - return expr.Sel.Name == typeName - case *ast.StarExpr: - return matchesType(expr.X, typeName) - case *ast.IndexExpr: - return matchesType(expr.X, typeName) - case *ast.IndexListExpr: - return matchesType(expr.X, typeName) - default: - return false - } -} diff --git a/.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.sh b/.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.sh deleted file mode 100755 index d4ac0e53a..000000000 --- a/.agents/skills/archie-codebase-discovery/scripts/scan-go-type-syntax.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/bin/sh -set -eu - -script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd) -cache_root=${ARCHIE_DISCOVERY_CACHE:-"${TMPDIR:-/tmp}/archie-codebase-discovery"} -mkdir -p "$cache_root/go-build" "$cache_root/tmp" - -export GOCACHE="$cache_root/go-build" -export GOTMPDIR="$cache_root/tmp" -export GOPROXY=off -export GOFLAGS=-mod=readonly - -exec go run "$script_dir/scan-go-type-syntax.go" "$@" diff --git a/.agents/skills/archie-codebase-discovery/scripts/trace-go-position.sh b/.agents/skills/archie-codebase-discovery/scripts/trace-go-position.sh deleted file mode 100755 index 50be4283a..000000000 --- a/.agents/skills/archie-codebase-discovery/scripts/trace-go-position.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/bin/sh -set -u - -usage() { - printf '%s\n' "usage: $0 file.go:line:column" >&2 - exit 2 -} - -[ "$#" -eq 1 ] || usage -position=$1 - -command -v go >/dev/null 2>&1 || { - printf '%s\n' "error: go is required" >&2 - exit 127 -} -command -v gopls >/dev/null 2>&1 || { - printf '%s\n' "error: gopls is required" >&2 - exit 127 -} - -case "$position" in - *.go:[1-9]*:[1-9]*) ;; - *) usage ;; -esac - -cache_root=${ARCHIE_DISCOVERY_CACHE:-"${TMPDIR:-/tmp}/archie-codebase-discovery"} -mkdir -p "$cache_root/go-build" "$cache_root/xdg" "$cache_root/tmp" || exit 1 - -export GOCACHE="$cache_root/go-build" -export XDG_CACHE_HOME="$cache_root/xdg" -export GOTMPDIR="$cache_root/tmp" -export GOPROXY=off -export GOFLAGS=-mod=readonly - -gomod=$(go env GOMOD) -if [ "$gomod" = "/dev/null" ] || [ -z "$gomod" ]; then - printf '%s\n' "error: run from inside a Go module" >&2 - exit 1 -fi - -run_query() { - label=$1 - shift - printf '\n== %s ==\n' "$label" - if output=$(gopls "$@" 2>&1); then - printf '%s\n' "$output" - return 0 - else - printf '%s\n' "$output" - printf '%s\n' "(query is not applicable at this position, or failed)" - return 1 - fi -} - -successful=0 -run_query "definition" definition "$position" && successful=$((successful + 1)) -run_query "references (including declaration)" references -d "$position" && successful=$((successful + 1)) -run_query "implementations" implementation "$position" && successful=$((successful + 1)) -run_query "call hierarchy" call_hierarchy "$position" && successful=$((successful + 1)) - -[ "$successful" -gt 0 ] diff --git a/.agents/skills/archie-config-and-flags/SKILL.md b/.agents/skills/archie-config-and-flags/SKILL.md deleted file mode 100644 index 77e23674a..000000000 --- a/.agents/skills/archie-config-and-flags/SKILL.md +++ /dev/null @@ -1,266 +0,0 @@ ---- -name: archie-config-and-flags -description: Trace, add, rename, deprecate, or debug Archie configuration and command-line flags from external input through defaults, validation, overlays, environment and secret handling, worker snapshots, deployment passthrough, and the production consumer. Use for internal/config, config.example.toml, deployments/*.toml, docker-compose.yml, archied or archie-agent flags, multi-identity settings, mode-parity questions, and reports of a setting that parses but has no effect. ---- - -# Trace Archie configuration and flags - -Treat configuration as a dataflow, not as a struct inventory. Prove every -claimed setting has an input, normalisation path, composition seam, and runtime -consumer. - -Current evidence date: **2026-09-18** for the matrix below. Entries added later -carry their own date inline. - -Use these status terms exactly: - -| Status | Meaning | -| ------------------------------- | ---------------------------------------------------------------------------------- | -| **production-wired** | A real entrypoint decodes or accepts the value and a runtime consumer uses it. | -| **partially-wired** | Some modes, scopes, or fields consume it, but parity is incomplete. | -| **test/library-only** | An API and tests exist, but no current binary selects it. | -| **decoded-but-unwired** | Decoding/defaulting succeeds, but no production consumer uses the effective value. | -| **external-production-unknown** | The repository does not contain the deployed effective value. | - -Never upgrade a status merely because decoding tests pass. - -## Trace one setting before editing it - -1. Find every external spelling, Go field, flag, environment name, example, and - deployment reference. -2. Identify the selected loader or flag set. -3. Read `finalize` and any consumer-side defaults. -4. Follow copies across `ForTask`, `ToConfig`, NATS messages, subprocess - env selection, container env construction, and identity overlays. -5. Find the production composition site and final behaviour-changing read. -6. Find tests for decoding, defaulting, invalid input, production composition, - and mode parity. -7. Check `config.example.toml`, `deployments/*.toml`, `docker-compose.yml`, and - deployment environment passthrough. -8. Assign one status from the table above. - -```bash -rg -n 'Resolve|Overlay|Dir|ForTask|ToConfig|flag\.' \ - internal/infrastructure/configuration internal/config internal/app/archied cmd/archie-agent -rg -n 'FIELD_NAME|external_key|ENV_NAME' \ - --glob '*.go' --glob '*.toml' --glob '*.yml' --glob '*.yaml' . -``` - -## Select the real input path - -| Input path | Current behaviour | Status | -| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | -| `archied -config PATH` | Defaults to `$XDG_CONFIG_HOME/archie/config.toml`, or `$HOME/.config/archie/config.toml`; `internal/app/archied/bootstrap.go` builds `configuration.New(log)` and calls `Loader.Resolve`. | production-wired | -| `archied -config-overlay PATH` | Resolves a file or directory overlay through the same loader. Omitted overlay fields retain base values. This is the only overlay: the dashboard runtime overlay and its SQLite store were deleted when the control plane took over settings writes. | production-wired | -| `configuration.Loader.Dir(base, overlay)` | Supports main YAML/TOML plus feature YAML and `conf.d`; no current entrypoint calls it. | test/library-only | -| `config.Load(path)`, `config.LoadDir(...)` | Removed. The old `internal/config` package-level helpers no longer exist; decoding is `Loader`-based. | not applicable | -| `config.example.toml` | Load-tested example, not a deployed configuration. | test/library-only | -| `deployments/docker-nats-stack.toml` | Complete host-daemon configuration for the Compose-managed NATS service. It is copied into the operator's config directory; Compose does not mount it. | supported-example | -| Operator config and environment | Lives outside the repository; contents are deployment-specific. | external-production-unknown | - -Both TOML and YAML decoding are non-strict at the field level. Add explicit -compatibility and typo tests; never use "the file loaded" as evidence that a -key took effect. - -A registered service client always resolves to a non-empty target, so -`Services.Get(name).Target != ""` proves nothing. `RegisterService` in -`internal/config/servicespec.go` supplies the fallback (`127.0.0.1:9090` for -the State Store, `127.0.0.1:8585` for the Gateway), which means a guard written -as "only dial when configured" dials always, and a test that sets no target -reaches for a real process on the developer's machine. Gate on an explicit -flag or on the dial succeeding, and give a binary its own -`--target` flag so tests can point it at a fake. - -## Inventory CLI flags - -### Public binaries - -| Binary | Flag | Default and effect | -| -------------- | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | -| `archied` | `-config PATH` | Computed config path described above. | -| `archied` | `-config-overlay PATH` | Empty; overlay only fields explicitly present in second TOML. | -| `archied` | `-once` | `false`; run one poll/process cycle and exit. | -| `archied` | `-requeue ID` | `0`; values greater than zero requeue one parked/waiting task, then exit unless `-once` also set. | -| `archie-agent` | `-nats-url URL` | Empty; takes precedence over `NATS_URL`. Missing both is fatal. | -| `archie-agent` | `-consumer NAME` | `archie-agent`; names the JetStream durable consumer. | -| both | `-quickchecks N` | Incidental flag registered by `github.com/traefik/yaegi/stdlib` importing `testing/quick`; default `100`. Treat as unowned candidate defect. | - -The standalone agent always reads its token from `NATS_TOKEN`; there is no -token flag. - -### Internal codesearch helper - -`archied workspace-codesearch` bypasses daemon configuration before normal flag -parsing: - -| Subcommand | Required flags | Optional flags | -| ------------ | ---------------------- | ------------------------------- | -| `build` | `--root`, `--index` | none | -| `candidates` | `--index`, `--pattern` | `--literal`, `--case-sensitive` | - -Do not expose these helper flags as daemon settings. - -## Read the current wiring matrix - -### Root daemon and capability settings - -| Keys | Default, validation, and consumer | Status | -| -------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- | -| `work_dir`, `state_dir` | Derive from `$XDG_DATA_HOME/archie`, else `$HOME/.local/share/archie`; explicit `~` paths are home-expanded. `state_dir` holds the embedded NATS store and endpoint file, task logs and the readiness disk target. | production-wired | -| `skills_dir` | Empty falls back to `work_dir` for startup workflow registry. Also the skills store `kitrun.Launcher` mounts read-only at a Kit's `agent-skills@1` path, read live per launch; empty withholds the mount. | partially-wired | -| `plugin_dir` | Empty disables daemon plugin loading; configured directory loaded in `internal/app/archied`. | production-wired | -| `poll_interval` | Default `60s`; root poll loop uses it, identities may override only interval. | production-wired | -| `label` | No default or validation; used for `dispatch.trigger = "label"` or `"either"`. | production-wired | -| `max_retries` | Default `3`; repository value greater than zero overrides. | production-wired | -| `bot_user`, `bot_email` | Single-identity requires `bot_user`; email defaults by forge type. | production-wired | -| `forge.type`, `host`, `token` | Type defaults `github`, host defaults `https://github.com`; only `github` and `gitea` validate. | production-wired | -| `dispatch.trigger` | Default `assignee`; validates `assignee`, `label`, or `either`. | production-wired | -| `dispatch.ack_reaction` | Default `eyes`; case-insensitive `off` normalises to empty. | production-wired | -| `dispatch.labels.*` | Missing keys default independently to `agent:*`. | production-wired | -| `models.` | Workflow stages read requested role then fall back to `builder`; triage judge falls back `triage` to `planner`. | production-wired | -| `providers..class`, `api_key_env`, `base_url` | Builds ai-sdk catalogue. `base_url` rejects parse errors, userinfo, query, and fragment. | production-wired | -| `budgets.max_steps`, `max_tokens`, `wall_clock`, `gate_max_failures` | No loader defaults; `Budgets` documents zero as disabling. | production-wired | -| `review.precision_gate`, `review.approve_before_post` | 2026-10-02: one control-plane resource `review-settings` (`internal/app/controlplane/review_settings.go`), seeded from `[review]`; the stored document outranks the file, layers field-by-field into `cfg.Review` (`runtimeConfigFrom`), and is watched live (`archie/control_plane.go`). Reaches a run through `Daemon.configFor` → `ForTask` → `TaskContext.Cfg`; the dashboard writes it on the Review settings page. | production-wired | -| `diff_cap_lines` | Zero replaced by `400` in `finalize`; `StageDiffCap` treats `<= 0` as disabled. TOML zero cannot disable; negative value does. | production-wired | -| `web.listen` | Empty becomes `127.0.0.1:8484`; literal `off` disables. No authentication. | production-wired | -| `notify.webhook` | Empty disables; feasibility workflow POSTs human-decision notifications when set. | production-wired | -| `nats.url`, `token_env` | Empty URL keeps the in-process path. Configured token variable must be non-empty. | production-wired | -| `containers.*` | See dedicated table below. | production-wired | -| `chat.*` | See channel table below. | production-wired | -| `memory.provider`, `provider_config` | Feature YAML decodes these; `internal/app/archied` always starts built-in file provider at `work_dir/memory`. | decoded-but-unwired | -| `tools.mcp_servers` | `internal/app/archied` registers daemon-side MCP providers. Empty transport becomes `stdio`; only `stdio` accepted. `url` decoded but unused. | partially-wired | -| `indexing.index_dir`, `indexing.db_path` | `finalize` derives paths under `work_dir`; no entrypoint constructs `internal/indexing.Manager` (the exported `NewManager` exists but has no production caller). | decoded-but-unwired | -| `extra` / unknown `conf.d` values | Test/library-only `Loader.Dir` stores untyped data; no core production consumer. | decoded-but-unwired | -| `[identities.forge].intake`, `.webhook_secret`, `.webhook_addr` | 2026-09-22: these parse because `IdentityConfig` embeds `Forge` (`internal/config/config.go:573`), while every read is the root `[forge]` block (`validate.go`, `defaults.go`, `bootstrap.go`). Wiring them is the intake migration, tracked as `archie-core-1786637497036-275-8838629e`. | partially-wired | - -**Three shapes of an unwired field.** All three read as working from the file -alone, and only the first two are defects - so establish which shape you are -looking at before reporting one: - -1. **not-consumed.** Decoded and normalised, but no production consumer uses the - effective value (`memory.provider` and `indexing.*` above; per-identity intake - was this shape until 2026-09-22, when the configuration was made to reject it - rather than accept it). -2. **not-projected.** A read exists, but at a layer that does not own the - effective copy, so editing the wrong layer does nothing. Direction matters as - much as presence: for most `[chat.*]` keys the stored resource outranks the - file, so writing a new file value is a no-op once a resource exists. A file - key in that position is a **seed**, not the contract. -3. **deliberately-not-projected.** File-only by design and therefore - indistinguishable from a dropped field to an auditor unless the projection - says so in a comment. `runtimeChatConfigFrom` reads - `Telegram.UpdateCheckCommand`/`UpdateInstallCommand` from `base` rather than - from the stored resource, on purpose. Check for that comment before filing a - defect. - -### Repository settings - -| Keys | Effective behaviour | Status | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------- | -| `owner`, `name` | Required for every declared repo. Single-identity config with zero repos loads but polls nothing. | production-wired | -| `base` | `BaseBranch()` maps empty to `main`, but `daemon.process` pre-clones with raw `repo.Base`. Set it explicitly. | partially-wired | -| `gate` | Argv arrays run in order. Empty entries skipped. TDD inverts last non-empty command as repro test by convention. | production-wired | -| `protect` | Path suffixes enforced by agent runner; not prompt-only rule. | production-wired | -| `ecosystem`, `preflight`, `test_glob` | Resolved preflight/test-glob treats empty ecosystem as Go. Container storage receives raw ecosystem. Go/Python/Node/Rust have defaults; `custom` or unknown yields none. | partially-wired | -| `persistent_storage` | Controls Docker-backed per-repo volume setup; no equivalent without container storage. | partially-wired | -| `max_retries` | Values greater than zero override global; zero or negative falls back to global. | production-wired | -| `allow_concurrent` | Root repo entries affect dispatcher. `allowConcurrentFor` does not inspect identity repo lists. | partially-wired | - -### Container settings - -| Key | Effective behaviour | -| ----------------- | ------------------------------------------------------------------------------------------------------------------ | -| `image` | Required at boot. Read by the container pool on every acquire (`containerLiveSettings` -> `Pool.current`, archie-core-zfb0.2), so a stored change applies without a restart. | -| `max_concurrency` | Zero means no limit. Read by the pool per acquire and applied to the daemon's running task dispatcher on publish (`ResizeTaskDispatcher`). | -| `max_uptime` | Default `60m` at boot; caps container lifetime. Read by the pool per acquire, so a stored change reaps the next container under the new cap. | -| `volume_ttl` | Default `72h` only when enabled; negative rejected. Re-read per cleanup cycle. | -| `pull_policy` | Default `missing` at boot. Pool code recognises `missing` and `always`; other strings silently skip pre-pull. Read by the pool per acquire. | -| `registry_auth` | `SecretRef` (file-owned, `json:"-"`). Resolved at boot by `archied`'s `resolveRegistryAuth` and passed to `container.Config.RegistryAuth`; the pool base64url-encodes it into the `X-Registry-Auth` header (`internal/container/pool.go`'s `registryAuthHeader`). Zero ref = anonymous pull. Unresolvable/empty credential or an unencodable one warns and pulls anonymously rather than failing the pool. A half-named ref is refused by `configuration.validateContainers`. `container-runtime-policies` cannot carry a secret ref, so this stays boot-resolved and requires-restart, unlike `image`/`pull_policy`. | -| `network` | Empty uses best-effort self-network detection at boot; the repository overlay pins `archie-core_default`. Read by the pool per acquire, falling back to the boot-resolved network when the live value is empty. | -| `profiles` | Named agent execution environments (image or Kit); resolved per task dispatch (`ContainerConfig.Profile`). Own control-plane resource `agent-profiles` (`json:"-"` on the field so `container-runtime-policies` never carries it), `ApplyMode: live`. | -| `credentials` | Maps a Kit `credential@1` service to a secret (`config.CredentialBinding`). Own control-plane resource `credential-bindings`, `ApplyMode: live`, `json:"-"` on the field. `kitrun.Launcher` reads it fresh from the live `config.Holder` on every `Launch`, never a value captured at boot -- see `internal/infrastructure/kitrun/launcher.go`'s `resolveCredentials`. A binding alone grants nothing; see `org`/`granted_credentials` below. | -| `org` / `granted_credentials` (root and per-identity) | An identity's org and the `credentials` service names it may resolve. `daemon.runKitTask` reads both fresh per dispatch (`d.configFor(task)`) and passes them to `kitrun.Request`; `config.ContainerConfig.BoundCredentials` computes the declared (Kit) ∩ granted (identity) ∩ org-matched intersection -- neither declared nor granted widens the other. | - -### Channel settings - -| Keys | Effective behaviour | -| -------------------------------------------------------------- | ---------------------------------------------------------------------------------------- | -| `chat.models` | Optional interactive catalogue; empty falls back to workflow model references. | -| `chat.telegram.token` | Unset disables Telegram; otherwise a secret reference resolved at channel start. | -| `chat.telegram.allowed_user_ids` | Empty denies every sender; IDs match Telegram sender IDs, not chat IDs. | -| `chat.telegram.update_check_command`, `update_install_command` | Argv arrays; check enables update status; install further enables approved installation. | -| `chat.email.listen_addr`, `relay_addr` | Empty listen disables SMTP; relay configures outbound replies. | -| `chat.webhook_addr` | Empty disables; malformed host/port falls back inside `parseListenAddr`. | - -Telegram `/restart` re-runs same TOML overlay load, then replaces only gateway -token and allowed-user list. Every other file setting is startup-only. - -A stored `channel-settings` change is reconciled live by `archie-messaging`: -on a new version it re-resolves the file, layers the store over it, and restarts -only the channel whose transport settings changed (Telegram token/allowlist, -email relay, webhook route/secret). `chat.email.listen_addr` and -`chat.webhook_addr` are bound listen addresses, so those changes, and enabling -or disabling a channel, are reported outstanding and take effect on restart. - -## Treat multi-identity as partially wired - -`finalize` requires each identity's `name`, `bot_user`, non-empty repos, forge -type, and `SecretRef` token. `internal/app/archied` builds an identity forge -client and worktree manager. - -Do not infer complete isolation: - -- `internal/app/archied` resolves root forge client before all identity runners. -- Identity `name`, forge, repos, poll interval, bot user, bot email have - production reads. Identity bot email not defaulted despite comment. -- Identity `models`, `providers`, `dispatch`, `budgets`, `notify`, and - `diff_cap_lines` decode but workflows still receive root `Config`. -- Identity polling reads root `dispatch`, `label`, and `bot_user`. -- Container task snapshots and provider maps come from root config; task RPC - servers are root-forge/root-worktree. -- Root-only concurrency lookup ignores identity repo `allow_concurrent`. - -Classify multi-identity changes field by field. Never label aggregate -`IdentityConfig` production-wired. - -## Preserve worker and secret boundaries - -`Config.ForTask` creates a detached root snapshot: models, budgets, the -retry/remediation cap (`MaxRetries`), dispatch, diff cap, notification, and -forge host. `TaskConfig.ToConfig` reconstructs -only those fields. Forge tokens, provider values, NATS credential references, -repos, and infrastructure settings do not enter `TaskConfig`. - -Every credential except `nats.token_env` is a `{engine, key}` secret -reference; the flat `token_env` aliases for forge, artifacts and Telegram are -removed. A stale alias in a file is reported at startup as an unrecognised key -(`bootstrap.go`), not silently ignored. - -| Source | Archied | Subprocess | Agent container / standalone worker | -| ------------------------------------------ | --------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------- | -| Forge `token = {engine="env", key="X"}` | Resolves `X`; empty is fatal. | Not forwarded. | Not forwarded; forge ops proxy to daemon. | -| Provider `api_key_env = "X"` | Runtime reads `X`. | Auto-allowlists selected provider's `X`. | Daemon forwards each present provider variable under original name. | -| `nats.token_env = "X"` | Reads `X`; empty fatal when configured. | Not agent subprocess setting. | Daemon maps to fixed `NATS_TOKEN`; worker also reads `NATS_URL`. | -| Telegram `token = {engine="env", key="X"}` | Resolves `X`. | Not forwarded. | Not forwarded. | - -`internal/app/archied` creates `secret.NewRegistry`, which registers only the -`env` engine. Non-env `SecretRef` values are not production-wired. - -The host supervisor or launch shell supplies daemon secrets. Compose supplies -no `archied` environment because the daemon is not a Compose service. - -## Follow the approved target - -Current code puts infrastructure paths, domain policy, channel settings, -secrets, execution settings, repository associations, and extension data in one -mutable `config.Config`. Treat this as a current load-bearing weakness, not a -pattern to copy. - -`docs/architecture/configuration.md` is approved as of 2026-07-28: - -- move file/env/secret/overlay loading to private - `internal/infrastructure/configuration` input boundary; -- translate inputs in `internal/app`; -- give each domain/plugin typed owned settings and validation; -- dissolve `internal/config` rather than rename the global model; -- split `Repo` and `IdentityConfig` by actual capability ownership. diff --git a/.agents/skills/archie-config-and-flags/agents/openai.yaml b/.agents/skills/archie-config-and-flags/agents/openai.yaml deleted file mode 100644 index a0b413c7b..000000000 --- a/.agents/skills/archie-config-and-flags/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Config and Flags" - short_description: "Trace Archie configuration from input to runtime" - default_prompt: "Use $archie-config-and-flags to trace this Archie setting or CLI flag from declaration through production wiring." diff --git a/.agents/skills/archie-debugging-playbook/SKILL.md b/.agents/skills/archie-debugging-playbook/SKILL.md deleted file mode 100644 index 200c35904..000000000 --- a/.agents/skills/archie-debugging-playbook/SKILL.md +++ /dev/null @@ -1,235 +0,0 @@ ---- -name: archie-debugging-playbook -description: Project-specific symptom-to-evidence triage for archie-core. Load this skill when Archied hangs, parks a task, loses or duplicates work, cannot reach NATS or an agent container, rejects configuration or secrets, shows stale Telegram or dashboard state, loses streamed text, fails MCP startup, reports task-state surprises, degrades an optional feature, or when Go tests disagree between a sandbox, editor, CI, and the host. Use it to separate environment failures from code regressions and to choose the next exact diagnostic. ---- - -# Debug Archie from evidence - -**current** = 2026-09-18 verified (HEAD `2e1e1549`); **fixed history** = -regression patterns; **open** = verified gap. - -**Composition root**: `cmd/archied/main.go` → `internal/app/archied.Run()`; -wiring lives in `internal/app/archied/bootstrap.go`. **Core NATS -request/reply**: direct subject + reply inbox. **JetStream**: persisted stream -`ARCHIE_TASKS`. **State Store**: gRPC (`internal/infrastructure/staterpc`), not -NATS. -**Environment failure**: test/process cannot use host resource (listener, tmp, -Docker). **Code regression**: behaviour fails where prerequisites available. - -## Run the first-ten-minutes protocol - -Do not begin with `task check` (mutates via `gofumpt -w .`/`go fix ./...`). -Compile, then run: - -```bash -GIT_CONFIG_GLOBAL=/dev/null go test ./PATH/TO/PACKAGE -run '^TestName$' -count=1 -v -``` - -Classify: compile-only, listener failure, read-only tmp, code regression. - -- Behavioural assertion with the prerequisite available: code regression. - -Use this symptom index: - -| Symptom | First boundary | Go to | -| ----------------------------------------------------- | ----------------------------------- | --------------------------------------- | -| `Run() = "\n"` in `TestRunWrapsExternalCommand` | Skill-script test command shape | Fixed history — passes since 2026-09-16 | -| Embedded NATS panics before a test assertion | Listener permission | Test environment | -| `nats: no responders available for request` | Core NATS subscription | NATS request/reply | -| Agent reply timeout | JetStream request, inbox, or worker | NATS request/reply | -| Queue looks empty while NATS reports an error | `Client.Fetch` batch error | NATS request/reply | -| Config test passes but daemon ignores the field | Composition/wiring | Configuration | -| Daemon has an env var but container does not | Compose or `containerEnv` | Configuration | -| Telegram reply hangs on the first token | Stream consumer | Streaming | -| MCP unit tests pass but a real server hangs | Framing mirror | MCP | -| Telegram shows old commands | Token-scoped Telegram state | Telegram | -| Transition succeeds from the wrong state | Store semantics | Database/state | -| Dashboard skips events but task state is correct | Bounded event buffers | Events | -| Search works but never becomes indexed | Missing production wiring | Optional features | -| Agent container cannot resolve `nats` | Docker network | Containers | -| `agent.mode = "subprocess"` fails at protocol startup | Worker binary mismatch | Subprocess mode | - -## Separate test-environment failures from regressions - -```bash -go version -go env GOTMPDIR GOCACHE GOPATH GOMODCACHE GOENV -``` - -Listener-dependent tests include embedded NATS, `httptest.NewServer`, and SMTP -listeners: - -```bash -rg -n 'httptest\.NewServer|net\.Listen|RunRandClientPortServer|RunServer' \ - --glob '*_test.go' cmd internal -``` - -Do not attribute go-git commit failures to GPG without checking the -repository-local mitigation. `worktree.Manager.setIdentity` pins -`commit.gpgsign=false`. Isolate ambient global config: - -```bash -GIT_CONFIG_GLOBAL=/dev/null go test ./internal/worktree -count=1 -``` - -## Confirm the skill-script regression stays fixed - -The `TestRunWrapsExternalCommand` failure (`Run() = "\n"`) was a test bug, not -a product bug: `exec.CommandContext(ctx, "sh", "-c", "echo", "wrapped")` -passes `wrapped` as shell `$0`, so only `echo` ran. It failed from commit -`308c199` and **passes as of 2026-09-16**. Re-run it to confirm the fix has not -regressed; a failure now is a new defect, not this one. - -```bash -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-skillscript-gocache \ - GIT_CONFIG_GLOBAL=/dev/null go test ./internal/skillscript \ - -run '^TestRunWrapsExternalCommand$' -count=1 -v -``` - -## Triage NATS request/reply and JetStream - -| Surface | Subject or resource | Bound/current behaviour | -| ----------------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| Task discovery | `archie.task.>` in `ARCHIE_TASKS` | Work-queue retention; daemon durable `archie-daemon`; max deliver 3 | -| Per-stage agent request | `archie.agent..request` | Reply inbox in `X-Archie-Reply`; wall-clock budget or 30m | -| Full task handoff | `archie.taskrun.` | Core request/reply; no-responder retry 20s every 250ms | -| Store RPC | gRPC State Store (`internal/infrastructure/staterpc`) | Client timeout 60s (`rpcTimeout` in `internal/app/agentworker/worker.go`); task-scoped grants for Update/Transition/InsertEvent only | -| Forge RPC | `archie.forge.*` | Error travels in a JSON envelope | -| Worktree RPC | `archie.worktree.prepare`, `.push` | Server default handler bound 15m | -| Discovery dedup | `Nats-Msg-Id: archie://` | JetStream duplicate window 2m | - -```bash -docker compose ps -docker compose logs --since=10m nats -docker compose exec -T nats wget -q -O - http://localhost:8222/healthz -``` - -Branch on `no responders`: container startup lag if responder appears within 20s; -inspect agent's network/environment if every task exhausts window; confirm -`registerTaskRPCServers` if only RPC calls time out. - -**Fixed history:** auto-detection once put task containers on default bridge; -explicit `containers.network` plus warning logs now fence that path. - -Check semantics: republishing same owner/repo/issue within 2m is dedup'd; reply -inbox auto-unsubscribes after one response; `Client.Fetch` must inspect -`batch.Error()`; an empty poll reports `eventbus.ErrNoMessage` rather than -`(nil, nil)`. - -```bash -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-nats-unit-gocache \ - go test ./internal/infrastructure/eventbus/nats -run 'TestPublishUniqueSuppressesDuplicateKeyOnWorkQueueStream' -count=1 -v -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-agent-unit-gocache \ - go test ./internal/agentexec -run '^TestToolSetHandler' -count=1 -v -``` - -## Trace configuration from source to behaviour - -Trace: `cmd/archied` (`internal/app/archied/bootstrap.go`) reads -`-config`/`-config-overlay` → `configuration.New(log)` + `Loader.Resolve` -decodes, `finalize` defaults/validates → secrets resolve → composition root -constructs service → Compose/subprocess/`containerEnv` propagate → consumer. - -```bash -rg -n 'Loader\.(Resolve|Overlay|Dir)|configuration\.' internal/app/archied internal/infrastructure/configuration -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-config-gocache \ - go test ./internal/infrastructure/configuration \ - -run 'Test(ResolveSelectsFileFormatsAndDirectories|LoadForgeTokenEnvBackwardCompat)' -count=1 -v -``` - -The `config.Load`/`config.LoadDir` helpers are gone; decoding is -`Loader`-based. A YAML field decoding correctly without a composition-root read -is a wiring gap, not a parser bug. - -For environment failures: - -- The host supervisor supplies the daemon environment; inspect its unit or - launch environment rather than Compose. -- `containerEnv` translates configured NATS token name into `NATS_TOKEN` and - forwards configured provider key variables. - -Do not print secret values. - -## Diagnose streaming, MCP, and Telegram - -### Streaming - -Must drain `stream.FullStream`, collect `core.StreamPartTextDelta`, check -`FinishReason`. `TextStream` is best-effort. **Fixed history:** consuming -`TextStream` while `FullStream` unread deadlocked every reply. - -### MCP - -Stdio framing is one compact JSON-RPC object per line. Stale -`internal/tools/mcp/types.go` comment mentions `Content-Length` — not the -implemented contract. - -```bash -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-mcp-gocache \ - go test ./internal/tools/mcp \ - -run 'Test(ReadMessage|WriteMessage|StdioTransportBadFraming)' -count=1 -v -``` - -Test helper and client share the same `readMessage`/`writeMessage` — can mirror -mistakes. With `npx`: - -```bash -ARCHIE_TEST_DESKTOP_COMMANDER=1 env GOTMPDIR=/tmp \ - GOCACHE=/tmp/archie-mcp-integration-gocache \ - go test ./internal/tools/provider/mcp \ - -run '^TestDesktopCommanderClientCompatibility$' -count=1 -v -``` - -Gate: non-empty discovery with `start_process`, `interact_with_process`, -`read_process_output`. - -### Telegram - -Three command scopes in `internal/channels/telegram/commands.go`: default, all -private chats, all group chats. Narrower scope shadows default; state keyed by -bot token. Empty `allowed_user_ids` denies everyone. - -```bash -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-telegram-gocache \ - go test ./internal/channels/telegram \ - -run 'Test(SenderAllowlistFailsClosed|IsSenderAllowed|SessionManagementCommandsArePublished)$' \ - -count=1 -v -``` - -**Fixed history:** publishing only default left ~60 old Hermes commands visible. - -## Diagnose state, events, containers, and optional features - -### Database and transitions - -`internal/infrastructure/postgres.Store.Transition` owns task state changes and -transition history: it guards on `from`, returning -`storecontract.ErrStaleTransition`, and writes status plus history in one transaction. -When state is surprising: read `TaskByID` before/after caller; trace every -`Transition`, `Requeue`, `RecoverStale`, `Update` — and remember the daemon -exposes these over the gRPC State Store, not NATS. - -```bash -env GOTMPDIR=/tmp GOCACHE=/tmp/archie-state-gocache go test ./internal/infrastructure/postgres -count=1 # needs Docker -``` - -### Events - -DB sink buffer 256; SSE client buffers 64. Drop counter not read in production. -Dashboard gap can coexist with correct task state. - -### Containers, worktrees, and subprocess mode - -Container-mode: clones on host, mounts `/data/worktree`, writes `.git/task.json`, -dedicated `archie.taskrun.` subscription. **Open:** container RPC is -root-identity-bound; `SubprocessRunner` expects stdin JSON protocol. - -### Optional feature degradation - -| Feature | Current failure behaviour | -| --------------------- | --------------------------------------------------------------------------------------------- | -| Daemon plugins | Warn and skip | -| Invalid MCP config | Warn and continue | -| Skill catalogue | Warn, continue without tool | -| Worktree augmentation | Log error, use startup registry | -| Workspace indexing | **Open:** `indexing.NewManager` exists but has no production caller in `internal/app/archied` | diff --git a/.agents/skills/archie-debugging-playbook/agents/openai.yaml b/.agents/skills/archie-debugging-playbook/agents/openai.yaml deleted file mode 100644 index eeafe07c4..000000000 --- a/.agents/skills/archie-debugging-playbook/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Debugging Playbook" - short_description: "Diagnose Archie failures from symptoms" - default_prompt: "Use $archie-debugging-playbook to diagnose this Archie failure from symptoms and evidence." diff --git a/.agents/skills/archie-diagnostics-and-tooling/SKILL.md b/.agents/skills/archie-diagnostics-and-tooling/SKILL.md deleted file mode 100644 index 25d83d72d..000000000 --- a/.agents/skills/archie-diagnostics-and-tooling/SKILL.md +++ /dev/null @@ -1,265 +0,0 @@ ---- -name: archie-diagnostics-and-tooling -description: "Measure Archie codebase maintainability, Go package dependency shape, configuration consumption, production composition, test and delivery-gate drift, tracked-artifact hygiene, coverage, races, and runtime evidence. Load when establishing a dated baseline, finding large or complex functions, investigating duplicate or dead-path candidates, checking whether configuration reaches an entrypoint, comparing architecture before and after a refactor, or replacing an eyeballed quality claim with reproducible numbers." ---- - -# Measure Archie instead of eyeballing it - -Collect evidence before judging quality. Keep collection read-only, save raw -output, state what each metric cannot prove. - -Volatile facts and numeric snapshots below were verified on **2026-09-18** -(HEAD `2e1e1549`). - -Route to `archie-codebase-discovery` for semantic traces, -`archie-config-and-flags` for config enumeration, -`archie-debugging-playbook` for live failures. - -## Define the measurement terms - -- **Baseline:** dated raw output tied to a commit, toolchain, command, and - environment. -- **Candidate:** a machine-found item requiring semantic confirmation. -- **Production composition:** concrete construction selected by a shipped - entrypoint. Principal: `cmd/archied/main.go` → `internal/app/archied.Run()`. -- **Fan-in:** number of packages in the same module that directly import a - package. -- **Fan-out:** number of packages in the same module that a package directly - imports. -- **Physical line:** a newline-delimited source line, including comments and - blanks. -- **Syntactic complexity:** this skill's approximation: one plus `if`, loop, - non-default case, communication clause, `&&`, and `||` nodes. - -## Establish a reproducible snapshot - -```sh -export LC_ALL=C -export GOCACHE=/tmp/archie-diagnostics-gocache -export GOTMPDIR=/tmp -export XDG_CACHE_HOME=/tmp/archie-diagnostics-xdg -export GOLANGCI_LINT_CACHE=/tmp/archie-diagnostics-lint -export GOPROXY=off -export GOFLAGS=-mod=readonly - -skill=.agents/skills/archie-diagnostics-and-tooling -stamp=$(date -u +%Y%m%dT%H%M%SZ) -evidence_dir=/tmp/archie-diagnostics-"$stamp" -mkdir -p "$evidence_dir" - -git rev-parse --verify HEAD >"$evidence_dir/revision.txt" -git status --short >>"$evidence_dir/revision.txt" -go version >"$evidence_dir/tools.txt" -gopls version >>"$evidence_dir/tools.txt" -golangci-lint version >>"$evidence_dir/tools.txt" -staticcheck -version >>"$evidence_dir/tools.txt" - -go run "$skill/scripts/source-metrics.go" -root . >"$evidence_dir/source.tsv" -go run "$skill/scripts/config-use-candidates.go" -root . >"$evidence_dir/config.tsv" -"$skill/scripts/package-shape.sh" . >"$evidence_dir/packages-root.tsv" -"$skill/scripts/package-shape.sh" tools >"$evidence_dir/packages-tools.tsv" -"$skill/scripts/delivery-snapshot.sh" >"$evidence_dir/delivery.tsv" -``` - -Both filesystem-walking scripts (`source-metrics.go`, -`config-use-candidates.go`) skip `.worktrees/`, which holds live git worktrees -nested inside the repo root. Each is a near-complete copy of the module, so -walking them multiplies every count by the number of checkout worktrees. If a -new nested-checkout convention appears, extend `excludedDirectory` in both; -`.git/info/exclude` does not help, because the scripts walk the filesystem -rather than `git ls-files`. `package-shape.sh` reads `go list`, so it is immune. - -## Use the bundled reports - -### Measure source shape - -```sh -go run "$skill/scripts/source-metrics.go" -root . -top 30 -``` - -Read its tab-separated schema: - -| Record | Columns after record name | -| --------- | --------------------------------------------------------------------------------------------------------------- | -| `META` | key, value | -| `METRIC` | module, metric, integer | -| `PACKAGE` | module, directory, production files, test files, generated files, production lines, test lines, generated lines | -| `HOTSPOT` | module, file, declaration line, symbol, body-span lines, statement nodes, approximate syntactic complexity | - -The defaults (80 body lines, complexity 15) mirror numeric triage points in -`.golangci.yml`. They do **not** implement `funlen` or `cyclop`. Run configured -linters for authoritative findings: - -```sh -golangci-lint run --enable-only=funlen,gocognit,gocyclo,cyclop,maintidx,nestif ./internal/... -``` - -If a hotspot shrinks, verify that responsibility moved to a cohesive owner. -Moving the same work into unowned helpers is not improvement. - -### Measure package shape - -```sh -"$skill/scripts/package-shape.sh" . >"$evidence_dir/packages-root.tsv" -"$skill/scripts/package-shape.sh" tools >"$evidence_dir/packages-tools.tsv" -awk -F ' ' '$1=="PACKAGE" {print $3 "\t" $4 "\t" $2}' "$evidence_dir/packages-root.tsv" | - sort -nr -k1,1 -k2,2 | - sed -n '1,20p' -``` - -Read `PACKAGE package fan_in fan_out` and `EDGE from -> to` rows. High fan-in -signals change risk; high fan-out signals orchestration. The report contains -only direct, intra-module imports. - -### Find configuration-consumption candidates - -```sh -go run "$skill/scripts/config-use-candidates.go" -root . >"$evidence_dir/config.tsv" -rg 'candidate-no-(selector-outside-config|entrypoint-selector)' "$evidence_dir/config.tsv" -``` - -Read each `CONFIG_FIELD` row as path, line, Type.Field, tags, same-name -definition count, config-package selectors, cmd selectors, other-production -selectors, test selectors, generated selectors, candidate status. The report -finds named fields with `toml`/`yaml`/`json` tags in `internal/config`, then -counts selectors with the same **spelling**. It is deliberately fast and not -type-aware. - -Only `candidate-no-selector-outside-config` is a signal. -`candidate-no-entrypoint-selector` fires for ~180 of 196 rows because the -script looks for selectors only in `cmd/`, and most fields are read from the -composition root under `internal/app/archied`. Even the signal row has false -positives: a field consumed by **spelling** rather than by a Go selector -(`LegacyEnabled` via the reload allowlist map, `ReloadStatus.*` via JSON -marshalling) reports zero. Confirm each candidate by hand before calling a -field dead. - -For every candidate: run `gopls references -d` on the exact field identifier; -trace decode → default → validation → normalisation/copy → composition-root read -→ concrete component → observable behaviour. - -### Measure delivery and hygiene drift - -```sh -"$skill/scripts/delivery-snapshot.sh" >"$evidence_dir/delivery.tsv" -``` - -Read: `SURFACE axis scope literal_count` as literal text evidence; -`HYGIENE metric count` as tracked-path candidates; `MODULE path` as discovered -Go module boundaries. The snapshot compares Task, GitHub CI, and -composition-root anchors under `internal/app/archied`. - -Composition-root anchors must name the file that actually does the wiring. -`cmd/archied/main.go` is a thin dispatcher that routes to -`internal/app/archied`; anchoring on it yields a silent `0` for every row, -which reads as "no composition root" rather than "wrong file". A zero here is -evidence about the anchor, not about production. - -Inspect hygiene candidates directly: - -```sh -git ls-files | - rg '(^|/)(node_modules|bin|dist|\.gotmp)(/|$)|\.(exe|test|out)$' -git ls-files -s | awk '$1=="120000" {print}' -``` - -## Investigate duplication and hidden dead paths - -```sh -golangci-lint run --enable-only=dupl ./internal/... -``` - -```sh -staticcheck -checks=U1000 ./internal/... -``` - -On 2026-09-18, the focused `dupl` command reported zero issues. Two code paths -can implement the same responsibility with different syntax. - -For every candidate: name the externally visible operation; search all -entrypoints and modes; use `gopls call_hierarchy`, `gopls references -d`, and -AST construction scan; check interfaces, registrations, reflection, build tags, -OS files, and wire names; identify what a new feature supersedes; record -production-only, test-only, compatibility, generated, and unreachable paths -separately. - -As of 2026-09-18, `Taskfile.yml` defines no `deadcode` task and `go tool` lists -no dead-code analyser. - -## Collect test, race, coverage, and runtime evidence - -```sh -go test ./internal/infrastructure/postgres -count=1 -coverprofile=/tmp/archie-store.cover -go tool cover -func=/tmp/archie-store.cover -go test -race ./internal/infrastructure/postgres -count=1 -``` - -As of 2026-09-18, the package reported 78.6% statement coverage and passed its -race run. - -```sh -docker compose logs nats >"$evidence_dir/nats.log" -journalctl --user -u archied >"$evidence_dir/archied.log" -curl -fsS http://localhost:8222/healthz >"$evidence_dir/nats-health.txt" -``` - -Run only when local Compose stack is in scope. - -## Compare before and after - -Predict exact deltas before changing code. Collect a second snapshot with the -same script revision, flags, environment, and toolchain: - -```sh -after_dir=/tmp/archie-diagnostics-after -mkdir -p "$after_dir" -go run "$skill/scripts/source-metrics.go" -root . >"$after_dir/source.tsv" -go run "$skill/scripts/config-use-candidates.go" -root . >"$after_dir/config.tsv" -"$skill/scripts/package-shape.sh" . >"$after_dir/packages-root.tsv" -"$skill/scripts/delivery-snapshot.sh" >"$after_dir/delivery.tsv" - -diff -u "$evidence_dir/source.tsv" "$after_dir/source.tsv" -diff -u "$evidence_dir/config.tsv" "$after_dir/config.tsv" -diff -u "$evidence_dir/packages-root.tsv" "$after_dir/packages-root.tsv" -diff -u "$evidence_dir/delivery.tsv" "$after_dir/delivery.tsv" -``` - -If output differs from prediction: confirm checkout, dirty state, script -revision, flags, toolchain; explain each delta; branch to semantic discovery -when a count cannot explain behaviour. Reject a "better" metric that moved -duplication, hid a path, or weakened a gate. - -## Dated current snapshot - -The bundled scripts measured this checkout on 2026-09-18 (HEAD `2e1e1549`). -These are post-fix numbers: earlier runs of the same scripts reported roughly -3x these file and line counts because they walked `.worktrees/`. - -| Observation | Unstable value | -| --------------------------------------------------------------- | -----------------------: | -| Root production/test/generated Go files | 408 / 402 / 9 | -| Root production/test/generated physical lines | 74,752 / 95,264 / 12,774 | -| `internal/app/archied.Run` body span / approximate complexity | 97 / 19 | -| Root internal packages / direct internal edges | 110 / 316 | -| Tagged config field rows | 194 | -| Tracked paths / tracked `node_modules` paths / tracked symlinks | 1,088 / 0 / 1 | -| `.dockerignore` present | 1 | - -`source-metrics.go` and `git ls-files` reconcile here: 408 + 9 generated -production files and 402 test files, plus the `tools` module's 5 / 2 / 0, -against 422 non-test and 403 test tracked files. The single extra file is an -untracked probe under `.local/issue-tracker/probes/`. - -The scripts count themselves: the skill's own Go files contribute 640 of those -production lines. Editing a bundled script therefore moves -`production_physical_lines` on its own, so re-baseline after any script change -rather than reading the delta as a change in the product code. - -The delivery snapshot found no Taskfile literals for race; docs now has 6 and -the `tools` module 7, both grown by wiring `task docs:check` into the gate; -GitHub `go gate` 4 and container publish 3; and non-zero literals for all five -composition-root anchors under `internal/app/archied`. - -The focused test -`go test ./internal/skillscript -run '^TestRunWrapsExternalCommand$' -count=1 -v` -failed on 2026-07-28 with `Run() = "\n"` and **passes** as of 2026-09-16. diff --git a/.agents/skills/archie-diagnostics-and-tooling/agents/openai.yaml b/.agents/skills/archie-diagnostics-and-tooling/agents/openai.yaml deleted file mode 100644 index 8e4014620..000000000 --- a/.agents/skills/archie-diagnostics-and-tooling/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Diagnostics and Tooling" - short_description: "Measure maintainability, wiring, and delivery drift" - default_prompt: "Use $archie-diagnostics-and-tooling to collect a dated, reproducible evidence baseline before changing Archie." diff --git a/.agents/skills/archie-diagnostics-and-tooling/scripts/config-use-candidates.go b/.agents/skills/archie-diagnostics-and-tooling/scripts/config-use-candidates.go deleted file mode 100755 index 72667abaf..000000000 --- a/.agents/skills/archie-diagnostics-and-tooling/scripts/config-use-candidates.go +++ /dev/null @@ -1,287 +0,0 @@ -//go:build ignore - -// Command config-use-candidates reports syntax-level selector evidence for -// tagged fields declared by internal/config. Results are candidates, not proof -// that a field is wired, live, or dead. Run it by name: go run -// config-use-candidates.go. The directory holds several standalone programs, so -// each carries this constraint. -package main - -import ( - "flag" - "fmt" - "go/ast" - "go/parser" - "go/token" - "io/fs" - "os" - "path/filepath" - "reflect" - "sort" - "strconv" - "strings" -) - -type fieldDefinition struct { - path string - line int - typeName string - fieldName string - tags string - duplicates int -} - -type referenceCounts struct { - config int - entrypoint int - production int - test int - generated int -} - -func main() { - root := flag.String("root", ".", "repository root to inspect") - flag.Parse() - - absoluteRoot, err := filepath.Abs(*root) - if err != nil { - fail(2, "resolve root: %v", err) - } - info, err := os.Stat(absoluteRoot) - if err != nil { - fail(2, "inspect root: %v", err) - } - if !info.IsDir() { - fail(2, "root is not a directory: %s", absoluteRoot) - } - - fset := token.NewFileSet() - fields, err := readFieldDefinitions(absoluteRoot, fset) - if err != nil { - fail(1, "%v", err) - } - if len(fields) == 0 { - fail(1, "no tagged fields found under internal/config") - } - - nameCounts := map[string]int{} - for _, field := range fields { - nameCounts[field.fieldName]++ - } - for index := range fields { - fields[index].duplicates = nameCounts[fields[index].fieldName] - } - - references := map[string]*referenceCounts{} - for name := range nameCounts { - references[name] = &referenceCounts{} - } - if err := countSelectors(absoluteRoot, fset, references); err != nil { - fail(1, "%v", err) - } - - sort.Slice(fields, func(i, j int) bool { - if fields[i].typeName != fields[j].typeName { - return fields[i].typeName < fields[j].typeName - } - if fields[i].fieldName != fields[j].fieldName { - return fields[i].fieldName < fields[j].fieldName - } - if fields[i].path != fields[j].path { - return fields[i].path < fields[j].path - } - return fields[i].line < fields[j].line - }) - - fmt.Println("META\tschema\tarchie-config-use-candidates/v1") - fmt.Println("META\tmeaning\tselector-name counts are heuristic candidates; confirm exact fields with gopls references and production composition") - for _, field := range fields { - count := references[field.fieldName] - status := "candidate-selector-seen-in-entrypoint" - switch { - case count.production == 0 && count.entrypoint == 0: - status = "candidate-no-selector-outside-config" - case count.entrypoint == 0: - status = "candidate-no-entrypoint-selector" - } - fmt.Printf( - "CONFIG_FIELD\t%s\t%d\t%s.%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\t%s\n", - field.path, - field.line, - field.typeName, - field.fieldName, - field.tags, - field.duplicates, - count.config, - count.entrypoint, - count.production, - count.test, - count.generated, - status, - ) - } -} - -func readFieldDefinitions(root string, fset *token.FileSet) ([]fieldDefinition, error) { - configDir := filepath.Join(root, "internal", "config") - info, err := os.Stat(configDir) - if err != nil { - return nil, fmt.Errorf("inspect internal/config: %w", err) - } - if !info.IsDir() { - return nil, fmt.Errorf("internal/config is not a directory") - } - - var fields []fieldDefinition - err = filepath.WalkDir(configDir, func(path string, entry fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - if entry.IsDir() || filepath.Ext(entry.Name()) != ".go" || strings.HasSuffix(entry.Name(), "_test.go") { - return nil - } - body, err := os.ReadFile(path) - if err != nil { - return err - } - file, err := parser.ParseFile(fset, path, body, parser.ParseComments) - if err != nil { - return fmt.Errorf("parse %s: %w", path, err) - } - relative, err := filepath.Rel(root, path) - if err != nil { - return err - } - relative = filepath.ToSlash(relative) - for _, declaration := range file.Decls { - general, ok := declaration.(*ast.GenDecl) - if !ok || general.Tok != token.TYPE { - continue - } - for _, specification := range general.Specs { - typeSpec, ok := specification.(*ast.TypeSpec) - if !ok { - continue - } - structType, ok := typeSpec.Type.(*ast.StructType) - if !ok { - continue - } - for _, field := range structType.Fields.List { - tags, ok := configTags(field.Tag) - if !ok { - continue - } - for _, name := range field.Names { - fields = append(fields, fieldDefinition{ - path: relative, - line: fset.Position(name.Pos()).Line, - typeName: typeSpec.Name.Name, - fieldName: name.Name, - tags: tags, - }) - } - } - } - } - return nil - }) - return fields, err -} - -func configTags(literal *ast.BasicLit) (string, bool) { - if literal == nil { - return "", false - } - raw, err := strconv.Unquote(literal.Value) - if err != nil { - return "", false - } - tag := reflect.StructTag(raw) - var parts []string - for _, key := range []string{"toml", "yaml", "json"} { - value, ok := tag.Lookup(key) - if !ok { - continue - } - parts = append(parts, key+"="+value) - } - return strings.Join(parts, ";"), len(parts) > 0 -} - -func countSelectors(root string, fset *token.FileSet, references map[string]*referenceCounts) error { - return filepath.WalkDir(root, func(path string, entry fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - relative, err := filepath.Rel(root, path) - if err != nil { - return err - } - relative = filepath.ToSlash(relative) - if entry.IsDir() { - if relative != "." && excludedDirectory(relative, entry.Name()) { - return filepath.SkipDir - } - return nil - } - if filepath.Ext(entry.Name()) != ".go" { - return nil - } - body, err := os.ReadFile(path) - if err != nil { - return err - } - file, err := parser.ParseFile(fset, path, body, parser.ParseComments) - if err != nil { - return fmt.Errorf("parse %s: %w", relative, err) - } - generated := ast.IsGenerated(file) - isTest := strings.HasSuffix(entry.Name(), "_test.go") - inConfig := strings.HasPrefix(relative, "internal/config/") - inEntrypoint := strings.HasPrefix(relative, "cmd/") - - ast.Inspect(file, func(node ast.Node) bool { - selector, ok := node.(*ast.SelectorExpr) - if !ok { - return true - } - count := references[selector.Sel.Name] - if count == nil { - return true - } - switch { - case generated: - count.generated++ - case isTest: - count.test++ - case inConfig: - count.config++ - case inEntrypoint: - count.entrypoint++ - default: - count.production++ - } - return true - }) - return nil - }) -} - -// excludedDirectory reports whether a walked directory is outside the module. -// -// ".worktrees" holds live git worktrees of this same repository, nested inside -// the root. countSelectors walks the whole root, so without this every selector -// count is multiplied by the number of checkout worktrees. -func excludedDirectory(_, name string) bool { - switch name { - case ".git", ".claude", ".references", "node_modules", "vendor", ".gotmp", ".worktrees": - return true - } - return false -} - -func fail(code int, format string, arguments ...any) { - fmt.Fprintf(os.Stderr, "config-use-candidates: "+format+"\n", arguments...) - os.Exit(code) -} diff --git a/.agents/skills/archie-diagnostics-and-tooling/scripts/delivery-snapshot.sh b/.agents/skills/archie-diagnostics-and-tooling/scripts/delivery-snapshot.sh deleted file mode 100755 index 97837906c..000000000 --- a/.agents/skills/archie-diagnostics-and-tooling/scripts/delivery-snapshot.sh +++ /dev/null @@ -1,95 +0,0 @@ -#!/bin/sh -set -eu - -if [ "$#" -ne 0 ]; then - printf '%s\n' "usage: delivery-snapshot.sh" >&2 - exit 2 -fi - -for tool in git rg sed wc; do - command -v "$tool" >/dev/null 2>&1 || { - printf 'delivery-snapshot: %s is required\n' "$tool" >&2 - exit 127 - } -done - -script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd) -repo_root=$(CDPATH= cd "$script_dir/../../../.." && pwd) -if [ ! -f "$repo_root/go.mod" ] || [ ! -f "$repo_root/Taskfile.yml" ]; then - printf 'delivery-snapshot: expected Archie repository root at %s\n' "$repo_root" >&2 - exit 2 -fi - -temporary=$(mktemp -d "${TMPDIR:-/tmp}/archie-delivery-snapshot.XXXXXX") -trap 'rm -rf "$temporary"' EXIT HUP INT TERM -cd "$repo_root" - -printf '%s\n' "META schema archie-delivery-snapshot/v1" - -scan_literal() { - axis=$1 - scope=$2 - pattern=$3 - shift 3 - result="$temporary/$axis" - if rg -n --no-heading --color never -e "$pattern" "$@" >"$result"; then - : - else - status=$? - if [ "$status" -ne 1 ]; then - printf 'delivery-snapshot: scan failed for %s\n' "$axis" >&2 - exit "$status" - fi - fi - count=$(wc -l <"$result" | sed 's/[[:space:]]//g') - printf 'SURFACE\t%s\t%s\t%s\n' "$axis" "$scope" "$count" -} - -scan_literal task_format taskfile 'gofumpt[[:space:]]+-w|go fix' Taskfile.yml -scan_literal task_vet taskfile 'go vet' Taskfile.yml -scan_literal task_build taskfile 'go build|task:[[:space:]]+build' Taskfile.yml -scan_literal task_test taskfile 'go test|task:[[:space:]]+test' Taskfile.yml -scan_literal task_lint taskfile 'golangci-lint|task:[[:space:]]+lint' Taskfile.yml -scan_literal task_race taskfile 'go test[^#\n]*-race|-race[^#\n]*go test' Taskfile.yml -scan_literal task_tools_module taskfile 'go -C tools|cd tools|task:[[:space:]]+tools' Taskfile.yml -scan_literal task_docs taskfile 'docsgen|docs:generate|docs:check' Taskfile.yml - -# One CI surface: .github/workflows. The Gitea workflow was dropped in dd9bddc2 -# ("ci: build and push images to GHCR, drop the Gitea workflow"), so scanning -# .gitea/workflows aborted the whole snapshot under `set -eu`. -scan_literal github_go_gate github-workflows 'go test|go vet|go build|golangci-lint|task[[:space:]]+check' .github/workflows -scan_literal github_container_publish github-workflows 'docker build|docker push|docker/build-push-action|docker login' .github/workflows - -# Composition root. cmd/archied/main.go is now a ~30-line dispatcher that only -# routes to internal/app/archied, so anchoring on it reported a silent zero for -# every row below -- which reads as "no composition root" rather than "wrong -# file". The wiring lives in internal/app/archied. -scan_literal production_config_resolve composition-root 'configuration\.New\(' internal/app/archied -scan_literal production_config_load composition-root 'loadConfig\(|loadRuntimeConfig\(' internal/app/archied -scan_literal production_task_store composition-root 'openStateStore\(' internal/app/archied -scan_literal production_daemon composition-root '&daemon\.Daemon\{' internal/app/archied -scan_literal production_rpc_servers composition-root 'registerTaskRPCServers\(' internal/app/archied - -git ls-files >"$temporary/tracked" -tracked_total=$(wc -l <"$temporary/tracked" | sed 's/[[:space:]]//g') -tracked_node_modules=$(rg -c '(^|/)node_modules(/|$)' "$temporary/tracked" || true) -tracked_artifacts=$(rg -c '(^|/)(node_modules|bin|dist|\.gotmp)(/|$)|\.(exe|test|out)$' "$temporary/tracked" || true) -tracked_symlinks=$(git ls-files -s | awk '$1 == "120000" {count++} END {print count + 0}') - -printf 'HYGIENE\ttracked_paths\t%s\n' "$tracked_total" -printf 'HYGIENE\ttracked_node_modules_paths\t%s\n' "${tracked_node_modules:-0}" -printf 'HYGIENE\ttracked_artifact_candidates\t%s\n' "${tracked_artifacts:-0}" -printf 'HYGIENE\ttracked_symlinks\t%s\n' "$tracked_symlinks" -if [ -f .dockerignore ]; then - printf '%s\n' "HYGIENE dockerignore_present 1" -else - printf '%s\n' "HYGIENE dockerignore_present 0" -fi - -find . \ - \( -path './.git' -o -path './.claude' -o -path './.references' -o -name node_modules -o -name .worktrees \) -prune -o \ - -name go.mod -print | - LC_ALL=C sort | - while IFS= read -r module; do - printf 'MODULE\t%s\n' "$module" - done diff --git a/.agents/skills/archie-diagnostics-and-tooling/scripts/package-shape.sh b/.agents/skills/archie-diagnostics-and-tooling/scripts/package-shape.sh deleted file mode 100755 index 76d1ac12d..000000000 --- a/.agents/skills/archie-diagnostics-and-tooling/scripts/package-shape.sh +++ /dev/null @@ -1,86 +0,0 @@ -#!/bin/sh -set -eu - -if [ "$#" -gt 1 ]; then - printf '%s\n' "usage: $0 [module-directory-relative-to-repo]" >&2 - exit 2 -fi - -command -v go >/dev/null 2>&1 || { - printf '%s\n' "package-shape: go is required" >&2 - exit 127 -} -command -v awk >/dev/null 2>&1 || { - printf '%s\n' "package-shape: awk is required" >&2 - exit 127 -} - -script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd) -repo_root=$(CDPATH= cd "$script_dir/../../../.." && pwd) -module_relative=${1:-.} -module_root="$repo_root/$module_relative" -edge_helper="$repo_root/.agents/skills/archie-codebase-discovery/scripts/package-edges.sh" - -if [ ! -f "$module_root/go.mod" ]; then - printf 'package-shape: no go.mod at %s\n' "$module_root" >&2 - exit 2 -fi -if [ ! -x "$edge_helper" ]; then - printf 'package-shape: required sibling helper is missing or not executable: %s\n' "$edge_helper" >&2 - exit 2 -fi - -temporary=$(mktemp -d "${TMPDIR:-/tmp}/archie-package-shape.XXXXXX") -trap 'rm -rf "$temporary"' EXIT HUP INT TERM -mkdir -p "$temporary/cache" "$temporary/build-tmp" - -export GOCACHE="$temporary/cache" -export GOTMPDIR="$temporary/build-tmp" -export GOPROXY=off -export GOFLAGS="-mod=readonly -buildvcs=false" -export ARCHIE_DISCOVERY_CACHE="$temporary/discovery" - -( - cd "$module_root" - go list ./... | LC_ALL=C sort -) >"$temporary/packages" -if ( - cd "$module_root" - "$edge_helper" ./... -) >"$temporary/edges" 2>"$temporary/edge-stderr"; then - # The sibling helper sets its own GOFLAGS and can trigger a harmless, - # nondeterministic temporary filename when GOMODCACHE is read-only. - # Preserve the warning while normalizing only that filename suffix. - sed 's/\.info[0-9][0-9]*\.tmp/.info.tmp/' "$temporary/edge-stderr" >&2 -else - status=$? - cat "$temporary/edge-stderr" >&2 - exit "$status" -fi -( - cd "$module_root" - go list -m -f '{{.Path}}' -) >"$temporary/module" - -module_path=$(sed -n '1p' "$temporary/module") -printf '%s\n' "META schema archie-package-shape/v1" -printf 'META\tmodule\t%s\n' "$module_path" - -awk -F ' ' ' - NR == FNR { - packages[$0] = 1 - next - } - { - split($0, edge, " -> ") - outbound[edge[1]]++ - inbound[edge[2]]++ - } - END { - for (packageName in packages) { - printf "PACKAGE\t%s\t%d\t%d\n", packageName, inbound[packageName] + 0, outbound[packageName] + 0 - } - } -' "$temporary/packages" "$temporary/edges" | LC_ALL=C sort - -awk '{printf "EDGE\t%s\n", $0}' "$temporary/edges" diff --git a/.agents/skills/archie-diagnostics-and-tooling/scripts/source-metrics.go b/.agents/skills/archie-diagnostics-and-tooling/scripts/source-metrics.go deleted file mode 100755 index d5bc28d2d..000000000 --- a/.agents/skills/archie-diagnostics-and-tooling/scripts/source-metrics.go +++ /dev/null @@ -1,361 +0,0 @@ -//go:build ignore - -// Command source-metrics emits deterministic, syntax-derived Go source metrics. -// It never writes to the inspected tree and uses only the Go standard library. -// Run it by name: go run source-metrics.go. The directory holds several -// standalone programs, so each carries this constraint. -package main - -import ( - "bytes" - "flag" - "fmt" - "go/ast" - "go/parser" - "go/token" - "io/fs" - "os" - "path/filepath" - "sort" - "strings" -) - -type counts struct { - productionFiles int - testFiles int - generatedFiles int - productionLines int - testLines int - generatedLines int - functions int - methods int -} - -type packageCounts struct { - module string - path string - productionFiles int - testFiles int - generatedFiles int - productionLines int - testLines int - generatedLines int -} - -type hotspot struct { - module string - path string - line int - symbol string - spanLines int - statements int - complexity int -} - -func main() { - root := flag.String("root", ".", "repository root to inspect") - top := flag.Int("top", 30, "maximum hotspot rows; zero means all") - largeLines := flag.Int("large-lines", 80, "minimum body span for a hotspot") - complexity := flag.Int("complexity", 15, "minimum approximate syntactic complexity for a hotspot") - includeTests := flag.Bool("include-test-hotspots", false, "include test functions in hotspot rows") - flag.Parse() - - if *top < 0 || *largeLines < 1 || *complexity < 1 { - fail(2, "top must be non-negative; thresholds must be positive") - } - - absoluteRoot, err := filepath.Abs(*root) - if err != nil { - fail(2, "resolve root: %v", err) - } - info, err := os.Stat(absoluteRoot) - if err != nil { - fail(2, "inspect root: %v", err) - } - if !info.IsDir() { - fail(2, "root is not a directory: %s", absoluteRoot) - } - - modules := map[string]*counts{} - packages := map[string]*packageCounts{} - var hotspots []hotspot - fset := token.NewFileSet() - - err = filepath.WalkDir(absoluteRoot, func(path string, entry fs.DirEntry, walkErr error) error { - if walkErr != nil { - return walkErr - } - relative, err := filepath.Rel(absoluteRoot, path) - if err != nil { - return err - } - relative = filepath.ToSlash(relative) - if entry.IsDir() { - if relative != "." && excludedDirectory(relative, entry.Name()) { - return filepath.SkipDir - } - return nil - } - if filepath.Ext(entry.Name()) != ".go" { - return nil - } - - body, err := os.ReadFile(path) - if err != nil { - return err - } - file, err := parser.ParseFile(fset, path, body, parser.ParseComments) - if err != nil { - return fmt.Errorf("parse %s: %w", relative, err) - } - - module := moduleFor(relative) - moduleCounts := modules[module] - if moduleCounts == nil { - moduleCounts = &counts{} - modules[module] = moduleCounts - } - dir := filepath.ToSlash(filepath.Dir(relative)) - packageKey := module + "\x00" + dir - pkg := packages[packageKey] - if pkg == nil { - pkg = &packageCounts{module: module, path: dir} - packages[packageKey] = pkg - } - - lines := physicalLines(body) - generated := ast.IsGenerated(file) - isTest := strings.HasSuffix(entry.Name(), "_test.go") - switch { - case generated: - moduleCounts.generatedFiles++ - moduleCounts.generatedLines += lines - pkg.generatedFiles++ - pkg.generatedLines += lines - case isTest: - moduleCounts.testFiles++ - moduleCounts.testLines += lines - pkg.testFiles++ - pkg.testLines += lines - default: - moduleCounts.productionFiles++ - moduleCounts.productionLines += lines - pkg.productionFiles++ - pkg.productionLines += lines - } - - for _, declaration := range file.Decls { - function, ok := declaration.(*ast.FuncDecl) - if !ok || function.Body == nil { - continue - } - if function.Recv == nil { - moduleCounts.functions++ - } else { - moduleCounts.methods++ - } - if generated || (isTest && !*includeTests) { - continue - } - - start := fset.Position(function.Body.Lbrace).Line - end := fset.Position(function.Body.Rbrace).Line - row := hotspot{ - module: module, - path: relative, - line: fset.Position(function.Pos()).Line, - symbol: symbolName(function), - spanLines: end - start + 1, - statements: statementNodes(function.Body), - complexity: syntacticComplexity(function.Body), - } - if row.spanLines >= *largeLines || row.complexity >= *complexity { - hotspots = append(hotspots, row) - } - } - return nil - }) - if err != nil { - fail(1, "%v", err) - } - - fmt.Println("META\tschema\tarchie-source-metrics/v1") - fmt.Printf("META\tthresholds\tlarge_lines=%d;syntactic_complexity=%d;top=%d\n", *largeLines, *complexity, *top) - - moduleNames := sortedKeys(modules) - for _, module := range moduleNames { - value := modules[module] - emitMetric(module, "production_go_files", value.productionFiles) - emitMetric(module, "test_go_files", value.testFiles) - emitMetric(module, "generated_go_files", value.generatedFiles) - emitMetric(module, "production_physical_lines", value.productionLines) - emitMetric(module, "test_physical_lines", value.testLines) - emitMetric(module, "generated_physical_lines", value.generatedLines) - emitMetric(module, "functions", value.functions) - emitMetric(module, "methods", value.methods) - } - - packageRows := make([]*packageCounts, 0, len(packages)) - for _, row := range packages { - packageRows = append(packageRows, row) - } - sort.Slice(packageRows, func(i, j int) bool { - if packageRows[i].module != packageRows[j].module { - return packageRows[i].module < packageRows[j].module - } - return packageRows[i].path < packageRows[j].path - }) - for _, row := range packageRows { - fmt.Printf( - "PACKAGE\t%s\t%s\t%d\t%d\t%d\t%d\t%d\t%d\n", - row.module, - row.path, - row.productionFiles, - row.testFiles, - row.generatedFiles, - row.productionLines, - row.testLines, - row.generatedLines, - ) - } - - sort.Slice(hotspots, func(i, j int) bool { - if hotspots[i].spanLines != hotspots[j].spanLines { - return hotspots[i].spanLines > hotspots[j].spanLines - } - if hotspots[i].complexity != hotspots[j].complexity { - return hotspots[i].complexity > hotspots[j].complexity - } - if hotspots[i].path != hotspots[j].path { - return hotspots[i].path < hotspots[j].path - } - if hotspots[i].line != hotspots[j].line { - return hotspots[i].line < hotspots[j].line - } - return hotspots[i].symbol < hotspots[j].symbol - }) - if *top > 0 && len(hotspots) > *top { - hotspots = hotspots[:*top] - } - for _, row := range hotspots { - fmt.Printf( - "HOTSPOT\t%s\t%s\t%d\t%s\t%d\t%d\t%d\n", - row.module, - row.path, - row.line, - row.symbol, - row.spanLines, - row.statements, - row.complexity, - ) - } -} - -// excludedDirectory reports whether a walked directory is outside the module. -// -// ".worktrees" holds live git worktrees of this same repository, nested inside -// the root. Each is a near-complete copy of the module, so walking them -// multiplies every count by the number of checkout worktrees and floods the -// HOTSPOT and PACKAGE rows with duplicates of the same declarations. -func excludedDirectory(_, name string) bool { - switch name { - case ".git", ".claude", ".references", "node_modules", "vendor", ".gotmp", ".worktrees": - return true - } - return false -} - -func moduleFor(relative string) string { - if relative == "tools" || strings.HasPrefix(relative, "tools/") { - return "tools" - } - return "root" -} - -func physicalLines(body []byte) int { - if len(body) == 0 { - return 0 - } - lines := bytes.Count(body, []byte{'\n'}) - if body[len(body)-1] != '\n' { - lines++ - } - return lines -} - -func symbolName(function *ast.FuncDecl) string { - if function.Recv == nil || len(function.Recv.List) == 0 { - return function.Name.Name - } - return receiverName(function.Recv.List[0].Type) + "." + function.Name.Name -} - -func receiverName(expression ast.Expr) string { - switch value := expression.(type) { - case *ast.Ident: - return value.Name - case *ast.StarExpr: - return "*" + receiverName(value.X) - case *ast.IndexExpr: - return receiverName(value.X) - case *ast.IndexListExpr: - return receiverName(value.X) - default: - return "receiver" - } -} - -func statementNodes(node ast.Node) int { - count := 0 - ast.Inspect(node, func(candidate ast.Node) bool { - statement, ok := candidate.(ast.Stmt) - if !ok { - return true - } - switch statement.(type) { - case *ast.BlockStmt, *ast.EmptyStmt: - default: - count++ - } - return true - }) - return count -} - -func syntacticComplexity(node ast.Node) int { - value := 1 - ast.Inspect(node, func(candidate ast.Node) bool { - switch item := candidate.(type) { - case *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.CommClause: - value++ - case *ast.CaseClause: - if len(item.List) > 0 { - value++ - } - case *ast.BinaryExpr: - if item.Op == token.LAND || item.Op == token.LOR { - value++ - } - } - return true - }) - return value -} - -func sortedKeys(values map[string]*counts) []string { - keys := make([]string, 0, len(values)) - for key := range values { - keys = append(keys, key) - } - sort.Strings(keys) - return keys -} - -func emitMetric(module, name string, value int) { - fmt.Printf("METRIC\t%s\t%s\t%d\n", module, name, value) -} - -func fail(code int, format string, arguments ...any) { - fmt.Fprintf(os.Stderr, "source-metrics: "+format+"\n", arguments...) - os.Exit(code) -} diff --git a/.agents/skills/archie-docs-and-writing/SKILL.md b/.agents/skills/archie-docs-and-writing/SKILL.md deleted file mode 100644 index 69bad5173..000000000 --- a/.agents/skills/archie-docs-and-writing/SKILL.md +++ /dev/null @@ -1,201 +0,0 @@ ---- -name: archie-docs-and-writing -description: Maintain Archie's documentation of record and write durable architecture decisions, migration plans, parity matrices, incident and dead-end records, feature ownership and deprecation records, operational runbooks, and documentation reviews. Use when deciding where an Archie fact belongs; reconciling code with `CLAUDE.md`, `docs/architecture`, `docs/prds`, `docs/archive`, or generated contracts; changing `tools/docsgen`; documenting a feature so future maintainers can find its owners, consumers, invariants, superseded paths, deletion gates, evidence, and rollback; or checking documentation authority, drift, links, copied content, and source-artifact hygiene. ---- - -# Maintain Archie documentation - -Write one durable record for each decision or behaviour. Separate what runs now -from what Archie has approved as its destination. - -Route to `archie-architecture-planning-campaign` for ownership/boundary -decisions (parked outside this checkout, under -`/work/apps/archie-skills-parked/`), -`archie-architecture-contract` for invariants, -`archie-codebase-discovery` for live entry points, -`archie-failure-archaeology` for incidents, -`archie-config-and-flags`, `archie-build-and-env`, or `archie-run-and-operate` -for runtime/operations facts. - -## Use the authority vocabulary - -Define a **record of authority** as the one canonical location whose owner may -change a claim. - -| State | Meaning | Permitted wording | -| ----------------- | -------------------------------------------------------------------------------- | ---------------------------------------------- | -| `CURRENT` | Verified behaviour in checked-out code, tests, composition, or executable config | "Currently does" | -| `APPROVED TARGET` | Normative destination approved in architecture index | "Must become"; never "currently does" | -| `OPEN` | Investigation, candidate, or unresolved decision | "Candidate", "unknown", or "requires decision" | -| `HISTORICAL` | Prior design, incident, dead end, or superseded choice | "Previously did" | -| `GENERATED` | Derivative output produced from owned source definition | "Generated from"; never hand-edit | -| `EXTERNAL` | Fact held outside repository, such as deployed config or host state | Date, name verifier, give re-check command | - -When `CURRENT` conflicts with `APPROVED TARGET`, preserve both and state the -migration delta. - -## Use the repository authority map - -Verified on 2026-09-18: - -| Location | Role | Discipline | -| ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| Live Go code, tests, `Taskfile.yml`, executable config parsing, composition under `internal/app/` (entered from `cmd/`) | `CURRENT` execution evidence | Trace producers and consumers; tests prove only asserted behaviour | -| `CLAUDE.md` | Current contributor and safety protocol plus compact architecture orientation | Verify operational claims against code and `Taskfile.yml`; `AGENTS.md` is a symlink to it | -| `docs/prds/01-project-management.md` | Index and approved foundation for target architecture | Add or change target decisions in the focused document it names | -| `docs/architecture/*.md` | Focused target decisions, active review procedure, migration inventory | Read each file's status | -| `docs/architecture/migration-decisions.md` | `OPEN` migration inventory constrained by approved decisions | Close a question only after code-grounded review | -| `docs/archive/` | `HISTORICAL` material | Mine rationale and failure evidence | -| `CHANGELOG.md` | Release stream and packaged runtime input | One file holds every release; `internal/releaseannounce` parses version headings | -| `tools/docsgen` | Current, partial generator in nested `tools` Go module | Treat its flags and tests—not planned PRD commands—as executable truth | -| `docs/data/generated/contracts.json` | Current working-tree `GENERATED` output | Regenerate; never edit by hand | -| `docs/` | Markdown sources and generated JSON for the external Astro website | This repository generates and validates artifacts; the website repository renders and deploys them | - -The repository root has no `README.md` or `CONTRIBUTING.md` as of 2026-09-18. - -## Choose one destination - -1. State the reader's question. -2. Identify the owner of the behaviour or decision. -3. Find the existing record of authority. -4. Extend that record or link to it. Do not make a second canonical table. -5. If no owner exists, route the ownership decision through the architecture campaign. -6. If the fact is generated, change the owned source definition and generator. -7. If the fact is external, date it and name the exact observation command. - -| Content | Destination | -| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Cross-cutting approved architecture index | `docs/prds/01-project-management.md` | -| New capability with no settled design yet (CLAUDE.md's "write a decisive doc before coding") | New `docs/prds/.md` — use the PRD template in `references/templates.md`, which folds in a multi-agent execution breakdown so the sub-issues can be picked up without re-deriving the design | -| Focused domain or requirement decision | Matching `docs/architecture/*.md` file | -| Unresolved migration question | `docs/architecture/migration-decisions.md` | -| Contributor protocol that must load before work | `CLAUDE.md` | -| Runtime/API/config reference derivable from code | Domain-owned registry/type, then `tools/docsgen` output | -| Repository documentation prose | `docs/`, linking back to authority with repository-relative paths | -| Shipped release behaviour | Matching component changelog; keep `CHANGELOG.md` as two-component index | -| Superseded design retained for context | `docs/archive/`, with historical status | -| Incident or rejected approach | `archie-failure-archaeology`'s chronology | - -Do not duplicate a package map across `CLAUDE.md`, a PRD, and -the site. Name the authoritative map and link to it. - -## Write for future change - -Every architecture, feature, or migration record must answer: - -- **Responsibility:** What cohesive job exists? -- **Owner:** Which domain, application boundary, or infrastructure adapter owns - its meaning and mutable state? -- **Boundaries:** What is explicitly inside and outside? -- **Consumers:** Which entry points, interfaces, commands, events, config, and - processes depend on it? -- **Invariants:** What must remain true, and where is each enforced? -- **Superseded path:** Which older mechanism becomes redundant? -- **Deletion gate:** What observable proof permits removal? -- **Evidence:** Which symbols, tests, commands, and runtime observations support - the record? -- **Rollback:** How can behaviour and data return safely? -- **Unresolved questions:** What remains `OPEN`? - -Name one owner for every mutable record. A new path is incomplete until the -document says whether each older path remains, delegates, migrates, or is -deleted. - -## Cite evidence without freezing line numbers - -Prefer: repository-relative path plus exact Go symbol, test name, config key, -workflow job/step, or Markdown heading; a relative Markdown link to the record -of authority; the command that re-discovers the evidence. - -Write `internal/agentexec.Request` and `tools/docsgen.currentContractTypes`. -Distinguish evidence strength: - -1. Runtime composition and executable behaviour. -2. Tests that exercise the relevant production seam. -3. Approved target decision. -4. Comments and summaries corroborated by the first three. -5. Historical or external notes, explicitly dated. - -## Maintain component changelogs - -Keep every release's notes in `CHANGELOG.md`; a release is one version, and -the components' entries are labelled sections inside it. -`Dockerfile.archied` copies it to `/usr/share/archie/`, and -`internal/releaseannounce.changelogSection` parses a version heading. - -Version-heading format is settled as of 2026-09-18: the changelog uses -`## [1.27.0]` with no `v` prefix, `changelogSection` searches for -`## []`, and `.github/workflows/deploy.yml` gates each release tag with -`grep -q "^## \[$ver\]" CHANGELOG.md`. The earlier -`vX.Y.Z`-vs-`X.Y.Z` contradiction involved `.gitea/workflows/deploy.yml`, which -was dropped (`dd9bddc2 ci: build and push images to GHCR, drop the Gitea -workflow`), so that question is `HISTORICAL`, not `OPEN`. The remaining guard is -the CI shell gate plus `internal/releaseannounce`'s announcer tests -(`TestAnnouncerReportsMissingReleaseSectionWithoutAdvancingState`); the old -`cmd/archied.TestChangelogsTrackGatewayAndRuntimeIndependently` no longer exists. - -## Maintain generated contracts - -Current behaviour, verified 2026-09-18: - -- Tool path is `tools/docsgen`, not `tools/cmd/docsgen`. -- Separate Go module replacing root module with `../`. -- Accepts `--repo-root` and `--out`, plus a `check` subcommand that compares - against the committed artifact without writing. No implemented `data`, - `asyncapi`, or `all` subcommands. -- `currentContractTypes` publishes three top-level contracts and collects - referenced schemas into one JSON object. -- Default output is `docs/data/generated/contracts.json`. - -```bash -GOTMPDIR=/tmp GOCACHE=/tmp/archie-docsgen-gocache go -C tools test -mod=readonly ./docsgen -count=1 -task docs:check # fails loudly, and names the Go type behind each mismatch -``` - -`docsgen check` and the `docs:generate`/`docs:check` tasks are implemented, and -`task check` runs `docs:check` — generated drift is gated. `docsgen data`, -`docsgen asyncapi`, and `docsgen all` remain `APPROVED TARGET`. - -The check is deliberately non-destructive: it generates into a temporary -directory, so a failing gate never rewrites the artifact it judges. Fix a -failure with `task docs:generate` and commit the result with the code change -that shifted the contract surface. - -## Maintain documentation consumed by the external Astro website - -`docs/` holds Markdown sources and generated JSON consumed by the Astro website -at `offloaded.dev/docs/`. The website is maintained outside this repository. -This repository owns artifact generation and drift checks; it does not build, -preview, or deploy the website. - -| Surface | Current state | -| ---------------- | ---------------------------------------------------------------------- | -| Content | Markdown under `docs/` and generated JSON under `docs/data/generated/` | -| Rendering | External Astro website consumes generated artifacts | -| Build and deploy | Owned by the Astro website repository | -| Local checks | `task docs:check`, `task docs:artifact:check`, and `task news:check` | - -The repository checks artifact drift, not the external site's rendered routes or -links. Verify those in the website repository. - -```bash -# every relative markdown link target that does not resolve -grep -rhoE '\]\([^)#]+' docs --include=*.md | sed -E 's/^\]\(//' | sort -u -``` - -### Enforce source-artifact hygiene - -Git tracks no `node_modules` entries or website build output. The external Astro -repository owns its installed dependencies and generated site files. - -```bash -git ls-files | grep -c node_modules # expect 0 -ls docs/package.json docs/pnpm-lock.yaml 2>&1 # expect: No such file -ls .github/workflows/ # expect deploy.yml only -``` - -Historical mentions of VitePress in `docs/architecture/` are deliberate — they -record what was removed. A grep for the word alone is not a failure signal. - -Never stage dependency installs, renderer output, generator scratch files, -credentials, absolute paths, wall-clock data, or machine-specific values. diff --git a/.agents/skills/archie-docs-and-writing/agents/openai.yaml b/.agents/skills/archie-docs-and-writing/agents/openai.yaml deleted file mode 100644 index 7cd8e4bde..000000000 --- a/.agents/skills/archie-docs-and-writing/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Archie Docs and Writing" - short_description: "Maintain authoritative Archie documentation" - default_prompt: "Use $archie-docs-and-writing to write or update an authoritative Archie design, migration, incident, ownership, or operations document." diff --git a/.agents/skills/archie-docs-and-writing/references/templates.md b/.agents/skills/archie-docs-and-writing/references/templates.md deleted file mode 100644 index 486b6f285..000000000 --- a/.agents/skills/archie-docs-and-writing/references/templates.md +++ /dev/null @@ -1,485 +0,0 @@ -# Archie durable-writing templates - -Use one template at a time. Replace every angle-bracket prompt. Remove unused -sections. Keep facts, decisions, and open questions visibly separate. - -## Contents - -- [Architecture decision record](#architecture-decision-record) -- [Migration plan and parity matrix](#migration-plan-and-parity-matrix) -- [Incident or dead-end record](#incident-or-dead-end-record) -- [Feature ownership and deprecation record](#feature-ownership-and-deprecation-record) -- [Operational runbook](#operational-runbook) -- [Documentation change review](#documentation-change-review) -- [PRD: open capability design with multi-agent execution](#prd-open-capability-design-with-multi-agent-execution) - -## Architecture decision record - -```markdown -# - -**Status:** Proposed | Approved | Superseded by -**Date:** YYYY-MM-DD -**Owner:** -**Record of authority:** -**Change-control reference:** - -## Decision - - - -## Problem and scope - - - -## Current evidence - -| Claim | Evidence | -| ------------------ | ------------------------------------- | -| | `` — `` | - -## Constraints and invariants - -- - -## Consumers and boundaries - -| Consumer | Contract used | Failure effect | -| ----------------------------- | ------------------------------ | -------------- | -| | | | - -## Options considered - -| Option | Benefits | Costs and risks | Evidence | Result | -| -------- | --------- | --------------- | -------------------- | ------------------- | -|