Commit Graph
88 Commits
Author SHA1 Message Date
sam 4131f05036 feat(webui,gateway): wire config, channel, log-feed, and work-intake seams
Composition root work tying the config resolver, channel manager, log
feed, and executable workflow registry into the running daemon and
dashboard server: web.Channels/LogFeed/Workflows/ConfigProvenance,
channel-reload wiring, TaskStopper for the Stop action, and
SpawnRequest.Body/WorkRequests threading dashboard "Start work" requests
through the same admission path chat uses. Touches all three features at
once because this is where they're composed, not owned by any single one.

Refs #53, #54, #55
2026-08-09 01:26:58 +10:00
sam 0d500a4ca9 feat(webui): lifecycle-safe task controls with atomic retry and archive
Add cancel/stop/approve/reject/retry/abandon/archive to the dashboard task
action matrix, each guarded by an optimistic status check against the
store. Retry accounting (RetryCount, max_retries) is now atomic with the
status transition instead of a separate write. Archive removes a terminal
task's local record with a fail-safe audit event first. Add always-labelled
responsive navigation, mobile Jump-to search, and versioned Setup-complete
dismissal.

Fixes #53
2026-08-09 01:25:51 +10:00
sam b876fc80cc feat(gateway): make chat turns durable and idempotent 2026-08-09 01:15:41 +10:00
sam 6aa3772ce9 feat(gateway): tool-approval gate, session tools for chat, and /delete command
Adds a human-consent gate for tools marked RequiresApproval, exposes
session management as LLM-invokable chat tools, and gives the operator
/delete to retire conversations permanently.

**Tool-approval gate (internal/tools, internal/agentexec)**

- ApprovalRequester contract lives in internal/tools (not gateway) so
  agentexec can import it without pulling in the chat-adapter stack.
- ToolSetOptions.Approval wires the approver through to toolExecute.
- BuildToolSetFrom omits RequiresApproval tools when no approver is
  configured; dispatch paths (invokeTool, tool_call bridge) refuse
  them too, so the invariant holds at every indirection.
- The gate fails closed: only Approved/PermanentlyApproved pass;
  an unknown decision value from a faulty approver does not execute.
- Tool-level timeout (2 min) returns a plain error, not a context
  cancellation, so the model can report "approval timed out" instead
  of the turn aborting.
- BuildApprovalDescription callback lets a tool surface the specific
  resource being acted on ("Delete session \"abc123\"") rather than
  showing a static tool description.

**Session tools (internal/gateware/session_tools.go)**

- session_list (idempotent), session_resume (mutating), session_title
  (mutating), session_delete (mutating + RequiresApproval).
- Scoped to the current platform + channel: GetByChannel replaces
  List() so a model in chat A cannot list or manipulate chat B.
- session_title validates the session belongs to this channel before
  writing; session_resume/session_delete resolve refs against the
  channel-scoped list.
- Shared limit helper extracted to tools.ListLimit.

**Telegram approval adapter (internal/channels/telegram/approval.go)**

- telegramApprover implements ApprovalRequester via the three-button
  inline keyboard (Approve/Permanent/Deny). 2-min token expiry.
- Own map + mutex + "approval:" callback prefix — separate from the
  dangerous-command system.
- Permanent approval uses exact-match (not prefix) lookup keyed by
  action + resource description, so permanently approving "delete
  session abc123" only covers that one session, not every call to
  session_delete for 24h.

**Session lifecycle**

- /delete <session-id>: removes a session and its history. Refuses
  prefixes shorter than 4 chars even when unique. Exact ID wins over
  an ambiguous prefix. sessionTracker.forget sweeps every channel+
  thread pointing at the deleted session.
- Extracted resolveSessionRef and shortSessionID for /resume and
  /delete to share.

**Wiring**

- submitTurn builds the approver onto ctx before the LLM turn.
- chatGenerateOptions reads approver from ctx, passes it through
  ToolSetOptions.
- SessionTools built per turn on the current message, combined with
  taskTools into a single toolset.
2026-08-08 16:42:59 +10:00
sam 1081a6c3ed feat(daemon): identity-scoped isolation + gateway session titles and /delete
Multi-identity daemon isolation:
- Split runIdentities into per-identity poll loops plus one shared
  maintenance-and-drain loop, so reconcilePRs and storage cleanup run in
  multi-identity mode and the global max_concurrency / per-repo
  serialization holds across identities.
- Make the poll path identity-aware: each identity polls with its own
  forge client, bot user, label, trigger, and ack reaction.
- Make allowConcurrentFor task-based and identity-aware via repoFor.
- Roll back storage mounts when container acquisition fails; log
  Store.Update failures after branch set.

Container-mode RPC identity routing:
- forgerpc/worktreerpc gain identity-scoped subjects (SubjectFor,
  RegisterFor) and identity-carrying clients.
- registerTaskRPCServers registers one server pair per identity (plus
  root), so a container-mode task owned by a non-root identity is served
  by its own forge client and worktree manager.

Gateway/Telegram:
- LLM-proposed session titles generated in the background after turns
  (TitleGenerator + chatTitleGenerator), persisted by the gateway.
- /delete session command with prefix guard and tracker forget.
- Shared session display helpers (shortSessionID, sessionDisplayTitle,
  resolveSessionRef).
2026-08-08 01:32:35 +10:00
sam 7e896c9411 refactor: migration of workflow into it's own domain 2026-08-07 00:24:05 +10:00
sam 308666b410 chore: remove legacy terminology and dead code
- Reword docs and comments to drop vague "legacy" qualifiers where they no longer describe deprecation status
- Remove unused code: RecentEvents, MessageEvent.ToLegacy, index setState, stderr redaction tool, telegramOnlyCommands
- Delete or comment out tests covering removed or superseded behavior
2026-08-06 22:55:26 +10:00
sam e10cbbc92c refactor: pre-cleanup. 2026-08-06 01:40:15 +10:00
sam 36d00963a5 feat(curator): trigger accounting — primary-input wake path (archie-core-035)
A completed chat turn is published as turn_completed from the single
responder choke point shared by the telegram and web gateways
(redeliveries return earlier and never emit). The runtime wake path
forwards ONLY primary-input kinds to input-driven curators; curator-
produced activity (curator_run/action/error and any future derived
kinds) never appears on that path, so a curator that writes memories
cannot schedule itself again — the feedback-loop guard, with the
rationale recorded in the regression test so it is not removed as
redundant.

