68 Commits
Author SHA1 Message Date
sam 1fa3acdbe9 fix(security): bound harness IDs to int and drop a summed map size hint
deploy / gate (push) Failing after 3m38s
deploy / build-and-push (push) Skipped
deploy / dist-zip (push) Skipped
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.
2026-09-28 02:20:25 +10:00
sam cdc3e83740 chore(agentexec): strip the recording session's personal tool list from claude fixtures 2026-09-27 18:35:28 +10:00
sam 585df0f81e feat(agentexec): output adapters for Codex, Pi, OMP and Copilot CLI 2026-09-26 10:28:40 +10:00
sam a8c8dfbd7d feat(daemon): run a Kit profile's task in its Kit container on the egress path 2026-09-26 10:14:33 +10:00
sam 0d042b72d9 feat(agentexec): run a Kit task's stages on its harness through a named output adapter 2026-09-26 09:20:30 +10:00
sam 7a54db0cc6 fix(agentexec): count Claude cache tokens as prompt tokens, as the built-in loop does
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.
2026-09-26 09:11:57 +10:00
sam 4067949ce8 feat(agentexec): parse Claude Code's stream-json output for the harness 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.
2026-09-26 09:11:57 +10:00
sam 235b9c1a87 refactor(agentexec): own the capture file format in agentexec, not the app layer 2026-09-26 03:30:19 +10:00
sam 37d913c5fd feat(agentexec): serve capture tools to harnesses over MCP
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.
2026-09-26 03:28:58 +10:00
sam 5b6572bcea feat(agentexec): run harness invocations as the Kit's user with no inherited environment
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.
2026-09-26 03:08:34 +10:00
sam e7611903a8 feat(agentexec): harness runner driving a Kit's agent headlessly
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.
2026-09-26 02:54:03 +10:00
sam d8bec1ae06 fix(eda): clear completed tasks; document the tool allowlist's reach and unchecked profile names
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.
2026-09-24 20:53:51 +10:00
sam d320a1a01a feat(eda): workflow inputs, optional repository and agent profiles
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.
2026-09-24 20:29:33 +10:00
sam c94986cf38 Merge pull request #878 from samcharles93/feat/attempt-attribution
Feat/attempt attribution
2026-09-19 02:48:25 +10:00
sam fe7ee44dcc fix(workflow): require a workflow from triage when a code change is needed
The selection criteria alone left workflow optional and defaulted an omitted
or unrecognised value to implement, so a decide call could still skip the
decision and send an unsettled capability straight to the builder.

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

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

Splits validateCaptureArgs into per-constraint checks (cyclop) and carries
the regenerated contracts.json.
2026-09-19 00:33:39 +10:00
sam 2c09f42ff4 feat(tasks): attribute events, changes and config to the attempt that produced them
The events table had no attempt column, so two attempts of the same task were
indistinguishable: a retried task's stage events interleaved into one timeline and
nothing could say which run produced a given result.

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

