102 Commits
Author SHA1 Message Date
sam 6c287b48e6 fix: return write-side close errors; the gate checks unhandled errors 2026-11-14 03:31:46 +11:00
sam 65e6bafb23 fix(tools): the path jail is a value each tool set owns, not a process global (#1921) 2026-11-13 03:47:34 +11:00
sam 892ed291b9 refactor(mcp): use the official MCP Go SDK for the client
Deletes the hand-written internal/tools/mcp client and transports. The
provider talks to an SDK ClientSession over CommandTransport,
StreamableClientTransport or SSEClientTransport, and reconnects when the
server exits. The http transport now keeps a real streamable session
instead of stateless POSTs. Sampling goes through one adapter, since the
SDK marks it deprecated (SEP-2577). message_endpoint is removed: the
SSE transport takes the POST URL from the server's endpoint event.
2026-11-13 03:44:55 +11:00
sam db346b159d fix(webui): mark cookies Secure behind a TLS proxy; run gosec in the gate (#1919)
Cookies took Secure from r.TLS, which is nil behind a proxy that terminates
TLS, so sign-in cookies went out without it. Every dashboard cookie now goes
through one builder that reads the scheme the way the origin check does.

The worktree reset and the agent worker's chown walk use os.Root, so a
symlink swapped in mid-walk can't point them outside the worktree.

gosec runs in golangci-lint, tests included. G104, G115, G204 and G304 are
excluded in config; each remaining finding is fixed or suppressed at the site
with its reason.
2026-11-13 03:16:15 +11:00
sam b548cabcbf refactor(publicnet): one public-address dial guard for webhooks, attachments and web fetch (#1795)
deploy / gate (push) Failing after 8m13s
deploy / archied-image (push) Skipped
deploy / agent-image (push) Skipped
deploy / dist-zip (push) Skipped
2026-11-08 15:52:39 +11:00
sam 0c137d9319 refactor(fsutil): consolidate nine copies of the atomic write helper
Nine packages each had their own write-temp-then-rename helper with
slightly different behaviour (some synced, some did not; some created
the parent directory, some did not; modes and temp-file patterns
varied). They are replaced by one fsutil.WriteFileAtomic that always
syncs before rename, creates the parent directory, and takes the file
mode as a parameter.
2026-10-28 00:48:59 +11:00
sam f2b8681611 refactor(workflow): stop assuming a human decides
An approval, ask or park can be resolved by an operator, a rule, a
classifier or automatically, so the vocabulary stops naming a person:

- step type human.approve -> workflow.approve
- park class needs_human -> needs_decision (ParkNeedsDecision)
- event kinds human_* -> operator_*
- alert kind task.needs_human -> task.needs_decision
- status grouping "needs you" -> "needs attention"

0061 rewrites the stored values, including the approval step type in the
workflow-definitions resource and each task's pinned definition, with the
digest recomputed so resumed tasks still match.
2026-10-25 17:31:16 +11:00
sam 340223de2e feat(modelloop): run a step's tool calls in parallel as each tool's classification allows 2026-10-25 16:45:34 +11:00
sam 55c201e7c1 fix(builtin): send_file resolves symlinks before the confinement check 2026-10-25 16:45:34 +11:00
sam 01acb97f96 chore: delete code no binary or test reaches 2026-10-17 10:14:26 +11:00
sam 819cfc655b refactor: slices.Sorted over map keys and one shared IsNil check 2026-10-10 11:14:36 +11:00
sam 5afe5bcf99 refactor: use slices.Index/Delete and slices.Clone for small copies 2026-10-10 11:14:36 +11:00
sam a69b3455d3 refactor(tools): back generate_video with ai-sdk's minimax video provider
Delete the hand-rolled MiniMax HTTP/poll client; ai-sdk v0.1.43 already
ships provider/minimax implementing video.Provider with the same endpoints,
defaults and poll semantics. The tool now takes a video.Provider and the
composition root builds it, matching the transcription and embedding
capabilities.
2026-10-08 22:42:49 +11:00
sam 647b9bcce7 chore: remove Yaegi
yaegiutil, the go.mod dependency, the .yaegi host-code entry and the legacy
guard stages for .archie/gate.go and .archie/stages are gone.
2026-10-04 03:08:46 +11:00
sam cb6b8618c2 refactor: cut remaining long comments down to what the code does 2026-10-03 22:06:57 +10:00
sam e10980dc33 refactor(postgres,mcp,archieui,task,prreview,playbook): cut comments down to what the code does 2026-10-03 22:01:54 +10:00
sam 4ebde6b315 refactor(configuration,builtin): cut comments down to what the code does 2026-10-03 21:58:23 +10:00
sam 030b4ed176 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 780bc44d82 refactor: testing from the beginning. a journey in 150k lines of tests to none 2026-10-03 21:16:25 +10:00
sam ab86442156 feat(tools): reconcile MCP servers and tool settings live
Flip tool-settings to ApplyMode live (archie-core-zfb0.3): the daemon now
watches the kind, diffs the stored MCP server set against the running
providers -- connecting added servers, disconnecting removed ones and
reconnecting changed ones while an unchanged server keeps running -- and
rebuilds the web_fetch and minimax entries, whose config is captured at
construction. A changed server whose replacement fails to start is rolled
back to the one running, and the refusal is reported through apply status.

toolprovider.Registry grows running-state Add/Remove/Replace beside
Register, Start and Stop, isolating a provider's failure the way the plugin
host's Add/Replace do. The chat turn model resolves its tool-output policy
per turn instead of capturing it at construction, and the boot registration
reads the running holder so a stored update that lands during boot is not
lost.
2026-10-02 11:46:37 +10:00
sam 04d0495f12 revert(tools): drop the checkpoint writer with no restore caller
The pre-mutation file checkpoint added in e10d862f wrote a full copy of
every write/edit target into .git/archie-checkpoints, but nothing could
restore it: CheckpointStore.RestoreLatest (and its latest/restore
helpers) had no production caller, no rollback surface reaches the
workspace, and the store was never pruned, so it grew without bound in
every workspace.

A writer whose only reader is unreachable is dead weight and an
unbounded disk cost, so the write half goes with the read half: write
and edit no longer snapshot, and CheckpointStore is deleted. The
regression test pins the decision by asserting a write and an edit
leave no .git/archie-checkpoints behind.
2026-10-02 11:36:10 +10:00
sam a9f441042e style(mcp): apply go fix to the sampling transport 2026-10-02 09:35:21 +10:00
sam a8a04929af feat(mcp): answer server-initiated sampling from the chat model
MCP servers could not ask the client for a completion: the transports
routed only responses by id and dropped every server-initiated request,
so a server calling sampling/createMessage hung waiting for a reply.

Route server->client requests through the transport readers to a handler
on the client. The client answers sampling/createMessage from a
configured SamplingHandler and maps a missing handler, malformed params
and handler failure to JSON-RPC errors for that request alone -- never a
silent drop or a failed session. stdio and SSE implement the routing;
the stateless HTTP transport cannot receive the request at all and says
so in its doc.

The daemon wires the handler to its own chat runtime and active model
role, so a sample is answered by the model a chat turn uses, capped by
the request's maxTokens and the model's output ceiling, and recorded on
/status like every other model call. No model configured is a refused
request with a clear error.
2026-10-02 09:33:32 +10:00
sam e10d862f6a feat(tools): checkpoint files before mutating write and edit
The built-in workspace write and edit tools replaced file content with
no recoverable pre-state. Each now snapshots its target immediately
before the write and refuses the mutation when the snapshot cannot be
taken, so a checkpoint is never silently skipped.

Checkpoints land in .git/archie-checkpoints inside the workspace, the
same per-task state directory that already holds the task brief and the
prepared sentinel: nothing under .git can be swept onto the task branch
by go-git's Add{All:true}. A checkpoint records either the file's bytes
or its absence, so creating a file restores by removing it;
RestoreLatest returns the most recent pre-state for a path.

Shell, Go-script, MCP and plugin tools are deliberately not covered:
the set of files they can touch is not enumerable from the call.
2026-10-02 09:18:47 +10:00
sam 6703cc77cf refactor(indexing): delete the workspace codesearch indexer
The index built google/codesearch over the chat workspace on every daemon
start, for the process lifetime, through a child-process helper and a
SQLite metadata DB -- and grep consulted it only for searches confined to
the workspace root, which the analysed sessions showed was a small
fraction of searches. The compute was continuous; the benefit was not.

Removes internal/indexing, the workspace-codesearch helper subcommand,
the [indexing] config section, and the GrepIndex accelerator seam from
the grep tool, which returns to its direct walk. google/codesearch
leaves go.mod with it.
2026-09-23 00:36:38 +10:00
sam 8485f24332 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 b54f01065c feat(tools): add per-server parallel_tool_calls to the MCP client
MCPServer gains ParallelToolCalls (default false). The client's
per-server callMu is now nil for a server that opted in, so CallTool
stops serializing that server's calls and the caller's own concurrency
decides; every other server keeps exactly one tools/call in flight.

The flag is threaded from config through the provider constructor -
the only place MCPServer configs become Client instances - into
NewClient, in both the daemon and the agent worker.
2026-09-22 01:57:58 +10:00
sam 4750ac097b feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

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

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

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

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

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

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

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

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

* fix(build): drop the Dockerfile pin assertion

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Two findings from the review of q9au.

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

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

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

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

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

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

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

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

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

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

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

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

Rewrites ARCHITECTURE.md's "Memory engine family" section to describe the
current engine (internal/domain/memory contract, internal/infrastructure/
memory builtin engine + its builtin/ markdown store, the per-turn read seam
in gateway/turn_memory.go, the per-turn write tools in
gateway/turn_memory_tool.go) instead of the deleted Manager. Fixes two
docs/architecture/configuration.md rows that described the deleted
manager's literals and SaveConfig mechanism.
2026-09-19 13:43:16 +10:00
sam 32f9c6b0ab feat(tools): wire the workspace codesearch index into grep
internal/tools/builtin.RegisterBuiltins has always accepted a GrepIndex and
nothing ever passed one, so every grep ran the direct walk no matter what
[indexing] was set to. internal/indexing was fully implemented and tested
with zero production callers, and internal/config decoded IndexingConfig into
nothing. Two halves of one defect.

The composition root now builds an indexing.Manager and hands it to the
workspace tool provider, which forwards it to RegisterBuiltins. deadcode
confirms the result rather than the commit message asserting it: unreachable
functions drop from 88 to 73, and all 15 internal/indexing entries are gone.

Failure degrades rather than propagates. A manager that cannot build logs a
warning and grep keeps its direct walk, which is exactly what it did before
this was wired. An accelerator must never stop the daemon starting.

The context is detached with WithoutCancel rather than replaced with
Background: the index build's lifetime is the process, while the gateway
path's boot context is cancelled once startup returns, so inheriting
cancellation would kill the build mid-flight. Background would have satisfied
the linter too, but would silently drop the caller's context values, so
registerTools now takes the context its callers already had.

internal/agentexec's RegisterBuiltins call is deliberately left alone. It
registers builtins only to harvest their names for a plugin tool-name
collision check and never executes them, so there is no grep there to
accelerate.
2026-09-18 13:40:45 +10:00
sam a0dd21273b fix(mcp): cancel in-flight SSE reconnect on Stop
WIRE: the SSE transport's Stop contract already says it closes the
connection and waits for background readers, but the reconnect loop issued
its HTTP GET with the Start context, which Stop could not cancel, so Stop
blocked on readerWg.Wait() against an unreachable endpoint. Wire a
per-lifecycle cancel (mirroring the stdio transport's stopCh plus guarded
commit) so Stop interrupts the in-flight reconnect request.
2026-09-15 13:30:29 +10:00
sam bf7eb16bc4 fix(builtin): bound read/edit filesystem work by DefaultToolTimeout
WIRE: read and edit each declared a DefaultToolTimeout deadline and then
discarded it, so the documented contract (Tools that exceed this are
cancelled) was a no-op on the live tool-executor path. Wire the deadline
through runWithContext, the same helper write already uses, so a hung
filesystem cannot block the tool executor.
2026-09-15 13:12:21 +10:00
sam 8ea45e836b refactor(tools/mcp): delete unreachable MCP adaptation path
DELETE: mcp.Client.RegisterTools and its handlerFor/writeMultimodalResult
chain, plus the WithMediaDir and WithParallelToolCalls options, had no
production caller -- the live adaptation path is provider/mcp.Provider,
which now owns binary media persistence itself. A repo-wide search finds
no remaining reference outside the composition contract test that asserts
RegisterTools must not appear, so the two paths can no longer diverge.
2026-09-15 12:58:10 +10:00
sam c9a5ae4aeb fix(tools/provider/mcp): preserve MCP binary tool results for delivery
WIRE: the live provider/mcp adaptation path is the only production MCP
consumer and its handlerFor detected image/audio/resource-blob blocks but
returned an empty MultimodalResult, so telegram_setup's multimodalMediaRefs
(which reads only result.URLs) had nothing to deliver. Decode each media
block into the provider's media root and populate Files, SubdirHint and
URLs with local-path refs the channel uploads.
2026-09-15 12:54:07 +10:00
sam abb23247c5 refactor(tools): delete unused plugin-tool registration API from builtin.Registry
RegisterPluginTool/SetPluginToolExecutor/UnregisterPluginTools and the
PluginToolDef/PluginToolExecutor types have no production caller.
Plugin/MCP tool registration flows through agentexec.pluginToolSet and
internal/tools.Registry, not this staging registry (tools-builtin-2,
duplicate of tools-core-8).
2026-09-15 10:25:59 +10:00
sam 5c8f2f400a refactor(tools): delete unreachable AST-based tool discovery
Registry.Discover, DefaultRegistry and the go/ast extraction helpers
have no production caller; static source discovery has no PRD and no
consumer. Production registration goes through bootstrap.go's
toolReg.Register and the provider Registry's RegisterBatch (tools-core-3).
2026-09-15 10:23:17 +10:00
sam 778d33f89c refactor(tools): delete unreachable dispatch/gating engine
DispatchSequential, DispatchConcurrent, ClassifyEntry and their
supporting types (dispatch.go) have zero non-test callers; the live
tool path is agentexec/toolset.go's BuildToolSetFrom. Removes the
dead engine and its tests, and updates the PRD status table that
referenced it (tools-core-1).
2026-09-15 10:19:39 +10:00
sam b0e7b03ca1 fix(tools): judge the rm guard by base name so absolute paths cannot bypass it
checkRecursiveDelete compared the raw segment name, `seg.Name != "rm"`, while
every sibling rule in the same table resolves the command through baseName --
checkMkfs, checkBlockDeviceWrite, checkKillAll, checkSystemPower,
checkSelfTermination and checkDaemonLaunch all call baseName(seg.Name), and
baseName's own doc says its purpose is that /sbin/reboot and reboot are judged
the same. The test suite already pinned that convention for /sbin/poweroff.

Because tokenise yields the raw first word, `/bin/rm -rf /` produced
seg.Name == "/bin/rm", the rule declined, no other rule matched, and Hardline
returned nil. Since provider/builtin calls command.Hardline on the shell tool's
command field before every execution, an absolute path defeated the
recursive-root-delete gate entirely. `/bin/rm -rf /etc` (any critical path, not
just the root) was equally reachable; an overlay probe confirmed both, and
confirmed the sibling /sbin/poweroff case was already correct.

Resolve through baseName, matching the rest of the rule table, and add table
cases for absolute-path rm plus an allow case for an ordinary absolute-path
recursive delete so the normalisation cannot over-block.

Found by an adversarial package sweep (temp tracker: tools-command-1,
.local/issue-tracker/).
2026-09-15 01:51:03 +10:00
Samuel Catlow 0e4cc46c8e feat(gateway): wire progressive tool disclosure (bridge tools)
Compose the base registry with per-turn extras into a turn-local registry and
let ContextPressureGate decide full-vs-bridge disclosure per chat turn. The
three bridge tools (tool_search, tool_describe, tool_call) are now wired into
the chat toolset and only disclosed under context pressure, keeping the LLM's
schema footprint small while preserving full arsenal access on demand.

Per-turn extras are identity-bound per channel and cannot live in the
process-wide registry (agentexec.BuildToolSetFrom invariant), so the bridge is
composed turn-locally rather than registered globally. Thread the model's
context window through TurnModel.Prepare (TurnPrepareContext) so the gate
activates with a real window.

Refs #167
2026-09-05 16:02:53 +10:00
samcharles93 83dc672074 fix: baseline gate repair (go test ./... -count=1) 2026-09-02 03:53:40 +00:00
sam 29f47b5439 test: replace brittle assertions with behavior checks
- mcp client_test: assert both initialize handshake calls happened and
  notifications/initialized has an empty ID, not their exact order
- telegram model_test: assert the resolved model has an openrouter/
  prefix instead of scanning button text for the string; replace the
  single-hardcoded-count pagination test with cases covering 0/1/8/9/100
  models so pageBounds and nav-row logic are actually exercised
- webui api_chat_test: assert the actionable file path is present in the
  streamed error instead of matching generic wording
2026-09-01 23:39:23 +10:00
sam 536e4bc0d1 refactor(lint): extract Apply/findWalkVisitor helpers; go fix modernization
- tomlwrite.go: split Apply into collectPending + an applier struct
  (indexTables/resolveTable/matchActiveKeys/uncommentKeys/
  appendMissingKeys/render). gocognit 82 -> under threshold.
- find.go: split findWalkVisitor's closure into findSkipEntry/
  findMatchesFilters. gocognit 46 -> under threshold. This clears the
  last complexity finding from archie-core-agui's original 31.
- richblocks.go: go fix modernization (strings.SplitSeq).

Behavior-preserving.
2026-08-31 21:35:58 +10:00
sam 01a6c4a70e refactor(lint): reduce cyclomatic/cognitive complexity in tools, workflow, webui
Extracts focused helpers out of applyEdits, grepFallback/grepDirFallback,
serveReadContent, handleChatStream, TDD, runFindGoFallback,
makeGrepExecutor and makeShellExecutor to bring them under the
project's cyclop/gocognit/funlen thresholds. Behavior-preserving.

Partial pass on archie-core-agui: richblocks.go (gocognit),
gateway.go dispatchLocal (gocyclo), and a couple of remaining
gocognit/nestif findings are left for a follow-up.
2026-08-31 21:26:22 +10:00
sam adb958d93c fix(app): repoint archied wiring contract test at internal/app/archied
Follow-up to the cmd/archied -> internal/app/archied wiring extraction:
the architecture test that greps main.go for required wiring strings
still pointed at the old cmd/archied path.
2026-08-31 21:25:45 +10:00
sam 32c722fe4a refactor: go modernisation fixes 2026-08-29 00:20:05 +10:00
sam 12f85a581f fix(webui,sendfile): close three holes the adversarial review found
Follow-up to 0b2398f, which claimed non-delivery is never silent and that
oversized files fail visibly. Both claims had gaps.

chatStreamSink.Media skipped any attachment with an empty URL, exactly as
liveReply.Media used to. The tool registry is shared between the Telegram
and dashboard chat setups, so send_file is offered on the dashboard too:
the model announced a sent file, the sink dropped the event, and nothing
reached the transcript. The dashboard cannot upload at all, so the fix is
to REPORT the file as undeliverable and name where it is on the host,
rather than to stay quiet. The skip was right while media meant a hosted
URL; it stopped being right when a host path could arrive here.

send_file applied one 50MB ceiling to every type while the sender enforces
10MB for photos, so an 11-50MB image passed the early check, was reported
sent, and was rejected by a layer the model cannot see. The early check is
now per-type and mirrors the sender's limits.

MediaType called every image/* an image, but a photo endpoint rejects
image/svg+xml and image/tiff outright. Photo-safe formats are now an
explicit set, so an svg goes as a document and arrives, which is what the
"unrecognised means document" reasoning intended all along.

Also tests the readability probe's own error path (mode 0000), which was
the one case it exists for and the one case not covered; verified it fails
with the probe removed.

Remaining review findings are filed, not fixed: fallback lines appended
after the live reply finalizes are dropped by a stopped renderer
(archie-core-atv2), confinement is symlink-blind and re-opens after
checking (archie-core-jkmu), and concurrent uploads are uncapped
(archie-core-3svc).
2026-08-25 01:55:16 +10:00
sam 0b2398f026 feat(telegram): send local files as uploads, not fetchable URLs
The agent could produce a file -- a transcript, a log dump, a screenshot --
and had no way to hand it over. Asked to send one it offered a "download"
link; nothing arrived and it had no signal that anything had failed. The
defect was not that it lied: success and silent non-delivery were
indistinguishable to it.

Three places made a local file undeliverable, and each is fixed here:

  - liveReply.Media skipped any attachment with an empty URL, so a local
    file was dropped before it ever reached a sender.
  - telegramMediaSender built every attachment as models.InputFileString,
    which tells Telegram to FETCH the string as a URL. A host path is not
    fetchable, so the send did nothing while reporting success. It now
    chooses by what the attachment carries: URL -> fetch, Path -> upload
    via models.InputFileUpload over an open file.
  - Nothing let the agent ask for a send at all. New send_file tool
    (internal/tools/sendfile) validates the file and returns a
    MultimodalResult naming it; the turn's channel delivers it.

Meaning changes, called out because the names did not:

  - MediaAttachment gains Path, the alternative to URL. Exactly one is
    meaningful for an outbound send.
  - tools.MultimodalResult.URLs used to mean remote-hosted media only; it
    now means media this result wants delivered, which may be local. JSON
    name unchanged so existing producers keep working.
  - errNoURL is now errNoSource: having neither source, not having no URL,
    is what makes an attachment undeliverable.

Failures are visible at every layer, which is the actual fix. send_file
errors on an absent, irregular, unreadable, oversized or confinement-
refused path, so the model sees it and can report it. The sender checks
Telegram's ceilings (10 MB photos, 50 MB otherwise) before the request and
reports the real size rather than leaving a 400 nobody reads. A delivery
that still fails now appends "could not send <name>" to the reply instead
of an empty link, which read as a delivered file.

Exposing a public URL for local files was explicitly rejected: it trades a
missing feature for a hosting and access-control problem.

send_file resolves paths through builtin.ResolveReadable -- the read tool's
own policy, exported rather than reimplemented -- so sending cannot reach
what reading cannot, whatever [chat] unrestricted_filesystem is set to.
2026-08-25 01:43:15 +10:00
sam 5d00ec7b0c refactor(agentexec): remove legacy execution paths
Autonomous workflows now have exactly one production boundary: a task-scoped archie-agent receives a full-task core-NATS request and runs the worker-local stage loop. The legacy [agent] section remains decode-only for migration; it no longer selects runtime behavior.
2026-08-24 14:56:57 +10:00
sam 691e10c251 fix(telegram): compact tool output and drop turn caps
Render completed ToolCallEvents as Telegram-safe streaming blocks
with compact name/status and a short cleaned preview. Summarize
file contents and listings instead of dumping source or quoted
JSON. Collapse repeated legacy turn-budget failures.

Remove max_tokens turn gating and the 200000 turn_budget_chars
default so absent or commented config cannot restore an aggregate
cap. Keep per-result max_result_chars and spill.

Confine find/grep discovery to the active workspace/worktree.

Refs #604
2026-08-23 16:40:16 +00:00