The bus subscription is bounded and dropping, so the wake path can
never backpressure the chat publisher; a dropped event only delays a
run to the next check-in.
2026-08-05 15:00:29 +10:00
sam 4ece064026 feat(curator): engine family contract, registry, and runtime (archie-core-rfp, archie-core-89x)
internal/curator is a conforming engine family per the strict plugin
engine rule: typed CuratorEngine contract (Lifecycle + domain ops),
owning Registry (registration, discovery, start/health/stop with
failure isolation, reverse-order shutdown, ctx-bounded stop), and a
narrow typed Registrar — each curator receives a capability-filtered
view of the host at Bind, never the daemon.

Runtime: one loop per curator on an injectable clock (fake-clock
testable), best-effort wake nudges with the trigger decision kept in
Check (a dropped nudge only delays to the next check-in, never
corrupts accounting), per-pass timeout and a max-concurrent-passes
slot so curator bursts cannot starve chat turns, per-pass panic
recovery, and bounded shutdown even when a pass ignores cancellation.
curator_run / curator_action / curator_error ride the in-process
event bus so activity stays attributable.

Wired in cmd/archied/main.go (constructed beside memory, Start after
daemon startup, shutdown ordered before memory/LLM teardown) and
exposed as daemon.Daemon.Curators.
2026-08-05 14:54:12 +10:00
sam 68ba3456ee feat(webui): chat from the dashboard
Brings the chat surface to the Web UI: /api/chat with its own handlers
and tests, a self-contained ui/src/chat feature folder, and the shared
plumbing to reach the same router Telegram uses.

Includes a dangerous-command approval path (internal/gateway/dangerous.go,
internal/webui/dangerous.go, and the Telegram counterpart) so /rollback
and /stop are gated the same way on both surfaces, persona handling for
web sessions, and release-update formatting split out of the Telegram
service so both can render it.

web_parity_test.go pins that the two surfaces expose the same commands.

Authored in a parallel session; committed here so it lands with the rest
rather than sitting uncommitted while other work builds on top of it.
task check passes with it in place.

Screenshots used while building are gitignored (*.png) rather than
committed, matching the call made on the earlier design reference.
2026-08-05 10:48:51 +10:00
sam fa6f4aef5f fix(gateway,daemon): repair regressions found by the adversarial review
Six defects, four of them introduced by the fixes in dbacb96, 44d43ef,
d5e016e, de1a899 and 4d44ef7. This is the third round in this codebase
where a round of fixes broke something the next round caught.

SANDBOX SILENTLY DROPPED. startContainers degrades a failed container
pool to nil, and the daemon's only test was `if ContainerPool != nil`.
So `containers.enabled = true` plus a missing agent image ran every
task's agent loop in-process, with the daemon's own authority and the
host filesystem -- the one thing [containers] exists to prevent -- while
logging only that containers were disabled. Nil now means two things and
they are distinguished: SandboxRequired parks the task instead. The
daemon still stays up; chat and the dashboard are unaffected.

SUMMARY AT THE WRONG END OF HISTORY. compressedHistory returns [head,
summary, tail], but ordering is by timestamp, not slice position. The
retained messages keep their original timestamps -- that is what
preserves their identity -- so the summary, being new, was clamped to
now and sorted after the tail it was meant to precede. The model read
the recent conversation and was only then told earlier context had been
summarised. Confirmed on both backends: index 23 of 24.

The monotonic clamp belongs to the append path, where an inbound message
must not sort ahead of the one that provoked it. ReplaceMessages is a
rewrite primitive and now honours explicit placement, and the summary
takes a timestamp inside the span it replaces.

A COMPRESSION SUMMARY ANSWERED A QUESTION. Following from the above,
PriorReply saw a bot-attributed record immediately after an unanswered
message and replayed it as the answer: a redelivered question was
"answered" with the compression banner and the model never ran. The
user's question was silently swallowed.

RECENCY STILL DIVERGED. sessionRecency preferred LastActiveAt whenever
set; SQLite used MAX(last_active_at, created_at). Those agree only when
LastActiveAt is the later of the two, so a clock step or an older record
made the caller and the store order the same sessions differently.

LASTACTIVEAT WAS NEVER UPDATED. Touch had no caller, so "resolve the
most recently active session" meant the most recently created one -- an
operator who moved to an older session with /topic and worked there was
dropped back into the newer, abandoned one on restart, which is the bug
d5e016e claimed to fix, with the direction reversed.

/branch WITH NO ACTIVE SESSION PANICKED, slicing an empty parent ID for
its default title. Pre-existing, but reachable: email and webhook call
Route directly without resolving first, and the email path runs in a
goroutine with no recover, so one message took the daemon down.

The sandbox guard has no test. The honest reason is that exercising it
needs a daemon with a forge and worktree the current harness does not
build, and a test that re-states the condition proves nothing -- which
is the same false confidence that let these regressions through.
2026-08-05 04:24:16 +10:00
sam 1f2e7a42eb refactor: one definition of what approving or declining a task means
The dashboard and chat both let an operator approve or refuse work, and
they had drifted. Declining from the dashboard left the task
closed_wont_do; cancelling the same task from chat left it rejected. Two
operators looking at one queue saw different states for the same
decision, and "rejected" -- which reconcilePRs also uses for a pull
request closed without merging -- stopped meaning one thing.

internal/gateway deliberately does not import internal/store, so it kept
a hand-synced copy of the status strings with a comment asking future
editors to keep them aligned. That is the same defect one level down,
and it is how the drift happened.

internal/taskstate is a leaf package with no dependencies holding the
lifecycle vocabulary and the rules for operator actions. gateway, store
and the dashboard all import it, so gateway stays decoupled from store
without a copy, and CheckApprove/CheckRetry/CheckDecline have one
implementation. Declined is named for what it is -- a human said no --
and stays distinct from Rejected, which is something archie observed.

Chat cancel now records Declined. That is the behaviour change: same
decision, same state, whichever surface the operator used.

Rules were preserved rather than tidied while unifying. A parked task
still cannot be declined, which both surfaces already refused, even
though "not terminal" would have allowed it -- widening a rule under
cover of a refactor is how you ship a change nobody reviewed. The
comment says where to change it if that is ever wanted.

TestDashboardAndChatAgreeOnTerminalStates drives both real surfaces
against one store, so this cannot drift apart again without a red test.

Also removes a second rule for the dash-top-standalone class: renderSetup
already reconciles it from the data at the top of every call, and a later
branch cleared it again. Harmless, but it reads as two sources of truth
for one bit of layout state.
2026-08-05 04:15:39 +10:00
sam 170fe0250b fix: close the duplicate-work loop and the dead paths around it
Applies the four-reviewer pass over the forge/dashboard-actions work.
The through-line is that several capabilities were wired but inert, and
one of them could cost real work.

DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of
LinkBranch, which is sidebar linkage on Gitea and a no-op stub on
GitHub -- neither closes anything, and nothing else did either. So a
merged task left its issue open, labelled and assigned; the next poll
re-enqueued it, and once the dashboard's Clear removed the task row that
became a second implementation and a second PR for work already merged.
reconcilePRs now closes the issue on merge, and a rejected task closes
its issue too. A PR closed without merging deliberately leaves the issue
open: that usually means "try again".

MAX RETRIES. Configured, defaulted and reported by /api/config, and
enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had
no callers, so the dashboard's retry incremented retry_count forever.
The retry action now retires a task to dead at the cap.

DEAD ON ARRIVAL. Tasks() never selected plan or source, so the
"Decision required" panel could not render and chat tasks -- whose issue
number is synthetic -- linked to forge issues that do not exist.

COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when
LinkBranch errored, so the pull request was never opened and the task
parked; a retry re-links the same branch, which Gitea answers with a
conflict, so every retry parked again. It is best-effort now.

INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing
else, so the timeline and activity stream never showed that a human had
intervened. They emit events now.

Also: store write failures answer 500 rather than 409; the dashboard
surfaces the server's actual reason instead of "409 Conflict"; action
buttons stop propagation (acting on a task no longer also expands it),
disable in flight, keep per-task errors instead of one shared string,
and confirm before rejecting.

Removed: the maybeRetryParked shim and markDead with their now-vacuous
tests, WaitingTasks (no consumers; its tests were rewritten to assert
the same routing through TaskByID), write-only Daemon.Runtime, and
dir/dirs response bloat from /api/skills. skillSource checked workDir
before sharedDir, mislabelling every shared skill when the two are equal.
DefaultRoots now dedupes roots differing only by a trailing separator.

The air build rule claiming to keep ui/dist current never ran -- it
required one file to satisfy include_dir and include_file together, and
ui/ is excluded from the walk. Deleted with the comment that promised it.
task test:ui joins task check and CI; it ran nowhere before, so the
dashboard suite could rot silently.

Docs corrected where they described behaviour that no longer exists:
parks no longer comment on the issue, state labels no longer drive
retries, and forgerpc's doc claimed four proxied methods while listing
three of five.
2026-08-05 03:54:25 +10:00
sam a2b2dc9ef2 fix(tools): let an optional provider fail without taking the daemon down
provider.Registry.Start was atomic for every provider: one failure
unregistered every other provider including the builtins, returned an
error up through the capability host, and exited archied. Under
Restart=on-failure that is a crash loop. Observed on carina 2026-07-30 --
mcp.desktop-commander could not start because the runtime image was
missing unzip, and the daemon restarted continuously, losing chat, the
gateway and every builtin tool over one third-party npm package.

Atomicity is right for a provider archied requires. It is wrong for an
external MCP server pulled from a registry at runtime, which is exactly
the category allowed to be absent -- the same reasoning already applied
to the forge, and to containers.

RegisterOptional marks a provider the daemon can run without. Its
failure to start, discover or index stops only itself and excludes it;
Register keeps today's rollback. Required/optional is a deployment fact
rather than a property of the code, so the registrar states it instead
of the engine declaring it in its own manifest -- which also keeps
plugin.Manifest metadata-only, per the plugin engine rule.

A skipped provider's dependents cannot run either: an optional dependent
is skipped with the reason, a required one is a hard failure, since it
declared it cannot work without something now absent.

Degradation is reported, not silent -- Health goes degraded naming each
provider and cause, Skipped() exposes the set, and the daemon logs one
error line per exclusion. Silence is how this went unnoticed until the
crash loop. A provider that half-started before failing is still
stopped, so no child process is left behind.

The regression test drives the real capability host, the path main.go
calls: with desktop-commander registered as required it fails with the
verbatim carina error, and as optional the daemon starts with its
builtins intact.

Closes archie-core-ky6
2026-08-04 23:32:47 +10:00
sam f64353f0b5 fix(gateway): do not answer a redelivered message twice
Making the store idempotent stopped redelivery duplicating the inbound
record, but nothing consulted that result: respond() saved the message,
ignored the fact that nothing had changed, and called the model anyway.
The cost was a second billed turn, any tool side effects run a second
time, and a second assistant reply appended -- replies carry no upstream
reference, so they always get a fresh identity and always append. The
stated problem, "a re-delivered update appends a duplicate turn", was
only half fixed.

PriorReply answers "have I already replied to this?" from the history
the caller has already loaded, and the chat path replays that answer
instead of regenerating it. A message with nothing after it was never
answered -- the turn may have died partway -- so that still runs, since
the user is owed a reply.

CanonicalMessageID exposes the store's own derivation rather than
letting the caller reimplement it, since a lookup that silently never
matches is indistinguishable from a message never seen.

Refs archie-core-i6q
2026-08-04 22:23:17 +10:00
sam 0d4d045050 fix(memory): fall back to the default directory instead of exiting
d615de5 made an unusable memory directory fatal. That was the wrong
call and contradicts the forge and container paths: memory is one
capability among many, and refusing to start over a path denies the
operator chat, the dashboard and everything else -- then crash-loops
under Restart=on-failure with the real error scrolling past unread.

builtin.New now reports an unusable directory through IsAvailable and
Err rather than failing, so the caller decides. The daemon warns and
falls back to the location an unset work_dir would have produced, which
is where someone who copied a config from another host will look. If
that is unusable too it says what the operator loses -- no recollection
between conversations, and failing writes -- and carries on.

The provider stays readable while degraded, so a bad path reads as an
empty memory rather than breaking mid-conversation, and the dashboard's
memory page already renders IsAvailable so this is visible there.

Also fixes a defect the fallback test caught: an empty work_dir made
filepath.Join produce the relative path "memory", which MkdirAll
creates wherever the daemon was started from -- succeeding, and putting
memory somewhere nobody would look.

Refs archie-core-rml
2026-08-04 02:13:05 +10:00
sam 4d44ef76f5 feat(webui): rebuild the dashboard
The old UI was a single 200-line Go file serving one hand-written HTML
page of task rows. It showed that archied was running and almost nothing
about what it was doing -- skills, workflows, memory, channels, logs and
configuration were all invisible unless you read the source or the
config file.

The dashboard now covers each of those as its own section, built as a
Vite app under ui/ at the repo root: it is a separate artefact from the
Go daemon, not an internal package of it. dist/ is committed so building
archied never needs a Node toolchain, and the !no_ui build tag keeps an
embed-free build available.

