Commit Graph
145 Commits
Author SHA1 Message Date
sam ff5c27ba72 refactor: remove personas
Personas were a misread requirement: SOUL is the chat identity and
identities are per action. The selected persona's prompt never reached the
model. Drops the resource, /personality, the chat selector, the settings
page and ChatService.SetPersona, and deletes stored persona documents.
2026-10-16 03:57:08 +11:00
sam 417d379ede feat(releaseupdate): transactional self-update through archied (#1633)
archied update install verifies the release zip, checks every binary
reports the release, pulls the agent image by digest, backs up the
database in-process and stages the binaries before handing off to
archied update watchdog in its own process. The watchdog restarts units
in release order, requires archied healthy for 120s and otherwise rolls
back binaries and image policy, restoring the database only when a
migration ran. Boot recovery resumes the frozen watchdog.

Deletes scripts/archie-update-install, scripts/archie-update-watchdog,
the updater's --from-source and --auto, CommandInstaller,
ScriptInstaller and the update-image and update-topology subcommands.
2026-10-12 03:21:02 +11:00
sam 332b1702c3 fix(telegram): publish /approve, which the router already serves 2026-10-11 03:57:10 +11:00
sam f2f07fcb9b refactor: slices.Sorted over map keys and one shared IsNil check 2026-10-10 11:14:36 +11:00
sam 1c47b86413 fix(archiemessaging): apply channel enablement live 2026-10-08 22:44:15 +11:00
sam b0f1ad7cdc feat(telegram): /stop stops the chat agent, else the tasks it created, or one task; delete the dead approval actions 2026-10-06 01:12:28 +11:00
sam efa1e5cf85 feat(messaging): serve MessagingService.Deliver and deliver chat schedules through it 2026-10-05 18:01:33 +11:00
sam 482d3c1ff5 refactor(channels): webhook and email run only as extensions; their channel settings go 2026-10-04 17:04:21 +11:00
sam 11085f447c refactor: cut remaining long comments down to what the code does 2026-10-03 22:06:57 +10:00
sam d5a1da1213 refactor(telegram): cut comments down to what the code does 2026-10-03 21:55:00 +10:00
sam 3c338a9722 refactor: strip doc and issue narration from code comments
Remove PRD/doc paths, bead IDs, phase notes and deleted-test references
from comments; drop test-only hooks left by the test deletion. Includes
in-progress archied bootstrap, gateway and query changes.
2026-10-03 21:47:46 +10:00
sam a45300d626 refactor: testing from the beginning. a journey in 150k lines of tests to none 2026-10-03 21:16:25 +10:00
sam 51f9f087cf fix(webhook): set a ReadHeaderTimeout on the forge webhook receivers
Both listen on the network without a header-read bound, the slowloris surface. Matches the timeout the other daemon servers already carry.
2026-10-02 22:45:02 +10:00
sam 8f21692b5d feat(telegram): carry clarify and picker through the text fallback
Telegram had no generic question or choice widget in the agent-turn path,
so the interactive contract could not be carried by the only channel that
ships. telegramInteractor implements ClarifyRequester and PickerRequester
on the shared TextFallback and reports both capabilities honestly: the
capability is about carrying the interaction, not the widget, and the cost
is a typed answer. A reply typed while a prompt is pending is consumed by
the blocked interaction rather than dispatched as a new turn; a command is
never consumed, so /stop still cancels the turn.

The carrier is set on the turn context in the Messaging process. It does
not cross the gRPC boundary into the Gateway process, so in the extracted
messaging deployment the gateway turn has no interactive adapter and
ask_user is not offered -- the same gap that already makes
WithApprovalRequester unreachable there. That transport is a product
decision recorded on the lane, not silently worked around; the in-process
path, the capability report and the tests land here.

Red-first: TestInteractivePickUsesTextFallback and
TestInteractiveClarifyReturnsTypedAnswer (plus the command guard) failed at
the assertion before the interactor was implemented.
2026-10-02 11:52:07 +10:00
sam a8ea4e0656 fix(messaging): transcribe voice notes on the model-owning side of the boundary
The Messaging Service built the voice-transcription client in-process
from [models].transcription and [providers.*], which the messaging
boundary PRD reserves to the process that owns the model runtime and its
provider credentials. The deletion gate only measured linked packages,
so the PRD violation shipped green: config reads are not imports.

Move the capability across the boundary:

- archiemessaging no longer reads [models] or [providers], builds no
  transcription client, and drops the ResolvedConfig.Transcriber field.
- telegram classifies a voice note as messaging.MediaTypeVoice and stops
  transcribing; it carries the attachment bytes and its note to the turn,
  which is all a frontend without the credential can do.
- archied builds the transcriber beside the chat runtime from its own
  model-role configuration (setupTranscriber) and gives it to every
  gateway TurnRunner.
- the turn runner transcribes a speech attachment before recording the
  inbound message, so stored history and the model context carry the
  transcript; a nil/failed/empty transcription keeps the frontend note.
- messaging.TranscribedMessageText renders the transcript into the text a
  frontend built from its media note, preserving the sender's caption.

Red first: TestTurnRunnerTranscribesSpeechOnTheModelOwningSide failed at
'Transcribe calls = 0, want 1' with the transcription call disabled.
2026-10-02 11:12:59 +10:00
sam 00e5b431e4 feat(webui): let the operator choose the retry worktree mode
A retry now carries the operator's worktree choice (refresh onto the base
branch or continue the work already pushed on the task branch) from the
dashboard through the task action to the daemon dispatch, and persists it
on the task row so it survives a reload. The daemon resolves the mode from
the task, never from the workflow; BeginRemediation records continue
explicitly so a remediation still resumes its pull request branch.
2026-10-02 10:53:21 +10:00
sam c70b144782 fix(messaging): carry an inbound attachment's bytes to the gateway turn
A Telegram photo or document was dropped between the process that receives
it and the one that runs the turn. Telegram runs in archie-messaging, which
downloads the attachment; the turn runs in archie-gateway/archied, which
never holds the bot token. gatewayrpc stripped MediaAttachment.Data on the
inbound request, so by the time the Gateway's model seam ran, the
attachment had no bytes and no URL, and mediaParts dropped it -- the model
read only the "[photo]" placeholder.

