Commit Graph
770 Commits
Author SHA1 Message Date
sam 40a35c9c52 feat(messaging): Messaging Service operator surface, chat report rendering, and the diff-cap config fix (#899)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.

* fix(gateway): render chat reports as lines, not one run-on paragraph

/status and /tasks are line-oriented reports, but their newlines were plain
"\n" -- CommonMark's soft wrap. The Telegram rich-block renderer space-joins
soft-wrapped lines, by design: a Telegram paragraph renders an embedded
newline as nothing at all, so a space is the only separator that survives.
The reports therefore arrived as one line each: "Runtime Provider: DeepSeek
Model: deepseek/deepseek-flash", and every task's title, state and park
reason jammed together.

The renderer now implements CommonMark's hard line break (two trailing
spaces, or a trailing backslash): the line closes its own block and the next
one hugs it, so a stanza keeps its lines without the spacer paragraph that
separates unrelated blocks. Ordinary prose is untouched -- a model's wrapped
paragraph still joins with a space. The producers mark their report lines
with it.

Two report fixes alongside:

- A park reason is capped to its first line at 160 runes. It carries whatever
  the failing stage reported, which for a lint gate is the whole tool log;
  unbounded, one parked task pushed every other task out of the reply. The
  full reason is still on the task.
- /status loses its "Runtime" sub-header. A section header over two fields
  made a four-fact report read like a document.

* fix(config): let diff_cap_lines = 0 actually switch the cap off

Config.DiffCapLines was a plain int, so the defaults pass could not tell an
absent key from an explicit 0 and rewrote both to 400. The dashboard schema
said "0 means unlimited" and StageDiffCap treated <= 0 as unlimited, but 0
never reached the step: the documented way to switch the cap off was
unreachable through config.

Same root cause, worse instance: configForIdentity assigned
root.DiffCapLines = identity.DiffCapLines unconditionally, so an identity
that simply omitted the key overwrote the shared cap with the zero value and
silently disabled the safety rail for that identity.

DiffCapLines is now *int on both Config and IdentityConfig -- nil is absent,
0 is no cap -- read through Config.DiffCap(). Defaults fill only nil, and an
identity overrides only when it set the key. TaskConfig keeps a resolved int,
so the daemon/agent wire format is unchanged and a version-skewed agent
cannot misread a null.

The park reason changes too. It told the operator to "approve manually", but
a parked task's actions are retry, abandon and reject (internal/taskstate):
there is no approve path out of diff-cap, so it sent them looking for a
button that does not exist. It now names the two things that work.

* feat(config): make the daemon's readiness dependency timeout configurable

The daemon's gateway probe bounded its call with a hardcoded 5s constant,
while every other NewContractProbe call site (archie-ui, archie-messaging)
passes the service's configured DependencyTimeout. It was the only magic
number among them.

[health].dependency_timeout carries it, defaulting to the same 5s the
extracted services' -dependency-timeout flag defaults to, so every process
bounds a probe into a dependency the same way out of the box.

It is not added to the dashboard config schema or the reloadable set:
[health] appears in neither today, health.listen included, and a probe
assembled at boot would not observe a reload anyway.
2026-09-20 00:32:13 +10:00
sam af74e93a20 feat(gateway): give /status a real daemon-health surface (#892)
* feat(gateway): give /status a real daemon-health surface

Phase 2 of archie-core-wp9s. Phase 1 split the commands apart (health vs
work) but left /status with one aggregate queue line and a static runtime
block; it could not answer the questions an operator actually asks when
something feels wrong. /status now reports, between the queue line and the
runtime block:

- Broker: the live state of this process's own NATS connection
  (eventbus/nats.Client.Connected), not a fresh dial -- a probe would
  report the probe's reachability, not the daemon's.
- Containers: the pool's own active counter against the configured cap
  (Pool.Active/Cap), not a Docker listing, which would include containers
  this pool does not own. A zero cap means unlimited, so it is not shown
  as a ratio.
- Channels: the channel manager's real lifecycle state, including a
  failed adapter's reason (the documented decision: read the existing
  manager rather than re-deriving health per adapter).
- Chat model: last-known outcome of every chat-model call this process
  made, recorded once in sendChatTurn (the single choke point) and read
  back by /status. The second documented decision: never a live probe,
  so /status stays instant and reports what happened -- or says plainly
  that nothing has been attempted yet.
- Last poll: when the most recent poll pass began, stamped on both poll
  paths (Run's single-identity loop and runIdentities' per-identity
  goroutines). A pass that hangs leaves the stamp stale, which is the
  signal; stamping completion would leave a wedged poller looking
  healthy.

Truthful or absent: a section this process has no source for is omitted
rather than rendered as a zero. The standalone Gateway owns no poll loop,
pool or channel manager, so its /status reports broker and chat-model
health only; aggregating across processes would need a new daemon RPC and
is deliberately not built. Version stays out (/version owns it).

/status and /tasks descriptions now describe what each command actually
does on both published surfaces (Telegram menu/help and the shared
specs), pinned by a test that also fails if the two surfaces drift.

Sources are read through functions, not captured values: occupancy and
channel state move, and the daemon is built after the gateways, so a
source captured at construction would freeze /status on boot state.

Left in place deliberately: the Runtime (provider/model) block, which
Phase 1 flagged and which duplicates /model and /whoami. Removing it is a
product call on a command Sam uses daily, not a mechanical follow-up.

* docs(prds): record the two open /status health decisions as settled

Both were flagged in PR #892 as needing the maintainer's call; both are now
answered, and the PRD is the place a follow-up would look:

- The Runtime (provider/model) block stays. It is the one line in /status the
  ticket's own rule says should not be there, but /status is read daily to see
  the active model at a glance, so the duplication is deliberate. Recorded as a
  settled product decision so it is not removed later as an oversight.
- Health stays per-process. Pooling the daemon's and the Gateway's chat-model
  outcomes would need a new daemon<->gateway health RPC for one status line, and
  a per-process line is true where an aggregate would be a claim about a process
  the answering one cannot see.