Both sides are split by concern rather than by layer -- one Go file per
API area, one folder per UI section with its own CSS -- so a change to
logs cannot disturb tasks.

Pages report consequences, not just state: an empty memory page says
Archie starts every conversation with no recollection of earlier ones,
and the setup checklist names what is missing in plain language instead
of showing a grid of zeroes. Nothing greets by a hardcoded name; the
operator comes from [chat], which is deployment data.

Auth is exposure control, not capability control -- the agent already
holds this user's authority through its own tools. So a loopback bind
needs no token, and only a reachable bind mints one and logs a URL,
which means an instance cannot be exposed merely by omitting config.

Container startup now degrades instead of aborting, for the reason
resolveForge already does: a missing agent image should not deny the
operator chat and the dashboard, and under Restart=on-failure it turns a
recoverable problem into a crash loop with the real error scrolling past.

`task dev` runs the daemon under air and the Vite server together in one
terminal.
2026-08-04 01:45:36 +10:00
sam 449c925f29 feat(logging): optional rotating log file
Under systemd, journald held the only copy of archied's output, and
running it by hand left no record at all -- so "where are the logs?" had
no good answer, and the dashboard had no history to show from before it
connected. [log] adds a file destination alongside stderr, with
size-based rotation and retention done in-package rather than pulling in
a dependency for a few hundred lines.

A file that cannot be opened is reported and the daemon continues on
stderr: losing the durable copy is not worth refusing to start over.

reader.go owns the on-disk format so nothing else has to parse it, and
bounds every read -- tailing keeps the newest entries within a fixed
scan window, so pointing it at a large file cannot exhaust memory.
2026-08-04 01:44:56 +10:00
sam 3ae59c99c0 fix(secrets): wire provider credentials through engines 2026-07-31 08:45:58 +10:00
sam 2307c8c81a feat: unify provider and model selection 2026-07-31 03:40:03 +10:00
sam 6c32550345 chore: replace personal owner names in tests and config with generic values
Test fixtures used 'sam', 'samcharles93', and 'sam/<repo>' as owner
names. These are personal and machine-specific — the repo should use
generic placeholders like 'acme' (matching the existing convention in
worktree_test.go).

config.example.toml: samcharles93 -> your-github-username
Test owner: sam -> acme
Repo refs: sam/archie-core -> acme/archie-core, etc.
Example skills: sam -> acme
2026-07-31 02:15:41 +10:00
sam bc5d8dcdc9 test: drop tests that grep source text instead of behaviour
These asserted on file contents rather than what the code does:
Dockerfile strings, deploy.yml YAML, CHANGELOG headings, and greps of
main.go for identifiers. Two also referenced config.docker.toml and
docker-compose.yml, which were never committed, so they could not pass
at all.

The worst compared strings.Index byte offsets in main.go to assert
startup ordering -- it would pass on code that never runs and fail on
a correct refactor that moved a line.
2026-07-31 01:13:16 +10:00
sam 4c0a06df6d fix(container): write the task boot brief under .git
WriteTaskJSON wrote task.json to the worktree root -- the same worktree
the agent commits from. CommitAll stages with go-git's All option, and
go-git's Add does not honour .gitignore or .git/info/exclude, so the
brief was swept into the agent's commit and pushed onto every task
branch. That is how a task.json for issue #57 ended up committed in
the repo root.

This is the identical failure the prepared sentinel hit; worktree.go
already documents the fix. Nothing under .git can ever be tracked, so
put the brief there rather than papering over it with an exclude.
2026-07-31 01:13:08 +10:00
sam 75e58ef595 fix(archied): disable the forge on a missing credential, not the daemon
An unresolvable forge token aborted startup with exit 1, denying the
operator chat, the gateway and every other subsystem over a capability
they may not use -- and under the installed unit (Restart=on-failure,
RestartSec=5s) it crash-looped where the error was never read.

