Commit Graph
1088 Commits
Author SHA1 Message Date
sam b1a8a9a9da fix(archieui): exit cleanly when graceful shutdown overruns its deadline
The gate failed intermittently with "task: Failed to run task \"test\": exit
status 1" and a tailed log that hid the failing package. The package was
cmd/archie-ui, which sorts before internal/logging and so never appeared in the
visible tail.

Cause: serve() returned the error from server.Shutdown, which is
context.DeadlineExceeded whenever a request is still draining when
ShutdownTimeout elapses. That converted a normal load-induced overrun into a
non-zero process exit, and TestUIProcessServesTheDashboardAgainstLiveDependencies
asserts a clean exit after SIGTERM.

Fix at the producer, in serve(): on overrun, force-close the remaining
connections and report a clean shutdown. No timeout is lengthened, no retry,
skip or -p 1 is added, and the smoke test's assertion is untouched.

Reproduced under parallel build load: -count=30 on the suspect test produced the
exact shutdown-deadline signature once; after the fix, 30/30 pass with zero
occurrences. The new test drives the deadline path deterministically by holding
a request in flight rather than relying on machine load.
2026-09-19 01:51:11 +10:00
sam 0ee2b8a1cf feat(nats): provision the ARCHIE_REACTIONS fan-out stream
archie.reaction.* had no matching stream. bootstrap.go:501-502 bound only
ARCHIE_TASKS to archie.task.> under WorkQueuePolicy, so any publish to a
reaction subject made js.PublishMsg fail and the publisher saw a publish error
-- the reason a previously landed reaction producer would have answered HTTP 500
on every webhook delivery.

ARCHIE_TASKS must stay WorkQueuePolicy: under it a second consumer on an
overlapping filter subject silently receives nothing, which is the trap recorded
in CLAUDE.md. Reactions need the opposite property, so they get a second stream:

- workintake.SubjectReactionWildcard ("archie.reaction.>")
- nats.DefaultReactionStreamName ("ARCHIE_REACTIONS")
- nats.FanOutRetention(), a pointer helper so composition can select
  LimitsPolicy without importing the NATS SDK, since nil Retention already means
  WorkQueuePolicy and the zero value (LimitsPolicy) is a valid explicit choice
- a second nats.Connect in connectNATS carrying that stream, closed on failure
  and registered for shutdown cleanup

Red-then-green: TestConnectNATSCreatesReactionStream failed with "publish to
archie.reaction.* = nats: no response from stream, want it to land in
ARCHIE_REACTIONS" before the stream existed.

Step 1 of docs/prds/pr-review-remediation.md (bead archie-core-8li9.1).
2026-09-19 01:51:07 +10:00
sam 8ffa6ffb51 fix(daemon): sweep every identity's forge and repos at startup
daemon.Startup ran the invitation sweep and push verification only against the
root forge and Cfg().Repos. In multi-identity mode Run branches to
runIdentities, where each identity polls its own forge and its own repo list --
so per-identity invitations were never accepted and per-identity repos were
never push-verified. A task from those repos failed later at dispatch instead of
warning at boot.

Startup now branches on len(d.Identities) and sweeps each identity through
sweepIdentity, which reuses id.Forge and id.Repos -- the same IdentityRunner
fields runIdentities and pollForIdentity already iterate, so there is no second
identity-to-forge mapping. One identity's forge outage cannot abort a sibling's
sweep: failures are logged as warnings, matching Run's stated failure-isolation
intent.

