fix(webui,sendfile): close three holes the adversarial review found

Follow-up to e5e0316, which claimed non-delivery is never silent and that
oversized files fail visibly. Both claims had gaps.

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

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

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

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

Remaining review findings are filed, not fixed: fallback lines appended
after the live reply finalizes are dropped by a stopped renderer
(archie-core-atv2), confinement is symlink-blind and re-opens after
checking (archie-core-jkmu), and concurrent uploads are uncapped
(archie-core-3svc).
This commit is contained in:
sam committed 2026-08-25 01:55:16 +10:00
1 parent 51d67a8903
commit e8df26f6a6
5 files changed
+155 -22

No files matched your search

+4 -1
View File
@@ -6,7 +6,7 @@
{"_type":"issue","id":"archie-core-t2db.5","title":"Security: an unauthenticated endpoint must not be able to run an agent","description":"P0 within this epic because the feature's own pitch is the threat model: a public intake surface whose output is an agent with tool access and a repo. Get this wrong and a webhook URL is remote code execution with extra steps.\n\nNon-negotiables to design:\n\n- Per-source authentication. A source registers with a secret (HMAC, as internal/channels/webhook already does per route) before its events can trigger anything. Capture-only for unknown senders is acceptable; triggering is not.\n- Human approval before a binding goes live. An operator authoring a binding is a deliberate act; an event arriving is not. Nothing should self-arm.\n- Rate and volume limits per source, so capture cannot be used to exhaust disk or drown the inspector.\n- Payload content is untrusted input flowing into an agent prompt. Treat prompt injection as expected, not exceptional -- the sender controls that text, and the agent has tools. Bound what a playbook-triggered workflow may do.\n- Captured payloads may contain secrets from the sending system. Decide retention, redaction and who can view them; internal/memory/scrubber may already have applicable prior art.\n\nArchie's own principle applies: environmental enforcement over prompt rules. 'The agent should ignore instructions in the payload' is not a control.","acceptance_criteria":"An event from an unauthenticated source can be captured but cannot trigger a workflow; a new binding requires explicit human approval before it arms; per-source rate limits exist; the blast radius of a playbook-triggered workflow is bounded by code rather than by prompt text; retention and visibility of captured payloads is decided and documented.","notes":"2026-08-22: security design decided and documented in docs/prds/webhook-intake-security.md, covering all five non-negotiables from this bead's description:\n1. Per-source auth reuses internal/channels/webhook's existing HMAC-SHA256 scheme; capture accepts unsigned events (visible, marked unauthenticated), only authenticated events can ever match a binding.\n2. Bindings gain a draft -\u003e pending_approval -\u003e armed state machine; any edit to an armed binding drops it back to pending_approval so approval can't be bypassed by editing. Modeled on telegram's existing dangerousAction/pendingApproval flow (dangerous.go/approval.go).\n3. Per-source token-bucket rate limiting (precedent: pairing/store.go's MaxPendingPerPlatform); limit-exceeded is an observable 429, not a silent drop.\n4. Blast radius bounded by the SAME code-level controls every task already gets -- gate, diff_cap_lines, sandboxed container, worktree isolation -- no new relaxation for playbook-triggered work, and payload text is ordinary untrusted prompt input, never a trusted instruction.\n5. 7-day configurable retention on captured payloads; best-effort redaction reusing gateway/stream.go's sensitiveParameterKey heuristic before persisting; visibility gated by the same dashboard auth as every other webui surface.\n\nThis bead's code-level acceptance criteria (capture-can't-trigger, rate limits exist, blast-radius bounded, approval gate) cannot be implemented yet: they constrain t2db.1 (capture), 7d5u.3 (intake family) and t2db.4 (binding), none of which have landed. This document is the contract those beads build against -- do not build any of them without satisfying it. Leaving this bead in_progress rather than closing it; it closes when t2db.1/7d5u.3/t2db.4 land and demonstrably satisfy points 1-5, not before.","status":"in_progress","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:46Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:01Z","started_at":"2026-08-21T14:51:26Z","external_ref":"https://github.com/samcharles93/archie-core/issues/536","dependencies":[{"issue_id":"archie-core-t2db.5","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
{"_type":"issue","id":"archie-core-vq92","title":"task_logs truncates at 50KB with no pagination, so full logs are unreachable","description":"The task_logs chat tool caps its response at 50 KB and offers no way to fetch the rest. An operator asking the agent to retrieve or archive a task's logs gets a silently clipped window, and the agent has no mechanism to page past it. Observed 2026-08-24: asked to save a full transcript and agent logs, the agent could only produce a partial archive and had to document the truncation as a limitation rather than satisfy the request.\n\nThe failure compounds with archie-core-p1bl (errors logging as `{}`): a truncated log of uninformative errors leaves an operator with nothing at all, precisely when a task is stuck.\n\n## What is needed\n\nTruncation itself is legitimate -- a tool result must be bounded, and unbounded log text would blow the model's context. The defect is that truncation is TERMINAL: there is no continuation, no offset/cursor, no way to narrow the window, and the caller cannot tell how much was lost.\n\nEstablish first where the cap is applied (the task_logs tool in internal/gateway/task_tools.go and whatever log reader it calls in internal/logging -- note internal/logging owns the on-disk format end to end and internal/webui parses nothing, per CLAUDE.md, so the reader is the right place for range support).\n\nDesign points to decide:\n- A cursor or offset so successive calls walk the whole log, rather than always returning the same head or tail.\n- Filters that make bounded retrieval useful rather than merely possible: by level (errors only), by time range, by stage.\n- The response must state explicitly that it was truncated and how much remains, so the agent can report honestly instead of implying completeness.\n- Consider whether bulk retrieval belongs in a tool result at all, or whether the right answer for \"save the full logs\" is to write the file and deliver it via the new send_file path (archie-core-absb), keeping the tool result small.\n\n## Acceptance Criteria\n\nAn operator can obtain a task's complete logs through the agent, by paging or by file delivery; a truncated response says so and reports what remains rather than ending silently; level and time-range filtering exist so a bounded call can still answer a specific question; the cap remains enforced so no single response can exhaust the model's context; tests cover a log larger than the cap and assert that repeated calls retrieve all of it without gaps or duplication.\n","status":"open","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T15:48:15Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:50:10Z","external_ref":"https://github.com/samcharles93/archie-core/issues/625","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-p1bl","title":"Task logs serialise errors to an empty object, destroying diagnostics","description":"Error values in task logs sometimes render as an empty JSON object, so the one field that says WHY something failed carries no information. Observed in production task logs 2026-08-24, in the same stream:\n\n {\"time\":\"...\",\"level\":\"ERROR\",\"message\":\"handle failed\",\"fields\":{\"err\":{}}}\n {\"time\":\"...\",\"level\":\"ERROR\",\"message\":\"handle failed\",\"fields\":{\"err\":\"stage re…\"}}\n\nSame message, same field, two different encodings -- one useful, one useless. The empty-object form is what an operator hits when diagnosing a stuck task, which is exactly when the log is the only evidence available.\n\n## Likely mechanism (to be confirmed, not assumed)\n\n`{}` is what encoding/json produces for a struct with no exported fields. A custom error type (a struct implementing `error` via a value or pointer receiver, with all fields unexported) marshals to `{}` rather than to its Error() string, because encoding/json does not consult the error interface. Errors that happen to be `*errors.errorString` or `fmt.Errorf` results go through a different path and survive as text.\n\nStart at internal/logging (attrs.go and its tests already reference a \"handle failed\" record, so the attribute handling is there) and establish where an `error` attribute is converted for the JSONL sink. The fix is to render errors through their Error() string -- and, where the error carries structured context worth keeping, to do so ADDITIONALLY rather than instead.\n\n## Why P1\n\nSam's words: \"LOGGING! ... this is another critical requirement.\" Diagnosis of every other defect depends on it. Two separate investigations this week were slowed by log output that recorded that something failed without recording what.\n\nNote this compounds archie-core-1ysw-era debugging and the parked-task investigation: an operator seeing `{\"err\":{}}` has strictly less information than one seeing no log line at all, because the empty object implies the error was captured.\n\n## Steps to Reproduce\n\n1. Arrange for a code path that logs a custom error type (unexported fields) as an `err` attribute.\n2. Read the task's JSONL log via the dashboard, /api logs, or the task_logs tool.\n3. Observe `\"err\":{}` where the message should be.\n4. Compare with a path that logs a fmt.Errorf value and observe `\"err\":\"...\"` in the same file.\n\n## Acceptance Criteria\n\nEvery error logged as an attribute renders its Error() text in the JSONL sink regardless of the concrete error type; a custom error type with only unexported fields is covered by a test asserting the message survives; structured context on an error is preserved in addition to, never instead of, the message; a regression test fails against the current encoder; no log line can report an error as an empty object.\n","status":"open","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T15:47:44Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:50:11Z","external_ref":"https://github.com/samcharles93/archie-core/issues/626","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-440c","title":"Dashboard mutations 403 behind a TLS-terminating reverse proxy: Origin check ignores X-Forwarded-Proto","description":"Every operator action from the dashboard -- Stop, Cancel, Retry, Approve, Reject, Abandon, Archive -- fails with HTTP 403 in the production deployment. Observed 2026-08-24: `POST https://archie.catlow.cloud/api/tasks/3/action` returned 403 in 7ms with a 30-byte body. This left the operator with no way to stop a running task from the web UI at all.\n\n## Root cause\n\n`authorizeTaskMutation` (internal/webui/api_tasks.go:197-221) derives the expected Origin scheme from the daemon's OWN connection:\n\n wantScheme := \"http\"\n if r.TLS != nil {\n wantScheme = \"https\"\n }\n ...\n if ... || !strings.EqualFold(u.Scheme, wantScheme) || !strings.EqualFold(u.Host, r.Host) {\n http.Error(w, \"cross-origin mutation refused\", http.StatusForbidden)\n\narchied runs behind a reverse proxy that terminates TLS (confirmed: archie.catlow.cloud redirects to auth.catlow.cloud for forward auth, and the request was HTTP/2 to the proxy). The daemon therefore receives a PLAIN HTTP connection, so `r.TLS == nil` and `wantScheme == \"http\"`, while the browser correctly sends `Origin: https://archie.catlow.cloud`. Scheme mismatch -\u003e 403 on every mutation.\n\n`X-Forwarded-Proto` is never consulted anywhere in the codebase (`grep -rn 'X-Forwarded' internal/webui/ internal/config/` returns nothing).\n\n## Evidence the body confirms which branch fired\n\nThere are exactly two 403 paths in this handler. Their response bodies differ in length:\n- \"missing CSRF header\\n\" = 20 bytes\n- \"cross-origin mutation refused\\n\" = 30 bytes\n\nThe observed response was 30 B, so the Origin comparison is what rejected it, NOT the CSRF header. The dashboard is sending X-Archie-CSRF correctly.\n\n## Why this is P1\n\nIt is a total loss of the operator control surface in the supported deployment shape. It also removes the documented remedy for other faults: archie-core-0dic leaves a stopped task's row reading `running`, and `Parked`'s retry action is the stated recovery for a review that fails closed (docs/prds/adversarial-self-review.md section 4) -- both assume dashboard actions work.\n\nNote the deployment model is explicitly plural (CLAUDE.md \"Deployment model\": several supported shapes, systemd is not required), so \"runs behind a proxy\" is a first-class configuration, not an edge case.\n\n## Steps to Reproduce\n\n1. Serve archied behind any TLS-terminating reverse proxy (nginx, Caddy, Traefik, or a forward-auth proxy such as Authelia), with the daemon listening on plain HTTP.\n2. Load the dashboard over https and press Stop on a running task.\n3. Observe `POST /api/tasks/\u003cid\u003e/action` -\u003e 403, body \"cross-origin mutation refused\".\n4. The same build works when reached directly over http, or over https terminated by the daemon itself, which is why this does not reproduce in local development.\n\n## Acceptance Criteria\n\nDashboard mutations succeed when archied is behind a TLS-terminating reverse proxy; the effective scheme is derived from X-Forwarded-Proto (and the effective host from X-Forwarded-Host where applicable) ONLY when the request arrives from a trusted proxy, configured explicitly -- an unconditional trust of these headers would let any client forge the Origin check and defeat the CSRF protection this function exists to provide; direct (non-proxied) deployments keep their current strict behaviour; tests cover proxied-https, direct-http, direct-https, and a spoofed X-Forwarded-Proto from an untrusted source; the config surface and its default are documented in config.example.toml and the deployment profiles.\n","notes":"CONFIRMED LIVE against production 2026-08-25 via Playwright, signed in as the operator.\n\nReproduced the dashboard's own Stop request from the loaded page:\n\n fetch('/api/tasks/3/action', {method:'POST',\n headers:{'X-Archie-CSRF':'1','Content-Type':'application/json'},\n body:'{\"action\":\"stop\"}'})\n\nResult: status 403, body exactly \"cross-origin mutation refused\\n\" (30 bytes), with location.origin = https://archie.catlow.cloud and location.protocol = https:.\n\nThis settles which of the two 403 branches fires. The request carried a correct X-Archie-CSRF header and same-origin credentials, so it passed the CSRF check and was rejected by the Origin comparison in authorizeTaskMutation. Combined with the deployment shape (archie.catlow.cloud 302s to auth.catlow.cloud for forward auth, so TLS terminates at the proxy and the daemon sees plain HTTP), the scheme comparison is the failing term: browser Origin scheme 'https' vs the daemon's computed wantScheme 'http' from r.TLS == nil.\n\nThe dashboard confirms the operator impact at the same time: the header reads '1 running' and task #3 is still listed as running (that stale row is archie-core-0dic, a separate defect). So in production the Line truncated
{"_type":"issue","id":"archie-core-440c","title":"Dashboard mutations 403 behind a TLS-terminating reverse proxy: Origin check ignores X-Forwarded-Proto","description":"Every operator action from the dashboard -- Stop, Cancel, Retry, Approve, Reject, Abandon, Archive -- fails with HTTP 403 in the production deployment. Observed 2026-08-24: `POST https://archie.catlow.cloud/api/tasks/3/action` returned 403 in 7ms with a 30-byte body. This left the operator with no way to stop a running task from the web UI at all.\n\n## Root cause\n\n`authorizeTaskMutation` (internal/webui/api_tasks.go:197-221) derives the expected Origin scheme from the daemon's OWN connection:\n\n wantScheme := \"http\"\n if r.TLS != nil {\n wantScheme = \"https\"\n }\n ...\n if ... || !strings.EqualFold(u.Scheme, wantScheme) || !strings.EqualFold(u.Host, r.Host) {\n http.Error(w, \"cross-origin mutation refused\", http.StatusForbidden)\n\narchied runs behind a reverse proxy that terminates TLS (confirmed: archie.catlow.cloud redirects to auth.catlow.cloud for forward auth, and the request was HTTP/2 to the proxy). The daemon therefore receives a PLAIN HTTP connection, so `r.TLS == nil` and `wantScheme == \"http\"`, while the browser correctly sends `Origin: https://archie.catlow.cloud`. Scheme mismatch -\u003e 403 on every mutation.\n\n`X-Forwarded-Proto` is never consulted anywhere in the codebase (`grep -rn 'X-Forwarded' internal/webui/ internal/config/` returns nothing).\n\n## Evidence the body confirms which branch fired\n\nThere are exactly two 403 paths in this handler. Their response bodies differ in length:\n- \"missing CSRF header\\n\" = 20 bytes\n- \"cross-origin mutation refused\\n\" = 30 bytes\n\nThe observed response was 30 B, so the Origin comparison is what rejected it, NOT the CSRF header. The dashboard is sending X-Archie-CSRF correctly.\n\n## Why this is P1\n\nIt is a total loss of the operator control surface in the supported deployment shape. It also removes the documented remedy for other faults: archie-core-0dic leaves a stopped task's row reading `running`, and `Parked`'s retry action is the stated recovery for a review that fails closed (docs/prds/adversarial-self-review.md section 4) -- both assume dashboard actions work.\n\nNote the deployment model is explicitly plural (CLAUDE.md \"Deployment model\": several supported shapes, systemd is not required), so \"runs behind a proxy\" is a first-class configuration, not an edge case.\n\n## Steps to Reproduce\n\n1. Serve archied behind any TLS-terminating reverse proxy (nginx, Caddy, Traefik, or a forward-auth proxy such as Authelia), with the daemon listening on plain HTTP.\n2. Load the dashboard over https and press Stop on a running task.\n3. Observe `POST /api/tasks/\u003cid\u003e/action` -\u003e 403, body \"cross-origin mutation refused\".\n4. The same build works when reached directly over http, or over https terminated by the daemon itself, which is why this does not reproduce in local development.\n\n## Acceptance Criteria\n\nDashboard mutations succeed when archied is behind a TLS-terminating reverse proxy; the effective scheme is derived from X-Forwarded-Proto (and the effective host from X-Forwarded-Host where applicable) ONLY when the request arrives from a trusted proxy, configured explicitly -- an unconditional trust of these headers would let any client forge the Origin check and defeat the CSRF protection this function exists to provide; direct (non-proxied) deployments keep their current strict behaviour; tests cover proxied-https, direct-http, direct-https, and a spoofed X-Forwarded-Proto from an untrusted source; the config surface and its default are documented in config.example.toml and the deployment profiles.\n","notes":"CONFIRMED LIVE against production 2026-08-25 via Playwright, signed in as the operator.\n\nReproduced the dashboard's own Stop request from the loaded page:\n\n fetch('/api/tasks/3/action', {method:'POST',\n headers:{'X-Archie-CSRF':'1','Content-Type':'application/json'},\n body:'{\"action\":\"stop\"}'})\n\nResult: status 403, body exactly \"cross-origin mutation refused\\n\" (30 bytes), with location.origin = https://archie.catlow.cloud and location.protocol = https:.\n\nThis settles which of the two 403 branches fires. The request carried a correct X-Archie-CSRF header and same-origin credentials, so it passed the CSRF check and was rejected by the Origin comparison in authorizeTaskMutation. Combined with the deployment shape (archie.catlow.cloud 302s to auth.catlow.cloud for forward auth, so TLS terminates at the proxy and the daemon sees plain HTTP), the scheme comparison is the failing term: browser Origin scheme 'https' vs the daemon's computed wantScheme 'http' from r.TLS == nil.\n\nThe dashboard confirms the operator impact at the same time: the header reads '1 running' and task #3 is still listed as running (that stale row is archie-core-0dic, a separate defect). So in production the Line truncated
{"_type":"issue","id":"archie-core-0dic","title":"Stopped tasks stay 'running' forever: terminal writes ride the cancelled context","description":"/stop reports success and genuinely does stop the container, but the task row is never updated, so the dashboard, /status and task_list all show the task as running indefinitely. Observed 2026-08-24: task #3 was stopped and was still displayed as running the following day.\n\n## Root cause\n\n`Daemon.runViaAgent` (internal/daemon/daemon.go:1010-1100) writes its terminal state with the SAME context that was just cancelled, and discards the result:\n\n reply, err := d.requestTaskRun(ctx, task.ID, data) // returns ctx.Err() on /stop\n if err != nil {\n _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, \"taskrun request failed: \"+err.Error())\n\n`store.Transition` writes through `tx.ExecContext(ctx, ...)` (internal/store/store.go:358-365), so on a cancelled context the write fails immediately and the `_ =` throws the error away. The row stays `running` with nothing left to correct it.\n\nThere are SIX such writes in runViaAgent (grant unavailable, grant failed, encode failed, request failed, decode failed, run failed). Every one is unreachable in exactly the situation it exists for -- cancellation -- because cancellation is what invalidates the context it writes with.\n\n`cleanupTerminalTaskWorktree` (daemon.go:897) has the same defect: it re-reads via `d.Store.TaskByID(ctx, ...)` and returns early on error, so a cancelled task also skips worktree cleanup.\n\n## Why the container is NOT the problem\n\n`Pool.Release` already gets this right and is the precedent for the fix: it detaches deliberately with `context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)` and documents why -- \"the most important reason a task is on its way out is that it was cancelled... Teardown is cleanup, so it gets its own deadline rather than inheriting the caller's cancellation.\" So teardown works; only state recording is broken.\n\n## Contributing factor\n\n`StoreTaskController.StopRunning` (internal/gateway/tasks.go:227) deliberately writes no terminal state, documented as \"A stopped task unwinds through its own error paths and lands wherever that leaves it, usually parked\". That assumption is now false: the unwind path cannot record anything, so nothing lands. Note `CancelChatTask` (the /cancel path) DOES write state explicitly and is unaffected.\n\n## Steps to Reproduce\n\n1. Start an autonomous task so it reaches `running` with a live archie-agent container.\n2. Issue `/stop` from chat (or Stop from the dashboard).\n3. Observe the container is stopped and removed by Pool.Release.\n4. Observe the task row is still `status = running` in the store, in `task_list`, in `/status` and on the dashboard.\n5. Wait: nothing ever corrects it. Only a daemon restart re-queues it, via the crash-recovery path that re-queues tasks left `running`.\n\n## Acceptance Criteria\n\nTerminal state writes on the cancellation path use a context that survives cancellation (`context.WithoutCancel`, with its own timeout, mirroring Pool.Release); their errors are logged rather than discarded; a stopped task reaches a terminal state observable in the store, task_list and the dashboard without a daemon restart; cleanupTerminalTaskWorktree also runs for a cancelled task; a regression test cancels a task mid-run and asserts the row is no longer `running`, and fails against the current code.\n","notes":"Timeline correction: the task was observed still 'running' roughly ONE HOUR after /stop, not a day (an earlier note said a day; that was inferred wrongly from a date rollover). An hour is if anything stronger evidence, since no plausible refresh interval covers it.\n\nChronology correction: the agent's pre-/stop task_list reading 'still marked running' is NOT evidence of this bug -- nothing had stopped the task at that point, so it was reporting correctly. The genuine evidence is (a) the row still 'running' an hour after /stop, and (b) the code path itself, which predicts exactly that and was found by reading runViaAgent rather than from the transcript.\n\nScope note: this bug explains a stale ROW only. It does not explain a still-live container, because container.Pool.Release deliberately detaches from the cancelled context and does tear down. If a container is ever found alive after /stop, that is a SEPARATE defect, not this one.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-24T15:22:19Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:50:13Z","started_at":"2026-08-24T15:31:34Z","closed_at":"2026-08-24T15:42:47Z","close_reason":"Closed","external_ref":"https://github.com/samcharles93/archie-core/issues/628","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-ite6","title":"Flush daemon task-event subscription before accepting worker events","description":"cmd/archied.subscribeAgentEvents registers a core-NATS wildcard subscription but returns before flushing the SUB frame. A task worker can publish immediately and lose its first event; TestSubscribeAgentEventsDropsUnparseableMessages exposes the race under full-suite load.","acceptance_criteria":"subscribeAgentEvents flushes the NATS connection before returning; flush failure unsubscribes the just-created subscription; a regression test proves a publisher can deliver immediately after subscription setup.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T04:39:22Z","created_by":"Sam Catlow","updated_at":"2026-08-24T05:19:34Z","started_at":"2026-08-24T04:39:24Z","closed_at":"2026-08-24T05:19:34Z","close_reason":"Completed; reconciled with the already-closed GitHub issue.","external_ref":"https://github.com/samcharles93/archie-core/issues/616","metadata":null,"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-q15y.3","title":"Remove legacy inprocess subprocess and single-stage agent execution","description":"The configuration and worker still expose daemon inprocess, per-stage subprocess, and single-stage NATS execution paths. Remove those production choices and keep the agent-loop runner owned only by the full-task archie-agent worker.","acceptance_criteria":"agent.mode no longer selects inprocess/subprocess/nats production behavior; cmd/archied and internal/daemon cannot construct an agent loop runner; legacy SubprocessRunner and single-stage worker paths are deleted or proven test-only; architecture tests enforce worker-only ownership.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T03:03:38Z","created_by":"Sam Catlow","updated_at":"2026-08-24T06:58:30Z","started_at":"2026-08-24T03:49:36Z","closed_at":"2026-08-24T06:58:30Z","close_reason":"Implemented in 157e99b (refactor(agentexec): remove legacy execution paths); [agent] is decode-only. Verified: no SubprocessRunner/inprocess symbols in non-test code.","external_ref":"https://github.com/samcharles93/archie-core/issues/617","metadata":null,"dependencies":[{"issue_id":"archie-core-q15y.3","depends_on_id":"archie-core-q15y","type":"parent-child","created_at":"2026-08-24T03:03:38Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-q15y.3","depends_on_id":"archie-core-q15y.2","type":"blocks","created_at":"2026-08-24T03:03:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0}
@@ -68,6 +68,7 @@
{"_type":"issue","id":"archie-core-g7tm","title":"telegram: finalize the reply through a live context, matching the error branch","description":"The success path calls live.finalize(turnCtx, reply) with the raw cancellable turn context (telegram.go:582), while the error branch two lines above deliberately uses context.WithoutCancel(turnCtx). If /stop lands during finalize, the rich edit, the plain-text retry, and the split-send fallback all abort with context.Canceled (go-telegram/bot builds requests with NewRequestWithContext), so the authoritative reply is never delivered and the live message keeps the ▌ cursor forever. The reply is persisted to the ledger, so the loss is delivery-level — but the user sees a frozen half-answer.\n\nFailure: a long tool-using turn is /stop-ped as it completes; turnCtx is cancelled mid-finalize; every send fails on the dead context; the chat shows the last live frame with a blinking cursor and no final answer.\n\nFound by code-review of PR #476 (feat/467, merged 98e8dda).","design":"live.finalize(context.WithoutCancel(turnCtx), reply) — the one-liner the error branch already uses. Consider making finalize take a live context internally rather than trusting each caller to remember.","acceptance_criteria":"A /stop landing mid-finalize still delivers the authoritative reply and drops the cursor; a test covers the cancellable-context finalize path.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:08Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:07:36Z","started_at":"2026-08-14T14:53:28Z","closed_at":"2026-08-14T15:03:28Z","close_reason":"Fixed in internal/channels/telegram/live.go and telegram.go: finalize/abandon strip context cancellation before sending (mirroring each other), ToolCall escapes Markdown metacharacters via bot.EscapeMarkdown, splitLongMessage splits on rune boundaries. All new/changed tests verified red-then-green; task check clean; adversarial review pass found no blocking issues.","external_ref":"https://github.com/samcharles93/archie-core/issues/484","labels":["code-review","streaming","telegram"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-tb3a","title":"Fix streaming review blockers for inline tool calls","description":"Resolve the four evidence-gated findings in merged inline tool-call streaming: preserve the authoritative Telegram reply when final edits fail; keep Telegram network I/O off the model FullStream consumer and cancellable; correlate tool inputs with results and render a bounded redacted parameter summary; snapshot show_tool_calls per live reply to avoid reload races. Add regression tests for every path and run task check plus lint/race validation.","acceptance_criteria":"Regression tests fail on the merged implementation and pass after the fix. Final edit failure falls back to normal split delivery. Delta and ToolCall callbacks do not wait on Telegram HTTP and stop cancels in-flight rendering. Completed tool events include bounded redacted parameters correlated by tool-call ID. Reload cannot race an in-flight reply's show_tool_calls setting. task check passes, golangci-lint reports no new findings, and focused race tests pass.","notes":"Implemented in worktree /tmp/archie-core-tb3a on branch fix/archie-core-tb3a. Added cancellable async Telegram rendering, final edit failure fallback through normal split delivery, call-ID-correlated bounded conservative parameter summaries, atomic per-reply show_tool_calls snapshots, SSE/UI parameter rendering, rebuilt ui/dist, and regression tests. Validation: GOFLAGS=-buildvcs=false task check passed; golangci-lint --new-from-rev=HEAD ./... reported 0 issues; focused race suite passed; fresh adversarial reviewer reported PASS with zero findings. Plain task check is blocked in linked worktrees by Go VCS stamping exit 128, hence buildvcs override.\n2026-08-24 reconciliation: the close reason's 'worktree left uncommitted' is stale. The work did land on main via ba33527 (Merge pull request #477 from samcharles93/fix/archie-core-tb3a); verified on main: gateway/stream.go sensitiveParameterKey+redactToolParameters, telegram/live.go per-reply showToolCalls snapshot, webui/api_chat.go gating. The /tmp/archie-core-tb3a worktree and its branch are gone, as expected.\n","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T18:05:35Z","created_by":"Sam Catlow","updated_at":"2026-08-24T07:29:09Z","started_at":"2026-08-13T18:05:39Z","closed_at":"2026-08-13T18:35:26Z","close_reason":"Completed and independently reviewed; worktree left uncommitted per conservative repository policy.","external_ref":"https://github.com/samcharles93/archie-core/issues/485","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-dzx","title":"Remove duplicate archie-agent safe.directory setup","description":"## Problem\\ncmd/archie-agent/main.go configures git safe.directory inline and then calls markWorktreeSafe, so startup writes the same global git configuration twice.\\n\\n## Scope\\nKeep markWorktreeSafe as the single tested production path and remove the older inline exec.Command block/import. Add regression coverage proving startup wiring has exactly one authoritative safe-directory call.\\n\\n## Acceptance\\n- archie-agent startup invokes markWorktreeSafe exactly once\\n- no second inline safe.directory command remains in main.go\\n- cmd/archie-agent tests and repository quality gate pass","acceptance_criteria":"Single tested safe.directory setup path remains; duplicate inline command is removed; tests and task check pass","notes":"Red proof: TestMainConfiguresWorktreeSafetyOnce failed with 2 setup paths before implementation. Green proof: go test/vet/build ./cmd/archie-agent/... passed; golangci-lint --new-from-rev=HEAD reported 0 issues. Fresh adversarial review found no blockers. Full task check was not run because the working tree contains unrelated in-progress changes and task check rewrites files; scoped package gate used per repository protocol.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:09Z","created_by":"Sam Catlow","updated_at":"2026-08-13T16:13:48Z","started_at":"2026-08-13T16:10:24Z","closed_at":"2026-08-13T16:13:48Z","close_reason":"Removed duplicate inline safe.directory setup; markWorktreeSafe is now the single tested production path","external_ref":"https://github.com/samcharles93/archie-core/issues/470","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-atv2","title":"liveReply fallback lines appended after finalize are never rendered","description":"A media delivery that fails AFTER doFinalize has run appends its fallback line to l.toolLines and calls requestRender(), but stopRendering() has already closed renderDone and the renderer goroutine has exited. requestRender is a non-blocking send into a cap-1 channel with no consumer, so the line is dropped and the finalized Telegram message stands unchanged.\n\nMedia is fire-and-forget with a 30s budget while the turn's text finishes far earlier, so this is the NORMAL case for a large upload: a 40MB document that 400s or times out reports 'could not send x' into a slice nothing reads. Pre-dates the local-file work (URL fallbacks have the same hole) but archie-core-absb's guarantee that non-delivery is always visible depends on it.\n\nFound by adversarial review of 9a45fbb. internal/channels/telegram/live.go:419-437 with :498-532.\n\n## Acceptance Criteria\nA media failure occurring after the live reply has finalized still reaches the user -- e.g. as its own follow-up message rather than an edit to a message nothing re-renders. Covered by a test that finalizes first and fails the send second.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T15:54:42Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:54:42Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-h3lg","title":"Dashboard swallows failed operator actions, showing nothing in the UI","description":"When an operator action fails, the dashboard surfaces nothing. Pressing Stop on a running task issued POST /api/tasks/3/action, received 403, and the only evidence anywhere was a browser console line: \"Failed to load resource: the server responded with a status of 403\". The page itself showed no error, no toast, no change of state -- the button simply appeared to do nothing.\n\nThis is how archie-core-440c (every dashboard mutation 403s behind a TLS-terminating reverse proxy) went unnoticed: the operator pressed Stop, saw nothing happen, and reasonably concluded the task was unstoppable rather than that the request had been refused. The bug was only found by opening devtools.\n\nConfirmed live 2026-08-25 while signed in to the production dashboard.\n\n## Why this is its own bead\n\n440c fixes the 403. This bead fixes the fact that ANY failed action is invisible -- a 500, a store failure, a refused state transition, an expired session -- and each of those has its own way of going wrong. Fixing only 440c leaves the next failure equally silent.\n\nNote internal/webui/api_tasks.go already returns distinguishable, human-readable failures (\"missing CSRF header\", \"cross-origin mutation refused\", \"runtime task control is unavailable\"). The server side is doing its job; the client discards it.\n\n## What is needed\n\n- A failed action tells the operator it failed, in the UI, with the server's reason where one is given.\n- The distinction that matters most: refused (403, bad state, not permitted) versus broken (5xx, network). The operator's next move differs -- the first is \"you cannot do that\", the second is \"try again or check the daemon\".\n- A 401 or an expired forward-auth session should prompt re-authentication rather than reading as a generic failure, since the deployment sits behind Authelia.\n- The optimistic UI must not show an action as applied when it was refused.\n\nPer CLAUDE.md the frontend is one folder per feature under ui/src/\u003cfeature\u003e with shared primitives in ui/src/base -- error surfacing used by more than one feature belongs in base, extracted on the SECOND real consumer, not in anticipation. Remember ui/dist is committed: run `task ui` and commit the rebuilt output in the same change.\n\n## Steps to Reproduce\n\n1. Load the dashboard in a deployment where mutations fail (any 440c-affected proxied deployment reproduces it directly).\n2. Press Stop, Retry, Abandon or Archive on a task.\n3. Observe the request fails in devtools while the page reports nothing.\n\n## Acceptance Criteria\n\nA failed operator action is reported in the dashboard with the server's reason where supplied; refused and broken failures are distinguishable to the operator; an authentication failure prompts re-auth rather than a generic error; no optimistic state change survives a failed request; dashboard tests cover a refused action, a server error and a network failure; ui/dist is rebuilt and committed.\n","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T15:49:18Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:50:15Z","external_ref":"https://github.com/samcharles93/archie-core/issues/629","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-kkeg","title":"No byte-for-byte conversation replay: transcripts cannot be exported or examined","description":"Asked to save a complete transcript -- \"everything. My messages, yours, tools everything. Also save the agents logs\" -- the agent could not. It produced a summary archive and honestly documented the limitation: no chat export exists, and the task-log responses were clipped at the tool's 50 KB cap.\n\nSam's requirement: \"we should be able to receive and view and examine byte-for-byte replays of an entire transcript. exactly the commands run, the results received for those commands, the user messages, agent responses, EVERYTHING.\"\n\n## What exists and what does not\n\ninternal/gateway has session tooling -- session_list, session_resume, session_title, session_delete -- so sessions are already first-class and persisted (the turn ledger backs /gateway's replay of completed-duplicate turns, and archie-core-ippu made tool activity part of that record). What is missing is retrieval: nothing exposes a session's full contents for export or examination.\n\nEstablish first exactly what is persisted per turn today, because the answer determines whether this is an export feature or a capture feature. If tool ARGUMENTS and full tool RESULTS are not currently retained -- only rendered summaries -- then byte-for-byte replay requires changing what is written, not just adding a reader. That distinction is the main open question and should be settled before design.\n\n## Requirements\n\n- Fidelity: user messages, agent responses, every tool call with its arguments, and every tool result, in order, with timestamps. Not a rendered summary, and not the truncated preview the chat UI shows.\n- Retrieval: usable for a whole session, not capped at a tool-result size limit. Bulk delivery almost certainly belongs on the send_file path (archie-core-absb) rather than in a tool result -- write the file, deliver the file.\n- Examination, not just download: an operator should be able to inspect a replay in the dashboard, which is where the event inspector already lives.\n- Honesty: if anything is unavailable (rotated, compacted, never captured), the export must say so explicitly rather than presenting a partial record as complete. The agent got this right by hand; the mechanism should guarantee it.\n\n## Constraints\n\n- Transcripts contain secrets by nature -- tool arguments carry tokens, results carry file contents. internal/memory/scrubber and gateway/stream.go's sensitiveParameterKey are existing prior art for redaction and should be reused rather than reimplemented. Decide explicitly whether an export is redacted, raw, or offers both, and who may request one.\n- Retention: a full-fidelity record is large. Decide what is kept and for how long, consistent with the 7-day payload retention already decided for captured events.\n\n## Acceptance Criteria\n\nAn operator can export a complete session transcript containing user messages, agent responses, tool calls with arguments and tool results with content, in order and timestamped; the export is delivered as a file rather than clipped into a tool result; a replay can be examined in the dashboard; anything missing from the record is stated explicitly in the export; redaction policy is decided, documented and applied; tests cover a session larger than any tool-result cap and assert no gaps or reordering.\n","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-24T15:48:56Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:50:16Z","external_ref":"https://github.com/samcharles93/archie-core/issues/630","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-wp9s","title":"/status and /tasks have the wrong division of labour","description":"Sam's words: \"/status is fucking annoying. I'm invoking an actual status update, receiving minor information as well as shit I can get elsewhere. What's worse is that the /tasks command is meant to be for viewing the running agents, not /status.\"\n\nObserved 2026-08-24, the entire output of /status was:\n\n Tasks Parked: 2\n Runtime Provider: OpenAI Model: openai/gpt-5.6-luna\n\nTwo problems in one screen. It answers the question /tasks should own (what work is in flight), and it answers it thinly -- a count, with no task identity, no stage, no age, nothing actionable. Everything else it shows is static configuration available elsewhere. Later in the same session /status reported \"Running: 1\" for a task that was stuck in a failure loop and going nowhere, which is the specific case where a bare count actively misleads.\n\n## The division of labour to restore\n\n- `/tasks` owns WORK: what is running, what is parked and why, what needs the operator. This is the live view of the agents, and it is where task identity, workflow, stage, attempt and age belong.\n- `/status` owns HEALTH: is the daemon well. Broker connectivity, provider reachability, channel state, container pool, queue depth, last poll, version. The things an operator checks when something feels wrong and which are NOT visible elsewhere in chat.\n\nNeither should be a thin duplicate of the other, and neither should pad itself with static config the operator already knows.\n\n## Related, decide together\n\narchie-core-624 (task_action chat tool) adds operator verbs for tasks. /tasks is the natural surface for discovering the ids those verbs act on, so the two should be designed as one flow: see the work, then act on it. Check what internal/gateway/task_tools.go already returns before adding a new query path -- ChatTaskSummary may already carry most of what /tasks should show.\n\n## Steps to Reproduce\n\n1. Run /status in chat with tasks parked and one running.\n2. Observe a parked/running COUNT plus provider and model, with no way to identify or act on any task.\n3. Run /tasks and observe the overlap.\n\n## Acceptance Criteria\n\n/tasks shows the live work with enough identity and state to act on it (id, title, status, workflow/stage, age) and is the documented way to view running agents; /status reports daemon health that is not obtainable elsewhere in chat and does not duplicate the task list; a task that is running but not progressing is distinguishable from one making progress; the command descriptions registered with the platform match what each actually does.\n","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-24T15:48:33Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:50:17Z","external_ref":"https://github.com/samcharles93/archie-core/issues/631","dependency_count":0,"dependent_count":0,"comment_count":0}
@@ -567,6 +568,8 @@
{"_type":"issue","id":"archie-core-1786637489857-3-24abe68c","title":"fix(gateway): make /compress failure-safe","description":"applyCompress swallows MessageCount and DeleteRecentMessages errors (allCount, _ := and _, _ =) then deletes all messages BEFORE saving the compressed replacement. A crash or error between the two loses the session's entire history unrecoverably. Add a store-level ReplaceMessages that saves first and deletes the previously-listed IDs after, so the failure mode is recoverable duplicates rather than total loss.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:26:24Z","updated_at":"2026-08-08T15:33:31Z","closed_at":"2026-08-08T15:33:32Z","external_ref":"https://github.com/samcharles93/archie-core/issues/24","source_system":"github:https://github.com/samcharles93/archie-core/issues/24:24","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-1786637489834-2-109e7cab","title":"[BUG] /model \u003cname\u003e asked the router for a doubled model name","description":"The nestif extraction in 651de0a pulled --provider parsing out of parseModelRest into extractProviderFlag, which took the modelParts slice by pointer and appended every non-provider field to it. The caller's own loop then appended the same fields again, so every field of the model name was duplicated: '/model gpt-5.6' resolved to 'gpt-5.6 gpt-5.6' and SetActiveModel rejected it as an unknown model. '/model gpt-5.6 --provider openai' was worse -- the space-separated provider value was no longer consumed with its flag, giving 'gpt-5.6 gpt-5.6 openai'. Direct model switching over Telegram was broken for anything but a bare --refresh or a provider-only switch. Found while auditing 6d4e0be for archie-core-ifi: the naked return in the same function could not be regression-tested until the function produced correct values.\n\n### Design\n\nTwo ways to fix the double append were available. Rejected: keep the helper\nsignature and delete the caller's default-branch append. That restores correct\noutput but leaves the shape intact -- a helper holding a pointer to the\ncaller's accumulator, with two loops over the same fields -- so the next person\nwho adds a field type has the same trap waiting. It also does not fix the\nspace-separated provider value, because the helper returns early on the first\n--provider and never sees the fields after it.\n\nChosen: splitProviderFlag returns (provider, remaining) and is the sole\naccumulator. One loop owns the fields, and there is no shared slice to append\nto twice. The index loop is kept deliberately -- i++ after reading a\nspace-separated value is what removes it with its flag, and converting that to\na range loop is precisely what 651de0a did wrong.\n\nLast --provider wins if repeated, matching the pre-651de0a behaviour rather\nthan the buggy helper's first-wins. Not worth a flag: /model does not document\nrepeating it.\n\n### Acceptance Criteria\n\nparseModelRest returns the model name exactly once for bare names, scope flags, and both --provider spellings, with a regression test asserting field count rather than string equality.","status":"closed","priority":2,"issue_type":"bug","created_at":"2026-08-08T14:26:19Z","updated_at":"2026-08-08T15:34:07Z","closed_at":"2026-08-08T15:34:08Z","external_ref":"https://github.com/samcharles93/archie-core/issues/23","source_system":"github:https://github.com/samcharles93/archie-core/issues/23:23","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-1786637489768-1-2fd8288f","title":"Trigger accounting: curator output must not feed its own trigger","description":"Establish the invariant that work a curator produces does not count toward the condition that schedules the next curator run. The scheduler must explicitly exclude derived curator output from the observation threshold: counting it would inflate the threshold and create a feedback loop, so a curator that writes memories must not thereby schedule itself again.\n\n### Acceptance Criteria\n\nDerived curator output is distinguishable from primary input at the point the trigger is evaluated. A curator that writes memories does not thereby schedule itself again. There is a regression test that would fail if derived output were counted, with the feedback-loop rationale recorded in the test so the guard is not removed as redundant.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:26:17Z","updated_at":"2026-08-15T12:55:20Z","closed_at":"2026-08-15T12:55:20Z","close_reason":"Complete: internal/domain/curator/wake.go WakeOnPrimaryInput forwards only explicitly-passed inputKinds; curator-produced kinds (curator_run, curator_action, curator_error) are structurally excluded, per its own doc comment naming this exact invariant. internal/domain/curator/wake_test.go:11-21 TestWakeOnPrimaryInputForwardsOnlyPrimaryKinds carries the required feedback-loop rationale verbatim ('if derived curator output counted... a curator that writes memories would schedule itself again... This test fails if a derived kind is added to the forwarded set or the filter is removed as redundant') and asserts passCalls/checkCalls stay at 1 after publishing derived-kind events. All three acceptance-criteria clauses satisfied exactly.","external_ref":"https://github.com/samcharles93/archie-core/issues/22","source_system":"github:https://github.com/samcharles93/archie-core/issues/22:22","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-jkmu","title":"send_file confinement is symlink-blind and re-opens the file after checking it","description":"internal/tools/builtin/confinement.go ResolveReadable applies exactly the read tool's policy (resolvePath + isReadConfined), which is purely lexical: filepath.Abs/Rel, never EvalSymlinks. A symlink inside the workspace pointing at /etc/shadow passes the check, and the telegram sender then opens att.Path with no confinement check of its own, in a different goroutine after the turn. There is also a real TOCTOU window -- prepare stats/opens/closes, SendMedia re-stats and re-opens later.\n\nThe policy is unchanged from the read tool, so this is not a new hole; what changed is the consequence. The read tool caps at 5MB into the operator's own context; send_file ships up to 50MB OUT to a chat. The shell tool has never been confined either, so a model that wants the bytes already has them.\n\nDecide: either resolve symlinks in ResolveReadable (which changes read-tool behaviour too, and may break legitimate symlinked workspaces), or document the caveat explicitly and stop claiming 'sending cannot reach what reading cannot' without it.\n\nFound by adversarial review of 9a45fbb.\n\n## Acceptance Criteria\nEither the symlink case is closed at the resolver, or the limitation is written down where the claim is made (confinement.go doc comment and sendfile package doc).","status":"open","priority":3,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-24T15:54:43Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:54:43Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-1ysw.8","title":"Honor cancellation before local worktree commits","description":"CommitAll discards its context and can stage and commit after task cancellation.\n\nConfirmed still present on main: `Manager.CommitAll` (internal/worktree/worktree.go:387) takes `_ context.Context` and never reads it. Between entry and `wt.Commit` it performs `AddWithOptions{All: true}` and `wt.Commit`, neither of which is context-aware in go-git, so a task cancelled just before the call still mutates the index and HEAD.\n\n## Steps to Reproduce\n\n1. Prepare a task worktree with uncommitted changes.\n2. Create an already-cancelled context: `ctx, cancel := context.WithCancel(context.Background()); cancel()`.\n3. Call `Manager.CommitAll(ctx, dir, \"msg\")`.\n4. Observe it returns `(true, nil)`: the index was staged and a new commit is on HEAD despite the context being cancelled before the call.\n5. In production this leaves a commit on the task branch for work the operator cancelled, which the subsequent push/PR path can then publish.\n\n## Acceptance Criteria\n\nA pre-canceled context causes no index or HEAD mutation; cancellation is checked between non-context-aware go-git phases where possible, with regression tests.\n","acceptance_criteria":"A pre-canceled context causes no index or HEAD mutation; cancellation is checked between non-context-aware go-git phases where possible, with regression tests.","status":"closed","priority":3,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-22T11:01:48Z","created_by":"Sam Catlow","updated_at":"2026-08-24T08:15:48Z","started_at":"2026-08-24T07:42:10Z","closed_at":"2026-08-24T08:15:48Z","close_reason":"Fixed: CommitAll now takes a live context and checks ctx.Err() before open, worktree, staging, status and commit (worktree.go:398-430), so a pre-cancelled context mutates neither index nor HEAD. Proven red against pre-fix code: 'CommitAll() error = nil, want context canceled' for both a cancelled context and an expired deadline. task check green; fresh adversarial review zero findings.","external_ref":"https://github.com/samcharles93/archie-core/issues/603","dependencies":[{"issue_id":"archie-core-1ysw.8","depends_on_id":"archie-core-1ysw","type":"parent-child","created_at":"2026-08-22T21:01:47Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-0y4v","title":"agent: markWorktreeSafe checks existence, not mount-ness, so a stale dir writes to the operator's gitconfig","description":"markWorktreeSafe gates on os.Stat (existence and dir-ness), not mount-ness, despite the doc comment claiming a 'mount' check so host-mode agents don't write to the operator's own ~/.gitconfig for a path that was never mounted (commit 6b46ea1's stated purpose). A directory that merely exists at /data/worktree (a stale leftover) satisfies the guard and appends safe.directory=/data/worktree to the operator's gitconfig. Low severity — the entry is inert unless a repo exists at that exact path — but the guard's behavior does not match its documented contract, and the exists-but-not-a-mount case is untested.\n\nFailure: a host-mode agent (local-ollama-standalone.toml) on a machine with a leftover /data directory: an extra safe.directory line appears in the operator's ~/.gitconfig, exactly what the guard claims to prevent.","design":"Either implement a real mount check (e.g. /proc/self/mountinfo on Linux) or correct the doc comment to say the guard is existence-based and accept the (inert) entry. Decide which contract is intended.","acceptance_criteria":"Behavior matches the documented contract; the exists-but-not-mounted case is covered by a test, or the doc is corrected.","status":"closed","priority":3,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:38Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:48:45Z","started_at":"2026-08-14T15:47:55Z","closed_at":"2026-08-14T15:48:45Z","close_reason":"Corrected markSafe's doc comment to match its actual existence-based (not mount-based) check; pinned the exists-but-unmounted case with a new test rather than adding platform-specific mount detection for an inert failure mode. Committed f1d74ab.","external_ref":"https://github.com/samcharles93/archie-core/issues/494","labels":["agent","code-review"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-3svc","title":"Concurrent send_file uploads in one turn are uncapped","description":"liveReply.Media starts an unbounded mediaWg.Go per attachment. Not a leak (each is bounded by a 30s ctx) and not a memory problem (go-telegram streams via io.Pipe, nothing is buffered), but N send_file calls in one turn start N concurrent multipart uploads against a rate-limited API.\n\nAlso noted: send_file is ClassIdempotent, which makes it ExecParallelSafe. Defensible since the tool only validates and never sends, but minimax is ClassMutating for an equivalent 'produces an outbound artifact' tool -- worth deciding deliberately rather than by accident.\n\nFound by adversarial review of 9a45fbb. internal/channels/telegram/live.go:386.\n\n## Acceptance Criteria\nEither a bound on concurrent media sends per reply, or a recorded decision that the 30s timeout plus Telegram's own rate limiting is sufficient.","status":"open","priority":4,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-24T15:54:51Z","created_by":"Sam Catlow","updated_at":"2026-08-24T15:54:51Z","dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"archie-core-52f7","title":"telegram: the live-edit answer keeps its turn-start timestamp and can sort before the conversation","description":"The final reply is delivered by editing the message created at the first streamed frame, and editMessageText does not change the message date — so a long tool-using turn's answer is timestamped at turn start, can predate messages sent during the turn, and sorts before the conversation that produced it. Cosmetic and inherent to the watch-the-answer-being-written design (delete-and-resend would flicker and reorder), but it is a visible consequence nothing documents or tests.\n\nFailure: a turn with a two-minute tool phase produces an answer whose timestamp precedes a follow-up user message that references it; chat history ordering places the answer before the conversation that produced it.","design":"Either accept and document the limitation (a comment on liveReply/finalize), or investigate a delete-and-resend on finalize for turns that cross a meaningful time gap. Low priority; a documentation note may be the right fix.","acceptance_criteria":"The timestamp behavior is at least documented (or changed and tested), so it is a known trade-off rather than a surprise.","status":"closed","priority":4,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:38Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:48:45Z","started_at":"2026-08-14T15:46:50Z","closed_at":"2026-08-14T15:48:45Z","close_reason":"Documented the accepted trade-off on liveReply's doc comment per the design note's preferred option; no behavior change. Committed ed18bfb.","external_ref":"https://github.com/samcharles93/archie-core/issues/495","labels":["code-review","streaming","telegram"],"dependency_count":0,"dependent_count":0,"comment_count":0}
+46 -13
View File
@@ -33,13 +33,32 @@ import (
// ToolName is the registry name of the file-delivery tool.
const ToolName = "send_file"
// MaxUploadBytes bounds what may be handed to a channel for upload. It is
// the Telegram Bot API's 50 MB document ceiling, which is the tightest
// limit among the channels that can deliver at all; checking it here means
// an oversized file fails as a tool error the model can report instead of
// as a delivery failure it never sees. The channel enforces its own real
// limits regardless -- this is an early, visible check, not the authority.
const MaxUploadBytes int64 = 50 * 1024 * 1024
// Upload ceilings, in bytes. These are the Telegram Bot API's, the
// tightest among the channels that can deliver at all; checking them here
// means an oversized file fails as a tool error the model can report
// instead of as a delivery failure it never sees. The channel enforces its
// own limits regardless -- this is an early, visible check, not the
// authority.
//
// Images have their own, much lower ceiling. Applying MaxUploadBytes to
// every type made the early check useless for exactly the type that needed
// it: a 20 MB screenshot passed here, was reported to the model as sent,
// and was then rejected by a layer the model cannot see.
const (
MaxUploadBytes int64 = 50 * 1024 * 1024
MaxImageUploadBytes int64 = 10 * 1024 * 1024
)
// uploadLimit reports the ceiling for a media kind. It mirrors the
// telegram sender's own limits by design: the two must agree, or the early
// check either lets through what the send rejects or refuses what it would
// have accepted.
func uploadLimit(mediaType string) int64 {
if mediaType == "image" {
return MaxImageUploadBytes
}
return MaxUploadBytes
}
// Tool builds the registry entry rooted at workspace. Relative paths
// resolve against it, and confinement (when enabled) is measured from it,
@@ -107,9 +126,10 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) {
if !info.Mode().IsRegular() {
return tools.MultimodalResult{}, fmt.Errorf("%s: %s: %w", ToolName, resolved, errNotRegularFile)
}
if info.Size() > MaxUploadBytes {
return tools.MultimodalResult{}, fmt.Errorf("%s: %s is %d bytes, over the %d byte upload limit",
ToolName, resolved, info.Size(), MaxUploadBytes)
mediaType := MediaType(resolved)
if limit := uploadLimit(mediaType); info.Size() > limit {
return tools.MultimodalResult{}, fmt.Errorf("%s: %s is %d bytes, over the %d byte upload limit for %s",
ToolName, resolved, info.Size(), limit, mediaType)
}
// Opened, not just stat'd: an unreadable file is a failure the model
// must see now rather than one the channel discovers after the turn
@@ -129,13 +149,25 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) {
IsMultimodal: true,
Summary: summary,
URLs: []tools.MediaRef{{
Type: MediaType(resolved),
Type: mediaType,
Path: resolved,
FileName: name,
}},
}, nil
}
// photoFormats are the image types a chat platform will accept through its
// photo endpoint. Membership is by exact media type rather than an
// "image/" prefix: image/svg+xml and image/tiff are images that a photo
// endpoint rejects outright, so treating the whole prefix as photo-safe
// turned a deliverable file into a failed send. As documents they arrive.
var photoFormats = map[string]bool{
"image/jpeg": true,
"image/png": true,
"image/gif": true,
"image/webp": true,
}
// MediaType maps a filename onto the four-value media vocabulary
// gateway.MediaAttachment.Type uses.
//
@@ -143,9 +175,10 @@ func prepare(workspace, path, caption string) (tools.MultimodalResult, error) {
// arbitrary bytes: guessing "image" wrongly makes the platform reject the
// send, while sending an image as a document still delivers the file.
func MediaType(path string) string {
mt := mime.TypeByExtension(strings.ToLower(filepath.Ext(path)))
mt, _, _ := strings.Cut(mime.TypeByExtension(strings.ToLower(filepath.Ext(path))), ";")
mt = strings.TrimSpace(mt)
switch {
case strings.HasPrefix(mt, "image/"):
case photoFormats[mt]:
return "image"
case strings.HasPrefix(mt, "video/"):
return "video"
+40
View File
@@ -33,6 +33,11 @@ func TestPrepareReturnsLocalPathRef(t *testing.T) {
{"markdown is a document", "transcript.md", "document"},
{"unknown extension is a document", "dump.bin", "document"},
{"png is an image", "shot.png", "image"},
{"jpeg is an image", "photo.jpg", "image"},
// An svg IS an image, but no photo endpoint accepts one, so
// calling it one turns a deliverable file into a failed send.
{"svg is a document, not a photo", "diagram.svg", "document"},
{"tiff is a document, not a photo", "scan.tiff", "document"},
{"mp4 is a video", "clip.mp4", "video"},
{"mp3 is audio", "note.mp3", "audio"},
}
@@ -80,6 +85,14 @@ func TestPrepareFailuresAreErrors(t *testing.T) {
ws := t.TempDir()
outside := t.TempDir()
writeFile(t, outside, "secret.txt", 8)
locked := writeFile(t, ws, "locked.txt", 8)
if err := os.Chmod(locked, 0o000); err != nil {
t.Fatalf("chmod: %v", err)
}
if os.Geteuid() == 0 {
// root ignores the mode bits, so the probe cannot fail this way.
t.Skip("running as root: an unreadable file is still readable")
}
big := writeFile(t, ws, "big.bin", 0)
if err := os.Truncate(big, MaxUploadBytes+1); err != nil {
t.Fatalf("truncate: %v", err)
@@ -94,6 +107,7 @@ func TestPrepareFailuresAreErrors(t *testing.T) {
{name: "empty path", path: " ", wantSub: "path is required"},
{name: "missing file", path: "nope.txt", wantErr: os.ErrNotExist},
{name: "directory", path: ".", wantSub: "not a regular file"},
{name: "unreadable file", path: "locked.txt", wantErr: os.ErrPermission},
{name: "over the upload limit", path: "big.bin", wantSub: "upload limit"},
{
name: "outside the workspace",
@@ -121,6 +135,32 @@ func TestPrepareFailuresAreErrors(t *testing.T) {
}
}
// An image is capped far lower than everything else by the platform that
// delivers it. Checking one 50 MB ceiling for every type told the model an
// 11 MB screenshot was sent and left the rejection to a layer it cannot
// see -- the early check has to be the check that actually applies.
func TestPrepareAppliesTheImageLimit(t *testing.T) {
ws := t.TempDir()
png := writeFile(t, ws, "shot.png", 0)
if err := os.Truncate(png, MaxImageUploadBytes+1); err != nil {
t.Fatalf("truncate: %v", err)
}
if _, err := prepare(ws, "shot.png", ""); err == nil ||
!strings.Contains(err.Error(), "upload limit") {
t.Fatalf("err = %v, want an over-the-image-limit error", err)
}
// The same size as a document is fine: the limits must stay
// per-type rather than collapsing into one conservative number.
doc := writeFile(t, ws, "dump.bin", 0)
if err := os.Truncate(doc, MaxImageUploadBytes+1); err != nil {
t.Fatalf("truncate: %v", err)
}
if _, err := prepare(ws, "dump.bin", ""); err != nil {
t.Fatalf("prepare document of image-limit+1 bytes: %v", err)
}
}
// Confinement is a deployment posture: with the jail lifted, a path
// outside the workspace must be sendable, exactly as the read tool can
// read it.
+21 -8
View File
@@ -257,16 +257,29 @@ func (s chatStreamSink) ToolCall(event gateway.ToolCallEvent) {
// Media has no inline rendering path on the dashboard yet (see
// archie-core-1786748942243-6-f109697e), so it degrades to a link in the
// delta stream -- the same fallback Telegram's liveReply uses when its own
// SendMedia call fails. An attachment with no URL has nothing to link to
// and is skipped rather than emitting an empty line.
// SendMedia call fails.
//
// A local file cannot be linked and this channel cannot upload one, so it
// is REPORTED as undelivered rather than skipped. Skipping was right while
// media meant a hosted URL; once send_file could hand this sink a host
// path, silence here meant the model announced a file it had sent and
// nothing arrived -- the precise defect send_file was built to end,
// reappearing on the channel that cannot deliver.
func (s chatStreamSink) Media(event gateway.MediaEvent) {
if event.Attachment.URL == "" {
return
att := event.Attachment
switch {
case att.URL != "":
s.write(chatStreamEvent{Type: "delta", Text: "\n\n📎 " + att.Type + ": " + att.URL})
case att.Path != "":
name := att.FileName
if name == "" {
name = att.Path
}
s.write(chatStreamEvent{
Type: "delta",
Text: "\n\n📎 could not send " + name + ": this channel cannot deliver a local file. It is on the daemon host at " + att.Path + ".",
})
}
s.write(chatStreamEvent{
Type: "delta",
Text: "\n\n📎 " + event.Attachment.Type + ": " + event.Attachment.URL,
})
}
// chatShowToolCalls reports config.ChatConfig.ShowToolCalls, the one setting
+44
View File
@@ -835,3 +835,47 @@ func postTo(server *Server, body string) *httptest.ResponseRecorder {
server.Handler().ServeHTTP(res, req)
return res
}
// The dashboard cannot upload a file at all, so a local attachment must
// say so in the transcript. Skipping it silently is the same defect
// send_file was built to end: the model reports a file as sent and
// nothing arrives, with no signal either way.
func TestChatStreamReportsUndeliverableLocalFile(t *testing.T) {
stream := func(_ context.Context, _ gateway.Message, turn gateway.TurnStream) (string, error) {
turn.Media(gateway.MediaEvent{
ToolName: "send_file",
Attachment: gateway.MediaAttachment{
Type: "document",
Path: "/var/log/archie/session.log",
FileName: "session.log",
},
})
return "", nil
}
server, sessions := chatTestServer(t)
server.Chat.Router.LLMStream = stream
saveWebSession(t, sessions, "web-1")
req := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/api/chat/stream",
strings.NewReader(`{"channel_id":"browser-web-1","text":"send me the log"}`))
req.Header.Set("Content-Type", "application/json")
res := httptest.NewRecorder()
server.Handler().ServeHTTP(res, req)
if res.Code != http.StatusOK {
t.Fatalf("status = %d, body = %s", res.Code, res.Body)
}
var joined strings.Builder
for _, ev := range parseChatSSE(t, res.Body.String()) {
if ev.Type == "delta" {
joined.WriteString(ev.Text)
}
}
if !strings.Contains(joined.String(), "session.log") {
t.Errorf("delta stream = %q, want it to name the undelivered file", joined.String())
}
if !strings.Contains(joined.String(), "could not") {
t.Errorf("delta stream = %q, want it to report non-delivery", joined.String())
}
}