Forge setup moves into resolveForge, shared by the primary forge and
each configured identity, and degrades to NoopForge with a warning.
Malformed config still fails fast in validation. The systemd unit gains
StartLimitIntervalSec/StartLimitBurst as a backstop for other failures.
2026-07-30 02:01:28 +10:00
sam 6be754787d polish: add install.sh, XDG setup, deployments/ examples, and github-token docs\n\n- Add install.sh following XDG Base Directory specification (~/.config/archie, ~/.local/share/archie, ~/.local/bin)\n- Add interactive setup for code forge (GitHub / Gitea / Standalone) and LLM provider selection (Ollama model picker / Cloud keys)\n- Implement NoopForge in internal/forge/noop.go for running Archie in standalone mode without a forge\n- Enable loginctl user linger and systemd user unit setup in install.sh\n- Add docs/github-token.md with step-by-step guidance for Classic PAT generation\n- Add top-level deployments/ directory with scenario templates (single-forge GitHub, multi-forge GitHub+Gitea, local Ollama standalone, systemd runbook) 2026-07-30 01:25:46 +10:00
sam d3dd06d48f Merge remote-tracking branch 'origin/feat/75-add-mcp-client-capabilities-to-archied-and-archie-agent'
# Conflicts:
#	cmd/archie-agent/main.go
#	cmd/archied/main.go
#	cmd/archied/main_test.go
#	internal/agentexec/nats.go
#	internal/config/config.go
#	internal/tools/budget_test.go
#	internal/tools/dispatch_test.go
#	internal/tools/mcp/transport_sse.go
2026-07-29 23:19:36 +10:00
sam e7d39254e7 feat: make /stop reach running agent tasks
/stop cancelled the chat turn but could not touch a task the daemon was
executing, and /cancel refused outright:

    case statusRunning:
        return fmt.Errorf("task is actively running; cannot cancel
                           until it reaches a waiting state")

So the one case worth interrupting was the one case neither command
would touch.

The daemon now holds a cancel function for every executing task,
registered in process() -- the single point every dispatch path reaches
-- so a task is stoppable for its whole life, including the slow clone,
worktree prepare and image pull that is exactly when someone realises
they asked for the wrong thing.

- /cancel <id> interrupts the work first, then records the terminal
  state. That order matters: writing the state while the task still runs
  invites it to write its own afterwards and win. A task the store calls
  running that nothing is executing (crashed daemon) still gets its state
  recorded, which is what unsticks it.
- bare /stop now stops the reply, the queue behind it, and every running
  task for the identity, reporting which of those it actually did.
  Nobody reaching for the brake should have to look up a task ID first.
- StopRunning deliberately writes no terminal state: a stopped task
  unwinds to parked, which is resumable. Forcing rejected would discard
  work worth keeping.
- Without a runtime wired, cancelling a running task is still refused --
  recording it as cancelled while it carries on would be a lie.

Container teardown detaches from the task context. Release runs on the
way out, and the main reason a task is on its way out is cancellation --
at which point the graceful ContainerStop failed instantly and the
container was left to the forced remove. Cleanup gets its own deadline.

process() gained two statements and crossed the funlen limit, so the
container setup block is extracted rather than suppressed.
2026-07-29 19:19:04 +10:00
sam 561e56b70a feat: make /stop cancel the running chat turn
/stop could not reach a running turn, and the reason was worse than a
missing cancel. go-telegram/bot runs one update worker that calls
handlers synchronously (defaultWorkers = 1, never overridden), and the
chat turn ran on it. While a turn streamed -- or sat in a shell tool --
the worker was blocked and /stop sat unread in the update channel until
the turn it was meant to kill had already finished.

Add gateway.Turns: a per-session serial lane that turns are submitted to
and that the event loop never waits on. The worker is free again in
microseconds, so /stop is serviced immediately; ordering comes from the
lane being serial rather than from the loop being blocked.

- Bare /stop cancels the running turn and clears the backlog behind it,
  with no approval step. Approval guards destructive commands, and
  gating the brake behind a confirmation defeats it. /stop <name> keeps
  the existing process-termination behaviour and its approval.
- Cancellation propagates through the turn context, so it reaches the
  model stream and any tool underneath -- a shell command built with
  exec.CommandContext dies with the turn.
- Queues are unbounded and never shed. A dropped message is a silent
  failure that surfaces later as an agent that ignored something.
- Turns are recovered per-lane: the channel's panic middleware wraps the
  event-loop goroutine, which no longer runs the turn.

Also raise the chat step budget. It was hardcoded at 8 -- roughly one
read, one grep and two edits -- so turns hit the cap and stopped
mid-task with no indication they had been cut off. It is now
chat.max_steps, defaulting to 100. Interruption is /stop's job.
2026-07-29 16:41:55 +10:00
sam e03cef17c9 feat(tools): lift tau's file and shell tools into the tool registry
The chat agent had two tools -- memory_edit and skill_activate -- so it
could not read a file, search a tree or run a command. ai-sdk's runtime
already drives a tool loop for it (MaxSteps 8, toolExecute wired as the
executor), so the loop was never the missing piece: the registry was empty
of anything useful.

Lifted from tau internal/agent/tools at commit f5289ea, per the recorded
copy-and-mutate strategy: every file carries a provenance header naming its
tau source path, the commit, and the mutations made, so refreshing from
upstream is a diff rather than archaeology.

  internal/tools/builtin/          the lifted tools, ~3.1k lines
  internal/tools/provider/builtin/ the adapter to tools.ToolEntry

Six tools: read, write, edit, shell, grep, find. Tau's own tests came with
them and pass unmodified, which is the evidence that the lift is faithful.

Deliberately not lifted:
  - agent.go (1214 lines): subagent spawning, and the only real coupling in
    the package -- 10 tau packages including chat, sessions, store and
    registry. Nothing the chat agent needs to do work.
  - skill.go: depends on tau's skills package; archie has internal/skill and
    already exposes skill_activate.
  - docs.go: serves tau's own embedded documentation via tau/docs.

Not lifting the coordinator either. It is tau's agent loop (6.4k lines over
ten packages) and archie already has one in the ai-sdk runtime; porting it
would leave two loops competing. Its cancellation and tool events are worth
having, but they are a few hundred lines built against the existing path
rather than six thousand lifted onto a second one.

The adapter bridges two shape differences: archie hands handlers decoded
arguments where tau's executor takes raw JSON, and tau reports tool-level
failure in Result.IsError rather than as an error -- surfaced as a real
error so the runtime and the guardrail engine both see it. Tools are
classified idempotent or mutating for guardrails and budgets; that is
categorisation, not a jail.

chat.workspace roots the tools and defaults to empty, which registers none
of them. They read, write and execute, so the directory has to be a
deliberate choice rather than whatever the daemon started in -- in the
container that is /.

Verified: go build, go vet, gofmt clean; full suite passes.
2026-07-29 15:46:21 +10:00
sam bf5a7618e6 fix(chat): operator name from config, session wiring, prompt rules
Three defects found from a real Telegram transcript.

1. The operator's name was compiled into the prompt.

internal/gateway/persona.go and prompt.go both hardcoded "Sam's" into the
default persona and the fallback prompt. The persona renders first into
every system prompt, so a personal name was sent to the model provider on
every turn, and any other deployment got an assistant that believed it
worked for someone else. There was nowhere to put it: Repo.Owner is a repo
owner and config.Config had no operator concept.

ChatConfig.Operator now carries it, rendered in the prompt's <env> block as
runtime metadata and omitted entirely when unset. config.example.toml
documents that setting it sends the name to the model provider.

2. /new claimed to clear history that it had not cleared.

The chat responder keyed history by channel id through a local sessionKey
helper, while the session commands operate on tracked session ids.
sessionTracker.resolve mints deterministic ids so the two agree -- until
/new, /branch or /resume assigns a generated id, after which they address
different histories permanently. /new reported "Conversation history has
been cleared" while the next turn still saw everything, and /undo,
/compress, /resume and /sessions acted on a namespace the conversation
never read.

gateway.Router.ResolveSessionKey already existed for this, and
session_commands.go:104 said outright that main.go should call it instead of
its inline helper. It never got wired. The responder now resolves through
the router and the dead helper is deleted so it cannot come back.

buildTelegramRouter constructs the router before the responder so the
dependency is visible rather than captured by reference.

3. Prompt rules for two behaviours the transcript showed.

The agent offered to accept shell access it has no tool to use, which is
both unhonourable and a request for the user's secrets. It also opened
mid-conversation replies with a greeting, and described its own manner
("no fluff") in stock phrasing. Added core rule 7 and three communication
rules covering greetings, self-description and register.

Note the memory claim in that transcript was NOT a fabrication: the
memory_edit tool's own description names MEMORY.md and USER.md, and tool
descriptions are part of the prompt.

Also added chat-turn logging (session id, channel, thread, history depth).
Chat turns were entirely unlogged, so a report of lost context had no
evidence to check: 76 log lines covered two days and none of them was a
conversation. A separate report of mid-conversation amnesia remains
undiagnosed -- single process, 43h uptime, compression untriggered at three
messages -- and this is what makes it diagnosable next time.

Regression tests: prompt renders/omits the operator and carries no personal
name; the responder resolves via ResolveSessionKey and defines no local
session key helper.