Red-then-green: TestStartupSweepsEveryIdentityForgeAndRepos failed with
"identity one AcceptInvitations = 0, want 1" (and both identities' repos empty)
before the change.
2026-09-19 01:51:03 +10:00
sam fe8d64cc9f fix(chat): wire the Telegram adapter restart callback into the chat router
/restart could never work in production. boot.setupGateways captured the
Telegram adapter's restart callback into boot.restartTelegram, a field no code
ever read, so gateway.Router.Restart was nil in every composition:
handleRestartAdapter always answered "not configured" and LocalChatAdapter's
snapshot always reported RestartAvailable: false.

Fix at the producer: buildTelegramRouter assigns Router.Restart directly from
the adapter it already holds. The dead field and the telegramSetup.RegisterRestart
indirection are deleted rather than kept alive.

Red-then-green: TestBuildTelegramRouterWiresRestartCallback failed with
"router.Restart = nil, want the telegram adapter restart callback wired into the
router" before the change. TestBuildTelegramRouterRestartUnconfigured pins the
unchanged no-adapter behaviour, including the not-configured reply.
2026-09-19 01:50:41 +10:00
sam 42bfd35514 fix(config): enforce the service context at registration
ServiceSpec.Context documented which addresses a service must end up with, but
nothing read it, so a typo'd context was accepted and meant nothing. Review
caught it as scaffolding that looked load-bearing.

RegisterService now validates it: an unknown context, or a hosted (server/both)
service registered with no default listen address, panics. Registrations come
from this repository's own init(), never from operator input, so an invalid one
is a programming error with no caller positioned to handle an error return, and
failing at process start beats a service binding where nobody dials.

Services.RequireTarget replaces the same check and message hand-written in
composeStateStoreClient and composeChatContract. An empty registered default
target is what declares a target operator-supplied, so the requirement belongs
to the registry rather than to each consumer. It stays a lazy check at
composition time rather than becoming load-time validation: a process that
never dials a service must still load a configuration that omits it.

The review's stated failure mode does not occur. A hosted service with an empty
listen does not reach net.Listen as an ephemeral port; resolveServiceListen
returns "no listen address" and archied refuses to start. The defect was the
inert field, not a silent bind.

Refs: archie-core-u23g
2026-09-19 01:50:25 +10:00
sam 5e15bfd07a Merge pull request #870 from samcharles93/fix/label-routing-and-triage-criteria
fix: restore kind routing for namespaced labels, and give triage real criteria
2026-09-19 00:35:05 +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 af56021267 feat(workflow): give triage criteria for choosing between workflows
The classify stage picked between implement, tdd and feasibility with no
stated criteria: the mission spent its guidance on needs_code_change and the
schema said only 'Which workflow fits best', with implement as the free
default for an omitted or unrecognised answer. Issue 813 was classified
implement on that basis.

Both surfaces now state what each workflow is for and say not to pick
implement merely because nothing else obviously fits. The mission moves to a
named triageMission so a test can assert the criteria reach the model.

Closes archie-core-s5ys
2026-09-19 00:17:44 +10:00
sam 681c5fb0ad fix(workintake): match namespaced forge labels when routing by kind
labelKinds is keyed on bare strings, and this repo namespaces its labels
(type::feature, priority::medium), so KindsForLabels matched nothing and
every issue fell through kind routing to Route's triage fallback. Kind
routing has therefore never fired here: issue 813, a type::feature that
defaultKindWorkflows binds to feasibility, reached implement instead.

Labels now resolve to the value after the last '::'. The namespace is not
checked: bug/feature/bootstrap is specific enough that a label ending in one
means that kind whatever the tracker files it under.

Closes archie-core-tjoc
2026-09-19 00:17:44 +10:00
sam ab8ba79966 fix(container): claim container teardown once instead of cancelling a timer
Timer.Stop cannot unwind a max-uptime callback that has already begun, so
cancelling still let the reaper and Release both stop and remove the same
container, which is the duplicate teardown and the misleading 'No such
container' warnings this was meant to remove.

Teardown is now claimed once per container: whichever of the two gets there
first talks to Docker and the loser skips to its own bookkeeping. Release
still claims after the grace period, so MaxUptime keeps biting during it.

Also table-drives the event pump priming cases, per the repo's test directive.
2026-09-19 00:13:36 +10:00
sam fed5bec709 fix(container): keep the max-uptime cap active during the grace period
The reaper was cancelled at the top of Release, before the grace-period
sleep, which let a container outlive MaxUptime by GracePeriod. MaxUptime is
documented as a cap from creation enforced regardless of task state, and a
grace period is task state, so the cancel belongs after the sleep.

Also asserts the disarmed reaper directly rather than only inferring it from
the absence of later Docker calls.
2026-09-19 00:06:26 +10:00
sam 4a566217f9 fix(container): cancel a container's max-uptime reaper on release
The timer stayed armed after Release removed the container, so an hour later
it stopped and removed an ID Docker had already forgotten and logged two
warnings that read like a failed teardown.
2026-09-18 23:59:40 +10:00
sam a345a85197 fix(webui): retry event pump priming until the state store answers
archie-ui binds before archie-state-store is guaranteed to be listening, so
the first prime is routinely refused. PumpEvents returned on that error, which
left the activity feed history-only for the life of the process. Prime now
retries with capped backoff and gives up only when the context ends.

Orders archie-ui.service after archie-state-store.service as well, which
narrows the window without closing it: After= sequences the start, it does
not wait for the listener.
2026-09-18 23:59:40 +10:00
sam 5aedc28aae feat(config): key services by name through a registry
Services was a struct with one field per service, so each service's name was
stated three times: the field, the loader's defaulting branch, and every
consumer's field access. Adding one meant editing all three, and nothing
stopped them disagreeing. The drift was already there: stateStoreResolvedToken
and gatewayResolvedToken were identical apart from the env var each hard-coded.

Services becomes map[string]ServiceConnection, and RegisterService declares a
service once with the five fields it has. Everything that differs between
services is now an argument rather than a branch elsewhere: an empty registered
target means the operator must supply one, which is how services.state.target
stays required while the gateway's is defaulted, and the registered token env
var replaces the two copied resolvers with Services.ResolvedToken.

Defaulting iterates the registry, so a new service needs no loader edit.
Consumers read Services.Get(name).

Keeping a typo'd section reported took explicit work. [services.gatway] used to
land in toml.MetaData.Undecoded() because the struct had no such field; a map
decodes any section, so it would have loaded silently and left the daemon
dialing the default. unregisteredServiceKeys asks the registry which names are
real, and the test for it fails with an empty UnknownKeys when that check is
removed.

The TOML shape is unchanged, so no deployment profile, config.example.toml or
install.sh edit is needed.

Refs: archie-core-u23g
2026-09-18 23:32:36 +10:00
sam 00eb1f3786 fix(update): write the agent version sidecar with a real newline
printf '%s\\n' emitted the literal characters backslash-n, which
archie-update-check's release-version check rejects, so every managed-agent
update left the installed agent version reported as unknown.
2026-09-18 23:14:34 +10:00
sam 095284678a feat(config): let the State Store and Gateway listen addresses be configured
Both gRPC listeners took their bind address from a -listen flag default alone,
with no config key. The port a service binds and the port its clients dial were
therefore two separate facts -- the flag default, and [services.<name>].target --
with nothing keeping them in step.

On a host that already owned the default the effect read as a code fault rather
than a port collision: the store died with "bind: address already in use" while
every client reported "state store: connection error ... error reading server
preface: EOF". Cockpit binds 9090 by default, so this is not hypothetical.
Verifying the dashboard on such a host needed a hand-written overlay plus a
matching -listen, two things to keep in step by hand.

- [services.state].listen and [services.gateway].listen now name the bind
  address. Precedence is -listen, then config, then a default applied by the
  loader. An empty result is a startup ERROR, never a fallback: net.Listen reads
  "" as "any free port", so defaulting there would bind the service somewhere no
  client looks and still report success.
- Both flag defaults become "" so configuration can win, mirroring how archie-ui
  already prefers [web].listen over its flag.
- Gateway listen defaults to the same constant as the gateway target, so a
  default deployment's client and server cannot drift onto different ports.
  [services.state].target still has no default: an empty target stays a startup
  error in the daemon and gateway, which no longer serve a local store.
- ServiceConnection gains the field. Its doc now says clients read only Target
  and TargetToken, and Listen belongs to the process that owns the service --
  the previous wording claimed the struct starts no listeners while carrying one.
- deployments/dev.toml states each port once, beside the target it must match, so
  `task dev` is retargetable on a host that owns 9090 by editing one overlay.

Tests. Unit: config defaults, explicit values, and precedence. Process: the
existing real-process smoke test now takes its listen from configuration instead
of -listen, so the end-to-end wiring is proven by the test that already starts
the binary, with no extra process. Both were verified load-bearing by mutation --
inverting the precedence fails the unit test, and making the app layer ignore
config fails the process test with "state: no listen address".

Verified: task check exit 0. Also documented in config.example.toml, the
configuration architecture table, and the `task dev` summary.
2026-09-18 19:15:02 +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 14e7512d14 feat(contracts): carry attempt on Event and stage on ReadTaskLogRequest
Add two field-only extensions to the State Store contract, no new message
and no new RPC: Event.attempt (11) gives every task event an attempt key,
and ReadTaskLogRequest.stage (9) lets a log read be scoped to one stage.

Generated stubs regenerated with tools/proto.sh and committed as LAW so
proto:check, which diffs the working tree against the index, can pass.
2026-09-18 17:28:31 +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 95aae832b3 fix(workflow): record a parked run's reason in its own log
The agent-side half of the same gap. A stage failure already logged
"stage failed -- parking" before parking, but a run whose OUTCOME was parked
(a review that could not run, a workflow that ended with no outcome) reached
the timeline as a KindParked event and the store as park_reason and never
the log an operator downloads.

park is the one place a park's reason is final, so it is now the one place
that logs it; the stage-failure branch no longer logs its own near-copy, and
the stage names itself inside the reason. The entry carries the stage as a
field so nothing is lost by dropping the duplicate line.

observability.md's "Implemented design" section documented the container's
system-log path as though it were the only source of task-log content; it
now records the daemon's and the workflow's own park writers, including why
the entry follows the transition rather than preceding it.
2026-09-18 01:49:56 +10:00
sam f1c8175491 fix(daemon): record every park reason in the attempt's own log
An operator who asks "why did task 1 attempt 3 park?" and downloads that
attempt's log got a zero-byte file, because nothing daemon-side wrote to a
task log at all: the container's system-log subscription was the only
writer, so an attempt that parked before any container produced output --
a worktree prepare failure, an unavailable worker, a taskrun error -- left
the file the sink had created empty and the reason only in the daemon-wide
log.

Both park paths now write the reason into that attempt's sink. The entry is
written after the guarded transition lands, so a park another actor won
does not leave a log claiming an outcome the task board contradicts -- the
same race the parked event is already withheld for.
2026-09-18 01:49:49 +10:00
sam f3e9c7614c refactor(logging): pass the caller's context to TaskRegistry.Write
Write built its own context.Background() for the handler call, which meant
any new caller with a context to offer could not hand it over. Taking the
caller's context is what the next commit's park-reason writer needs, and it
is what contextcheck requires of a daemon-side writer.

No behaviour change: the context is used for the handler's own attribute
extraction and never consulted for cancellation -- a park is recorded at
exactly the moment a run's context has been cancelled, so a cancelled
context must not suppress the entry.
2026-09-18 01:49:42 +10:00
sam bcf7622a8c fix(agentworker): hand the worktree back on every sandbox exit
A container run only restored ownership of the bind-mounted worktree on the
CommitAll/Push success path (archie-core#520). The agent runs as root inside
the container, so every other way a run can end -- a gate failure that parks
the task, a stage error, an early return -- left the worktree owned by UID 0
on the host. The daemon is the process that later cleans and resets that
directory as its own non-root user, and it cannot even unlink inside a
root-owned directory, so the next attempt failed before it could start no
matter what the worktree refresh did.

runTask now defers the same reconcileOwnership the commit and push paths
already call, so it runs at every exit. The retry recoveries in worktree
package cannot fix this from the daemon side: a non-root process cannot
chown, and removing the directory needs write access to it.

Observed through a supplementary group -- a non-root process may move a file
it owns into a group it is a member of -- so the test proves the chown ran
without needing root.

Residual, filed as archie-core-zcg8: a container that is SIGKILLed never
runs this defer.
2026-09-18 01:49:35 +10:00
sam fe3d508b6c fix(worktree): recover retries from path-type conflicts and stop masking the cause
A retry after any attempt that did not commit failed with

  worktree prepare failed: checkout branch <branch>:
  a branch named "refs/heads/<branch>" already exists

on a branch that was never the problem. refresh inferred "the branch does
not exist yet" from a failed checkout and reported whatever the Create
fallback then returned, so the real failure was replaced by a false one --
and the operator had no way to tell that the park reason was fiction.

The real failure, reproduced: a stage running in the container can leave a
path whose TYPE contradicts the tree refresh resets onto -- a directory
where the base tree has a file, or a file where the base tree has a
directory. go-git's hard reset cannot write over that contradiction and
fails with `openat <path>: is a directory` / `not a directory`, which is
exactly the failure the Create fallback then relabelled. Retry could not
recover from it, and a second path of the same class (a branch removed
while HEAD still pointed at it) failed with "reference not found".

refresh now clears the worktree against the tree it is resetting ONTO
before it checks anything out, which removes exactly those conflicts -- an
on-disk directory the tree declares as a file is untracked, and so is a
file the tree declares as a directory -- and resolves the branch's
existence from the reference store instead of inferring it. Resume gets the
same treatment, so the remediate path cannot fail the same way.

This is the third fix to this function (Force in 05944b6f was the second),
so the checkout/reset/clean sequence is rewritten rather than patched again.
2026-09-18 01:49:28 +10:00
sam f4f43badb0 fix(staterpc): never decode a collection field to a nil slice
Every client method that decodes a repeated proto field goes through
mapValues, which returned nil for nil input. Protobuf decodes an empty
repeated field to nil, so an empty collection crossed the wire as JSON null
rather than an empty list: the field's type depended on whether it happened
to have contents, and the wire path disagreed with the local path, which
normalises its own slices.

This is the nil-slice class the contract-conformance audit deferred, arriving
by the route its own revisit condition names -- a handler that can produce
nil. The audit checked the webui handlers (clean, as it said) and did not
cover the wire mapping added afterwards, so the regressed field was the new
one: ReadTaskLog's components, observed as "components": null from the live
dashboard.

mapValues now returns []B{} for empty input, which fixes the class once at
the mapping helper rather than at each of its 36 call sites -- none of them
compares the result to nil, so nothing depended on the old behaviour.
TaskLog also normalises components, which is read straight from the proto
rather than through mapValues.

Red first: the test drives the existing local/grpc matrix and asserts the
marshalled JSON, so it fails on a null collection without depending on which
path is under test. Both collections are exercised empty -- entries present
with components empty, and a log file that exists with no lines -- because
the first shape alone leaves the entries side untested. Verified by mutation:
restoring the nil return fails it on "entries marshalled to null".
2026-09-17 14:58:14 +00:00
sam a34490c4ce Merge pull request #845 from samcharles93/feat/839-telegram-tool-activity-block-is-uncapped-and-crowds-out-the
Telegram tool-activity block is uncapped and crowds out the answer (archie)
2026-09-17 22:40:21 +10:00
sam aa78270421 Merge pull request #846 from samcharles93/feat/835-disk-readiness-probe-watches-only-work-dir-so-a-full-root-fi
Disk readiness probe watches only work_dir, so a full root filesystem goes unreported (archie)
2026-09-17 22:39:15 +10:00
sam 5684674bc2 Merge pull request #848 from samcharles93/feat/state-store-task-log-download
feat(staterpc): read task logs through the State Store and make them downloadable
2026-09-17 22:38:16 +10:00
sam 7aca5b26c7 fix(webui): do not hand back an error as a .log download
The download sets its attachment headers before the read, because the body
streams straight from the reader and a log is unbounded input -- buffering it
to size the response would defeat the reason it streams. Nothing then cleared
those headers, so a 404 for an attempt with no log went out as

	Content-Disposition: attachment; filename="task-1-attempt-0.log"
	Content-Type: application/x-ndjson

A browser treats that as a download: the caller gets a .log file containing
the text "no log recorded for this attempt". A stale or direct download URL is
enough to trigger it. The 503 for a process with no reader had the same shape.

Both error paths now clear the attachment headers before writing, so the
response is an error rather than a file. The successful path is unchanged.

Red first: the existing test asserted the status only, which is how this
passed. It now asserts the headers are cleared on a 404 and on a 503.
2026-09-17 12:33:45 +00:00
sam 8b2f08102d feat(webui): read a task's log through the State Store and let it be downloaded
The dashboard's attempt-log panel answered every read with "task logging is
optional and was not enabled for this run". That message was false: logging is
wired unconditionally in the daemon, and the log files exist. The dashboard
process simply had no reader -- composition left TaskLogs absent because no
contract carried it -- so the handler saw a nil registry and reported the
disabled shape, which the page rendered as a claim about configuration.

internal/logging now answers whether an attempt has a log at all: Tail sets
Result.Found, so "this attempt has no log" is a value rather than an empty
list indistinguishable from a read that never happened. Its registry gains
TaskLog (a decoded page) and TaskLogContent (the file verbatim, streamed,
because a log is unbounded input), and an absent reader reports
ErrTaskLogsUnavailable rather than an empty page -- a process that cannot read
logs must not implicate the attempt.

Those two answers travel the State Store contract as storecontract.TaskLogStore
(ReadTaskLog, StreamTaskLogContent) and are rehydrated on the client by
(Unavailable, canonical message), so archie-ui composes the reader from its own
store client instead of opening another process's files. The daemon's registry
is wired as the server-side reader in the State Store process only.

On top of that read, GET /api/tasks/{id}/logs/download serves the attempt's log
as a Content-Disposition attachment named task-<id>-attempt-<n>.log, and the
panel offers it. The JSON route keeps its shape and gains found, so the page
states the attempt has no log instead of blaming a setting.

Task log files stay owned by their directory's owner: archiving still removes a
task's log directory, and that removal is the daemon's, not the dashboard's.
2026-09-17 12:12:43 +00:00
sam b75335582d feat(staterpc): add the task-log read contract to the State Store service
One task attempt's persisted log lives in the state directory the State Store
process owns, and no contract carried it: the dashboard process therefore had
no way to read a log at all, and answered every attempt with "task logging is
optional and was not enabled for this run" in a deployment where logging is
unconditional.

ReadTaskLog returns a decoded page and StreamTaskLogContent returns the raw
bytes server-streamed -- a log rotates at 20 MB, past gRPC's unary cap, the
same reason StreamCaptures superseded ListCaptures. found=false with no error
means the attempt has no log; a service with no reader answers Unavailable,
and keeping those apart is the point: only the second is a deployment
condition.
2026-09-17 12:09:43 +00:00
sam 3b0ec1b79b feat(gateway): persist the channel-native sender id on messages
Slice 1 of docs/prds/memory-engine-unification.md: persist the
participant, so a later curator can address agent-user memory scope.

- messages gains sender_id: schema, ALTER migration (idempotent via
  duplicate-column detection), both inserts, and both history selects.
  Pre-existing rows default to empty.
- curator.SessionSummary gains AgentID and ConversationMessage gains
  SenderID; the sessioncurator adapter fills them from the session's bot
  identity and the stored record.

The memory contract is untouched and nothing consumes the new fields
yet. Deriving a session's participant from its user-role messages, and
failing closed on ambiguity, stays with the curator rewrite.
2026-09-17 22:06:54 +10:00
sam 66b171f88f fix(readiness): keep required status when an optional target shares a path
Targets are deduplicated by path so a shared filesystem is probed once, but
the first target seen won. With root, then an optional /var, then a required
data path that resolves to /var, the optional target is the one that survived
-- so its rules were applied to a path the daemon requires. An absent /var is
skipped as "optional absent", and with another healthy target present the
probe reported OK while a required path was unavailable.

Deduplication now keeps the strictest requirement any target places on a
path, and its name, so the failure is both visible and correctly attributed
rather than reported against the optional target that happened to come first.

Red first: the new test drives the reported scenario through an injected
statfs and failed with `status = "ok", want degraded` before the fix.
Verified by mutation -- restoring first-wins dedup fails it again.
2026-09-17 11:48:23 +00:00
sam 43957c22eb fix(telegram): keep every tool line that fits and mark every answer cut
Two defects in the activity/answer budget, both found in review.

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

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

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

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

Removing clampToOneMessage, which this change orphaned: all three of its call
sites were replaced with clampToRunes directly, and `unused` flagged it. Dead
code left behind by a rewrite does not ship.
2026-09-17 11:31:05 +00:00
samcharles93 8865b265f9 Telegram tool-activity block is uncapped and crowds out the answer (archie)
Implements #839
2026-09-17 11:27:52 +00:00
sam f353a58d22 Merge pull request #844 from samcharles93/fix/archied-watchdog-test-flake
fix(archied): stop the shutdown-watchdog test racing the scheduler
2026-09-17 21:24:29 +10:00
sam a3dba83d0a Update internal/gateway/stream.go 2026-09-17 21:19:53 +10:00
sam 1cbf4e3a94 fix(archied): stop the shutdown-watchdog test racing the scheduler
TestShutdownWatchdogHangingPastLeashForcesExit gave the watchdog two leash
lengths (60ms) to force an exit, but the 30ms leash only starts the timer --
the firing goroutine must then be scheduled before the injected exit is
observable. Measured margin is ~29.7ms, so the test is a wall-clock race
against the Go scheduler and fails intermittently on a loaded machine, where
it parks real work behind a gate failure unrelated to the change under test.

The assertion is now the contract that actually matters and that scheduling
jitter cannot falsify: the exit must not happen before the leash, and it must
happen. Waiting for it uses a generous ceiling, and the new elapsed >= leash
check catches an early fire strictly -- something the old test could not do,
because it only bounded lateness.

The inverse test asserts the ABSENCE of a forced exit, which load cannot
falsify (a slow runner only delays the exit being checked for), so it keeps a
tight bound and the suite stays fast.

Verified by mutation: removing the forced exit fails the first test, and
firing before the leash now fails it on the new elapsed check.
2026-09-17 11:17:19 +00:00
samcharles93 804121424f fix: Repeated successful tool calls are never collapsed into a counted entry (archie)
Fixes #840
2026-09-17 11:13:11 +00:00
samcharles93 45f6283ad8 test: failing repro
Refs #840
2026-09-17 11:10:30 +00:00
samcharles93 a94150bb0c fix: baseline gate repair (go test ./... -count=1) 2026-09-17 11:03:29 +00:00
sam 9123f6ef62 fix(telegram): require the truncation wrapper before treating a count as metadata
Review found that a bare "showing 3/197 lines" inside ordinary output was
accepted as truncation metadata and replaced by a summary, hiding the real
result. Both built-in producers wrap the notice as "[truncated: …]"
(internal/tools/builtin/truncate.go), so the wrapper is now required rather
than tolerated: it is the only marker separating a notice the tool printed
from content that merely mentions a count.
2026-09-17 10:13:07 +00:00
sam 85c6a59fdc fix(telegram): address greptile review on tool-result rendering
Four findings from review, all valid:

1. Search detection is now gated on the tool name rather than applied to every
   result. A compiler diagnostic ("file.go:42: message") has the same shape as
   a search hit, so counting it reported a build error as "N matches" and hid
   the diagnostic.

2. Only ripgrep match lines are counted. The hyphen context form
   ("path-N-text") and "--" group separators were being counted as matches, so
   a search with context requested reported the match count plus every
   surrounding context line.

3. The notice parser accepts shell's "showing last N/M lines" form as well as
   the plain "showing N/M lines" one. Shell emits the "last" form, which failed
   integer parsing and was not recognised as metadata -- so a truncated shell
   result quoted the raw truncation notice as its preview, the exact defect this
   change set out to remove. The summary now also states which end was kept
   ("97 lines total; showing last 66" for a tail truncation).

4. The renderer cases are consolidated into one table-driven test per the
   development protocol in AGENTS.md, covering all four defects above plus
   singular/plural, colons in paths, and module-cache noise.
2026-09-17 09:49:49 +00:00
sam 4cef7dd365 fix(telegram): summarise tool results instead of quoting an arbitrary line
Operator report: tool output in the Telegram channel was unreadable during
search-heavy turns -- a wall of fenced blocks each showing one arbitrary
match line ("/path/config.json-322-          }") under a heading that said
only "grep -- done".

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

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

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

Remaining work from the report (collapsing repeated calls into one counted
entry, and a ring of recent activity lines with a capped frame) is tracked
in #837.
2026-09-17 09:36:28 +00:00
sam aa62d1aca5 refactor(config): delete the two decoded-but-unread policy fields
MemoryConfig.SessionTTL and ToolPolicy.ParallelExecution were decoded by
config loading and read nowhere, so setting either silently did nothing.
Removing them routes both keys into the unknown-key detector, which names
them in a boot warning instead. A live-looking knob wired to nothing is
the worse state, and the sibling memory.provider already earned a loud
load-time rejection for exactly this.

Also drops the config.example.toml line that shipped session_ttl into
every first-run config.toml via configtemplate.go, and the commented-out
dir_test.go assertions that would have re-created both fields under that
file's "make these pass without modifying them" header.
2026-09-17 00:32:02 +10:00
sam 0b3dc6c01f refactor(forge): delete the unwired RepliesAfter surface
DELETE: IssueForge.RepliesAfter and its Reply type had no production caller --
the waiting_human status exists and is reachable, but automatic detection of a
human reply never landed, so the intended poller was never built. Neither
implementation paginated either (both read one page of 50), so the method
would have been wrong if wired as-is.

The manual path is untouched: waiting_human remains reachable and an operator
requeues through the existing task-action flow. Removing the interface method
also removes seven test fakes that existed only to satisfy it.

No behavioural test accompanies this: a pure deletion has no assertion to
make fail, and the compiler enforces completeness across every implementation.
2026-09-15 16:54:16 +10:00
sam 51b0902926 merge: lane G (tools-builtin-3, tools-mcp-3, infra-misc-2, persistence-5) 2026-09-15 13:40:46 +10:00
sam 242d8322d5 refactor(store): use taskstate status constants in SQL
WIRE: internal/taskstate documents itself as the single source for the
persisted task status strings, but store.go re-declared them as bare SQL
literals. Reference the workflow status constants (aliases of taskstate)
so a rename of a status is a compile-time-visible migration instead of a
silent change in what ClaimNext/RecoverStale/OpenPRs/ClearTerminalTasks
match.
2026-09-15 13:39:15 +10:00