- proto/gateway/v1: Media gains a `data` field, populated only on the
  inbound request. Stored-history and outbound-event directions keep it
  empty: a persisted record still strips the bytes, and a streamed media
  event still carries metadata only.
- gatewayrpc: the inbound conversion maps Data; the stored and outbound
  conversions deliberately do not.
- archied: the Gateway server raises its gRPC receive limit from the 4 MB
  default to the messaging contract's inbound attachment ceiling plus
  framing headroom, so a maximal (20 MB) attachment is accepted rather than
  failing the RPC.
- messaging: MaxInboundAttachmentBytes is the single ceiling the Telegram
  download gate and the Gateway receive limit both derive from.

Red first: a new TestInboundMediaBytesReachTheTurn asserted the bytes crossed
the wire and failed at that assertion before the mapping changed; it was then
consolidated into TestInboundMediaRoundTrip, which now pins metadata plus bytes.
2026-10-02 10:18:01 +10:00
sam 6985be0abd fix(messaging): report the daemon version this process was built from
The Telegram update-report relay verified every pending report against a
nil running-version map, so a successful update always ended with "I still
can't confirm which version is actually running" and read as a failure.

The 2026-09-19 extraction decision left RunningVersions nil because the
Messaging Service could obtain only another binary's stamp. 6a3b3509
(archie-core-k94o) then gave every host binary, archie-messaging included,
a buildinfo.Version self-report stamped with the archied release tag, so
the process now has a truthful source for its own running version: report
daemon = buildinfo.Version and leave the agent Unverified, since every
archie-agent process is task-scoped and observed only through
daemon.AgentStatus. A relaying process that the update did not replace
still reports its old build, which Verify reads as drift.
2026-10-02 10:16:22 +10:00
sam acfba9121f feat(messaging): adapter-facing clarify, picker and approval contract
The optional-capability pattern had media and delete but no interactive
UX: a channel could ask a human to approve an action through
ApprovalRequester, but there was no domain contract for posing a
clarifying question or presenting a single-choice picker, and no
capability flag a caller could read before attempting one.

Add ClarifyRequester and PickerRequester to internal/domain/messaging
alongside ApprovalRequester, with Clarify/Picker/Approval flags on
AdapterCapabilities and ClarifierOf/PickerOf/ApproverOf lookups that
treat the capability as the contract rather than the method set, so a
mis-reporting adapter degrades instead of panicking.

TextFallback is the shared text degrade: a channel with no native
question or selection UI still carries the interaction (numbered
prompt, parsed reply) instead of failing or silently dropping it.
FormatClarifyText/FormatPickerText/ParsePickerReply hold the rendering
and matching logic once.

The approval half reuses the existing decision model: Telegram's
telegramApprover already renders a native prompt, so it now reports the
Approval capability and deliberately does not claim Clarify/Picker it
has no native UI for. Gateway re-exports the contract.

Red-first: internal/domain/messaging/interactive_test.go drives the
test double adapters (native, degrade, mis-reporting, over-claiming)
and the text rendering/parsing; telegram/approval_test.go pins the
honest capability report.
2026-10-02 09:57:44 +10:00
sam df3eb523ec feat(messaging): transcribe Telegram voice notes
A Telegram voice note was stored as the placeholder "[voice message]" and
nothing turned its audio into text, so the agent could not read it. Add a
channel-neutral Transcriber capability to the messaging media layer
(internal/domain/messaging), an ai-sdk Whisper implementation behind it
(internal/infrastructure/transcription), and wire it for Telegram.

The capability is config-driven like the other model roles:
models.transcription names a provider/model, the matching [providers.*]
entry carries the credential (api_key_env or an api_key secret ref), and
a missing role, provider, class or credential degrades to today's
behaviour with a log -- never an error that fails the turn.