Verified: go build, go vet, gofmt clean; full suite passes.
2026-07-29 15:17:23 +10:00
sam 9d5040fd65 refactor: add internal/eventbus as the broker-neutral messaging contract
dependencies-and-contracts.md rule 1 says domains must not import
internal/infrastructure. internal/daemon and internal/agentexec both did,
and for exactly the thing the doc carves out: "internal/eventbus is an
approved shared application contract ... it MUST remain broker-neutral."

The Publisher/Consumer/Requester interfaces existed but lived inside the
NATS package, so a caller could depend on the behaviour yet still had to
import the implementation to name it. They now live in internal/eventbus,
and nats.Client asserts against eventbus.Bus.

The larger violation was ownership of meaning. The doc says "message schemas
stay with their owning domains; the event bus transports messages, it does
not own their meaning." The bus exported TaskEnvelope and a PublishTask
method, so the transport knew what a unit of work was, and it exported the
archie.agent.* subject helpers, so it also owned the agent protocol.

  - TaskEnvelope, its routing Kind, the label vocabulary and the task
    subjects move to internal/domain/workintake, which encodes and decodes
    its own bytes. This starts internal/domain/ per organisation.md.
  - The agent request/response/system subjects move to internal/agentexec,
    which defines what those messages mean.
  - internal/workflow keeps only the kind-to-registry mapping; the label
    table stays single and lives with the domain that reads forge issues.
  - The bus now carries opaque payloads on plain-string subjects.

Consumers declare the smallest interface they need rather than taking the
whole Bus: daemon.TaskBus is publish-unique/fetch/request, agentexec.
RequestBus is publish-request/reply-inbox, and archie-agent's stageBus is
fetch/respond. None can reach what it does not use.

Two defects this surfaced:

  - archie-agent declared its own JetStream stream with a second copy of the
    name, subjects, retention, dedup window, MaxDeliver and TTLs that
    nats.Connect already sets -- two definitions of one stream, free to
    diverge. Config now takes Subjects and FilterSubject from composition,
    which is what let the agent use the shared client and delete its
    hand-rolled setup.
  - Replying to a request needs core NATS, not the JetStream publish path:
    a reply inbox is ephemeral and belongs to no stream, so a durable
    publish to it fails. The old code hid this by using the raw connection.
    The contract now distinguishes Respond from Publish. The agentexec
    round-trip test caught it after I had made the same mistake in
    archie-agent.