/agents' published description is still left to archie-core-mxls, unchanged.
2026-09-20 00:30:23 +10:00
sam af7a334599 fix(container): stop the reaper from deleting teardown bookkeeping early (#893)
The reaper's deferred forgetTeardown could delete a container's teardown
entry between the reaper's own claim and Release's later claim check.
teardownLocked then recreated a fresh, unclosed entry, letting Release
believe it still owned teardown and re-run ContainerStop/ContainerRemove.
Release is now the sole owner of deleting the entry, since it always
runs for every acquired container.
2026-09-20 00:20:31 +10:00
sam 0644d8291e Feat/q9au inline review comments (#895)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.

* fix(gateway): render chat reports as lines, not one run-on paragraph

/status and /tasks are line-oriented reports, but their newlines were plain
"\n" -- CommonMark's soft wrap. The Telegram rich-block renderer space-joins
soft-wrapped lines, by design: a Telegram paragraph renders an embedded
newline as nothing at all, so a space is the only separator that survives.
The reports therefore arrived as one line each: "Runtime Provider: DeepSeek
Model: deepseek/deepseek-flash", and every task's title, state and park
reason jammed together.

The renderer now implements CommonMark's hard line break (two trailing
spaces, or a trailing backslash): the line closes its own block and the next
one hugs it, so a stanza keeps its lines without the spacer paragraph that
separates unrelated blocks. Ordinary prose is untouched -- a model's wrapped
paragraph still joins with a space. The producers mark their report lines
with it.

Two report fixes alongside:

- A park reason is capped to its first line at 160 runes. It carries whatever
  the failing stage reported, which for a lint gate is the whole tool log;
  unbounded, one parked task pushed every other task out of the reply. The
  full reason is still on the task.
- /status loses its "Runtime" sub-header. A section header over two fields
  made a four-fact report read like a document.
2026-09-19 23:44:51 +10:00
sam 91769fa022 fix(ui,gateway): load the served lifecycle vocabulary, and make the page registry match the routes (#890)
* fix(ui): make the served lifecycle vocabulary actually load

base/task-meta.jsx documents the backend as the source of truth: /api/task-meta
returns the statuses (label, pill severity, "needs you") and the operator
actions, and loadTaskMeta() replaces the freeze-dried defaults with that
catalog. Nothing called it. Every pill, status filter and action control read
the snapshot, so a catalogue change on the server never reached the browser --
the module's first paragraph was simply not true.

main.jsx now asks for the catalog once at boot, alongside the capabilities read
it already does for the same reason: the shell paints immediately and upgrades a
moment later.

The two vocabularies the dashboard mirrors rather than serves -- FILE_STATUS
(ids owned by internal/domain/workflow/task/changes.go) and CONFIG_SCHEMA
(events.ConfigCapturedSchema) -- are now documented as the deliberate second
tier, with their two-sided pins named, so the tree stops telling two stories
about where a vocabulary comes from. Both degrade to a raw id or the verbatim
payload rather than rendering something wrong, which is why mirroring is
tolerable there and not for a presentation catalog.

RED before (loader never called):

    x booting the dashboard replaces the freeze-dried vocabulary with the served catalog
      actual: 'custom_status', expected: 'Custom status'

Also repairs a drifted LAW asset. A fresh build of pristine main dirties both
ui/dist/assets/index.css and index.js: 4c484887 (#889, memory unification slice
5) changed ui/src without rebuilding ui/dist, and task check runs task ui --
which repairs dist instead of verifying it -- so a stale dist is invisible to
the gate. Rebuilding here restores the invariant; a dist-freshness gate is filed
as follow-up.

* fix(ui,gateway): restore the search focus the port dropped, and the page registry truth

An adversarial review of the port (5787287e) found three things worth acting on.

1. Topbar search -- a regression the port introduced. The el() version focused
   the input when the narrow-layout toggle opened it, and blurred it after a
   successful jump; the port kept neither. That layout hides the field with
   width:0/pointer-events:none until .is-open or :focus-within, so without
   focus() the caret was not in the field the operator had just opened, and
   without blur() :focus-within left it expanded across the topbar after the
   jump. Both calls are back, with the ref they need.

2. dashboard_tools.go advertised a page that does not exist and omitted two that
   do. The registry calls itself "the single source of truth for what the
   dashboard exposes", but it is a hand-copy of the route table in
   ui/src/main.jsx: /memory stayed after the page was deleted (that deletion
   also left ui/dist stale -- archie-core-1vhh), and /bindings and /curators
   were never added. So the agent could hand the operator a chip to a route that
   now falls back to the dashboard, and could not answer "where do I go for
   playbook bindings?".

3. TestDashboardPagesRegistryCoversEveryRoute did not test that. It asserted
   three hardcoded paths and passed while the registry listed a deleted page. It
   now reads the route table back out of ui/src/main.jsx and compares in both
   directions, which is what makes the registry's claim holdable. RED before:

     route "/bindings" is a dashboard page the registry does not list, so the agent cannot point at it
     route "/curators" is a dashboard page the registry does not list, so the agent cannot point at it
     registry lists "/memory" (Memory), which is not a dashboard route: the agent would send the operator somewhere that does not exist

Also deletes the dead .chat-page rules the deleted chatPage() bridge left
behind: nothing renders .chat-page any more (chat.jsx renders
.chat-page-content, and the drawer sizes it from layout.css).

Not changed: the unreachable `soon` path, which predates the port and was
reported rather than acted on.

* fix(build): verify ui/dist is fresh instead of never looking at it

ui/dist is committed because the Go build embeds it, so it is a generated
source file. Nothing in the gate read it: task check does not run task ui, and
nothing else compares the bundle with ui/src. So when 4c484887 (#889) changed
ui/src without rebuilding, the committed bundle went on serving the Memory page
whose source had been deleted -- with the gate green throughout.

task ui:check (tools/uidist.sh) rebuilds into a temporary directory and compares,
never rewriting the committed artifact. That is the rule docs:check already
states for the contract reference -- a gate that silently rewrote the artifact
would bless an unintended change with no reviewer ever seeing it -- and it
matters more now that several agents work in their own worktrees, where each
could otherwise pass while producing a different bundle.

Evidence:
  fresh tree                            exit 0, matches
  hand-staled bundle                    exit 1, names the differing file
  the #889 drift replayed               exit 1, names BOTH index.css and index.js
  (pre-#889 bundle, post-#889 sources)
  git status after a run                unchanged: the check never writes ui/dist

Cost: ui:check declares ui:deps like ui and test:ui do, so the gate runs npm
install once per dependent. Task's sources/generates up-to-date check does not
apply to a node_modules directory (measured: it ran on every invocation), so the
target does not claim otherwise; guarding that is follow-up work.

Gate: task check exit 0, UI suite 230/230, all Go packages ok.

* fix(ui): make the served vocabulary reach an already-painted page

Greptile's finding on the first cut of this fix, and it was right: loadTaskMeta()
resolves after a page has painted and only mutated module state. The route tree
renders into its own root, so App re-rendering cannot reach it, and a painted
page kept the freeze-dried labels it read on the way up.

show() is split so the page render can be repeated on its own: renderRoute()
mounts the current route into the outlet without the teardown/chrome side
effects, and the catalog effect calls it once the catalog lands. The key is
unchanged, so Preact re-renders the mounted page in place and keeps its state.

Deeper instance of the same defect, found while fixing that one:
task-filters.jsx captured the vocabulary in module-level constants at import
(ATTENTION_STATUSES/TASK_STATUSES), so the task filter could never see a served
status, no matter when or how correctly the catalog landed. Both are read at
call time now.

Tests, and what they actually cover:
  - the task-filter test has teeth: with the source fix stashed it fails, with
    the fix it passes.
  - task-meta-late-catalog.test.js guards the boot fetch end to end (it fails
    when loadTaskMeta is never called), but it does NOT isolate the re-render:
    a page also re-renders for its own reasons, so the assertion holds without
    renderRoute too. Said plainly here rather than implied as coverage -- the
    fix makes the re-render deterministic instead of incidental, and this
    harness cannot tell those apart.
  - it lives in its own file because main.jsx boots once per process; a second
    test in the same file would assert against a detached tree.

UI suite 232/232, task check exit 0.
2026-09-19 23:38:19 +10:00
sam 4750ac097b feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00
sam 74682465ca chore(plugin): delete the unwired capability-host health surface (#882)
* chore(plugin): delete the unwired capability-host health surface

plugin.Host.Health, plugin.Host.Manifests, ModuleStatus and their private
safeHealth helper were implemented, exhaustively tested, and called from nowhere
but their own tests. AGENTS.md forbids speculative surfaces, and no settled
design places plugin module status anywhere that exists:

- docs/prds/status-health-surface.md Phase 2 is self-described as "a proposed
  resolution, awaiting Sam's sign-off -- not yet implemented", and does not
  mention plugin status even in that unapproved list.
- The readiness subsystem enumerates exactly five probes -- state_db, config,
  disk, model, gateway (internal/app/archied/readiness.go) -- with no plugin
  probe.
- docs/architecture/plugins-and-extensions.md names no operator-visible plugin
  status surface.
- The only bead naming it is closed.

plugin.Host itself stays: it is the daemon's live capability host, constructed
and Start/Stop-ed from internal/app/archied. Only the unconsumed observability
methods go.

host_contract_test.go encoded the defect -- it asserted plugin.Host *defines*
"Health" and "Manifests" -- so those two names are removed from its list, which
is now exactly the shipped lifecycle: Register, Start, Stop. The three tests
covering the deleted surface are removed with it.

The Yaegi symbol table (internal/plugin/pluginextract) was regenerated rather
than hand-edited, so ModuleStatus leaves the reflected type set with it.

Reachability evidence: Host.Health and Host.Manifests appear only in their own
tests; plugin.Host is otherwise reached from bootstrap.go and gateway.go for
Register/Start/Stop. Note that "task reachability" does NOT flag these -- the
address-taken constructor is a known blind spot of the whole-program RTA.

* chore(plugin): delete the dead Module.Health chain wired to nothing

Extends the capability-host observability deletion: plugin.Module.Health
was a required interface method with real implementations in
tools/provider/mcp and tools/provider/builtin, aggregated by
tools/provider.Registry.Health via a provider-package-local safeHealth,
and backed by per-module LifecycleState bookkeeping in plugin.Host
(registeredModule.state, setModuleState). None of it had a caller before
this change -- Host.Health was the only thing that would ever have read
a registered module's Health(), and Host.Health was already deleted as
unreachable. registeredModule.state was write-only: nothing ever read it.

Deleted:
- plugin.Module.Health, plugin.Health/HealthStatus (+ consts),
  plugin.LifecycleState (+ consts), legacyModule.Health,
  registeredModule.state, Host.setModuleState and its call sites.
- tools/provider.Registry.Health, tools/provider.safeHealth.
- tools/provider/mcp.Provider.Health, tools/provider/builtin.Provider.Health.
- Tests exclusively covering the above, and fakes' now-unnecessary Health
  methods (plugin/host_test.go, pluginextract/reachability_test.go,
  tools/provider/{provider,optional}_test.go, tools/provider/mcp/provider_test.go,
  app/agentworker/mcp_providers_test.go).

internal/plugin/pluginextract's generated file was regenerated via
`go generate ./internal/plugin/...` and the yaegi wrapper nil-guards
(dropped by fresh generation, as documented in reachability_test.go)
were reapplied by hand to WManifest/WStart/WStop/WName/WVersion,
following this repo's established post-regen pattern.
2026-09-19 14:10:39 +10:00
sam 4c4848878f chore(memory): delete internal/memory (unification slice 5) (#889)
Deletes internal/memory (Manager, builtin.Provider, memory_edit tool) now
that slices 2-4 built the CRUD engine family and its per-turn read/write
seams. Also deletes internal/infrastructure/memory/builtin/provider.go (the
memory_edit adapter over the old package -- its markdown store already
relocated in slice 2), internal/tools/provider/memory (the old tool
registration, redundant with slice 4's memory_create/update/delete/list),
config.Memory.{Provider,ProviderConfig} and the validateMemory rejection
that existed only to complain about Provider, and webui.MemoryStatus/
MemoryProviderHandle plus its dashboard page -- never wired in production
(s.Memory was always nil), confirmed by /api/capabilities always reporting
"memory": false.

Rewrites ARCHITECTURE.md's "Memory engine family" section to describe the
current engine (internal/domain/memory contract, internal/infrastructure/
memory builtin engine + its builtin/ markdown store, the per-turn read seam
in gateway/turn_memory.go, the per-turn write tools in
gateway/turn_memory_tool.go) instead of the deleted Manager. Fixes two
docs/architecture/configuration.md rows that described the deleted
manager's literals and SaveConfig mechanism.
2026-09-19 13:43:16 +10:00
sam 5d04bea3d4 feat(gateway): chat memory write path (unification slice 4) (#888)
Build a per-turn memory tool set (memory_create/update/delete/list) onto
the turn's resolved Subject, matching slice 3's read-side scope model.
The model picks a scope KIND from an enum built off Subject.WritableScopes()
(never global); the agent and user ids a scope resolves to come from the
turn's Subject, with no schema field either could ever land in. A subject
with no writable scope, or a nil write store, gets no memory tools at all.

TurnRunnerConfig gains MemoryWriter (MemoryWriteStore: Create/Update/
Forget/List), wired alongside the existing MemoryEngine read surface
through the same active engine (boot.activeMemoryEngine, narrowed by
memoryStore/memoryWriter).
2026-09-19 12:59:11 +10:00
sam c6b4fe237f fix(gateway): enforce per-scope memory quota and escape-aware byte cap
Greptile review on #887 (slice 3, merged):

- BuiltinEngine.Query bounds Limit across the whole result, not per scope
  it is given. renderMemory passed one Limit for all of subject.Scopes()
  combined, so an early scope (agent-user, queried first) could exhaust
  the whole budget and starve later, wider scopes. Now queries each scope
  separately, each capped at memoryRecordsPerScope.
- memoryBlockByteCap was checked against each line's raw size, but
  BuildSystemPrompt's {{xml .Memory}} escapes &/</> afterward, expanding
  a byte up to fivefold. The cap is now measured against the escaped
  size (escapeXML, extracted from prompt.go's template func) while the
  block itself still accumulates raw lines, since the template escapes
  once on render -- escaping here too would double-escape it.
2026-09-19 11:46:05 +10:00
sam f8d6ea33e5 feat(gateway): chat memory read path (unification slice 3) (#887)
Wires the durable-memory engine into the chat turn: prepareTurn resolves a
per-channel Subject (BotUser as AgentID, TurnRunnerConfig.UserIdentity for
the user), runs a scope-only Query over Subject.Scopes(), and renders the
result into a new <memory purpose="durable_context" trust="data"> block
between <tools> and <env>, following the same untrusted-data framing as
those two blocks. The read is synchronous, total, and never surfaces an
error: a nil engine, a failing Query, or a panicking provider all degrade to
no memory block (recovered in gateway.renderMemory).

UserIdentity is supplied per channel by the composition
(userIdentityResolver in internal/app/archied): telegram and email resolve
their native SenderID, the dashboard ("web") and webhook resolve nothing, so
a webhook's route-path SenderID can never become a user identity and the
dashboard's shared bearer token can never impersonate a person.

Fixes the composition-ordering bug that left every turn runner holding a nil
memory engine: setupMemoryAll now runs before setupGateways in main.go, and
before setupGatewayChat in gateway.go's startGatewayRuntime, so
boot.memoryStore() has a live engine at every turn-runner construction site.

Named constants bound the read: memoryRecordsPerScope per scope, and
memoryBlockByteCap on the rendered block, which drops (and logs) trailing
records rather than truncating one mid-line.
2026-09-19 11:40:45 +10:00
sam 7244f9ea1f feat(memory): four-scope contract and builtin engine CRUD (unification slice 2) (#886)
* feat(memory): four-scope contract with CRUD and revisions

Seam for memory unification slice 2 (docs/prds/memory-engine-unification.md
§1, §2, §7): internal/domain/memory is now a scope-addressed CRUD contract.

- Scope{Kind,Agent,User} with the four ratified kinds, Validate rejecting a
  component present where it is not required, and a length-prefixed Key so
  opaque channel-native ids cannot collide.
- Subject{AgentID,UserID} with Scopes()/WritableScopes(): global is never
  writable, and an absent user id removes every scope requiring one.
- Store becomes Create/Get/Query/List/Update/Forget/Revisions over
  NewRecord/RecordUpdate/Record/Revision, with ErrNotFound/ErrStaleRevision.
  Observation, Identity and Metadata are deleted.
- The content scanner moves into the family (internal/domain/memory) so every
  engine applies it in Create and Update; internal/memory re-exports the types
  until slice 5 deletes it.
- The markdown store moves to internal/infrastructure/memory/builtin, its
  correct home per organisation.md.

WIP: internal/infrastructure/memory and internal/infrastructure/sessioncurator
are converted in the lanes that follow this commit.

* feat(memory): builtin engine CRUD, retained revisions and the curator's agent-user write

Slice 2 implementation (docs/prds/memory-engine-unification.md §1, §2, §6,
§7), on top of the contract seam in the previous commit.

- internal/infrastructure/memory: per-scope markdown heads with a JSON
  provenance marker, per-scope HISTORY.md retaining superseded and deleted
  states, Update superseding before replacing the live block, ErrStaleRevision
  via RecordUpdate.Expected, idempotent Forget, and the family scanner applied
  in Create and Update. Scope directories are hex(sha256(Scope.Key())).
- internal/infrastructure/sessioncurator: the participant is derived from the
  session's user-role senders; exactly one writes agent-user scope, zero or
  several write nothing and return ActionSkipped naming the count.
- docs/architecture: the settled decision recorded in migration-decisions §5
  (superseding the 2026-09-02 marker entry) and agent-system.md pointing at it.

Draft: to be squashed and reviewed before publication.

* test(curator): conform the registry's fake memory engine to the CRUD contract

The fake still implemented the pre-CRUD Store surface (Write taking an
Observation, List/Forget keyed by a bare string), so the package's test
binary no longer compiles: fakeMemoryEngine is missing Create, Get, Update
and Revisions, and domainmemory.Observation no longer exists. That took
`go fix ./...`, `go vet ./...` and `go test ./...` down with it, which is
what `task check` runs first.

Missed by the same commit that updated internal/infrastructure/sessioncurator's
own fake to the new interface. Repaired on the fake, not by loosening the
interface: the fake is the only thing out of date.

* fix(sessioncurator): refuse to attribute a session with unidentified user messages

sessionParticipant skipped user-role messages with an empty SenderID and
counted only the identified ones, so a session holding one identified sender
plus any number of unidentified user messages yielded that sender as the
single participant. Those messages are still part of the excerpt the
extraction model reads, so facts derived from content of unknown provenance
were written into the identified sender's agent-user scope: user A's memory
can end up crediting content that may belong to someone else. It is exactly
the case the function's own doc comment claims to handle, which it only
caught when no message at all was identified.

An unidentified user message now makes the session unattributable outright,
beside any number of identified senders, and the skip action's reason names
the count instead of reporting a sender count that no longer explains the
skip. Assistant-role messages are unaffected: they carry the bot, so they
still cannot manufacture a participant.

Fixed in sessionParticipant rather than at the write, because it is the
single producer of the attribution decision: it now returns the participant
or the reason there is none, so the caller cannot print a reason that
disagrees with what it decided. The fail-closed path (nothing written, one
ActionSkipped) and the extraction flow are unchanged.

* fix(memory): carry record content through the block format intact

builtin.Store's format ends a block at a blank line and starts a section at a
"## " line, but storeContent only trimmed the content and rejected an empty
one. Content holding either delimiter was accepted, written, and answered back
to the caller in full -- then read back truncated at the delimiter by Get,
List, or a process restart, with the remainder unaddressable and no error
anywhere along the path.

Fixed at the producer, in the render/parse pair that owns the block format:
renderBlock escapes the two delimiter shapes (an empty line becomes a single
backslash, a line already starting with a backslash or "## " gains one) and
parseBlocks undoes it on the way back, so a record's content survives the
write whole. Rejecting the content instead would have made an ordinary
multi-paragraph note or a quoted heading unrepresentable; escaping every line
would have changed the on-disk shape of every record. Only the lines that need
it are escaped, so a one-paragraph record is byte-identical to what the
unfixed engine wrote and the document stays hand-editable.

Reachable from both producers: the chat tool's note and the curator's
model-extracted fact are free text, and neither is constrained to one
paragraph.

Tests: TestBuiltinEngineRenderedBlockRoundTripsContent asserts
parseBlocks(renderBlock(c)) == c for eleven content shapes, and
TestBuiltinEngineContentSurvivesTheWriteAndAReopen carries the same shapes
through Create, Get, and a second engine reading the file a restart would.

* fix(memory): compare Update's expected revision against the file, not the cache

Update read the record to compare against out of findBlock(stores.live, ...)
-- the engine's cached copy of the scope document -- and checked Expected
against that copy. This engine caches one document per scope and rewrites it
whole, so a second engine over the same scope file (archied and the gateway,
or a restart) holds a copy taken when it last read the file: its view of the
record's revision is superseded, Expected matches the revision it remembers,
ErrStaleRevision never fires, and the rewrite that follows writes that stale
copy back over the file -- discarding the other writer's update and every
record written since the copy was loaded. The field existed and could not
fire.

Reload the scope document before anything is decided from it, so the check
answers about the revision actually on disk and the rewrite starts from the
current document. That is the smaller of the two fixes the PRD leaves open
("Not determined": a reload-before-mutate or an advisory lock); no locking
scheme, no retry loop, and no change to the read paths.

Still unsolved, and deliberately: the whole-document rewrite is
last-writer-wins between the reload and the write, so two engines writing one
scope concurrently can still lose one of the two writes, and HISTORY.md is
rewritten from the cached copy the same way.

Tests: TestBuiltinEngineSecondEngineCannotReuseAStaleRevision asserts the
second engine gets ErrStaleRevision and the first writer's state survives;
TestBuiltinEngineUpdateDoesNotEraseRecordsItHasNotLoaded asserts the record
written after the second engine loaded is still there after its update.

* fix(memory): emit the scanner's warning instead of dropping it

scanContent returned nil for every result that was not ThreatBlock, so a
ThreatWarn result -- documented in the scanner as "allow the write but emit a
warning", and what every sensitive-data match produces (API keys, passwords,
tokens, private keys) -- was stored with no audit signal anywhere. The
comment justified the silence by pointing at Bind, but Bind's argument is
about Registrar.Events: internal/events declares no memory kind and the
composition binds no memory event sink, so an invented kind would look wired
and not be. A scanner warning is a diagnostic rather than an event, and there
was nothing else to carry it: the registrar had no logger.

Bind now takes Registrar.Log, optional and mirroring the curator family's
Registrar for the same reason, scanContent emits the warn-level result
through it before the write is allowed, and bootstrap passes the daemon's
logger so the line reaches archied's configured sinks instead of only the
process default. The write is still allowed: only the silence changed.

Tests: TestBuiltinEngineScanWarnsWithoutRefusingTheWrite runs Create and
Update over warn, clean and block content, asserting the write lands either
way, that a warn-level scan result logs exactly one warning carrying the
scanner's own message, that clean content logs none, and that a refused
block-level match logs none.

* test(memory): carry every content shape through Update and Revisions

Update replaces the block it read out of the document by that text, and
retains the superseded state in HISTORY.md, so an escaped block has to be
found, superseded and retained exactly like an unescaped one. Covered here
rather than left to the Create path: without the escaping, every shape in
this table came back truncated after an update, including the plain
one-paragraph record whose replacement holds a blank line.

The test asserts values only: the updated record as a second engine reads it
off disk, and the superseded content as Revisions returns it.

* style(memory): apply the linter's gofumpt form to the Update revision error

golangci-lint's bundled gofumpt wants the closing paren of that wrapped
fmt.Errorf on its own line; the standalone gofumpt binary the fmt task uses
(0.7.0, a different version) leaves it as it was. The text is unchanged from
before the engine fixes in this branch, so this is pre-existing drift inside a
function these commits already touch -- taken so the file is clean under both
formatters rather than only one.
2026-09-19 11:13:21 +10:00
sam 3773856c70 feat(workintake): authorize review reactions by owned PR 2026-09-19 10:46:18 +10:00
sam 15d2b86535 feat(workintake): define review reaction envelope 2026-09-19 10:46:18 +10:00
sam e26001082b Merge pull request #881 from samcharles93/fix/daemon-sweep-budget-diagnostics
fix(daemon): name an exhausted sweep budget as the cause
2026-09-19 03:38:55 +10:00
sam becc2fc698 fix(daemon): don't call a cancelled startup a spent sweep budget
ctx.Err() is non-nil for a parent cancellation as well as for the sweep
budget, so SIGINT/SIGTERM during the boot sweep logged "sweep budget
exhausted" with err="context canceled" -- an expected shutdown reported
as a failed sweep (Greptile P2 on #881).

Attribute on this sweep's own context instead: DeadlineExceeded is the
budget, any other non-nil context error means the startup was cancelled,
and neither is a repo access failure. A forge's own request timeout,
with the sweep context still live, still reports per repo.

RED before (cancelled parent, three repos):

    budget warnings = 1, want 0
    level=WARN msg="push check abandoned: sweep budget exhausted" repo=acme/one err="context canceled"
2026-09-19 03:10:46 +10:00
sam c4349deaac fix(config): clone the Services map so an overlay cannot mutate the published snapshot
Config.Clone deep-copies every reference-type field except Services, which became a
map[string]ServiceConnection. A value copy shares the map header, and yaml.Unmarshal
writes keys into whatever map it is handed -- so Loader.ApplyOverlay, which clones
precisely so it cannot corrupt the base document, rewrote the published snapshot in
place:

  ApplyOverlay(doc, {"services": {"state": {"target": "10.0.0.5:9090"}}})
  left doc.Config.Services["state"].Target changed

That defeats the reason Clone exists: a failed or partial overlay must not alter the
configuration still being served.

Red: TestConfigCloneDeepCopiesReferenceFields failed with "Services map is shared"
after the case was added; green with the one-line clone.
2026-09-19 03:07:14 +10:00
sam 79e39ecf16 fix(config): stop a partial overlay clearing the fields it omits
An overlay or dashboard PATCH naming only some fields of a map-valued config entry
silently zeroed the rest. For [services.<name>] that meant losing the bearer token,
so changing a State Store endpoint dropped its authentication:

  start   Services{"state": {Target: "127.0.0.1:50051", TargetToken: "secret"}}
  overlay {"services": {"state": {"target": "10.0.0.5:50051"}}}
  result  Services{"state": {Target: "10.0.0.5:50051", TargetToken: ""}}

Cause: ApplyOverlayValues did yaml.Marshal(overrides) then yaml.Unmarshal into cfg.
yaml gives a struct FIELD the field-level treatment the doc comment promises, but a
map VALUE is decoded into a fresh zero value, so an entry the overlay only partly
addresses loses every field it does not name. That contract was written when
Services was a struct; making it map[string]ServiceConnection changed the behaviour
underneath it.

Fix at the producer: fold the fields the overlay omits forward out of the entry cfg
already holds, so the decoder is handed a complete entry. Recursion follows the
destination type, so the promise now holds for every map of structs -- services,
image.hosted, image.local and providers -- in one place instead of at each field's
reader. Struct field-level merge, scalar-valued map-key merge and slice replacement
are unchanged, and overrides is read, never mutated.

The regression test also converts to the map form, which is what unbreaks the build:
apply_test.go still built Services with the struct form after services.go became a
map, and because the two live in different files the breakage merged cleanly. There
is no Go build or test CI, so nothing compiled it.

Red: four cases failed with the token, the target and the sibling fields zeroed.
Green after the fold.
2026-09-19 03:07:14 +10:00
sam c94986cf38 Merge pull request #878 from samcharles93/feat/attempt-attribution
Feat/attempt attribution
2026-09-19 02:48:25 +10:00
sam 3dc0c4eea4 Merge pull request #879 from samcharles93/fix/docs-ci-and-overlay-coverage
fix(ci): unbreak the docs workflow, and cover nested config-overlay merge
2026-09-19 02:41:37 +10:00
sam 9bdf999b85 fix(daemon): name an exhausted sweep budget as the cause
sweepAccess spends one sweepTimeout budget on a forge's whole boot
sweep. When that budget ran out mid-loop, every remaining repo was
warned as "repo not pushable -- tasks from it will fail" -- asserting
that access had been denied when all that was known was that the
deadline passed, once per repo.

Report the budget once, name it as the cause, and stop: later calls
return the same deadline error, so continuing only multiplies a
misleading warning.

RED before (three repos, budget exhausted by the first):

    VerifyPush calls = 3, want 1
    "sweep budget exhausted" logged 0 times, want 1
    level=WARN msg="repo not pushable  --  tasks from it will fail" repo=acme/one err="context deadline exceeded"
    level=WARN msg="repo not pushable  --  tasks from it will fail" repo=acme/two err="context deadline exceeded"
    level=WARN msg="repo not pushable  --  tasks from it will fail" repo=acme/three err="context deadline exceeded"
2026-09-19 02:31:28 +10:00
sam dcb56ecc88 test(daemon): prove a stalled forge cannot block a sibling sweep
sweepAccess sweeps each forge in its own goroutine, but nothing pinned
that: the table test asserts coverage, not ordering, so the sweep could
be made sequential again without a failure.

The test stalls the root forge in AcceptInvitations and asserts the
sibling identity is swept while it is still blocked, then that Startup
returns once the stall is released. Verified RED against a sequential
sweepAccess (times out waiting for the sibling) and GREEN against the
goroutine-per-forge implementation.
2026-09-19 02:28:20 +10:00
sam 9373596188 Merge pull request #873 from samcharles93/fix/restart-command-wiring
fix(chat): remove unreachable Telegram-router restart wiring
2026-09-19 02:25:52 +10:00
sam 9f4eae5f74 Merge pull request #874 from samcharles93/fix/per-identity-boot-sweep
fix(daemon): sweep the root forge and every identity at startup
2026-09-19 02:25:27 +10:00
sam 49f7157d50 fix(ci): stop the docs workflow failing on a missing pip manifest
.github/workflows/docs.yml runs actions/setup-python@v6 with cache: pip. That
option hashes a requirements.txt or pyproject.toml to build the cache key and
fails outright when neither exists:

    ##[error]No file in ... matched to
            [**/requirements.txt or **/pyproject.toml]

This repository is Go and has no Python manifest, so the step failed as the
first step of every run triggered by the workflow's pull_request paths: docs/**
filter. mkdocs build --strict therefore never executed: docs changes were not
being verified, and every docs-touching PR was reported as a build failure. It
only surfaced on #878 because #878 touches docs/architecture/; PRs that do not
touch docs report no checks at all.

Drop cache: pip. The only Python use is a single `pip install mkdocs-material`,
so there is nothing worth caching.
2026-09-19 02:24:37 +10:00
sam d450f0f8e1 Merge pull request #875 from samcharles93/feat/archie-reactions-stream
feat(nats): provision the ARCHIE_REACTIONS fan-out stream
2026-09-19 02:22:29 +10:00
sam a2598299ba fix(chat): remove unreachable Telegram-router restart wiring
Review fix for PR #873. The previous attempt wired Router.Restart on the
Telegram router, but that path is unreachable: telegram.go:260 registers an
exact-match /restart handler (restartHandler, restart.go:24) which consumes the
update before the chat router is reached.

The wiring was therefore a false affordance: it made the Telegram router report
RestartAvailable: true for a callback no production path invokes, and the test
only passed because it assembled a LocalChatAdapter by hand rather than driving
the composition production uses.

Remove it. Telegram's own restartHandler remains the sole path to
RequestRestart. The removals of boot.restartTelegram and
telegramSetup.RegisterRestart stand: those were written and never read, which is
the real defect (channels-telegram-3).

Tests are retargeted and table-driven: buildTelegramRouter leaves Restart nil
with and without an adapter (regression guard against re-adding the unreachable
wiring), the router's /restart route reports not-configured, and
RequestRestart's queue-then-reject contract is pinned at the adapter level.

This deliberately does NOT fix dashboard /restart: the web router runs in the
archie-gateway process while the Telegram adapter runs in archied, and no
gateway->daemon restart RPC exists. That needs its own design (see the bead
referenced in the PR body).
2026-09-19 02:17:59 +10:00
sam 36cf7c4cd4 fix(nats): bound the ARCHIE_REACTIONS stream by age
Review fix for PR #875. ARCHIE_REACTIONS is provisioned under LimitsPolicy,
which retains every message until a limit is reached. With no limit configured,
acknowledged reactions accumulated without bound and continuous traffic could
grow the stream until it exhausted disk.

nats.Config gains MaxAge *time.Duration, using the same pointer form as
Retention so "unset" (nil) is distinguishable from an explicit zero. It is
applied to the stream config only when set, so every existing caller keeps its
current behaviour.

ARCHIE_REACTIONS sets MaxAge = 24h. A reaction is a producer-only wake event
whose authoritative state is re-read at pass time, so a dropped reaction delays
work until the next poll (default 60s) rather than losing it; 24h tolerates a
consumer down for a full maintenance window and matches the package's existing
DefaultInactiveTTL.

ARCHIE_TASKS is deliberately left unbounded. It uses WorkQueuePolicy, which
discards a message on acknowledgement, so its size is bounded by outstanding
work; a limit there could discard a task that has not been delivered yet, which
is a worse failure than the disk risk. The table asserts that non-change.
2026-09-19 02:16:38 +10:00
sam 7e9348b05b Merge pull request #876 from samcharles93/fix/flaky-ui-shutdown-deadline
fix(archieui): exit cleanly when graceful shutdown overruns its deadline
2026-09-19 02:13:59 +10:00
sam 9777125937 test(archieui): make the shutdown regression test table-driven and bounded
Review fixes for PR #876. The production fix is unchanged; this reworks only
the test.

- Bound the wait for the handler-start signal and select on the request
  goroutine's error and on an early serve() exit, so a request that never
  reaches the handler fails promptly instead of hanging until the package-wide
  timeout.
- Restructure into a table, per AGENTS.md:256 / CLAUDE.md:256 ("table-driven
  tests against target behaviour"): a request that drains within
  ShutdownTimeout returns nil, and a request still in flight when it elapses is
  force-closed and still returns nil.

The overrun row was verified to fail against the previous
"return server.Shutdown(shutdownCtx)" and to pass against the approved
force-close. Both rows hold the request in flight deterministically, so no case
depends on machine load.
2026-09-19 02:12:27 +10:00
sam 788f698047 fix(daemon): sweep the root forge alongside every identity
The per-identity sweep skipped the root forge and root repo list whenever
[[identities]] was configured, on the reasoning that Run never polls them
there. Polling is not the only way a task reaches a repo: dispatchBinding
enqueues with an empty identity, resolveBindingRepo falls back to the root
repo list, and forgeFor/repoFor resolve an empty identity to the root forge
and root repos. Root targets stay reachable in multi-identity mode, so they
stay worth verifying at boot.

Collapse both sweeps into one sweepAccess path over the root plus every
identity. Each forge is swept in its own goroutine under its own deadline:
Startup gates the gateways and the run loop and a forge client carries no
request deadline, so warning on a failed sweep isolated a failing sibling
but not a stalled one.

Test is table-driven over single-identity, multi-identity, and an identity
with no repos.
2026-09-19 02:00:23 +10:00
sam 4ae14a4ddd docs(messaging): correct the Sender field's role-discrimination claim
Message.Sender's doc comment asserted "role discrimination uses Role, never this
field", which the code contradicts: at the gateway wire boundary Role is
deliberately dropped and rebuilt from Sender via RoleForSender, and the wire
carries no role field at all.

The comment was wrong, not the code. gatewayrpc already documents the design
(values.go:28, server.go:152 -- "The wire carries no role; both sides derive from
... messaging.RoleForSender"), and RoleForSender's own comment states the rule.
Only the Sender comment disagreed, so it is corrected to say that Role is
authoritative in-process while Sender is preserved for the wire reconstruction,
history search, and transcript rendering.

Resolves .local/issue-tracker messaging-2. Doc-only: no behaviour change.
2026-09-19 01:53:52 +10:00
sam b1a8a9a9da fix(archieui): exit cleanly when graceful shutdown overruns its deadline
The gate failed intermittently with "task: Failed to run task \"test\": exit
status 1" and a tailed log that hid the failing package. The package was
cmd/archie-ui, which sorts before internal/logging and so never appeared in the
visible tail.

Cause: serve() returned the error from server.Shutdown, which is
context.DeadlineExceeded whenever a request is still draining when
ShutdownTimeout elapses. That converted a normal load-induced overrun into a
non-zero process exit, and TestUIProcessServesTheDashboardAgainstLiveDependencies
asserts a clean exit after SIGTERM.

Fix at the producer, in serve(): on overrun, force-close the remaining
connections and report a clean shutdown. No timeout is lengthened, no retry,
skip or -p 1 is added, and the smoke test's assertion is untouched.

Reproduced under parallel build load: -count=30 on the suspect test produced the
exact shutdown-deadline signature once; after the fix, 30/30 pass with zero
occurrences. The new test drives the deadline path deterministically by holding
a request in flight rather than relying on machine load.
2026-09-19 01:51:11 +10:00
sam 0ee2b8a1cf feat(nats): provision the ARCHIE_REACTIONS fan-out stream
archie.reaction.* had no matching stream. bootstrap.go:501-502 bound only
ARCHIE_TASKS to archie.task.> under WorkQueuePolicy, so any publish to a
reaction subject made js.PublishMsg fail and the publisher saw a publish error
-- the reason a previously landed reaction producer would have answered HTTP 500
on every webhook delivery.

ARCHIE_TASKS must stay WorkQueuePolicy: under it a second consumer on an
overlapping filter subject silently receives nothing, which is the trap recorded
in CLAUDE.md. Reactions need the opposite property, so they get a second stream:

- workintake.SubjectReactionWildcard ("archie.reaction.>")
- nats.DefaultReactionStreamName ("ARCHIE_REACTIONS")
- nats.FanOutRetention(), a pointer helper so composition can select
  LimitsPolicy without importing the NATS SDK, since nil Retention already means
  WorkQueuePolicy and the zero value (LimitsPolicy) is a valid explicit choice
- a second nats.Connect in connectNATS carrying that stream, closed on failure
  and registered for shutdown cleanup

Red-then-green: TestConnectNATSCreatesReactionStream failed with "publish to
archie.reaction.* = nats: no response from stream, want it to land in
ARCHIE_REACTIONS" before the stream existed.

Step 1 of docs/prds/pr-review-remediation.md (bead archie-core-8li9.1).
2026-09-19 01:51:07 +10:00
sam 8ffa6ffb51 fix(daemon): sweep every identity's forge and repos at startup
daemon.Startup ran the invitation sweep and push verification only against the
root forge and Cfg().Repos. In multi-identity mode Run branches to
runIdentities, where each identity polls its own forge and its own repo list --
so per-identity invitations were never accepted and per-identity repos were
never push-verified. A task from those repos failed later at dispatch instead of
warning at boot.

Startup now branches on len(d.Identities) and sweeps each identity through
sweepIdentity, which reuses id.Forge and id.Repos -- the same IdentityRunner
fields runIdentities and pollForIdentity already iterate, so there is no second
identity-to-forge mapping. One identity's forge outage cannot abort a sibling's
sweep: failures are logged as warnings, matching Run's stated failure-isolation
intent.

Red-then-green: TestStartupSweepsEveryIdentityForgeAndRepos failed with
"identity one AcceptInvitations = 0, want 1" (and both identities' repos empty)
before the change.
2026-09-19 01:51:03 +10:00
sam fe8d64cc9f fix(chat): wire the Telegram adapter restart callback into the chat router
/restart could never work in production. boot.setupGateways captured the
Telegram adapter's restart callback into boot.restartTelegram, a field no code
ever read, so gateway.Router.Restart was nil in every composition:
handleRestartAdapter always answered "not configured" and LocalChatAdapter's
snapshot always reported RestartAvailable: false.

Fix at the producer: buildTelegramRouter assigns Router.Restart directly from
the adapter it already holds. The dead field and the telegramSetup.RegisterRestart
indirection are deleted rather than kept alive.

Red-then-green: TestBuildTelegramRouterWiresRestartCallback failed with
"router.Restart = nil, want the telegram adapter restart callback wired into the
router" before the change. TestBuildTelegramRouterRestartUnconfigured pins the
unchanged no-adapter behaviour, including the not-configured reply.
2026-09-19 01:50:41 +10:00
sam 42bfd35514 fix(config): enforce the service context at registration
ServiceSpec.Context documented which addresses a service must end up with, but
nothing read it, so a typo'd context was accepted and meant nothing. Review
caught it as scaffolding that looked load-bearing.

RegisterService now validates it: an unknown context, or a hosted (server/both)
service registered with no default listen address, panics. Registrations come
from this repository's own init(), never from operator input, so an invalid one
is a programming error with no caller positioned to handle an error return, and
failing at process start beats a service binding where nobody dials.

Services.RequireTarget replaces the same check and message hand-written in
composeStateStoreClient and composeChatContract. An empty registered default
target is what declares a target operator-supplied, so the requirement belongs
to the registry rather than to each consumer. It stays a lazy check at
composition time rather than becoming load-time validation: a process that
never dials a service must still load a configuration that omits it.

The review's stated failure mode does not occur. A hosted service with an empty
listen does not reach net.Listen as an ephemeral port; resolveServiceListen
returns "no listen address" and archied refuses to start. The defect was the
inert field, not a silent bind.

Refs: archie-core-u23g
2026-09-19 01:50:25 +10:00
sam 5e15bfd07a Merge pull request #870 from samcharles93/fix/label-routing-and-triage-criteria
fix: restore kind routing for namespaced labels, and give triage real criteria
2026-09-19 00:35:05 +10:00
sam fe7ee44dcc fix(workflow): require a workflow from triage when a code change is needed
The selection criteria alone left workflow optional and defaulted an omitted
or unrecognised value to implement, so a decide call could still skip the
decision and send an unsettled capability straight to the builder.

Omission is now a retryable rejection: CaptureTool gains RequiredWhenTrue, a
conditional requirement a flat RequiredFields entry cannot express, because
the close-without-change branch has no workflow to name and must not be made
to invent one. A rejected call is not recorded, so it does not consume
MaxCalls and the model retries with the field.

A value outside the enum now fails the stage rather than degrading to
implement: reaching OnResult with one means the model ignored its own schema.

Splits validateCaptureArgs into per-constraint checks (cyclop) and carries
the regenerated contracts.json.
2026-09-19 00:33:39 +10:00
sam af56021267 feat(workflow): give triage criteria for choosing between workflows
The classify stage picked between implement, tdd and feasibility with no
stated criteria: the mission spent its guidance on needs_code_change and the
schema said only 'Which workflow fits best', with implement as the free
default for an omitted or unrecognised answer. Issue 813 was classified
implement on that basis.

Both surfaces now state what each workflow is for and say not to pick
implement merely because nothing else obviously fits. The mission moves to a
named triageMission so a test can assert the criteria reach the model.

Closes archie-core-s5ys
2026-09-19 00:17:44 +10:00
sam 681c5fb0ad fix(workintake): match namespaced forge labels when routing by kind
labelKinds is keyed on bare strings, and this repo namespaces its labels
(type::feature, priority::medium), so KindsForLabels matched nothing and
every issue fell through kind routing to Route's triage fallback. Kind
routing has therefore never fired here: issue 813, a type::feature that
defaultKindWorkflows binds to feasibility, reached implement instead.

Labels now resolve to the value after the last '::'. The namespace is not
checked: bug/feature/bootstrap is specific enough that a label ending in one
means that kind whatever the tracker files it under.

Closes archie-core-tjoc
2026-09-19 00:17:44 +10:00
sam ab8ba79966 fix(container): claim container teardown once instead of cancelling a timer
Timer.Stop cannot unwind a max-uptime callback that has already begun, so
cancelling still let the reaper and Release both stop and remove the same
container, which is the duplicate teardown and the misleading 'No such
container' warnings this was meant to remove.

Teardown is now claimed once per container: whichever of the two gets there
first talks to Docker and the loser skips to its own bookkeeping. Release
still claims after the grace period, so MaxUptime keeps biting during it.

Also table-drives the event pump priming cases, per the repo's test directive.
2026-09-19 00:13:36 +10:00
sam fed5bec709 fix(container): keep the max-uptime cap active during the grace period
The reaper was cancelled at the top of Release, before the grace-period
sleep, which let a container outlive MaxUptime by GracePeriod. MaxUptime is
documented as a cap from creation enforced regardless of task state, and a
grace period is task state, so the cancel belongs after the sleep.

Also asserts the disarmed reaper directly rather than only inferring it from
the absence of later Docker calls.
2026-09-19 00:06:26 +10:00
sam 4a566217f9 fix(container): cancel a container's max-uptime reaper on release
The timer stayed armed after Release removed the container, so an hour later
it stopped and removed an ID Docker had already forgotten and logged two
warnings that read like a failed teardown.
2026-09-18 23:59:40 +10:00
sam a345a85197 fix(webui): retry event pump priming until the state store answers
archie-ui binds before archie-state-store is guaranteed to be listening, so
the first prime is routinely refused. PumpEvents returned on that error, which
left the activity feed history-only for the life of the process. Prime now
retries with capped backoff and gives up only when the context ends.

Orders archie-ui.service after archie-state-store.service as well, which
narrows the window without closing it: After= sequences the start, it does
not wait for the listener.
2026-09-18 23:59:40 +10:00
sam 5aedc28aae feat(config): key services by name through a registry
Services was a struct with one field per service, so each service's name was
stated three times: the field, the loader's defaulting branch, and every
consumer's field access. Adding one meant editing all three, and nothing
stopped them disagreeing. The drift was already there: stateStoreResolvedToken
and gatewayResolvedToken were identical apart from the env var each hard-coded.

Services becomes map[string]ServiceConnection, and RegisterService declares a
service once with the five fields it has. Everything that differs between
services is now an argument rather than a branch elsewhere: an empty registered
target means the operator must supply one, which is how services.state.target
stays required while the gateway's is defaulted, and the registered token env
var replaces the two copied resolvers with Services.ResolvedToken.

Defaulting iterates the registry, so a new service needs no loader edit.
Consumers read Services.Get(name).

Keeping a typo'd section reported took explicit work. [services.gatway] used to
land in toml.MetaData.Undecoded() because the struct had no such field; a map
decodes any section, so it would have loaded silently and left the daemon
dialing the default. unregisteredServiceKeys asks the registry which names are
real, and the test for it fails with an empty UnknownKeys when that check is
removed.

The TOML shape is unchanged, so no deployment profile, config.example.toml or
install.sh edit is needed.

Refs: archie-core-u23g
2026-09-18 23:32:36 +10:00
sam 00eb1f3786 fix(update): write the agent version sidecar with a real newline
printf '%s\\n' emitted the literal characters backslash-n, which
archie-update-check's release-version check rejects, so every managed-agent
update left the installed agent version reported as unknown.
2026-09-18 23:14:34 +10:00
sam 095284678a feat(config): let the State Store and Gateway listen addresses be configured
Both gRPC listeners took their bind address from a -listen flag default alone,
with no config key. The port a service binds and the port its clients dial were
therefore two separate facts -- the flag default, and [services.<name>].target --
with nothing keeping them in step.

On a host that already owned the default the effect read as a code fault rather
than a port collision: the store died with "bind: address already in use" while
every client reported "state store: connection error ... error reading server
preface: EOF". Cockpit binds 9090 by default, so this is not hypothetical.
Verifying the dashboard on such a host needed a hand-written overlay plus a
matching -listen, two things to keep in step by hand.

- [services.state].listen and [services.gateway].listen now name the bind
  address. Precedence is -listen, then config, then a default applied by the
  loader. An empty result is a startup ERROR, never a fallback: net.Listen reads
  "" as "any free port", so defaulting there would bind the service somewhere no
  client looks and still report success.
- Both flag defaults become "" so configuration can win, mirroring how archie-ui
  already prefers [web].listen over its flag.
- Gateway listen defaults to the same constant as the gateway target, so a
  default deployment's client and server cannot drift onto different ports.
  [services.state].target still has no default: an empty target stays a startup
  error in the daemon and gateway, which no longer serve a local store.
- ServiceConnection gains the field. Its doc now says clients read only Target
  and TargetToken, and Listen belongs to the process that owns the service --
  the previous wording claimed the struct starts no listeners while carrying one.
- deployments/dev.toml states each port once, beside the target it must match, so
  `task dev` is retargetable on a host that owns 9090 by editing one overlay.

Tests. Unit: config defaults, explicit values, and precedence. Process: the
existing real-process smoke test now takes its listen from configuration instead
of -listen, so the end-to-end wiring is proven by the test that already starts
the binary, with no extra process. Both were verified load-bearing by mutation --
inverting the precedence fails the unit test, and making the app layer ignore
config fails the process test with "state: no listen address".

Verified: task check exit 0. Also documented in config.example.toml, the
configuration architecture table, and the `task dev` summary.
2026-09-18 19:15:02 +10:00
sam 2c09f42ff4 feat(tasks): attribute events, changes and config to the attempt that produced them
The events table had no attempt column, so two attempts of the same task were
indistinguishable: a retried task's stage events interleaved into one timeline and
nothing could say which run produced a given result.

- events gains an `attempt` column through the existing presence-gated
  migrateTasks loop rather than a version bump, so user_version stays 3 and an
  existing archie.db is migrated in place. A legacy-database test builds the
  pre-change schema and proves both that existing rows survive unattributed
  (attempt = 0) and that a new value round-trips.
- Event.attempt = 11 and ReadTaskLogRequest.stage = 9 are field additions to
  existing messages: no new RPC, no new table, and no change to any canonical error
  message that crosses the state-store wire.
- Every task event the workflow engine emits now carries the attempt. Producers
  that have no attempt yet (task_queued, binding_dispatch_failure) stay
  unattributed rather than guessing one.
- Changed files are captured as a durable changes_captured event at commit and push
  time, reusing the existing three-dot diff primitive: paths from FilePatches(),
  counts from Stats(), base_sha recorded as the merge base actually diffed rather
  than the base tip, a 200-file cap with totals kept complete. Consumption goes
  through an unexported optional interface so workflow.Trees -- the yaegi capability
  surface for interpreted stage plugins -- is not widened. A capture is also taken
  once the pull request exists, so the capture can link it.
- The per-attempt configuration is captured as a durable config_captured event
  carrying the non-secret config.TaskConfig, instead of a new table plus two new
  state-store RPCs: events are already this system's per-attempt provenance stream,
  so a table would have given one feature two provenance mechanisms. Redaction is
  proven against canary secrets. Measured payload: 539 bytes typical, 2333 bytes at
  20 models.
- Captures carry a schema marker and are refused unless their key set matches the
  declared payload shape, so drift surfaces as "recorded but could not be read"
  rather than as a capture of zeroes.
- Three read endpoints serve the attempt rail, the changed-file captures and a raw
  debug view, mapping to UI-owned response types rather than dumping store types.
- The task-log read gains a stage filter, bound to the stage logger for that
  stage's own lines; agent and tool output records no stage.

A task-scoped grant may already insert events on its own task, so this provenance
is exactly as trustworthy as the rest of that task's event stream. That limit is
documented rather than papered over.
2026-09-18 18:32:59 +10:00
sam 14e7512d14 feat(contracts): carry attempt on Event and stage on ReadTaskLogRequest
Add two field-only extensions to the State Store contract, no new message
and no new RPC: Event.attempt (11) gives every task event an attempt key,
and ReadTaskLogRequest.stage (9) lets a log read be scoped to one stage.

Generated stubs regenerated with tools/proto.sh and committed as LAW so
proto:check, which diffs the working tree against the index, can pass.
2026-09-18 17:28:31 +10:00