A transcribed note replaces its placeholder with "[voice transcription]"
followed by the transcript, preserving any caption, so stored history
shows the agent it is reading a machine transcript.
2026-10-02 09:36:48 +10:00
sam aab9e10edd feat(messaging): retract ephemeral replies after their TTL
An EphemeralReply is a status notice a channel delivers and then removes
once its TTL elapses, so a transient placeholder does not linger in the
chat history after it is superseded. The TTL lives on the reply, the
Delete capability joins AdapterCapabilities alongside Media, and
channels.EphemeralSender does the send-then-retract with an injected
clock. A sender that cannot delete still delivers the reply and logs the
missed retraction instead of failing the turn.

Telegram implements MessageDeleter through deleteMessage and honours the
mechanism for the "Archie reloaded." status notice; the pre-restart
"Reloading…" message remains the durable acknowledgement.
2026-10-02 09:36:16 +10:00
sam 15946dacfb feat(taskactions): one approval path answers the review gate from every surface
Decision 1 of docs/prds/pr-review-operator-response.md: the dashboard's
POST /api/tasks/{id}/action is the authoritative surface, chat's /approve
is a shortcut that posts every offered finding, and both reach the same
Service.Apply so one operator intent cannot be recorded as two decisions.

The action body now carries instructions (required by rereview) and the
finding keys an approve posts. taskactions.Service answers an offer
through the guarded RespondReviewGate write: approve records the
selection on the offer, rereview records the instructions, increments the
round and clears the offer, and a rereview with no instructions, with no
offer, or at the cap is refused as a conflict with nothing written. Chat
reaches the same service: chatTaskControllerAdapter.ApproveChatTask
delegates to b.taskActions() instead of its own requeue, which is what
removed the handler's hardcoded implement handoff -- feasibility's deliver
stage now names implement on the task before it waits, the invariant the
handler needs.

The payload crosses every hop it must: the NATS action request, the
gateway.v1 gRPC contract (regenerated), the LocalChatAdapter, and the
webui handler, which answers 400 for a rereview without instructions and
409 for the cap. A rereview event kind names its actor the way the
approval and rejection trios do.

taskactions.Task gains review_gate and rereview_rounds, and the two
surfaces' tests assert they agree.
2026-10-02 02:27:59 +10:00
sam 2ed9cb7455 feat(telegram): carry inbound media through the chat turn
Telegram dropped every incoming photo, document, video and audio
message: the default handler required message text, and nothing on the
turn path knew media existed. The receiving path now closes the gap
end to end.

- telegram: extract the attachment from the update (largest photo, plus
  document, video, video-note, audio and voice kinds), download its
  bytes on the turn lane through getFile + the Bot API file link with a
  20 MB gate, submit the turn with the attachment, and answer
  unsupported content kinds (sticker, location, contact, poll) with a
  clear notice instead of silence
- messaging: Inbound carries turn-scoped transport media and
  MediaAttachment a Data field for in-process bytes; Message gains
  Media attachment metadata which stores persist (Postgres jsonb via
 migration 0020, memory store) with Data stripped at the persist
  boundary, and pb.Message carries the metadata on the gateway wire
- gateway: TurnModelRequest threads the turn's media to the model seam
- archied: the chat turn model merges the attachments into the final
  user message as ai-sdk image/file part entries, so vision-capable
  models see the file for the turn it arrived in; stored history keeps
  the placeholder note plus caption

Session log: messages carry what was sent as data (the attachment
metadata), not just prose. Transcript rendering of attachments and a
re-look capability are tracked as archie-core-jaba.
2026-09-30 03:07:54 +10:00
sam df389b7773 fix(webhook): reject rate-limited deliveries with 429 instead of chat prose or a false 202
Router.Route returned the chat-facing rate-limit prose with a nil error, so
the webhook handler had no way to tell a genuine dispatch outcome from a
rejection: DeliverTo "origin" echoed the prose as a 200 reply, and any
other route got a 202 for an event that was actually dropped before
reaching the LLM, so the source never retries it.