Also translated the SDK's ErrNoResponders into eventbus.ErrNoResponders, so
the daemon's taskrun retry no longer imports the NATS SDK to name a
transient condition. The SDK is now confined to the nats package, the *rpc
packages (themselves NATS infrastructure), and cmd/*.

The agentexec test fake previously hand-rolled a JetStream consumer; it now
drains the client's own consumer, which is both closer to production and
avoids conflicting consumers on a work-queue stream.

Verified: go build, go vet, gofmt clean; full test suite passes.
2026-07-29 11:40:24 +10:00
sam c66c0a2a38 refactor(config): move loading into infrastructure/configuration
internal/config both defined the types every package imports and performed
the file I/O to produce them. Importing a settings struct therefore pulled
in a TOML decoder and a YAML decoder, and the shared model owned discovery,
decoding, overlays, defaulting and validation all at once. See
docs/architecture/configuration.md, which requires loading to move out and
internal/config to be dissolved.

internal/config is now types only -- no os, no filepath, no toml. The new
package owns loading, one concern per file:

  features.go    the closed set of recognised feature files
  discovery.go   directory scan and classification
  decode.go      TOML/YAML decoding, format dispatch
  defaults.go    filling absent values, no errors
  validate.go    judging supplied values, no mutation
  provenance.go  which file contributed what
  loader.go      Loader wiring the above; File/Overlay/Dir

Beyond relocating, this fixes what the old code conflated:

  - Defaulting and validation were interleaved. applyAgentDefaults and
    applyDispatchDefaults returned validation errors; validateContainers and
    validateSingleIdentity quietly mutated the config. There was no point at
    which you could see what the operator actually supplied. They are now
    separate passes: applyDefaults never fails, validate never writes.
  - Errors were fmt.Errorf strings prefixed "config: ", so a caller could not
    distinguish operator-fixable input from an unreadable file without
    matching message text. Five sentinels now carry that distinction.
  - dataHome() read XDG_DATA_HOME directly and discarded the error from
    os.UserHomeDir, so defaulting could not be tested without the
    environment. It is injectable on Loader and no longer swallows the error.
  - Nothing recorded where a value came from. With overlays, feature files
    and conf.d/ all able to set the same field, "which file set this?" was
    answerable only by re-deriving precedence by hand. Provenance records it.
  - Feature files were applied in map iteration order, making load order and
    any resulting error arbitrary. Discovery now returns them sorted.
  - loadMainConfig reported "no config.yaml or config.toml found in %s" with
    an empty string: the directory was lost when it was extracted from
    loadDirInto, so the error named no directory.
  - Unreadable or malformed conf.d/ extras were skipped silently, which
    presents as a setting the operator wrote simply not taking effect.
  - Decode errors from the main config were returned bare, without naming
    the file that failed to parse.

The 40 loader tests moved with the code and their assertions are unchanged,
so the defaulting and validation rewrite is behaviour-preserving.

Document.Config is the temporary seam: still internal/config.Config, named
as a field so the compromise is visible at each use site, with its deletion
condition recorded in doc.go. Building typed per-domain sections now, while
every consumer still reads config.Config, would mean two shapes kept in sync
by hand with no consumer for the new one; that belongs with the dissolution
work, not ahead of it.

No consumer outside cmd/archied changed.

Verified: go build, go vet, gofmt clean; go test ./internal/config/... and
./internal/infrastructure/configuration/... pass. Pre-existing gateway and
telegram failures are unchanged.
2026-07-29 11:07:41 +10:00
sam a8efbf5046 refactor: route tasks on a typed kind, not forge labels
The event bus was inspecting forge issue labels ("bug", "feature",
"bootstrap") to pick a subject. That put a forge vocabulary inside
infrastructure and duplicated the label table already owned by
workflow.Route -- adding a label meant remembering both places, and
nothing would have caught it if you forgot.

The label table now lives once, in internal/workflow, which already owns
label semantics:

  - workflow.Kind names the routing category, with labelKinds as the
    single label vocabulary and kindWorkflows mapping kind to registry
    entry. Route consumes the ordered kind list so a "bug,feature" task
    still falls through to feasibility when no tdd workflow is
    registered, exactly as the switch did.
  - nats.TaskKind is a closed, validated set of subject tokens.
    PublishTask rejects an unknown kind rather than silently delivering
    it to the default queue; the zero kind means default, so messages
    queued before this field decode unchanged.
  - The daemon classifies at the publish site and sets TaskEnvelope.Kind.

Also fixes two defects this exposed:

  - drainNATS never reached its SQLite fallback. Replacing the old
    (nil, nil) no-message signal with ErrNoMessage in 492ca20 made that
    case continue at the top of the loop, but no-message is precisely
    when the fallback must run -- requeued tasks (waiting_human approval,
    retry-parked) never go through a NATS publish, so nothing would ever
    arrive to trigger them. go vet caught it as unreachable code.
  - config.classifyFeatureFile silently overwrote duplicate feature
    files, so config.gateway.yaml and conf.d/gateway.yaml together
    applied one at random. Its own doc comment recorded the bug
    ("or "" on success/duplicate"). The known-feature list in the error
    message is now derived from knownFeatureNames instead of being
    spelled out a second time beside it.

A test also called t.Fatalf from a non-test goroutine, where it does not
stop the test.

Verified: go build, go vet, gofmt clean. Pre-existing gateway (18) and
telegram (1) failures are unchanged in count -- they are lost routing
wiring from the parallel telegram merges, tracked separately.
2026-07-29 10:43:52 +10:00
sam 2d082eef89 Merge branch 'crew/lint6' 2026-07-29 10:37:52 +10:00
sam 492ca209f9 refactor(nats): rebuild as infrastructure/eventbus/nats with real boundaries
Relocating internal/nats as-is would have cemented its problems into the
approved layout, so this is a rewrite rather than a move.

What was wrong:
- Conn() *nats.Conn, PublishMsg(*nats.Msg) and Fetch() jetstream.Msg pushed
  SDK types into all four consumers, so the broker was not replaceable --
  the opposite of what dependencies-and-contracts.md requires.
- PublishTask took seven positional parameters, six of them strings, where a
  transposed argument was a silent bug.
- Labels travelled as a comma-separated string and were re-split on every
  publish.
- Fetch returned (nil, nil) for 'no message', which every caller had to
  remember to special-case.
- The logger field was stored and never used.
- Stream name, consumer name and every timeout were hardcoded constants.
- Errors were inconsistently wrapped; several paths returned bare errors.
- Connect repeated nc.Close() on each failure branch.

What replaces it:
- One concern per file: config, errors, subjects, message, client,
  publisher, consumer.
- Publisher/Consumer/Requester interfaces with compile-time assertions, so
  callers depend on behaviour and can be faked without a broker.
- A Message wrapper keeps jetstream types behind the boundary; consumers no
  longer import the NATS SDK at all.
- TaskEnvelope with []string labels and JSON methods preserving the
  comma-separated wire form for already-queued messages.
- Sentinel errors (ErrNoMessage, ErrNotConnected, ErrNoReplyAddress,
  ErrInvalidConfig) and %w wrapping with operation context throughout.
- Config with validation and defaults; a single deferred cleanup in Connect.
- CoreConn() as the one documented escape hatch, for the *rpc packages that
  are themselves NATS infrastructure.

Consumers migrated: cmd/archied, cmd/archie-agent, internal/daemon,
internal/agentexec. Behaviour, subjects and wire format unchanged.
2026-07-29 10:19:09 +10:00
sam 712388dc6c fix: Phase 4 structural refactor — reduce lint findings from 28 to 5
cyclop (5→0): extract subcommand/case bodies in codesearch,
subprocess, Telegram, indexing
funlen (5→3): extract memory action handlers, tool provider startup
gocognit (7→2): extract config finalize/loadDirInto helpers, release
announcer, capture tool validation, Telegram gateway (200→108),
archie-agent main loop (35→0)
nestif (8→0): extract identity validation, container validation,
conf.d scanning, email multipart parsing, Telegram model/update
parsing, build-no-changes closure
interfacebloat (3→0): split Forge/IssueForge/PRForge/RepoForge,
SessionStore/SessionLifecycle/MessageHistory,
TaskStore/TaskLifecycle/TaskQueries/TaskEvents

Remaining: daemon process, workflow Feasibility/TDD/AgentStage,
archied main.go run (108→30 remaining). These require deeper
refactoring best done per-function in follow-up beads.

Updated contract tests and archied wiring tests to check both
main.go and the new telegram_setup.go.
2026-07-29 10:15:22 +10:00
sam a66da97ab7 gateway: implement session lifecycle and context commands (archie-core-alm.5)
Add gateway/runtime-owned commands that remain usable when LLM credits
are exhausted:

- /start — acknowledgement without consuming a reply
- /new [name] (alias: /reset) — create a fresh session
- /topic [off|help|<session-id>] — session switching for threaded chats
- /retry — remove last assistant message, replay last user turn
- /undo [N] — remove last N messages from history (default: 1)
- /title [name] — set or display session title
- /branch [name] (alias: /fork) — create child session with inherited history
- /compress [here N|focus topic|--preview|--dry-run] (alias: /compact)

Design:
- sessionTracker maps channel+thread to active session, auto-creating
  implicit sessions with the legacy sessionKey format for backward
  compatibility with existing persisted data
- /new and /branch create explicit UUID-backed sessions
- SessionStore extended with DeleteRecentMessages, MessageCount, and
  SaveMessages for undo/retry/branch/compress operations
- SessionContext extended with Title, ParentSessionID, BranchName
- All commands report 'not configured' when session store isn't wired

Session resolution is wired into the LLM responder so /new, /branch,
and /topic switches affect subsequent chat turns.
2026-07-29 03:43:34 +10:00
sam 65aa5b462d chore: cleanup 2026-07-28 18:46:50 +10:00
sam 15d746c2f6 style: phase 1 of lint remediation — autofix pass (qa4)
golangci-lint run --fix plus the formatters: errorlint, gocritic,
sloglint, usestdlibvars, usetesting, gci, gofumpt, goimports.
160 issues -> 130.

One autofix was wrong and had to be reverted by hand. gocritic rewrote

    ctx, cancel = context.WithTimeout(ctx, m.prefetchTimeout)

to `:=` inside an if-block in internal/memory/manager.go. That does not
compile, which is the good outcome — had it compiled, the shadowed ctx
would have scoped the timeout to the if-block and the prefetch deadline
would silently never have applied. Restored the assignment and commented
why it must not be a declaration.

Worth recording: --fix is not a safe no-op. It broke the build on a
24-file change, and the failure mode it was one compiler error away from
was a silent behaviour change.
2026-07-28 01:37:20 +10:00
sam 446dc6b3de feat(indexing): port tau's codesearch workspace index (4we)
First slice of the tau cherry-pick strategy: copy-and-mutate rather than
extracting tau to pkg/. Exporting would force designing metrics, session
and logger seams upfront, before archie-core knows which of them it wants
differently — a cost paid for reuse not yet proven. ai-sdk earned library
status by stabilising across two consumers; nothing in tau/internal has.

indexing is the cheapest high-value lift: 512 LoC, one file, and its only
coupling to tau was three calls to process-global config path helpers.
Nothing else in tau imports it.

Mutations from upstream:
  - path helpers become an explicit indexing.Config. Two archied instances
    share a host (archie and winter), so they must not share one index.
  - the child-process helper is archied's own workspace-codesearch
    subcommand, dispatched before flag parsing so it touches no config,
    store or NATS.
  - deferred db.Close calls explicitly discarded; archie-core runs errcheck.

The child process is not incidental: google/codesearch calls fatal exits on
a corrupt index and leaks mmapped regions. Verified end to end against this
repo — 2.2MB indexed, correct hits for BuildSystemPrompt, [] for no match,
and a deliberately corrupted index returns "corrupt index" with exit 1
instead of taking the process down.

Every lifted file carries a provenance header naming its tau path and
commit (4893818d0c76), so refreshing from upstream is a diff rather than
archaeology.
2026-07-28 01:37:19 +10:00
sam c79c623e9c feat(chat): real system prompt for Archie — identity, tools, env (sc5)
The chat agent's entire system prompt was the four-sentence static string
in gateway.DefaultPersonas(). It carried no tool inventory, no environment
block and no instruction precedence, so the model invented its own
capabilities: asked to set something up it announced it "only has the
memory editing tool", then offered to walk through installing software it
has no tool to install.

Renders a template modelled on tau's agent.md.tpl + tau.agent.md:
instruction precedence, core rules, communication rules, a <tools> block
and an <env> block. The persona stays the style layer on top; the rules
and the tool inventory live in the template so switching persona cannot
remove them.

The tool list is derived from the same core.ToolSet handed to the model,
so the prompt cannot drift from what the agent can actually call, and an
empty toolset renders an explicit "no tools are available" rather than
silence the model fills in for itself.

Tool metadata is third-party data from MCP servers, so it is markup-escaped
(<, >, & only — not xml.EscapeText, which mangles prose into &#xA;/&#39;)
and whitespace-flattened, so a description cannot forge a closing tag or a
second "- tool: ..." list entry.
2026-07-28 01:37:19 +10:00
sam bcca6f9c25 feat(telegram): add approved component updates 2026-07-27 13:02:11 +10:00
sam c1c3a973c6 feat(telegram): report installed component versions 2026-07-27 12:53:59 +10:00
sam 647537c00a refactor(telegram): keep one model selector command 2026-07-27 11:44:27 +10:00
sam ec8534dfe2 feat(gateway): ship model controls, shell tools, and release tracking 2026-07-27 06:16:39 +10:00
archie 5f964030c5 feat: add MCP client capabilities to archied and archie-agent (archie)
Implements #75
2026-07-26 19:51:36 +00:00
sam 19a6311f6c feat(telegram): /restart to reload config without dropping tasks (16.35)
Operator escape hatch: reload gateway config (notably the sender
allowlist) or recover a wedged adapter from chat, with no shell access to
the host.

Start becomes a supervisor loop that relaunches the bot on request, so a
restart is scoped to the gateway: the daemon keeps running and in-flight
agent tasks are untouched. Exiting the process would also have restarted
under the unless-stopped policy, but would have killed running work.

Two failure modes are handled deliberately:

- The handler runs on the very bot the supervisor is about to stop, so it
  hands off over a buffered channel and returns instead of tearing down
  inline, which would deadlock the restart it just requested. A duplicate
  request while one is in flight is dropped, not queued.
- A failed config reload logs and relaunches on the previous settings, so
  a bad config edit cannot take chat down permanently -- which would also
  remove the means to fix it.

Authorisation is inherited from authorizedMessage: only allowlisted
senders reach any handler, so /restart is admin-only by construction.
main.go supplies Reload, which re-reads config from disk and refreshes
token and allowlist; other fields still need a full daemon restart, since
they are wired at construction.
2026-07-27 05:21:58 +10:00
sam cb147b7a37 feat(telegram): deny-by-default sender allowlist + command menu (16.33, 16.34)
Allowlist (16.33). telegram.New was called with a nil allowlist and
isChatAllowed returned true whenever the list was empty, so any Telegram
user who found the bot could talk to it; AllowedChatIDs was not plumbed
into config, so there was no way to close it. Chat tools run with the
daemon's own authority, so this had to be fixed before wiring any real
tools to the chat agent.

Now chat.telegram.allowed_user_ids configures it and an empty list denies
everyone: a bot handle is public, so failing open is not a safe default.
The check matches the sender (from.id) rather than the chat, so adding
the bot to a group cannot be used to inherit access. Rejections log the
sender id and answer once, so a legitimate user missing from the list can
tell the bot is misconfigured rather than dead. Startup warns when the
gateway is enabled with an empty list.

The previous TestIsChatAllowed asserted 'empty allowlist allows all' --
it encoded the vulnerability -- and is replaced by fail-closed tests.

Command menu (16.34). SetMyCommands was never called, so Telegram showed
no menu and the commands Router implements were undiscoverable; asked
about /commands the LLM confidently answered it had none. The published
list mirrors what Router actually handles. Failure is logged, not fatal:
it costs discoverability, not function.
2026-07-27 05:14:34 +10:00
sam 285c618f74 fix(chat): drain FullStream, not TextStream — streaming deadlocked every reply
Streamed chat replies hung on the first token: the draft rendered an
empty cursor, the typing indicator never cleared, and the turn never
completed.

RouteStream consumed stream.TextStream, but ai-sdk's channel contract
makes FullStream authoritative and requires draining it until close --
its writes are synchronous, so an unread FullStream applies backpressure
and stalls the producer. Once its buffer filled, the producer blocked,
TextStream stopped yielding, and the range loop blocked forever.

TextStream was the wrong source regardless: it is explicitly best-effort
and drops deltas when not drained, so a reply reconstructed from it can
silently lose text. Range over FullStream and collect StreamPartTextDelta
parts, exactly as the SDK documents.

Also bumps ai-sdk v0.1.17 -> v0.1.18 (build, full suite and lint clean).
2026-07-27 05:04:04 +10:00