A task-scoped grant may already insert events on its own task, so this provenance
is exactly as trustworthy as the rest of that task's event stream. That limit is
documented rather than papered over.
2026-09-18 18:32:59 +10:00
sam 33da682887 refactor(lint): extract more helpers to clear nestif/gocyclo findings
- 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.
2026-08-31 21:28:46 +10:00
sam 4e2d90e34b refactor(agentexec): use ai-sdk NewTypedTool for pluginToolSet and scriptToolSet
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.
2026-08-31 21:25:58 +10:00
sam a825db283c fix: harden task and chat execution
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.
2026-08-25 05:48:17 +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 7b5dca3c42 fix(agentexec): recover omitted finish calls 2026-08-24 14:56:56 +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
sam d7801bb7d3 feat(storage): persist agent project state 2026-08-22 21:00:20 +10:00
sam 0ae6440a66 fix: address simple findings from a repo-wide golangci-lint sweep
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.
2026-08-22 02:03:11 +10:00
sam c12bd72f60 style: remove trailing whitespace 2026-08-16 01:28:25 +10:00
sam 89af556fa0 test: use t.Context() for helper subprocess 2026-08-16 01:08:47 +10:00
sam 20bff1a367 feat(agentexec,workflow): surface tool calls on the task timeline
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.
2026-08-15 12:53:41 +10:00
sam d9a9b17153 fix(agentworker): forward workflow events across the NATS worker boundary
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
2026-08-15 10:34:25 +10:00
sam 45345cdfb6 refactor(agent): move worker runtime into application layer
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.
2026-08-15 00:43:12 +10:00
sam 951ddbc9f4 feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
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).
2026-08-09 18:42:54 +10:00
sam 53da52ecd1 feat(agentexec): publish agent-side logs to the task's system subject
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.
2026-08-09 16:49:39 +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 e10cbbc92c refactor: pre-cleanup. 2026-08-06 01:40:15 +10:00
sam 5695f83037 style: gofmt import grouping after MCP merge 2026-07-29 23:19: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 366e8f412b Merge remote-tracking branch 'origin/fix/45-skillscriptrun-ignores-context-cannot-be-canceledtimed-out' 2026-07-29 23:15:58 +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 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 529b25eada docs: phase 3a — nilerr review, all 11 sites were false positives (qa4)
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.
2026-07-28 01:39:22 +10:00
archie ce0fc1fac0 fix: skillscript.Run ignores context, cannot be canceled/timed out (archie)
Fixes #45
2026-07-27 02:41:44 +00:00
archie c3aa0a0a02 test: failing repro for #45 2026-07-27 02:35:35 +00: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 f73b2d1c8c feat: memory manager sync/prefetch/scan/shutdown + broad in-flight epic work
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.
2026-07-27 03:34:46 +10:00
sam 146acf5466 feat: secret engine registry foundation (archie-core-xec)
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.
2026-07-26 14:20:19 +10:00
sam f6d51416f0 chore: replace 607 em-dashes with double hyphens project-wide
Includes MCP crash-after-init test fix (crash moved from handle() to serve()
entry point so transport sees immediate subprocess death).
2026-07-26 09:53:33 +10:00
sam 9df02f2b60 fix: golangci-lint baseline to zero findings (39→0)
19 files touched. All fixes are in code — no lint configuration
weakened:
- Added unchecked error handling in defer cleanup paths
- Removed dead variables and unused functions
- Added missing imports (io in gitea.go)
- Simplified conditions (TrimSuffix, De Morgan, slices.Contains)

Also fixes JetStream TempDir teardown race (archie-core-340):
t.Cleanup(srv.Shutdown) now registers after t.TempDir() so
server shutdown (including JetStream files) completes before
temp dir removal. Added srv.WaitForShutdown() for deterministic
cleanup ordering.

Closes: archie-core-756, archie-core-340
2026-07-25 23:51:13 +10:00
sam 75f237d1ad feat: daemon hands off tasks to archie-agent in sandboxed mode (archie-core-5zh.8)
daemon.process() branches on ContainerPool != nil: sandboxed tasks publish
a taskrun.Request to archie.taskrun.<id> and await the response via the
new runViaAgent method, instead of running workflow.Route/workflow.Run
locally. Non-container mode is unchanged. Every durable side effect
(Store, Forge, git push) already landed via the storerpc/forgerpc/
worktreerpc proxies during archie-agent's run by the time runViaAgent
returns — it only parks the task itself on transport/setup failure, never
duplicating a terminal state archie-agent's own workflow.Run already
recorded.

Also fixes a real correctness gap: with concurrent multi-task dispatch
(archie-core-u64/g1l) plus containerized archie-agent, a shared queue-group
subscription could let one container answer a sibling's taskrun message
while having a *different* task's worktree mounted. archie-agent now reads
its boot-time task.json and subscribes to its own exact per-task subject
when present, falling back to the shared queue group only in dev/pool mode
(no task.json).

Adds agentexec.ProvidersFromConfig, deduped from cmd/archied's former
executionProviders.

Closes the archie-core-5zh epic: archie-agent runs an entire task's
workflow per invocation instead of one stage per round trip, with all
credentials staying daemon-side throughout.
2026-07-24 09:14:56 +10:00