A task hosts the same configured MCP servers as a chat turn, but the
worker's provider builder passed no sampling handler, so a task-scoped
server's sampling/createMessage request got a JSON-RPC method-not-found
while the identical request succeeded on the chat path. The worker runs
its own model runtime, so it can answer.
Thread a sampling handler built from the task's builder model into the
worker's MCP provider builder, beside the chat path's handler. Build the
task's model runtime once and share it with the stage runners instead of
creating a second client for sampling.
Move the sampling message mapping and max-token bound to agentexec, next
to the runtime both paths call models through, so a server gets the same
bound on either path. Carry the catalog's reasoning flag in
ModelLimits: a reasoning-class builder model must omit the max-token
bound its provider rejects, exactly as the chat path does.
A remotely-shipped task log entry was re-emitted through the sink with
slog.Logger.LogAttrs, which stamps time.Now(): the entry's own event time
was discarded and replaced with the daemon's receipt time. Because a
container's records arrive in bursts, a multi-minute run collapsed onto a
few milliseconds of receipt timestamps and its timing became
unrecoverable -- which stage ran when, how long an iteration took, whether
a stage stalled.
Write now builds the record from entry.Time (falling back to receipt time
only for an entry that carries none) and dispatches it through the same
handler, preserving the sink's level gate. Receipt time stays available
separately in the record's received_at field, so event time and arrival
time cannot be confused. The agent-side producer already carried the
record's own time; a test now pins that half too.
The temp-repo fixtures in agentexec, domain/workflow and agentworker seeded
a repository and committed without disabling gpg signing, so a host with
commit.gpgsign=true and an agent-only SSH signing key failed those tests at
the fixture's own git call ("Couldn't get agent socket?").
Each producer now writes commit.gpgsign=false into the temporary repository's
own config, which also covers commits made inside the seeded repo by a
subprocess (the fake harness). A regression test per package pins the
fixture's hermeticity under a hostile global git config.
Clears the five open CodeQL alerts. harnessCredential parsed uid and gid
as 32-bit and os.Chown converted them to int, which wraps on a 32-bit
build; they are now parsed to 31 bits, so an out-of-range id is refused
where it is read. mergeMapping sized its map by len(base)+len(override);
it now hints len(base) and lets the map grow.
Claude's input_tokens excludes cache reads and writes; the built-in
loop's Anthropic provider folds them into PromptTokens so budgets count
total prompt size. The harness adapter now does the same, so one budget
means the same on either runner.
Pairs tool_use and tool_result blocks by ID into tool-call reports, keeps
the latest session_id, takes the run's usage from the result event and
falls back to per-message usage, counted once per message ID, for a run
killed before its result. Tested on streams recorded from Claude Code
2.1.282 and scrubbed of host detail.
archie-agent mcp is a stdio MCP server, on the official go-sdk, serving a
stage's capture tools and appending accepted calls to a captures file.
The harness runner writes the tool spec and a standard mcpServers config,
registers it through HarnessSpec.MCPConfig, and reads the captures back
into the stage result. The captures file is writable by the harness user,
so the worker validates every record again with the same acceptCapture
the built-in loop now shares, and forged, undeclared or over-cap records
are dropped. A stage with capture tools on a harness without MCP is
refused before it runs.
A Kit task runs worker and harness in one container, separated by user:
the worker keeps its credentials as root, and every harness invocation
runs as the Kit's user with only its declared environment. A nil env
would inherit the worker's, so the runner always passes an explicit one;
root is refused as a harness user, and a root worker refuses to start a
harness with no user. The PRD's container layout now says one container
per run, with the relay forwarding the proxy, NATS and the State Store.
A stage whose request carries a HarnessSpec runs the Kit's CLI as a
subprocess in its own process group, with the mission and archie's rules
as the prompt. After every invocation the runner compares HEAD, every ref
and the git configuration, and the worktree against a pre-run baseline:
any ref or config change, a protected-path edit, or a write in a
read-only stage parks the step whatever the CLI claimed. The runner runs
the gate itself and resumes the same session with the gate's output, up
to the gate's failure cap. The wall clock and cancellation kill the whole
process group, so the CLI's children cannot outlive the step.
ClearTerminalTasks now deletes completed tasks, with a test that holds its
SQL list to taskstate.Terminal. The AllowTools comment says agentloop's
built-in file tools are outside the allowlist and why. The PRD model
diagram lists only what a profile holds (image, tools), and the profile
field and AgentProfile say a workflow's profile name is resolved at
dispatch, not when the workflow is saved.
Workflow definitions declare inputs, repository (none, optional or
required; default required) and profile. A binding assigns each input
from a mapped parameter or a constant and may take its repository from a
parameter, which must name a configured repo; both are checked when the
binding is saved and again at dispatch. Inputs travel as structured task
data (tasks.inputs, the task brief, and a JSON block in the agent's
mission), never as body text.
A task with no repository runs in a per-task scratch workspace with no
clone and no publication grant. The agent.run step runs one mission
without a repository and finishes the task in the new completed status.
Agent profiles live under [containers.profiles.<name>]: an image and an
allowlist over the tools archie adds (MCP, scripts, plugins).
[containers].image is the default profile; an unconfigured profile parks
the task. The workflow is now pinned before the container starts so the
profile can choose its image.
Also stop two archied tests writing embedded NATS state into the package
directory, refuse an empty state_dir for embedded NATS, and drop the NATS
store files an earlier lane commit tracked.
The selection criteria alone left workflow optional and defaulted an omitted
or unrecognised value to implement, so a decide call could still skip the
decision and send an unsettled capability straight to the builder.
Omission is now a retryable rejection: CaptureTool gains RequiredWhenTrue, a
conditional requirement a flat RequiredFields entry cannot express, because
the close-without-change branch has no workflow to name and must not be made
to invent one. A rejected call is not recorded, so it does not consume
MaxCalls and the model retries with the field.
A value outside the enum now fails the stage rather than degrading to
implement: reaching OnResult with one means the model ignored its own schema.
Splits validateCaptureArgs into per-constraint checks (cyclop) and carries
the regenerated contracts.json.
The events table had no attempt column, so two attempts of the same task were
indistinguishable: a retried task's stage events interleaved into one timeline and
nothing could say which run produced a given result.
- events gains an `attempt` column through the existing presence-gated
migrateTasks loop rather than a version bump, so user_version stays 3 and an
existing archie.db is migrated in place. A legacy-database test builds the
pre-change schema and proves both that existing rows survive unattributed
(attempt = 0) and that a new value round-trips.
- Event.attempt = 11 and ReadTaskLogRequest.stage = 9 are field additions to
existing messages: no new RPC, no new table, and no change to any canonical error
message that crosses the state-store wire.
- Every task event the workflow engine emits now carries the attempt. Producers
that have no attempt yet (task_queued, binding_dispatch_failure) stay
unattributed rather than guessing one.
- Changed files are captured as a durable changes_captured event at commit and push
time, reusing the existing three-dot diff primitive: paths from FilePatches(),
counts from Stats(), base_sha recorded as the merge base actually diffed rather
than the base tip, a 200-file cap with totals kept complete. Consumption goes
through an unexported optional interface so workflow.Trees -- the yaegi capability
surface for interpreted stage plugins -- is not widened. A capture is also taken
once the pull request exists, so the capture can link it.
- The per-attempt configuration is captured as a durable config_captured event
carrying the non-secret config.TaskConfig, instead of a new table plus two new
state-store RPCs: events are already this system's per-attempt provenance stream,
so a table would have given one feature two provenance mechanisms. Redaction is
proven against canary secrets. Measured payload: 539 bytes typical, 2333 bytes at
20 models.
- Captures carry a schema marker and are refused unless their key set matches the
declared payload shape, so drift surfaces as "recorded but could not be read"
rather than as a capture of zeroes.
- Three read endpoints serve the attempt rail, the changed-file captures and a raw
debug view, mapping to UI-owned response types rather than dumping store types.
- The task-log read gains a stage filter, bound to the stage logger for that
stage's own lines; agent and tool output records no stage.
A task-scoped grant may already insert events on its own task, so this provenance
is exactly as trustworthy as the rest of that task's event stream. That limit is
documented rather than papered over.
- toolset.go: extract requireApproval out of toolExecute (nestif)
- gateway.go: extract handleDeny/handleVersion/handleUpdateCheck/
handleRestartAdapter out of dispatchLocal (gocyclo 26 -> under 20)
- cronstore/store.go: extract applyPatch/applyScheduleChange out of
Update (nestif, gocognit)
Behavior-preserving.
Replaces hand-written JSON Schema + manual unmarshal with
core.NewTypedTool[In], now available at the pinned ai-sdk v0.1.30. This
removes the class of bug where a hand-rolled schema drifts from the
struct a manual decode unmarshals into.
Task runs now preserve real model context limits, provider usage, baseline-repair spend, commit identity, durable agent-finish telemetry, and useful timeline details without imposing a token cap. Dashboard forge links are canonical per owning GitHub or Gitea identity. Chat turn claims acquire SQLite writer intent before reading, eliminating the concurrent SQLITE_BUSY snapshot race.
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.
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
Six mechanical fixes from `golangci-lint run ./...` (30 findings total, 23
deliberately left -- see the next commit's message for the one that grew
into something bigger, and the following note for the rest):
- apply.go: %v -> %w for the wrapped yaml error, matching the identical
double-%w pattern already used in decode.go/discovery.go/loader.go in the
same package (errorlint).
- contract_test.go: filepath.Join("provider.go") with a single argument is a
no-op join; replaced with the literal (gocritic).
- inprocess_test.go, yaegi_test.go: two goroutines whose whole purpose is
timing (does Execute return promptly on cancellation / does Run block
forever), where the call's result is irrelevant -- explicitly discarded
with `_, _ =` and a comment saying why, rather than silently ignored
(errcheck).
- find_test.go: an unchecked os.MkdirAll now matches the file's own
createTestFile helper, which already checks and t.Fatals on the same
operation (errcheck).
Not touched, and why: 18 cyclop/gocognit/gocyclo/funlen/nestif findings
require extracting helpers to reduce complexity -- the exact shape of two
regressions already recorded in CLAUDE.md's Lint-driven changes section
(one from --fix silently dropping a predicate, one from a nestif extraction
that doubled data), so a blind sweep across 9 unfamiliar files was declined
rather than risk a third. 2 godox findings (storage.go, worktree.go) mark
real missing work; deleting the comment would hide debt, not fix it. 3
recvcheck findings (Duration, TaskEnvelope, Provenance) each mix a
mandatory-pointer-receiver method (UnmarshalText/UnmarshalJSON's interface
contract, or genuine mutation) with correctly-value-receiver read-only
methods -- forcing consistency would either break interface conformance or
force pointer receivers onto call sites where the value isn't addressable.
Adversarially reviewed by a fresh subagent: all six confirmed
behavior-neutral or behavior-improving, all touched packages pass -race,
golangci-lint confirms exactly 23 issues remain (not more, not fewer), and
none are new.
archie-core-467 wired tool-call visibility into the interactive chat
gateway, but a workflow task's own transcript never showed what its
tools actually did -- only stage/agent-finish events existed, so
there was no way to confirm an agent's summary matched what it really
ran.
Adds a ToolCallReporter, invoked once per completed call from
toolExecute (the single choke point every tool call passes through
before reaching a model), reported via a new ToolSetOptions.OnToolCall
hook. Runner.Run grows a report parameter to carry it in: InProcessRunner
wires it through, since it executes in the same process as its tools;
SubprocessRunner and NATSRunner accept and ignore it, since their tool
calls happen in a different process with nothing here to observe them.
The workflow engine turns each report into a tool_call event on the
task's own Bus (agent.go, implement.go), riding the same NATS
event-forwarding archie-core-518 already built to get container
events onto the daemon's timeline.
Scoped to the central tool registry (read/write/edit/grep/shell/...)
built via BuildToolSet; capture tools (structured finish output) and
run_go_script build their ToolSet entries directly and are not yet
covered.
A workflow run through the container/NATS path never wired
workflow.TaskContext.Bus, so every tc.Emit call (stage_start,
stage_finish, outcome, parked) was a silent no-op. archied's own
in-process path sets Bus and always worked; anything dispatched to an
archie-agent worker did not, which meant the dashboard's per-task
timeline showed "No events yet" for every task regardless of status
or stage -- confirmed live across a Working task and two differently
parked tasks.
Bridges the gap the same way system logs already cross this boundary:
ForwardTaskEvents relays a per-task in-process *events.Bus to a new
NATS subject (SubjectForEvents), and a new daemon-side subscriber
(subscribeAgentEvents) republishes decoded events on the daemon's own
Bus, landing them in the same persist-and-broadcast pipeline an
in-process workflow already used.
Closes#518
cmd/archie-agent used to own worker construction, NATS lifecycle, task execution, MCP setup, and workflow wiring. It now owns process input only and invokes internal/app/agentworker, while transport-specific NATS, boot-brief, and git-safety mechanics live under infrastructure.
Closes the loop #451-#453 opened. archie-agent (#453) now publishes its
own logs to agentexec.SubjectForSystem(taskID) over NATS, and a task
log sink (#452) exists to persist them, but nothing on the daemon side
subscribed, demuxed, or wrote anything -- the messages had nowhere to
land.
- agentexec: SubjectSystemWildcard + TaskIDFromSystemSubject, the
inverse of SubjectForSystem, for a daemon subscribing to every
task's system subject with one wildcard subscription.
- logging: TaskRegistry manages one open TaskSink per running task
attempt, mirroring every write onto the live dashboard Feed the same
way a locally-written log would appear. Nil-receiver-safe, matching
every other optional composition-wired Daemon field.
- daemon: Daemon.process opens a task's log sink for its own duration
(covering both the sandboxed-container and in-process dispatch
paths uniformly) and closes it on every return path.
- cmd/archied: constructs the registry, subscribes core NATS to
SubjectSystemWildcard, and wires TaskLogs into both Daemon and
webui.Server.
- webui: archiving a task now removes its log directory too, so
archived tasks' logs don't accumulate forever. Documented as a
known, accepted race: a task can reach terminal status (satisfying
ArchiveTask's precondition) before process() itself returns and
closes the sink, so a very late system-log write can race an
archive's Remove. Not corrupting -- the write lands on a
soon-to-be-unlinked inode and is discarded -- and not worth fixing
here: it would mean tying Close to the store transition instead of
to process()'s return, a larger change than this issue's scope.
Adversarial review (fresh subagent) found and fixed two real issues in
the first draft: a doc comment accidentally spliced between two
functions during an extraction meant to fix a lint regression, and a
genuine test gap on openTaskLog (added, using TaskRegistry.Write's own
true/false contract as the observable -- no Store/Forge/Trees fakes
needed, since openTaskLog only touches TaskLogs and Log).
Part of #453 (task-observability epic #450). archie-agent logged to
os.Stderr only, and its container is created with AutoRemove: true
(internal/container/pool.go), so all of it disappeared the moment a
task's container exited -- there was no way to see why, say, a gate
command failed inside one.
Adds agentexec.SystemLogHandler: a slog.Handler that tees to whatever
it wraps (kept for an operator attached to a live container) and
additionally publishes each record, JSON-encoded as a logging.Entry,
to SubjectForSystem(taskID) -- a subject that already existed,
documented for exactly this ("log dumps, health... observability"),
with zero publishers anywhere in the codebase.
cmd/archie-agent/main.go wires it in only when this container was
spawned for one specific task (bootTaskID / .git/task.json present);
shared queue-group mode serves many unrelated tasks per process, so
there's no single task subject to ship to and keeps the stderr-only
logger.
Building this surfaced a real pre-existing bug: FeedHandler's attr
flattening applied the group chain active at Handle-time to *all*
accumulated attrs, including ones added via WithAttrs before a later
WithGroup call -- nesting them under a group they were never
actually inside, contrary to slog's own documented Handler contract.
It went unnoticed because nothing in the codebase called WithGroup
until this change needed to. Extracting the shared flattening logic
into exported FlattenAttrs/PrefixAttrs (so SystemLogHandler doesn't
duplicate it) is what surfaced it; fixed in the same change since I
was the one making it public API.
Docs on the wire format's own trap for the daemon-side consumer
(#454, not yet written): the published bytes are a marshaled
logging.Entry, meant for json.Unmarshal, not logging.decode() --
decode() parses raw slog JSON *log lines* off disk, a different and
incompatible shape. See the doc comment on SystemLogHandler.
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.
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.
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.
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.
97 -> 85. Not one of the eleven nilerr findings was a bug.
I called these "real bug candidates" when I planned the phases. I was
wrong, and the reason is worth recording: every site is the same
deliberate idiom, and a linter cannot see intent.
- inprocess.go (5) and gateway.go (2) are handlers that report a
problem as TEXT to their consumer. A tool handler returning a Go
error aborts the tool call; returning "rejected: ..." lets the model
read the feedback and retry with valid arguments. A chat handler
returning a Go error surfaces as a gateway fault instead of a usage
hint to the human.
- worker.go carries runErr in the response envelope's Error field.
Returning it as a Go error too would double-report and abort the
NATS reply.
- email.go returns nil when Accept fails because context cancellation
closed the listener. That is a clean shutdown.
- codesearch.go skips an unreadable entry and continues the walk. A
best-effort index must not abort on one bad file.
- skill.go is documented in the function comment already: a
non-directory skills path means "no skills", not a fatal error.
Annotated each with //nolint:nilerr and the specific reason rather than
excluding the linter by path, so nilerr stays live everywhere else and
the next reader wondering "why nil here?" gets an answer at the site.
This is the phase I insisted on keeping single-session and out of the
subagent fan-out. A worker told to "fix nilerr" would have converted all
eleven to error returns: malformed tool arguments would hard-fail the
agent loop instead of being correctable, chat typos would read as
gateway faults, and shutdown would log spurious errors. Every test would
still have passed.
Checkpoint commit covering concurrent work across several archie-core-abg
epics to avoid losing in-progress state:
- Memory manager (18.7-18.16): background sync pipeline, prefetch with
timeout, memory-write notification, threat scanning, shutdown drain
with abandoned-write tracking, frozen snapshot pattern. Wired
ScanContent and NotifyMemoryToolWrite into HandleToolCall so scanning
and notification actually apply to writes, not just exist as unused
primitives.
- Fixed a literal unresolved merge-conflict that had been committed to
internal/memory/scrubber/scrubber.go.
- Tool provider/registry, MCP client/transport (stdio, HTTP, SSE),
multimodal results, disclosure.
- Pairing device auth store, rate limiting.
- Gateway compression, session store, tasks.
- Various workflow, plugin host, and agentexec updates.
internal/secret package:
- Engine interface (Name, Version, Resolve) for pluggable secret backends
- SecretRef type replacing TokenEnv/APIKeyEnv string fields
- ResolveOrEnv for backward-compatible env-var fallback
- Built-in env engine registered by default
- Registry with Register/Get/Resolve/LoadDir (yaegi-based)
- DefaultRegistry() singleton for one-off resolution
- 12 tests, race-clean
Scoped to foundation only. Provider/NATS/Telegram migration deferred
to xec.4 (separate bead — those call sites forward env var names to
subprocesses/runtimes and need eager-resolve-then-inject, not a simple
field rename).
40/40 packages pass with -race.