ChatReply now carries RateLimited, set by a new Router.RouteResult (Route
is now a thin wrapper over it) so chat channels that render Text to a
human are unaffected. The webhook handler checks it and answers 429,
matching the precedent internal/webhookguard.RateLimiter's other callers
already set.
2026-09-27 05:20:30 +10:00
sam 3c7584bdea chore(config): remove token_env aliases for forge, artifacts and telegram
Each credential is now only a {engine, key} secret reference. A stale
token_env in a file is reported at startup as an unrecognised key.
nats.token_env stays (no secret-ref form), and providers.api_key_env stays:
it is the carrier the resolver writes each resolved key's env name into.
2026-09-24 23:58:26 +10:00
sam b56796b0a4 fix(messaging): render a tool call as one line with its own icon
A tool call rendered as a label line plus a ```text fence. Telegram draws a
fenced block as a full code widget (language header bar, copy button, panel),
and the block parser inserts a spacer paragraph before every block, so one
call cost four rendered elements. Three calls filled the screen to show three
word counts.

Every toolPreview path already summarises to a single line, so the fence was
never wrapping more than one. Drop it and put the preview on the header line.
Tool lines now join with a hard break rather than a bare newline: a soft
break would space-join them into one run-on paragraph, and a blank line would
put the spacer back. Three calls are now three consecutive blocks.

Two hardcoded values go with it. The status word is printed only when the
outcome is not success, since every line otherwise read "done" and
distinguished nothing. The icon is no longer a literal in the renderer: each
builtin declares its own on tools.Tool (not on Schema, which is the model's
contract), the provider carries it into ToolEntry, and the turn snapshots the
registry's icons alongside its tool set. A tool that declares none renders
without one rather than borrowing a generic wrench.

Carries a dependency upgrade (go.mod, go.sum, tools/go.mod, tools/go.sum).
2026-09-22 21:36:02 +10:00
sam 6d1be37e55 fix(telegram): close a code fence only on a matching run
CommonMark fences are three OR MORE backticks or tildes, and the closing
fence must be at least as long as the opening one. The parser hardcoded a
three-backtick prefix for both ends, so every longer fence was mangled:

  ````go              language became "`go", matching no grammar
  ```` wrapping ```   the outer fence closed at the inner one and the code
                      leaked out as paragraph blocks
  ~~~go               never recognised, and the "~~" emphasis pass then ate
                      two of the three tildes

The middle case is the damaging one: wrapping a reply in a longer fence is
how a model safely emits content that itself contains a fence, so getting it
wrong could wreck an entire reply rather than just its formatting.

Track the opening fence's character and run length, and close only on a run
of the same character that is at least as long and carries no info string.
2026-09-22 21:33:56 +10:00
sam 28128eb4ed feat(identity): attribute a task action to the identity that acted
The transport could carry an actor and nothing filled it. It does now, so a
dashboard approval is recorded as the person whose credential verified, and an
agent's token is recorded as the agent's action -- for an agent, agent_approved;
for a person, human_approved; and for a caller whose identity archie could not
verify, task_approved, which claims nothing about who did it.

The actor travels the path the action takes: webui reads it from the request
context the middleware resolved, carries it in the gateway request, the daemon
passes it through the in-process adapter, and the NATS request body carries it to
the service that records it. Scope stays separate from actor at every hop, because
scope is which task a caller may touch and the actor is who touched it.

A chat channel's bound identity is an actor too: a bot acting on its own channel's
task is recorded as an agent's action rather than a person's, via ActorFromScope,
whose empty kind is what keeps it out of human_approved. The agent-facing
task_action tool passes that identity and never input["identity"].

The UI process's credential check is now filled by endpoint references rather than
by configuration: -oidc-issuer and -oidc-audience on archie-ui, two URLs the
process already understands the shape of, with the verifier built in Run because
cmd/ parses flags and nothing else. The UI package still never reads config, and a
configured provider that cannot be reached fails boot rather than falling back to
the gate that names nobody.

Evidence for this change, stated as measured: go build ./... and go vet ./... are
clean, and every package this touches passes -- webui, domain/taskactions,
infrastructure/taskactions, infrastructure/gatewayrpc, gateway, app/archieui,
app/archied, domain/messaging, channels/telegram, cmd/archie-ui. task check could
not be run to completion: it fails in cmd/archie-messaging on an untracked
internal/buildinfo package another lane has in flight, which is not this change and
was left untouched. The end-to-end flip is covered in
internal/webui/api_tasks_actor_test.go: a person's credential produces a record
naming that person with human_approved, an agent's produces agent_approved, an
unverified request produces task_approved with no actor, and a request carrying
forged actor fields cannot name one.
2026-09-22 14:52:10 +10:00
sam 636a17b9db feat(telegram): publish the full command surface in /help
The menu and /help were generated from a hand-maintained spec list that had
drifted from the executable surface: /approve and /deny are real handlers but
were published nowhere, while /rollback and /stop are Telegram-only.

Registration now reads a single handler table, and a regression test derives
the executable set from messaging.LocalCommands() plus that table, failing when
the published specs and the executable surface disagree in either direction.

/approve and /deny are published with their Telegram meaning, the
dangerous-command approval list, not the shared task-approval copy; that split
is archie-core-ho86. The two tests that pinned them as hidden commands are
updated to the published decision. /help now also asserts it carries every
published command's description, not only its usage.
2026-09-22 05:47:54 +10:00
sam c8dbeebe83 fix(gateway): stamp the session platform from the channel that carried the message
One Router serves every channel and named itself "web", so Source.Platform -- the
FIRST component of the session natural key, and the platform GetByChannel filters
on -- was a constant, true of no channel but the dashboard. Two consequences
followed: the per-user identity policy was real code that no production call site
reached with a real channel name, and a curator pass's write to agent-user memory
could not be read back by the turn that wrote it, because that turn resolved no
UserID.

The channel now travels with the message. Frontends name the channel they carry
(pb.Message.platform: telegram, email, webhook, web), and the Gateway stamps the
session from it, falling back to its own name when a sender names none -- which is
what every existing row holds and what a frontend that does not participate keeps
doing.

Identity resolution reads the platform off the inbound rather than closing over a
channel name, so carriesPersonIdentity finally decides something in production:
telegram and email resolve a person, the dashboard and a webhook resolve nothing,
and an unknown platform fails closed.

Deliberately NOT changed, because it is where this could quietly widen scope:
TurnRunnerConfig.Channel still keys tool availability, so no channel gains or
loses a tool here. Only session lookup and identity follow the message's platform.

Consequence the maintainer accepted: a chat whose active session came from /new or
/branch re-resolves once, since GetByChannel now filters on the channel's name. A
chat with no /new re-resolves onto the same deterministic session id and heals
silently.

Verified: gateway, archied, gatewayrpc, messaging, webui, channels and cmd suites,
go vet ./..., go build ./..., golangci-lint run ./... (0 issues), docs:check.
New contracts: TestResolveSessionKeyStampsTheMessagesPlatform, the per-platform
identity table, and the transport-context wire round trip.
2026-09-22 04:30:15 +10:00
sam 708233a538 fix(webhook): keep a route path out of the sender identity
A webhook set SenderID to its configured route path. The turn path reads that
field through a per-channel resolver which refuses webhook, but the session
curator derives its participant from the raw field with no channel filter, so a
webhook session with exactly one distinct sender and one extracted fact wrote
agent-user memory addressed to User: "/hooks/...". Nothing reads it, and every
pass added more, because the facts are identical strings with no dedup.
docs/prds/memory-engine-unification.md criterion 7 requires that a route path
never become a user identity.

Clear it at the producer rather than teaching every consumer which channels are
lying: a route path is a source, not a person, so it no longer enters SenderID.
It still keys the inbound rate limit, where it is the documented per-source
budget for webhooks (config.RateLimitConfig), so it travels in the new
transport-only Inbound.BudgetKey -- carried on the wire beside Page, never
persisted, and never read as an identity.

pb.Message gains budget_key (field 9) for the same reason page (field 7) exists:
transport context that rides with an inbound message and is deliberately absent
from storedProto's rendering of a canonical record.

The curator needs no change. An empty SenderID already fails closed as an
unidentified user message, which is the path a dashboard session takes, and
sessionParticipant's existing skip covers it; the test name now says so.
2026-09-22 03:18:59 +10:00
sam 3944f544e8 feat(controlplane): runtime administration over the State Store's gRPC server
The Web UI and messaging channels now read and write Archie's runtime
settings through one versioned, audited control-plane API hosted on the
State Store's existing gRPC server: catalog, query, command, watch. Each
feature owns its resource, validation and commands; storage only writes
versions and audit records.

Workflows move with it. Definitions become portable YAML compiled through
a closed, typed step registry and stored as a control-plane resource, so
the yaegi interpretation paths (internal/gate, wfeval, wfextract,
gateeval, gateextract, skillbuild) are deleted rather than carried.

The UI process reads definitions as data: the JSON projection lives in
internal/domain/workflow/task so a dashboard decodes the stored
collection without linking the workflow engine, which cmd/archie-ui's
deletion gate forbids. Shipped definitions ride the catalog descriptor
rather than a bespoke REST route, keeping the API to its four operations.

archie-messaging gains -state-store-target/-state-store-token and reads
channel settings from the database, failing closed when the State Store
is unreachable: the database is authoritative for those settings.
2026-09-21 08:17:42 +10:00
sam f45ebd288d fix: address the Greptile findings on the merged PRs (#902)
* fix: address the Greptile findings on the merged PRs

Four valid review findings from PRs #892, #893, #898 and #899, which were
merged without the comments being read.

- Config.Clone left the new diff-cap pointers aliased (#899, mine). Clone
  deep-copies every reference field, including the *bool beside it, so a
  clone could write the cap through to the published snapshot. Both the
  top-level field and the identity overrides are copied, with the clone test
  extended to cover them.
- providerOutcomeRecorder.record could report an older call as the latest
  (#892). The completion time is taken before the lock, so two concurrent
  calls can reach the lock in the opposite order to their completion and the
  unconditional store overwrote the newer outcome. It now keeps the newer,
  via a recordAt seam that makes the reordering testable.
- Curator model calls bypassed the recorder (#892). curatorLLMRunner calls
  the runtime directly, so a daemon whose only recent model traffic was
  curator work reported "no calls attempted yet" while the provider was
  demonstrably reachable. It records at its own adapter, and sendChatTurn's
  "single choke point" comment is corrected to say there are two.
- A provider error reached /status raw (#892), unlike channel details, so a
  multiline or oversized error broke the one-line-per-fact layout. Both now
  share one bounded formatter.

Found while fixing the curator path: agentexec.NewRuntime returns nil when no
provider is configured, and a nil *runtime.Runtime panics on its first method
call, so a curator asking for a completion took the daemon down. It now
returns an error, and records nothing -- a local misconfiguration is not a
provider call.

Not fixed, filed instead: the shared lastPollAt masking a stuck identity, the
container max-uptime callback resurrecting teardown bookkeeping, the
dashboard dropping a served-only status filter on cold load, and the route
registry test's line-by-line parser.

* fix(build): drop goimports from the gate's formatter set

`task check` spent 136 of its 167 seconds in `task fmt`, and 134 of those
136 in one formatter: goimports alone over the tree.

golangci-lint's goimports formatter calls imports.Process once per file,
which builds a fresh x/tools ProcessEnv each time, so
internal/imports.getFixesWithSource re-reads modindex.Read($GOMODCACHE) per
file. On this machine that index is 62.7 MiB / 2,081,070 lines (an 11 GiB
module cache), and modindex's in-process memo does not take effect: 3 files
read 187.9 MiB back, 15 files open the payload 15 times. That is ~53 GiB of
I/O and CSV parsing per run, and it is linear at ~155 ms per file (122 files
-> 18.8s, 864 -> 133.8s). Pointing the index cache elsewhere drops the same
command to 3.9s.

The same analyzer runs under `golangci-lint run`, so a cold cache pays it
again: 169s cold with goimports, 31s without -- which is what CI and archied's
own PR gate see, since only `fmt` never caches locally.

Removing it costs no enforcement. gofumpt and gci remain, `task lint` still
reports formatter drift as an issue, and the whole-tree fmt is now 2.2s with
the tree byte-identical. What is given up is goimports' convenience of
adding and removing import lines, which compile errors already cover.

The examples/secret-engines exclusion stays: gofumpt and gci leave those
Yaegi programs alone today, but the exclusion is the stated invariant that a
formatter must not rewrite the imports of files it cannot type-check, and
TestFormattersExcludeInterpretedSecretEngines holds it. Its comment no longer
pins the reason to the formatter that was dropped.

* fix(gateway): stop /status promising and mis-reporting health it cannot see

Two findings from the cloud review of #892.

Title generation no longer records chat-model health. It runs detached after
a first turn under its own 30s bound and its error is swallowed by the
caller, but it shared the process-wide outcome recorder, so a title that
merely timed out overwrote the health line with "failed" -- reporting a
broken provider on the strength of a call no user was waiting for.

The /status command description no longer claims "workers" and "channels".
Neither can render: newStatusHealth reads the container pool and the poll
loop from boot, but the only production router.Health assignment is in
setupGatewayChat, which runs solely in the archie-gateway process, where
neither exists; channels is nil since the Messaging Service took the
front-ends. Only the broker and chat-model lines actually appear, so that is
what the help text now says.

The underlying split -- daemon owns the facts, Gateway owns the Router -- is
filed rather than patched here: it needs either a cross-process health
contract or a ratified two-section /status, not a quick wire-up.
2026-09-20 02:42:36 +10:00
sam 1dc212e50e 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 d4ac771e38 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 c29cdf6f79 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 267de032de 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 670fcaf9d4 fix(telegram): keep every tool line that fits and mark every answer cut
Two defects in the activity/answer budget, both found in review.

The tool block returned as soon as the newest line alone fit, so a turn with
several short tool calls discarded history that was never over budget and
reported a "+N earlier" that was untrue -- those lines had room. The window
now widens from the newest line backwards while the result still fits, so
every line that fits is kept. The indicator appears only when something is
genuinely left out.

The opening frame sliced the answer to its budget without an ellipsis, so a
large first chunk -- or a turn that never opened a reply, leaving messageID 0
-- rendered text that appeared to begin mid-sentence, while later frames
marked the same cut. Telegram messages are immutable, so it could never be
corrected. Every frame now marks the cut; the special case only ever bought
one rune.

TestLiveReplyFramesStayWithinOneMessage asserted the ellipsis on the last
frame only, which is what let the unmarked opening frame through. It now
checks every frame, and the count bound follows: identical frames are
deduplicated by render(), so an unmarked opening frame was previously a
distinct body where a marked one is not. Verified by mutation -- restoring an
unmarked opening cut fails the test on frame 0.
2026-09-17 11:40:08 +00:00
sam c1ccf2f023 chore(telegram): resolve the state-store test conflict and drop dead clamp helper
Rebased onto main, which now carries an equivalent STATE_STORE_TOKEN isolation
guard in state_store_client_test.go from an independent baseline repair. The
two changes were the same fix expressed twice, so main's wording is kept and
this branch's duplicate is dropped -- the file is now identical to main and no
longer appears in the diff.

That leaves one commit, touching only internal/channels/telegram/live.go.

Removing clampToOneMessage, which this change orphaned: all three of its call
sites were replaced with clampToRunes directly, and `unused` flagged it. Dead
code left behind by a rewrite does not ship.
2026-09-17 11:31:05 +00:00
samcharles93 9faa1f14d7 Telegram tool-activity block is uncapped and crowds out the answer (archie)
Implements #839
2026-09-17 11:27:52 +00:00
samcharles93 dae0fbe456 test: failing repro
Refs #840
2026-09-17 11:10:30 +00:00
sam 75403b3138 fix(telegram): summarise tool results instead of quoting an arbitrary line
Operator report: tool output in the Telegram channel was unreadable during
search-heavy turns -- a wall of fenced blocks each showing one arbitrary
match line ("/path/config.json-322-          }") under a heading that said
only "grep -- done".

The renderer quoted the first non-module-cache line of a result and appended
a line count recomputed from its own truncated sample, which could not agree
with the total the tool had already reported: one search rendered the tool's
"194 more lines" beside our "… 3 more lines". Two different numbers for one
result set read as noise, and the quoted line carried no context at all.

- Describe, don't quote: a search is reported as "N matches", a truncated
  result as "<total> lines total; showing <n>", and every other tool falls
  back to its first informative line. Truncation notices are skipped, since
  they are metadata rather than content.
- Never invent a count: the tool's own reported total is the only
  trustworthy source, parsed from its truncation notice rather than
  recomputed from the visible sample.
- Remove the now-dead compactToolPreview and countNonEmptyOrContentLines.

Also bump go-telegram/bot v1.25.0 -> v1.27.0, which fixes a streaming bug
that lands squarely on this path: rawRequest sent the multipart body through
an io.Pipe, which net/http cannot replay, so sendMessage/editMessageText
failed until the connection was dropped.

Remaining work from the report (collapsing repeated calls into one counted
entry, and a ring of recent activity lines with a capped frame) is tracked
in #837.
2026-09-17 09:36:28 +00:00
sam 0c5ea7b2a0 test(telegram): pin upload-ceiling agreement with send_file
Choice: cross-package test (pin). Both ceiling pairs are live producers
and currently agree, so the WIRE/DELETE rule does not apply. Deriving one
shared definition would either require a new package outside this lane's
ownership or bind the channel-free sendfile tool to the telegram package;
the cross-package test pins the documented 'the two must agree' contract
at the duplicate itself.
2026-09-15 12:48:51 +10:00
sam 7c68e1d436 feat(channels): wire ConfigSchema/ValidateConfig into a startup validation loop
Every chat gateway (Telegram, email, webhook) implemented channels.Channel's
ConfigSchema/ValidateConfig contract but nothing ever called it, so a
misconfigured gateway would only fail once it tried to start rather than at
boot. setupEmailGateway/setupWebhookGateway now call ValidateConfig before
registering a start function and return false (fatal boot error, matching
setupTelegramGateway's existing convention) on failure; telegram_setup.go
does the same for the already-constructed *telegram.Gateway.

Fixed telegram.Gateway.ValidateConfig/ConfigSchema along the way: it only
recognised token_env, but chat.telegram.token (a secret reference) is an
equally valid, already-precedent-ordered credential source per
resolveTelegramToken. Wiring the old validator unmodified would have
rejected every Token-only deployment. Also corrected ConfigSchema's stale
allowed_chat_ids property name to the real allowed_user_ids toml key.
2026-09-15 11:22:23 +10:00
sam f7815d3b62 fix(channels): delete unreachable Telegram webhook delivery mode
telegram.New only ever constructed with empty webhookURL/webhookSecret
(telegram_setup.go) and config.TelegramConfig has no field to set them, so
the SetWebhook/StartWebhook branch, WebhookHandler, and webhook teardown in
Stop were dead code exercised only by tests. Long-polling is the only
reachable mode; delete the webhook path and its ConfigSchema properties so
the schema no longer advertises unsupported config.
2026-09-15 10:18:48 +10:00
sam 6f26d790ba fix(email): stop dropping the first paragraph of plain-text bodies
extractBody re-split the already-isolated body on the first blank line it
found, intending to strip a stray content-header block some MTAs emit.
That heuristic can't distinguish a header block from an ordinary blank
line between paragraphs, so any multi-paragraph plain-text email silently
lost everything before the first paragraph break.
2026-09-15 04:55:44 +10:00
sam db18d2675a feat(ratelimit): wire per-identity inbound rate limiting into the gateway
internal/ratelimit was fully built (sliding-window limiter, ticker-driven
eviction) but had no consumer, leaving multi-identity deployments with no
inbound request budget on any channel (archie-core-6wxb / GH #797).

Adds Message.SenderID (Telegram numeric user ID, SMTP from address, or
webhook route path -- the closest thing webhook has to a caller identity),
threads it into Router.Route/RouteStream via a shared checkRateLimit, and
wires an opt-in [chat.rate_limit] config section through bootstrap with the
documented EvictStale ticker.
2026-09-15 01:24:20 +10:00
sam e427995d70 fix(telegram): stop the relay corrupting identifiers and code
Emphasis stripping ran two non-greedy regexes, `_(.+?)_` and `\*(.+?)\*`,
over every paragraph, heading, list item and quote. Neither honoured
CommonMark's flanking rules, so any two markers on a line paired up and
both characters were deleted:

    "allow_concurrent": true, "max_retries": true
    -> "allowconcurrent": true, "maxretries": true

    internal/webui/config_schema_test.go
    -> internal/webui/configschematest.go

    takes no *sql.Tx and returns *Result
    -> takes no sql.Tx and returns Result

Agent reports relayed to Telegram therefore cited files that do not
exist, which reads as hallucination rather than as the transport fault
it is. Replace both regexes with a scanner that pairs delimiters by
CommonMark's left/right-flanking rules, including the rule that an
underscore may not open or close inside a word. Single "*" additionally
may not open on punctuation: CommonMark reads "*.go files in cmd/*" as
emphasis, and in a relay carrying globs and pointer types that costs far
more than a surviving marker.

closeCode ran the same stripper over fenced code. Code is verbatim by
definition, so it no longer does.

Separately, markdownToBlocks knew only fenced code, not CommonMark's
indented form, which models emit constantly. An indented block fell
through to the paragraph case, which space-joins lines, arriving as one
run-on line with its markers eaten on the way. Parse it as code, ending
at the first non-indented non-blank line, and refuse to let it interrupt
an open paragraph so a wrapped prose line stays prose. Paragraph
continuations are now trimmed before joining, so the join is one space
rather than the source indentation.

Closes archie-core-8x1r, archie-core-cvu6.
2026-09-12 09:44:52 +10:00
sam a00c578cb7 refactor(ui): sever the archie-ui binary from every daemon runtime package
Completes the objective deletion gate for the UI Service
(archie-core-8cda.5.6): go list -deps ./cmd/archie-ui now links zero
banned packages -- no modernc.org/sqlite, no internal/store, gateway,
channels, memory, secret, agentexec, tools, skill, yaegiutil, curator,
or the workflow engine. The closure shrinks from 68 to 26 archie-core
packages. Each cut is a producer-side move; no consumer-side defensive
shims.

- Store contracts (TaskStore family, value types, sentinels) moved from
  internal/store to internal/domain/storecontract -- the approved contract
  location per state-store-contract rev. 2d, and NOT internal/contracts:
  that tree is buf generate output and tools/proto.sh check deletes
  hand-written files there. internal/store keeps aliases; sentinel
  message strings are byte-identical and remain the wire contract.
- Chat contracts (ChatContract, sessions, turns, streaming, commands)
  moved from internal/gateway to internal/domain/messaging; gateway keeps
  aliases. ToolCallEvent rendering helpers become gateway functions
  (methods cannot live on alias types).
- Task vocabulary (Task, statuses, mid-run Store, Definition) split into
  internal/domain/workflow/task; the pipeline engine stays in package
  workflow with aliases, so daemon-side callers are unchanged.
- overlay.DeniedKeys moved to internal/infrastructure/configuration:
  webui referenced the constant and that dragged the overlay SQLite
  store in.
- webui.Server's concrete runtime handles become webui-owned view
  interfaces with daemon-side bootstrap adapters: channel lifecycle
  (internal/channels/status), MemoryStatus, CuratorStatus, and a
  SkillCatalog seam replacing the direct skill.DefaultRoots/CatalogRoots
  calls. Each degrades to an empty page when unwired.
- config.SecretRef moved into internal/config (config vocabulary);
  internal/secret keeps an alias and Registry.Resolve absorbs the
  zero-value short-circuit.

Docs: state-store-contract rev. 2d relocation record; ui-service-boundary
deletion gate marked satisfied; ARCHITECTURE.md package map rows.
2026-09-10 03:03:33 +10:00
sam 6048c8ba91 feat(archied): serve the daemon's own health endpoint
The update watchdog verifies archied's restart, so archied has to be what
answers. It was probing the dashboard's /healthz, which belongs to the
dashboard: switch [web] off and nothing answers, and in the extracted UI
topology that endpoint reports a different process entirely, which would
confirm a release while the daemon it was meant to verify is down.

[health].listen (127.0.0.1:8485, defaulted, always on) serves /healthz,
/health and /health/detailed for the life of the process. Liveness answers
503 until the daemon reaches its run loop: the listener binds before the
subsystems do, so an unconditional 200 would tell the watchdog a half-booted
release came up. Failing to bind is fatal, because a daemon nothing can probe
gets every update rolled back. The State Store's readiness surface now shares
the listener plumbing, keeping its log and error text verbatim.

Closes archie-core-exbz, which asked which of two bad options to take when
the dashboard is off. Neither: the daemon owns its own liveness.

Also deletes TestInstallUpdateDetachesInstallerFromCallbackContext. It has
failed intermittently under load more than once, racing its fake bot server's
multipart parse against the cancellation it induces.
2026-09-09 23:29:11 +10:00