From 08fa79e5af26fe94c153ac41bdfc58fe554d82a8 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 23 Aug 2026 23:36:44 +1000 Subject: [PATCH] feat(webui): surface per-component update status on /api/version and Configuration The prior two changes gave every component an InstallType/Reference and a way to observe what's actually running (installtype.Type(), daemon.AgentStatus, [nats] config), but nothing consumed any of it -- an operator still had no single place to see whether a component's actual running state agrees with what the update-check command claims. Add GET /api/version: per component, install type, observed running version, the check command's installed/available claims, and a computed status -- ok / update_available / drift / unknown. drift takes priority over update_available (a claim the running system contradicts is worse than a newer release merely existing), and a component with no installed claim at all reports unknown rather than guessing "ok" or "update_available" from a comparison that was never actually made. Surface it as an "Update status" card above the Configuration page's existing config view, sourced independently so its own failure (or a 501 on deployments with no update-check command configured, which renders nothing rather than an error) never blocks the config view that's already there. Closes archie-core-1786751948782-3-837a8fd0.3 and, with it, archie-core-1786751948782-3-837a8fd0 (all 5 design points landed). --- .beads/issues.jsonl | 36 +++--- internal/webui/api_version.go | 101 ++++++++++++++++ internal/webui/api_version_test.go | 158 +++++++++++++++++++++++++ internal/webui/server.go | 1 + ui/dist/assets/index.js | 13 +- ui/src/base/api.js | 1 + ui/src/settings/settings.js | 22 +++- ui/src/settings/update-status.js | 73 ++++++++++++ ui/test/settings-update-status.test.js | 37 ++++++ 9 files changed, 417 insertions(+), 25 deletions(-) create mode 100644 internal/webui/api_version.go create mode 100644 internal/webui/api_version_test.go create mode 100644 ui/src/settings/update-status.js create mode 100644 ui/test/settings-update-status.test.js diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index b7de16e2b..334e71155 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -22,25 +22,25 @@ {"_type":"issue","id":"archie-core-1787489595508-2-98c4b849","title":"Playbook binding: matcher + mapping + workflow, editable at runtime","description":"The object that ties it together. A binding is: a matcher (which inbound events does this apply to), a mapping (which fields the workflow receives), and a target agentic workflow.\n\nRuntime-editable is the whole point -- creating or changing a binding must not require a redeploy or a daemon restart. That has real consequences the design must face:\n\n- Bindings are persisted state, not config. They live in the store, not config.toml, because operators create them from the UI while the daemon runs.\n- They need versioning. A binding that starts a task should record WHICH version ran, or a later edit makes historical task provenance a lie.\n- Matcher ambiguity needs a defined resolution: two bindings matching one event either both run, or the more specific wins, or it is an error. Pick one and say so.\n- A binding referencing a workflow that no longer exists must fail visibly at bind time, not at 3am when the event arrives.","status":"open","priority":1,"issue_type":"feature","created_at":"2026-08-23T12:22:09Z","updated_at":"2026-08-23T12:22:09Z","external_ref":"https://github.com/samcharles93/archie-core/issues/565","source_system":"github:https://github.com/samcharles93/archie-core/issues/565:565","metadata":null,"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1ysw.3","title":"Clean abandoned untracked files on retry","description":"Prepare refresh hard-resets tracked files but retains untracked files; CommitAll later stages and publishes them during the next attempt.","acceptance_criteria":"A regression test proves an untracked file left by an interrupted attempt is absent after retry and cannot appear in ChangedFiles or the next commit; deliberate .git control files remain intact.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-22T11:01:44Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:22Z","started_at":"2026-08-22T11:47:47Z","closed_at":"2026-08-22T11:55:20Z","close_reason":"Retry refresh now removes all non-HEAD worktree content including ignored output while preserving .git, tracked symlinks, and gitlinks; missing bases fail closed.","external_ref":"https://github.com/samcharles93/archie-core/issues/591","dependencies":[{"issue_id":"archie-core-1ysw.3","depends_on_id":"archie-core-1ysw","type":"parent-child","created_at":"2026-08-22T21:01:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1ysw.2","title":"Make worktree directory keys collision-free","description":"Manager.Dir flattens owner and repo with a hyphen, so distinct repositories such as a-b/c and a/b-c share a task directory for equal issue numbers.","acceptance_criteria":"Distinct owner/repo tuples always map to distinct contained paths; sequential and concurrent collision regressions cannot reuse, delete, reset, or push the other repository's clone.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-22T11:01:43Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:22Z","started_at":"2026-08-22T11:44:35Z","closed_at":"2026-08-22T11:47:03Z","close_reason":"Implemented per-dispatch publication grants, removed sandbox-selected prepare/path authority, made repository worktree keys collision-free, and added fail-closed legacy migration/cleanup coverage.","external_ref":"https://github.com/samcharles93/archie-core/issues/592","dependencies":[{"issue_id":"archie-core-1ysw.2","depends_on_id":"archie-core-1ysw","type":"parent-child","created_at":"2026-08-22T21:01:43Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-t2db.4","title":"Playbook binding: matcher + mapping + workflow, editable at runtime","description":"The object that ties it together. A binding is: a matcher (which inbound events does this apply to), a mapping (which fields the workflow receives), and a target agentic workflow.\n\nRuntime-editable is the whole point -- creating or changing a binding must not require a redeploy or a daemon restart. That has real consequences the design must face:\n\n- Bindings are persisted state, not config. They live in the store, not config.toml, because operators create them from the UI while the daemon runs.\n- They need versioning. A binding that starts a task should record WHICH version ran, or a later edit makes historical task provenance a lie.\n- Matcher ambiguity needs a defined resolution: two bindings matching one event either both run, or the more specific wins, or it is an error. Pick one and say so.\n- A binding referencing a workflow that no longer exists must fail visibly at bind time, not at 3am when the event arrives.","acceptance_criteria":"A binding can be created, edited and disabled from the UI while the daemon runs; a task records the binding version that started it; overlapping matchers resolve by a defined and documented rule; a binding naming a missing workflow is rejected when saved.","notes":"2026-08-22: the draft -\u003e pending_approval -\u003e armed state machine from t2db.5's decision belongs to the binding entity this bead defines, not to a shared package -- 7d5u.3 was narrowed to exclude it since there is exactly one consumer today. Implement the state transitions here.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:45Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:02Z","external_ref":"https://github.com/samcharles93/archie-core/issues/537","dependencies":[{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db.5","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db.3","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-t2db.4","title":"Playbook binding: matcher + mapping + workflow, editable at runtime","description":"The object that ties it together. A binding is: a matcher (which inbound events does this apply to), a mapping (which fields the workflow receives), and a target agentic workflow.\n\nRuntime-editable is the whole point -- creating or changing a binding must not require a redeploy or a daemon restart. That has real consequences the design must face:\n\n- Bindings are persisted state, not config. They live in the store, not config.toml, because operators create them from the UI while the daemon runs.\n- They need versioning. A binding that starts a task should record WHICH version ran, or a later edit makes historical task provenance a lie.\n- Matcher ambiguity needs a defined resolution: two bindings matching one event either both run, or the more specific wins, or it is an error. Pick one and say so.\n- A binding referencing a workflow that no longer exists must fail visibly at bind time, not at 3am when the event arrives.","acceptance_criteria":"A binding can be created, edited and disabled from the UI while the daemon runs; a task records the binding version that started it; overlapping matchers resolve by a defined and documented rule; a binding naming a missing workflow is rejected when saved.","notes":"2026-08-22: the draft -\u003e pending_approval -\u003e armed state machine from t2db.5's decision belongs to the binding entity this bead defines, not to a shared package -- 7d5u.3 was narrowed to exclude it since there is exactly one consumer today. Implement the state transitions here.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:45Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:02Z","external_ref":"https://github.com/samcharles93/archie-core/issues/537","dependencies":[{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db.3","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.4","depends_on_id":"archie-core-t2db.5","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-t2db.1","title":"Capture inbound events archie does not yet understand","description":"The precondition for everything else. Today an unrecognised inbound request is rejected; for schema-by-example it must be RECORDED, because you cannot map a payload you have never seen.\n\nAccept, store and retain inbound events with no binding: raw body, headers, source, arrival time, and the identity that sent it. Retention must be bounded -- an open capture endpoint is an unbounded disk write, and this is exactly the kind of surface an attacker fills.\n\nStrong argument for NATS JetStream as the store rather than the in-process events.Bus: durable, replayable, retention-bounded natively, already deployed. Note the constraint though -- internal/infrastructure/eventbus/nats/doc.go states 'when no NATS URL is configured the daemon uses its local SQLite claim flow instead; nothing here is required for single-process operation'. NATS is currently OPTIONAL. Decide deliberately whether capture requires it (making this feature unavailable in single-process deployments) or degrades to SQLite, and record which -- do not let it become a hard dependency by accident.","acceptance_criteria":"An unbound webhook POST is captured and visible rather than rejected; capture is retention-bounded with a documented limit; the single-process (no NATS) behaviour is a deliberate, recorded decision; capture cannot exhaust disk.","notes":"2026-08-22: capture-storage ownership confirmed here (not in 7d5u.3, which was narrowed to storage-agnostic HMAC/rate-limit/redaction mechanics only). This bead's capture path should call webhookguard's redaction before persisting and its rate limiter at the HTTP boundary, but owns its own storage engine and the NATS-vs-SQLite decision.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:03Z","started_at":"2026-08-21T16:18:24Z","closed_at":"2026-08-21T18:51:09Z","close_reason":"Built capture storage + endpoint: docs/prds/event-capture-storage.md decides SQLite over NATS JetStream (NATS not unconditionally available pre-7d5u.2, capture's single-writer/single-reader access pattern doesn't need JetStream fan-out/replay). internal/store/captures.go adds captured_events table + InsertCapture (prune-on-write by retention age and row count) + ListCaptures. internal/webui/api_capture.go adds POST /webhooks/capture/{source}, unauthenticated (bypasses requireToken like /healthz), applying webhookguard redaction before persisting and a per-remote-address rate limit + hard body-size cap before that. New [capture] config section with documented defaults. Adversarial self-review (the usual fresh subagent pass hit a session API limit mid-run, so this was a manual re-read with the same checklist) caught and fixed three real bugs before landing: (1) body-size cap silently unenforced when unset -- added a hardcoded fallback floor since it's the only bound on a SINGLE payload's size; (2) rate limiter was keyed by the request's own unregistered source path segment, violating webhookguard.RateLimiter's documented bounded-key-space assumption -- an attacker could rotate the segment to bypass the limit and grow the bucket map unbounded; rekeyed to remote address; (3) retention prune used time.RFC3339Nano, whose variable-width trimmed fractional seconds break lexicographic string comparison in `WHERE received_at \u003c ?` (an exact-second timestamp can sort after a later fractional one) -- switched to fixed-width RFC3339. All three have regression tests verified to fail against the pre-fix code. task check clean, golangci-lint zero new findings repo-wide.","external_ref":"https://github.com/samcharles93/archie-core/issues/538","dependencies":[{"issue_id":"archie-core-t2db.1","depends_on_id":"archie-core-7d5u.4","type":"relates-to","created_at":"2026-08-22T01:01:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.1","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":2,"comment_count":0} -{"_type":"issue","id":"archie-core-t2db.2","title":"Event inspector: see real inbound payloads in the dashboard","description":"The operator-facing half of capture. A live view of recent inbound events: source, arrival time, and the actual payload, pretty-printed and explorable.\n\nThis is the screen that makes the feature feel like magic: you hit 'send test webhook' in the other app, alt-tab to archie, and the event is sitting there. Latency from arrival to visible matters more than it looks -- it is the difference between a design loop and a guessing game.\n\nShow unbound events prominently. An event nothing is listening to is not noise here, it is the queue of integrations waiting to be built.","acceptance_criteria":"Recent inbound events are listed with source, time and full payload; unbound events are distinguishable from bound ones; a newly arrived event appears without a manual refresh; payloads are explorable rather than a wall of text.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:04Z","started_at":"2026-08-21T18:57:52Z","closed_at":"2026-08-21T19:17:03Z","close_reason":"GET /api/captures (token-gated, memory/skills-style enabled:false-not-an-error when Captures is nil) plus a new /captures dashboard page: recent captures newest-first, expandable per-row to explore redacted payload/headers pretty-printed. Live updates reuse the existing operator-activity event pipeline (Server.emit -\u003e Events.Publish -\u003e the /events SSE stream) as an invalidation signal, refetching the list rather than merging partial event data. Every row shows an 'Unbound' pill today since no binding model exists yet (t2db.4 wires the real distinction). Frontend follows the tasks/task-row.js precedent: row rendering split into capture-row.js for unit testing without the page's fetch/SSE wiring. Adversarial review (fresh subagent, full pass) found one real severe bug before merge: the live SSE event was embedding the full (up to 256KiB) redacted body/headers into the events table, which has no retention/row-count prune anywhere in the codebase -- silently defeating t2db.1's disk-bound guarantee for an unauthenticated, only-rate-limited endpoint. Fixed: the live event now carries just {id, source} as a pure invalidation signal; the dashboard refetches the authoritative list. Two smaller findings (untested Data[\"id\"] field the frontend's dedup depended on; a received_at precision mismatch between live and REST-fetched copies) were resolved as a side effect of that fix. task check clean, golangci-lint zero new findings.","external_ref":"https://github.com/samcharles93/archie-core/issues/539","dependencies":[{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:17Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-t2db.2","title":"Event inspector: see real inbound payloads in the dashboard","description":"The operator-facing half of capture. A live view of recent inbound events: source, arrival time, and the actual payload, pretty-printed and explorable.\n\nThis is the screen that makes the feature feel like magic: you hit 'send test webhook' in the other app, alt-tab to archie, and the event is sitting there. Latency from arrival to visible matters more than it looks -- it is the difference between a design loop and a guessing game.\n\nShow unbound events prominently. An event nothing is listening to is not noise here, it is the queue of integrations waiting to be built.","acceptance_criteria":"Recent inbound events are listed with source, time and full payload; unbound events are distinguishable from bound ones; a newly arrived event appears without a manual refresh; payloads are explorable rather than a wall of text.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:04Z","started_at":"2026-08-21T18:57:52Z","closed_at":"2026-08-21T19:17:03Z","close_reason":"GET /api/captures (token-gated, memory/skills-style enabled:false-not-an-error when Captures is nil) plus a new /captures dashboard page: recent captures newest-first, expandable per-row to explore redacted payload/headers pretty-printed. Live updates reuse the existing operator-activity event pipeline (Server.emit -\u003e Events.Publish -\u003e the /events SSE stream) as an invalidation signal, refetching the list rather than merging partial event data. Every row shows an 'Unbound' pill today since no binding model exists yet (t2db.4 wires the real distinction). Frontend follows the tasks/task-row.js precedent: row rendering split into capture-row.js for unit testing without the page's fetch/SSE wiring. Adversarial review (fresh subagent, full pass) found one real severe bug before merge: the live SSE event was embedding the full (up to 256KiB) redacted body/headers into the events table, which has no retention/row-count prune anywhere in the codebase -- silently defeating t2db.1's disk-bound guarantee for an unauthenticated, only-rate-limited endpoint. Fixed: the live event now carries just {id, source} as a pure invalidation signal; the dashboard refetches the authoritative list. Two smaller findings (untested Data[\"id\"] field the frontend's dedup depended on; a received_at precision mismatch between live and REST-fetched copies) were resolved as a side effect of that fix. task check clean, golangci-lint zero new findings.","external_ref":"https://github.com/samcharles93/archie-core/issues/539","dependencies":[{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:17Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.2","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-t2db.3","title":"Map payload fields by example, from a real captured event","description":"Pick a captured event, click through its payload, and bind JSON paths to named fields the workflow will receive. Schema by example, not schema by specification.\n\nThe hard part is not the happy path, it is drift. A mapping authored against one payload will eventually meet a payload where the path is missing, null, or a different type -- the sending app shipped a change nobody told you about. That must fail LOUDLY and land somewhere the operator sees, not silently pass an empty string into an agent prompt. An agent handed a blank field will confabulate around it, which turns a schema change into an agent doing confident nonsense in a repo.\n\nSupport a preview: given this mapping and this captured event, show exactly what the workflow would receive. Never ship a mapping the operator has not seen resolve against real data.","acceptance_criteria":"Fields are mappable from a captured payload without writing code; a mapping preview resolves against a real event before saving; a missing, null or type-changed path at runtime produces a visible failure rather than an empty value; the failure names the path and the event.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:18Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:05Z","started_at":"2026-08-22T08:39:40Z","closed_at":"2026-08-22T09:01:53Z","close_reason":"Payload field mapping: domain (internal/domain/mapping), SQLite store (internal/store/mappings.go), HTTP API (internal/webui/api_mapping.go), and dashboard editor (ui/src/mappings) shipped. PRD at docs/prds/payload-field-mapping.md. task check green; adversarial review found 4 issues (stale preview after rename, duplicate field names, hardcoded capture scan window, malformed path silently reinterpreted), all fixed and re-verified.","external_ref":"https://github.com/samcharles93/archie-core/issues/540","dependencies":[{"issue_id":"archie-core-t2db.3","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:18Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.3","depends_on_id":"archie-core-t2db.1","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-t2db","title":"[EPIC] Event capture and no-code playbooks: turn any inbound webhook into an agentic workflow","description":"The pitch, in the operator's words: point any app's outgoing webhook at archie, open archie, SEE the event that just arrived with its real payload, map the fields you care about, bind them to an agentic workflow, save. No code change, no redeploy, no restart. Adding a new integration stops being a development task.\n\nWhy this is different from n8n or Power Automate rather than a copy of them: their terminal node is a deterministic connector. Archie's is an AGENT with a repo, a worktree, tools and a gate. 'When Sentry reports a new issue in this project, open a PR that fixes it' is one binding here and an entire product elsewhere.\n\nThe design insight that makes it buildable: you cannot write a payload mapper against a payload you have not seen. Schema-by-example requires real recent events to map against, which means archie must CAPTURE events it does not yet understand -- including ones with no binding at all -- and retain them long enough to design against. That is also the strongest argument for putting inbound events on NATS JetStream rather than the lossy in-process bus: durable, replayable, retention-bounded, and already deployed. The capture requirement and the transport choice are the same decision.\n\nSequence: capture unrecognised events -\u003e inspect real payloads in the UI -\u003e map fields by example -\u003e bind matcher+mapping to a workflow -\u003e the next matching event runs it.\n\nThis is a public, unauthenticated-by-default intake surface whose output is an agent with tool access. Security is not a later hardening pass; it is a first-class child of this epic.","acceptance_criteria":"An operator can point a new external webhook at archie, see its payload in the UI without writing code, map fields, bind it to a workflow, and have the next matching event run that workflow -- with no redeploy and no daemon restart. A binding cannot go live without explicit human approval.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-21T13:44:56Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:06Z","external_ref":"https://github.com/samcharles93/archie-core/issues/541","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-7d5u.4","title":"GitHub forge webhook receiver behind a feature flag","description":"The concrete autonomy win: react to an issue being assigned or labelled the moment it happens, instead of up to poll_interval (default 60s) later.\n\nVerified absent on 2026-08-21: internal/forge/ and internal/daemon/ contain zero webhook references, and no bead tracked forge-event intake before this epic. internal/channels/webhook exists but is a CHAT channel -- it routes inbound text through gateway.Router for LLM processing, a peer of Telegram and email. It is not forge intake and should not be bent into it.\n\nShip as a source in the typed intake family, off by default: [forge] intake = 'poll' (default) | 'webhook' | 'both'. Verify GitHub's HMAC signature. Reuse the label/assignee dispatch predicate the poller already uses -- do NOT reimplement it, since it just took a fix (3209a1f, refusing to poll on an empty label match) and two implementations will drift.\n\nDeployment reality from CLAUDE.md: archied may run on a host, in a container, or behind no public ingress at all. A webhook receiver that assumes a reachable public URL will not fit every profile, which is exactly why polling has to remain a first-class option rather than a legacy fallback.","acceptance_criteria":"With intake='webhook', a labelled issue starts a task without waiting for the poll interval; an invalid HMAC is rejected and logged; intake='poll' behaves exactly as today; the dispatch predicate is shared with the poller, not duplicated; the flag defaults to poll.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:07Z","started_at":"2026-08-22T08:43:35Z","closed_at":"2026-08-22T09:21:16Z","close_reason":"GitHub webhook receiver shipped: [forge] intake=poll|webhook|both, shared MatchesDispatch predicate (case-insensitive assignee, case-sensitive label) consumed by poller and receiver, HMAC-verified, publishes via shared PublishTask. Adversarial self-review found and fixed 3 real defects (boot-crashing secret-resolve hard-fail under intake=both, assignee case-sensitivity mismatch vs GitHub's own filter, silent multi-identity misdispatch) before landing. task check + lint clean. Committed 41e43dc.","external_ref":"https://github.com/samcharles93/archie-core/issues/542","dependencies":[{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-t2db.1","type":"relates-to","created_at":"2026-08-22T01:01:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.3","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":2,"comment_count":0} -{"_type":"issue","id":"archie-core-7d5u.5","title":"Idempotency and poll/webhook parity: never double-dispatch, never lose work","description":"Webhooks deliver at-least-once, out of order, and sometimes not at all. Polling is the opposite: slow but eventually consistent. Running both (intake='both') is the honest production configuration, and it is also where the two failure modes meet.\n\nTwo things must hold. A single issue event must not start two tasks because the webhook and the next poll both saw it. And a webhook outage must not silently stop work -- if the receiver is wedged or the ingress is down, polling has to pick the work up, which is the entire argument for keeping it.\n\nNote archie-core-...-286 (WebhookAdapter: idempotency cache) already exists for the chat adapter. Decide whether that mechanism generalises to intake or whether forge dispatch needs its own key; do not build a second one by accident.\n\nThe silent-failure shape to design against is the one this codebase keeps hitting: a path that looks like it is working because nothing errors. A webhook receiver that has silently stopped delivering looks identical to a repo with no activity.","acceptance_criteria":"A duplicate delivery of the same forge event starts exactly one task; with intake='both', disabling the webhook path still results in the work being picked up by polling; a wedged or non-delivering webhook receiver is observable rather than indistinguishable from an idle repo.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-22T10:20:56Z","started_at":"2026-08-22T09:30:20Z","external_ref":"https://github.com/samcharles93/archie-core/issues/543","metadata":null,"dependencies":[{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u.4","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-1786637497328-286-9c985f28","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-7d5u.4","title":"GitHub forge webhook receiver behind a feature flag","description":"The concrete autonomy win: react to an issue being assigned or labelled the moment it happens, instead of up to poll_interval (default 60s) later.\n\nVerified absent on 2026-08-21: internal/forge/ and internal/daemon/ contain zero webhook references, and no bead tracked forge-event intake before this epic. internal/channels/webhook exists but is a CHAT channel -- it routes inbound text through gateway.Router for LLM processing, a peer of Telegram and email. It is not forge intake and should not be bent into it.\n\nShip as a source in the typed intake family, off by default: [forge] intake = 'poll' (default) | 'webhook' | 'both'. Verify GitHub's HMAC signature. Reuse the label/assignee dispatch predicate the poller already uses -- do NOT reimplement it, since it just took a fix (3209a1f, refusing to poll on an empty label match) and two implementations will drift.\n\nDeployment reality from CLAUDE.md: archied may run on a host, in a container, or behind no public ingress at all. A webhook receiver that assumes a reachable public URL will not fit every profile, which is exactly why polling has to remain a first-class option rather than a legacy fallback.","acceptance_criteria":"With intake='webhook', a labelled issue starts a task without waiting for the poll interval; an invalid HMAC is rejected and logged; intake='poll' behaves exactly as today; the dispatch predicate is shared with the poller, not duplicated; the flag defaults to poll.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:07Z","started_at":"2026-08-22T08:43:35Z","closed_at":"2026-08-22T09:21:16Z","close_reason":"GitHub webhook receiver shipped: [forge] intake=poll|webhook|both, shared MatchesDispatch predicate (case-insensitive assignee, case-sensitive label) consumed by poller and receiver, HMAC-verified, publishes via shared PublishTask. Adversarial self-review found and fixed 3 real defects (boot-crashing secret-resolve hard-fail under intake=both, assignee case-sensitivity mismatch vs GitHub's own filter, silent multi-identity misdispatch) before landing. task check + lint clean. Committed 41e43dc.","external_ref":"https://github.com/samcharles93/archie-core/issues/542","dependencies":[{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-7d5u.3","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.4","depends_on_id":"archie-core-t2db.1","type":"relates-to","created_at":"2026-08-22T01:01:02Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":2,"comment_count":0} +{"_type":"issue","id":"archie-core-7d5u.5","title":"Idempotency and poll/webhook parity: never double-dispatch, never lose work","description":"Webhooks deliver at-least-once, out of order, and sometimes not at all. Polling is the opposite: slow but eventually consistent. Running both (intake='both') is the honest production configuration, and it is also where the two failure modes meet.\n\nTwo things must hold. A single issue event must not start two tasks because the webhook and the next poll both saw it. And a webhook outage must not silently stop work -- if the receiver is wedged or the ingress is down, polling has to pick the work up, which is the entire argument for keeping it.\n\nNote archie-core-...-286 (WebhookAdapter: idempotency cache) already exists for the chat adapter. Decide whether that mechanism generalises to intake or whether forge dispatch needs its own key; do not build a second one by accident.\n\nThe silent-failure shape to design against is the one this codebase keeps hitting: a path that looks like it is working because nothing errors. A webhook receiver that has silently stopped delivering looks identical to a repo with no activity.","acceptance_criteria":"A duplicate delivery of the same forge event starts exactly one task; with intake='both', disabling the webhook path still results in the work being picked up by polling; a wedged or non-delivering webhook receiver is observable rather than indistinguishable from an idle repo.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-22T10:20:56Z","started_at":"2026-08-22T09:30:20Z","external_ref":"https://github.com/samcharles93/archie-core/issues/543","metadata":null,"dependencies":[{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-1786637497328-286-9c985f28","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.5","depends_on_id":"archie-core-7d5u.4","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-7d5u.1","title":"Design: event sources, reaction delivery, and how extensions hook them","description":"No settled design covers this. docs/architecture/plugins-and-extensions.md settles the PLUGIN FRAMEWORK (metadata-only contract, typed capability families, owning registries) but says nothing about event sources, reaction delivery, or intake. Under the scope-discipline rule merged as PR #533, that means design first -- one page, decisive -- then a diff.\n\nDecide and record in docs/prds/:\n\n1. THE HEADLINE QUESTION, which changes everything downstream: do extensions react in-process through typed capability families (what the approved rule mandates), or out-of-process like tau's generic DispatchEvent? If out-of-process generic dispatch is genuinely wanted, docs/architecture/plugins-and-extensions.md is an APPROVED document and must be amended first -- CLAUDE.md's organisation rule is explicit that you change the doc before the rule it states. Do not quietly work around it.\n\n2. Reaction delivery. events.Bus drops on overflow by design and must stay that way for the dashboard. Decide whether reactions get a second in-process bus with at-least-once delivery, or ride the existing NATS eventbus (internal/infrastructure/eventbus), which already has durable semantics and the work-queue traps documented in CLAUDE.md.\n\n3. Whether a reaction may INFLUENCE an outcome (veto, mutate, add work) or only observe. This is the difference between a hook and a subscriber, and it determines whether ordering and failure semantics matter. If a reaction can block, decide what a slow or crashed extension does -- tau's answer was a dispatch timeout, and it still deadlocked unload once.\n\n4. The typed source/intake family: its interface, its owning registry, and how a source declares what it produces.\n\nRespect dependency direction: cmd -\u003e app -\u003e {domain, infrastructure}. A domain declares the contract; app wires implementations. Cross-cutting packages may be imported by any layer and import none.","acceptance_criteria":"A one-page decision in docs/prds/ answering all four questions, naming the packages it will touch, and stating explicitly whether plugins-and-extensions.md needs amending. It decides rather than surveys.","notes":"CORRECTION 2026-08-22 (second): decision question 2 in this bead's description asked whether reactions get a second in-process bus or ride the existing NATS eventbus. That framing is wrong -- there is no 'or'. NATS is the settled transport; the only open axis is external-server vs embedded, not NATS vs something else. Do not design a second bus. See archie-core-7d5u and archie-core-7d5u.2 for the corrected framing and the verified state of github.com/nats-io/nats-server/v2 as an already-present, test-proven, production-unwired dependency.","status":"closed","priority":1,"issue_type":"decision","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:09Z","started_at":"2026-08-21T14:56:21Z","closed_at":"2026-08-21T15:00:55Z","close_reason":"Decided and documented in docs/prds/event-sources-and-reactions.md, satisfying this bead's own acceptance criterion (a one-page decision naming the packages it touches and stating whether plugins-and-extensions.md needs amending -- it does not).\n\nAnswers: (1) in-process typed families, no out-of-process dispatch -- archie has no existing extension-process boundary and neither epic's stated payoff needs one. (2) Reaction delivery reuses internal/eventbus's Publisher/Consumer contract (PublishUnique + Ack/Nak already provide at-least-once with dedup), but NOT the existing nats.Client as-is: it hardcodes Retention: jetstream.WorkQueuePolicy (client.go:65) for the competing-consumer ARCHIE_TASKS stream, which silently starves a second consumer on overlapping subjects per CLAUDE.md's documented trap -- reactions need fan-out, so retention needs to become a Config field and reactions get their own stream. (3) Reactions in these two epics are producer-only (cheap wake via curator's WakeOnPrimaryInput pattern, or produce real work via the existing pollNATS-\u003epublishTask path) -- no veto/mutate-in-flight-work capability is being built here; that belongs to archie-core-h019 if it's ever needed. (4) No single generic Source interface -- forge intake reuses workintake.TaskEnvelope unchanged (its IdempotencyKey is already keyed on owner/repo/number, not delivery source, so a webhook-sourced envelope naturally dedups against a poll-discovered one for free); chat webhook stays internal/channels/webhook, unmodified; what's genuinely new and shared is a small cross-cutting package for HMAC/rate-limit/approval/capture mechanics, owned by neither domain.","external_ref":"https://github.com/samcharles93/archie-core/issues/544","dependencies":[{"issue_id":"archie-core-7d5u.1","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":4,"comment_count":0} -{"_type":"issue","id":"archie-core-7d5u.2","title":"Reaction delivery via embedded NATS, no external server required","description":"Reactions need at-least-once delivery distinct from the lossy events.Bus (see epic description). The delivery mechanism is NATS -- that part is settled, not a design question. What's open is deployment shape.\n\nVERIFIED 2026-08-22: config.NATSConfig.URL empty currently means 'no NATS, use SQLite ClaimNext' (internal/config/config.go:573-582). That fallback was designed for task distribution working without a broker at all. It was never meant to generalise to 'archie has no NATS' as a permanent architectural stance -- the intended second deployment shape alongside an external NATS server was always NATS EMBEDDED (in-process), not a different eventbus.\n\ngithub.com/nats-io/nats-server/v2 is already a direct dependency and is proven to work in this codebase: internal/infrastructure/agenttransport/nats/transport_test.go and others already start a real embedded server via nats-server/v2/test for tests. It has just never been wired into production startup -- cmd/archied only knows 'external URL configured' vs 'fall back to SQLite'. No new library, no new bus, no architectural gap to design around: this is 'wire the dependency we already have and already test against into the daemon's own startup path.'\n\nDesign questions that remain, now correctly scoped: does an embedded NATS instance replace the SQLite fallback outright for single-process deployments, or run alongside it; what config controls embedded vs external vs disabled; does the daemon own the embedded server's lifecycle the same way it owns everything else (start/stop paired with daemon start/stop, per the shutdown-ordering rules in ARCHITECTURE.md).","acceptance_criteria":"A single-process deployment with no external NATS URL configured still gets reaction delivery via an embedded NATS instance; the daemon starts and stops the embedded server as part of its own lifecycle; no second eventbus type is introduced; internal/infrastructure/eventbus/nats is reused as the transport rather than duplicated.","notes":"2026-08-22, from docs/prds/event-sources-and-reactions.md: do not reuse the existing nats.Client's stream creation as-is. internal/infrastructure/eventbus/nats/client.go:65 hardcodes Retention: jetstream.WorkQueuePolicy -- correct for ARCHIE_TASKS (task distribution, one consumer claims each message) and wrong for reactions, which need fan-out (every registered reaction sees every matching event). Two reactions on overlapping subjects under WorkQueuePolicy hit the exact trap CLAUDE.md documents: the second consumer silently gets nothing. Config.StreamName/Config.Subjects are already composition-supplied (config.go:30-38); Retention is not parameterized and needs to become a Config field, defaulting to today's WorkQueuePolicy so ARCHIE_TASKS is unaffected, with reactions getting a second stream under a fan-out-capable policy and their own subject namespace.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:10Z","started_at":"2026-08-21T18:57:41Z","closed_at":"2026-08-21T19:18:55Z","close_reason":"Embedded NATS wired into production startup: mode=embedded/external/off resolves from url, daemon owns the in-process server lifecycle, Retention parameterized for a future fan-out reaction stream. task check + lint clean; adversarial review zero surviving findings. Committed 2c7db34.","external_ref":"https://github.com/samcharles93/archie-core/issues/545","dependencies":[{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-7d5u.2","title":"Reaction delivery via embedded NATS, no external server required","description":"Reactions need at-least-once delivery distinct from the lossy events.Bus (see epic description). The delivery mechanism is NATS -- that part is settled, not a design question. What's open is deployment shape.\n\nVERIFIED 2026-08-22: config.NATSConfig.URL empty currently means 'no NATS, use SQLite ClaimNext' (internal/config/config.go:573-582). That fallback was designed for task distribution working without a broker at all. It was never meant to generalise to 'archie has no NATS' as a permanent architectural stance -- the intended second deployment shape alongside an external NATS server was always NATS EMBEDDED (in-process), not a different eventbus.\n\ngithub.com/nats-io/nats-server/v2 is already a direct dependency and is proven to work in this codebase: internal/infrastructure/agenttransport/nats/transport_test.go and others already start a real embedded server via nats-server/v2/test for tests. It has just never been wired into production startup -- cmd/archied only knows 'external URL configured' vs 'fall back to SQLite'. No new library, no new bus, no architectural gap to design around: this is 'wire the dependency we already have and already test against into the daemon's own startup path.'\n\nDesign questions that remain, now correctly scoped: does an embedded NATS instance replace the SQLite fallback outright for single-process deployments, or run alongside it; what config controls embedded vs external vs disabled; does the daemon own the embedded server's lifecycle the same way it owns everything else (start/stop paired with daemon start/stop, per the shutdown-ordering rules in ARCHITECTURE.md).","acceptance_criteria":"A single-process deployment with no external NATS URL configured still gets reaction delivery via an embedded NATS instance; the daemon starts and stops the embedded server as part of its own lifecycle; no second eventbus type is introduced; internal/infrastructure/eventbus/nats is reused as the transport rather than duplicated.","notes":"2026-08-22, from docs/prds/event-sources-and-reactions.md: do not reuse the existing nats.Client's stream creation as-is. internal/infrastructure/eventbus/nats/client.go:65 hardcodes Retention: jetstream.WorkQueuePolicy -- correct for ARCHIE_TASKS (task distribution, one consumer claims each message) and wrong for reactions, which need fan-out (every registered reaction sees every matching event). Two reactions on overlapping subjects under WorkQueuePolicy hit the exact trap CLAUDE.md documents: the second consumer silently gets nothing. Config.StreamName/Config.Subjects are already composition-supplied (config.go:30-38); Retention is not parameterized and needs to become a Config field, defaulting to today's WorkQueuePolicy so ARCHIE_TASKS is unaffected, with reactions getting a second stream under a fan-out-capable policy and their own subject namespace.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:10Z","started_at":"2026-08-21T18:57:41Z","closed_at":"2026-08-21T19:18:55Z","close_reason":"Embedded NATS wired into production startup: mode=embedded/external/off resolves from url, daemon owns the in-process server lifecycle, Retention parameterized for a future fan-out reaction stream. task check + lint clean; adversarial review zero surviving findings. Committed 2c7db34.","external_ref":"https://github.com/samcharles93/archie-core/issues/545","dependencies":[{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.2","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-7d5u.3","title":"Shared webhook mechanics: HMAC verification, per-source rate limiting, payload redaction","description":"NARROWED 2026-08-22 from this bead's prior scope, which bundled capture-storage and an approval state machine into a single 'shared mechanics' package. On reflection those are not genuinely shared yet:\n\n- Capture STORAGE is t2db.1's job -- it depends on the NATS-vs-SQLite decision 7d5u.2 owns, and building a storage engine here would either duplicate or contradict that. This package may be USED by t2db.1's capture path, but does not own persistence.\n- The draft/pending_approval/armed state machine belongs to the entity that has that state -- t2db.4's binding -- not a generic package. There is exactly one consumer (bindings) today; per 'extract into a shared primitive on the second real consumer, never in anticipation of one,' building it here now would be speculative.\n\nWhat remains, and is genuinely storage-agnostic and reusable by any inbound HTTP source regardless of what consumes it:\n\n1. HMAC-SHA256 verification -- generalize internal/channels/webhook/webhook.go's existing unexported validateHMAC into an exported function here, and have that package call into it instead of keeping its own copy. One implementation of signature checking, not two that can drift.\n2. Per-source rate limiting -- a token bucket keyed by source ID (not global), so one noisy sender cannot exhaust another's budget. Limit-exceeded is an observable rejection, not a silent drop, per t2db.5's decision.\n3. Payload redaction -- generalize internal/gateway/stream.go's unexported sensitiveParameterKey/redactToolParameters heuristic (matches token/secret/password/passwd/api_key/apikey/authorization/credential/cookie/private_key against normalized JSON keys) into a reusable, storage-agnostic transform any capture path can apply before persisting.","acceptance_criteria":"webhookguard.VerifyHMAC replaces internal/channels/webhook's private copy with no behaviour change (its existing tests still pass); a per-source rate limiter rejects over-budget requests observably; a redaction function matches the same key heuristic already proven in gateway/stream.go; the package has zero imports of any domain, infrastructure or app package.","notes":"--notes=2026-08-22: merged to main as f3d3d32 (PR #534, squash of aa23ac9+46401ab+ce4f945).","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:26Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:11Z","started_at":"2026-08-21T15:19:09Z","closed_at":"2026-08-21T15:26:01Z","close_reason":"Built internal/webhookguard: VerifyHMAC (behavior-preserving extraction from internal/channels/webhook, which now calls it instead of keeping a private copy), RateLimiter (per-source token bucket, independent budgets, observable rejection), RedactPayload (key-name heuristic matching gateway/stream.go's marker list, but -- deliberately unlike that function -- redacts only values under sensitive keys and leaves ordinary strings/numbers/bools untouched, since a captured payload exists to be inspected for field mapping in t2db.3).\n\nAll four acceptance criteria met and independently confirmed by a fresh adversarial review with zero surviving findings: HMAC extraction is byte-for-byte behavior-preserving (diffed against the deleted function); rate limiter hand-traced correct on two scenarios plus race-clean under -race; redaction's divergence from gateway/stream.go verified by reading both functions side by side; zero non-stdlib imports confirmed by grep. The reviewer also mutation-tested both the redaction and rate-limit guards (disabled each in turn) and confirmed the test suite catches both, then reverted and re-verified go test -race and git status were clean.\n\ntask check exit 0, golangci-lint 0 issues (one forcetypeassert finding was caught and fixed properly during build, not suppressed), gofumpt clean. All 10 pre-existing internal/channels/webhook tests pass unmodified; the one now-redundant unit test was removed with a comment pointing to where its coverage relocated.","external_ref":"https://github.com/samcharles93/archie-core/issues/546","dependencies":[{"issue_id":"archie-core-7d5u.3","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.3","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.3","depends_on_id":"archie-core-7d5u.1","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-7d5u","title":"[EPIC] Event sources and typed reactions: archie as an extensible platform","description":"Goal: let archie react to things happening -- forge activity, inbound callers, schedules -- and let extensions hook those reactions, without a generic untyped event bus.\n\nTwo findings shape this, both verified in the tree on 2026-08-21.\n\n1. ARCHIE HAS TWO EVENT NEEDS AND ONE BUS. internal/events is documented as 'archied's in-process observability stream' with 'bounded per-subscriber buffers that DROP on overflow, so a stalled dashboard connection can never apply backpressure to the task engine'. Publish is fire-and-forget; subscribers get a read-only channel and cannot influence anything. Correct for the dashboard, wrong for reactions: a hook that silently misses events under load and cannot affect an outcome is worse than no hook, because it looks like it ran. Reactions need at-least-once delivery and the ability to change what happens. Do not bolt reactions onto events.Bus.\n\n2. THE OBVIOUS DESIGN IS PROHIBITED, DELIBERATELY. The tau model this is drawn from dispatches generically: DispatchEvent(ctx, eventName string, sessionID, ...) to out-of-process gRPC plugins. archie's approved foundation (docs/architecture/plugins-and-extensions.md) forbids that shape -- the generic plugin contract stays metadata-only and MUST NOT expose untyped hooks. plugin.Plugin is Name()/Version() only, enforced by internal/plugin/architecture_test.go and by the plugin engine rule in ARCHITECTURE.md. tau already carries the scar the rule avoids: TestUnload_DoesNotWaitForInFlightDispatch exists because a stuck plugin blocked plugin unload.\n\nThe reconciliation, and why this is an epic rather than a feature: separate INBOUND (callers push work in -- forge webhook, chat webhook, cron, channel) from REACTION (extensions respond to something that happened). Inbound becomes a typed source/intake capability family with an owning registry. Reactions become typed capability families owned by the domain whose semantics they affect. 'Webhooks aligned to types of callers' is exactly the typed-family model applied to intake: the instinct is right, the generic bus is what has to go.\n\nNear-term payoff: archie reacts to an issue being labelled the moment it happens, instead of up to poll_interval later.","acceptance_criteria":"A forge webhook triggers work behind a feature flag with polling still available as a backstop; inbound callers register through one typed family rather than bespoke wiring per caller; reactions have delivery guarantees distinct from the lossy observability bus; the generic plugin contract remains metadata-only and internal/plugin/architecture_test.go still passes.","notes":"CORRECTION 2026-08-22 (second): the earlier summary I gave characterized 'NATS is currently optional' as an open architectural gap for this epic to navigate around. That's wrong, and Sam corrected it directly: NATS was never meant to be optional as a technology. What's optional is running a standalone NATS SERVER -- config.NATSConfig.URL empty falls back to the existing SQLite ClaimNext flow (internal/config/config.go:573-582, internal/infrastructure/eventbus/nats/doc.go:24). The intended second deployment shape is NATS EMBEDDED (in-process, no external server to stand up), not 'no NATS, use some other eventbus'. There is no other eventbus in scope, was never meant to be one, and this epic must not introduce one.\n\nCurrent code state, verified: github.com/nats-io/nats-server/v2 (the embeddable NATS server package) is already a direct, non-indirect dependency, and is genuinely used to spin up an in-process server -- but only inside _test.go files (internal/infrastructure/agenttransport/nats/transport_test.go and others use github.com/nats-io/nats-server/v2/test to run tests against a real embedded server). It has never been wired into production as an actual deployment mode. So embedded NATS is proven to work in this codebase's own test harness, and the gap is purely that production startup only knows 'external URL configured' vs 'no NATS, fall back to SQLite' -- there is no production code path that starts nats-server in-process.\n\nThis changes 7d5u.2 (reaction delivery) materially: 'ride the existing NATS eventbus, or a second in-process bus' was the wrong framing. The actual question is whether reaction delivery requires an external NATS deployment or can run on an embedded NATS instance so single-process deployments still get it -- not whether to use NATS at all versus some other bus. If embedded NATS is wired for reaction delivery, capture (t2db.1) gets it too essentially for free, since they were flagged as needing the same underlying decision.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-21T13:25:57Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:11Z","external_ref":"https://github.com/samcharles93/archie-core/issues/547","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-h019.3","title":"Reviewer runs in a context that provably never saw the implementation","description":"This is the whole feature. A reviewer that shares the implementer's context is a second opinion from the same mind, and it will rationalise the same mistakes -- which is exactly the failure mode CLAUDE.md's 'never self-certified by the implementer' rule exists to prevent.\n\nArchie already has the machinery: each task runs in an isolated container against its own worktree. Launch the reviewer the same way, seeded only with the diff and the originating issue. It must not receive the implementer's conversation, its notes, its reasoning, or its own claims about what it did.\n\nPer 'environmental enforcement over prompt rules', isolation must be a property of construction, not a sentence in the prompt. The agent cannot talk its way out of a context it was never given. Assert it in a test rather than assuming it: a test that would fail if implementer context were threaded through.","acceptance_criteria":"The reviewer is launched with only diff + issue; a test fails if implementer context reaches it; the reviewer's prompt instructs it to assume every line is wrong until proven correct; the mechanism reuses the existing container/worktree isolation rather than inventing a second one.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:12Z","external_ref":"https://github.com/samcharles93/archie-core/issues/548","dependencies":[{"issue_id":"archie-core-h019.3","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.3","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-h019.4","title":"Wire review as an implement-workflow stage: after gates, before PR open","description":"Sequence matters. The review runs after gates pass -- there is no point reviewing code that does not build or test -- and before the PR is opened, because the point is to not spend the operator's attention on a PR that is not ready.\n\nA surviving CONFIRMED finding must not open a PR. It parks the task as waiting_human with the findings attached, which is the existing lifecycle state for 'a human needs to look at this' and needs no new state. Per CLAUDE.md, a finding that survives blocks closing the work; it does not get waved through.\n\nScope to the implement workflow first. Routing to tdd/bootstrap/feasibility is a later decision -- feasibility in particular produces a document rather than a diff, so 'review the diff' may not even apply.","acceptance_criteria":"An implement task with a clean gate and no confirmed findings opens a PR as it does today; one with a surviving confirmed finding parks as waiting_human with findings recorded and opens no PR; the stage is observable in the task's running(workflow:stage) status; retry after operator action re-runs the review.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:13Z","external_ref":"https://github.com/samcharles93/archie-core/issues/549","dependencies":[{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019.3","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019.2","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":3,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-h019.3","title":"Reviewer runs in a context that provably never saw the implementation","description":"This is the whole feature. A reviewer that shares the implementer's context is a second opinion from the same mind, and it will rationalise the same mistakes -- which is exactly the failure mode CLAUDE.md's 'never self-certified by the implementer' rule exists to prevent.\n\nArchie already has the machinery: each task runs in an isolated container against its own worktree. Launch the reviewer the same way, seeded only with the diff and the originating issue. It must not receive the implementer's conversation, its notes, its reasoning, or its own claims about what it did.\n\nPer 'environmental enforcement over prompt rules', isolation must be a property of construction, not a sentence in the prompt. The agent cannot talk its way out of a context it was never given. Assert it in a test rather than assuming it: a test that would fail if implementer context were threaded through.","acceptance_criteria":"The reviewer is launched with only diff + issue; a test fails if implementer context reaches it; the reviewer's prompt instructs it to assume every line is wrong until proven correct; the mechanism reuses the existing container/worktree isolation rather than inventing a second one.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:12Z","external_ref":"https://github.com/samcharles93/archie-core/issues/548","dependencies":[{"issue_id":"archie-core-h019.3","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.3","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-h019.4","title":"Wire review as an implement-workflow stage: after gates, before PR open","description":"Sequence matters. The review runs after gates pass -- there is no point reviewing code that does not build or test -- and before the PR is opened, because the point is to not spend the operator's attention on a PR that is not ready.\n\nA surviving CONFIRMED finding must not open a PR. It parks the task as waiting_human with the findings attached, which is the existing lifecycle state for 'a human needs to look at this' and needs no new state. Per CLAUDE.md, a finding that survives blocks closing the work; it does not get waved through.\n\nScope to the implement workflow first. Routing to tdd/bootstrap/feasibility is a later decision -- feasibility in particular produces a document rather than a diff, so 'review the diff' may not even apply.","acceptance_criteria":"An implement task with a clean gate and no confirmed findings opens a PR as it does today; one with a surviving confirmed finding parks as waiting_human with findings recorded and opens no PR; the stage is observable in the task's running(workflow:stage) status; retry after operator action re-runs the review.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:13Z","external_ref":"https://github.com/samcharles93/archie-core/issues/549","dependencies":[{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:54Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019.2","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.4","depends_on_id":"archie-core-h019.3","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":3,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-h019.1","title":"Design: adversarial self-review stage (one-page decision in docs/prds/)","description":"No settled design exists for this in docs/architecture/, so under the scope-discipline rule merged as PR #533 the design comes first -- briefly and decisively -- and is not finished until a diff follows it.\n\nDecide and record, in one page under docs/prds/: where the reviewer runs (reuse the per-task container pool, or a separate short-lived container); what it is given (diff plus originating issue, and explicitly what it must NOT be given); the findings contract and who owns the type; what a surviving finding does to the task lifecycle; and how the reviewer's model/effort is configured.\n\nConstraints from the repo that the design must respect: dependency direction is cmd -\u003e app -\u003e {domain, infrastructure}, so the reviewer contract belongs to the workflow domain and the execution to infrastructure/app. Agent execution is a data boundary. The model never runs git. Prefer environmental enforcement over prompt rules -- 'the reviewer cannot see the implementation' must be a property of how it is launched, not an instruction in its prompt.\n\nDo not write an architecture document, migration plan or review campaign. One page that decides.","acceptance_criteria":"A one-page decision exists under docs/prds/ answering: reviewer isolation mechanism, inputs and forbidden inputs, findings contract owner, lifecycle effect of a surviving finding, and model/effort configuration. It decides rather than surveys, and cites the packages it will touch.","status":"open","priority":1,"issue_type":"decision","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:39Z","created_by":"Sam Catlow","updated_at":"2026-08-22T10:20:56Z","started_at":"2026-08-22T09:30:19Z","external_ref":"https://github.com/samcharles93/archie-core/issues/550","metadata":null,"dependencies":[{"issue_id":"archie-core-h019.1","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":5,"comment_count":0} -{"_type":"issue","id":"archie-core-h019.2","title":"Findings contract: a structured review result the workflow can act on","description":"The reviewer's output must be data the workflow can branch on, not prose a human has to read to find out whether the PR is safe to open. Prose is what makes a review advisory; structure is what lets a finding block.\n\nDefine the finding type in the workflow domain (the domain declares the contract it needs; it never names who implements it). At minimum a finding carries: file and line, a one-sentence defect, a concrete failure scenario (inputs/state -\u003e wrong output), a verdict distinguishing CONFIRMED from PLAUSIBLE, and a disposition once acted on (fixed / skipped / no_change_needed).\n\nThe CONFIRMED/PLAUSIBLE split is load-bearing and must not be collapsed into a single boolean: only confirmed findings may block, or the feature degrades into crying wolf and the operator learns to skim past it.","acceptance_criteria":"A finding type exists in internal/domain/workflow with file, line, summary, failure scenario, verdict and disposition; it is serialisable across the agent-execution data boundary; a review result with zero findings is representable and distinct from a review that did not run.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:39Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:14Z","external_ref":"https://github.com/samcharles93/archie-core/issues/551","dependencies":[{"issue_id":"archie-core-h019.2","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:24Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.2","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:39Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":3,"comment_count":0} +{"_type":"issue","id":"archie-core-h019.2","title":"Findings contract: a structured review result the workflow can act on","description":"The reviewer's output must be data the workflow can branch on, not prose a human has to read to find out whether the PR is safe to open. Prose is what makes a review advisory; structure is what lets a finding block.\n\nDefine the finding type in the workflow domain (the domain declares the contract it needs; it never names who implements it). At minimum a finding carries: file and line, a one-sentence defect, a concrete failure scenario (inputs/state -\u003e wrong output), a verdict distinguishing CONFIRMED from PLAUSIBLE, and a disposition once acted on (fixed / skipped / no_change_needed).\n\nThe CONFIRMED/PLAUSIBLE split is load-bearing and must not be collapsed into a single boolean: only confirmed findings may block, or the feature degrades into crying wolf and the operator learns to skim past it.","acceptance_criteria":"A finding type exists in internal/domain/workflow with file, line, summary, failure scenario, verdict and disposition; it is serialisable across the agent-execution data boundary; a review result with zero findings is representable and distinct from a review that did not run.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:39Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:14Z","external_ref":"https://github.com/samcharles93/archie-core/issues/551","dependencies":[{"issue_id":"archie-core-h019.2","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:02:39Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.2","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:24Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":3,"comment_count":0} {"_type":"issue","id":"archie-core-h019","title":"[EPIC] Adversarial self-review before archie opens a PR","description":"Archie enforces gates on every PR it opens, but it does not run the adversarial review CLAUDE.md makes mandatory for every change in this repo: a fresh reviewer that did not write the code, told to assume every line is wrong, working a defined checklist, where a surviving finding blocks the work. It is the one discipline the project requires of its contributors and exempts itself from.\n\nWhy it matters, with evidence rather than assertion: on 2026-08-20/21 the update-verification change (PR #530) passed task check at every checkpoint -- exit 0, golangci-lint 0 issues, gofumpt clean -- and three adversarial passes still found six real defects, two of them blocking. A 'dev' version placeholder would have reported healthy updates as failures, and an 'unknown' install claim was still being worded as confirmed success. The gates were green throughout and would have stayed green. This is CLAUDE.md's own recorded lesson: tests catch behaviour that breaks, not behaviour that quietly starts meaning something else.\n\nArchie is unusually well placed to do this. It already runs each task in an isolated container and worktree, so it can spawn a reviewer that genuinely never saw the implementation -- not a second opinion from the same context pretending to be fresh, which is the failure mode of every single-context tool. The isolation boundary built for safety is what makes honest self-review possible.\n\nWhat the operator gets: a PR that arrives with a findings section -- what was checked, what was found, what was fixed, what survived. A surviving finding parks the task as waiting_human instead of opening a PR that looks ready and is not. Review shifts from hunting for bugs to adjudicating findings.\n\nThe risk that kills the feature is a reviewer that cries wolf. Findings must be adversarially confirmed before they surface, and the reviewer must be able to report zero findings on properties it checked and cleared. Calibration is the feature, not the finding count.","acceptance_criteria":"An implement-workflow task runs an adversarial review after gates pass and before the PR is opened; the reviewer provably cannot see the implementer's context; a surviving confirmed finding blocks PR creation and parks the task; findings and their disposition are visible on the PR and the dashboard.","status":"open","priority":1,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-21T13:02:17Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:15Z","external_ref":"https://github.com/samcharles93/archie-core/issues/552","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-3jag","title":"Chat/task agent persona is overconfident: presents unverified claims as verified, fabricates infrastructure details","description":"The chat assistant (archie, running via the Telegram/webui gateway) repeatedly\npresents unverified or fabricated information with false confidence, and only\nretracts it when directly challenged. This is a persona/system-prompt problem,\nnot a model quality problem -- reproduced on more than one underlying model.\n\nTwo concrete instances from a live Telegram transcript (2026-08-15):\n\n1. Fabricated infrastructure: asked \"are logs going anywhere else?\", the\n assistant invented an entire second log-shipping subsystem (\"Hermes\n gateway\") with specific fake file paths\n (/home/sam/.hermes/profiles/local-agent/logs/) that do not exist anywhere\n in archie-core, and stated it as verified fact (\"I confirmed the web UI\n token and task lifecycle messages are there\"). When challenged (\"Is there\n something in the codebase which tells you you're Hermes?\"), it admitted\n the paths were invented and carried forward from unrelated, unverified\n context.\n\n2. Overclaimed verification: asked \"Why did that last task fail?\", the\n assistant answered with a bulleted list explicitly labelled \"Verified\n details\" (attempt count, iteration count, token count, exact model name).\n When pressed with \"You checked it?\", it admitted the model name and\n change count were \"overstated\" -- i.e. it labelled unverified specifics as\n verified the first time, and only corrected itself under direct\n challenge.\n\nThe common shape: confident, specific claims presented as fact/verified\nfirst; a walked-back, hedged correction only appears after the user\nexplicitly challenges it. This erodes trust in every claim the assistant\nmakes about system state, since the default posture is confident assertion\nrather than \"I have/haven't actually checked this.\"","notes":"Root cause is believed to be the persona/system-prompt layer (internal/gateway/ BuildSystemPrompt + persona templates), not model selection -- reproduced across models per the reporter. Needs a system-prompt-level fix enforcing 'never label something verified unless it was actually checked this turn' and 'never state unconfirmed system details as fact.' Sam is reviewing the persona/prompt separately; this bead tracks the finding so it isn't lost.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-15T02:25:37Z","created_by":"Sam Catlow","updated_at":"2026-08-20T12:55:18Z","started_at":"2026-08-20T12:50:34Z","closed_at":"2026-08-20T12:55:18Z","close_reason":"Fixed in fix/persona-overconfidence (fba80e3): reworded core rule 1 and added rules 8/9 to the chat agent system prompt enforcing this-turn verification before labelling claims verified/confirmed.","external_ref":"https://github.com/samcharles93/archie-core/issues/524","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786756970855-1-72466b33","title":"worktree: retry fails on a dirty worktree left by an interrupted prior attempt","description":"## Problem\n\n`Manager.refresh` (`internal/worktree/worktree.go`) checks out the task's branch without `Force` before hard-resetting to base. If a prior attempt left uncommitted local changes in the worktree — a killed container, or a stage that edits files before ever reaching a commit — go-git's default checkout (`MergeReset` mode) can refuse to reconcile them, even when HEAD is already on the correct branch and the target commit hasn't moved.\n\nThat failure was then compounded by the fallback: the code assumed any checkout failure meant \"the branch doesn't exist yet in this worktree\" and retried with `Create: true`, which fails differently (and much more confusingly) since the branch *does* exist:\n\n```\ncheckout branch feat/1000000000000000-fix-github-issue-514-telegram-response-formatting-concatenat:\na branch named \"refs/heads/feat/1000000000000000-fix-github-issue-514-telegram-response-formatting-concatenat\" already exists\n```\n\n## Evidence\n\nReproduced directly against the actual broken worktree on a live deployment: `git status` showed a modified tracked file and an untracked file left over from an interrupted attempt, HEAD already correctly on the task branch. Retrying the task hit exactly the error above and parked again with the same unhelpful message, on every retry, since nothing about the state changes between attempts.\n\n## Fix\n\nAdd `Force: true` to both checkout attempts in `refresh`. This is safe unconditionally: `refresh` hard-resets to the base commit a few lines later regardless of what checkout leaves behind, so there is no scenario where discarding the working tree's local state here is wrong.\n\nRegression test: `TestPrepareRecoversFromADirtyWorktreeOnRetry` reproduces the exact production error (modified tracked file + untracked file, branch already checked out) and confirms retry now succeeds and correctly restores the tracked file to its base content.","status":"closed","priority":1,"issue_type":"bug","created_at":"2026-08-15T01:22:16Z","updated_at":"2026-08-15T01:22:38Z","closed_at":"2026-08-15T01:22:39Z","external_ref":"https://github.com/samcharles93/archie-core/issues/523","source_system":"github:https://github.com/samcharles93/archie-core/issues/523:523","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-1786751948782-3-837a8fd0","title":"Embed install-type at build time; verify updates against actual running state, not installer exit code","description":"## Problem\n\n`/update` and `/version` currently trust whatever the operator's external `update_check_command`/`update_install_command` reports (`internal/releaseupdate/command.go`). Nothing verifies that the reported version actually matches what's running. This already produced a false success: `/update` reported `archied`/`archie-agent` both updated to `v1.9.0` (the release containing the #468 fix), and a task run immediately after still hit the exact pre-fix failure — see #468 and #511 for the full evidence trail.\n\nSeparately, Archie ships in multiple install shapes (systemd-managed binary, Docker container via compose, possibly others). Nothing today tells the update mechanism which shape a given running component actually is, so a wrong-path update (e.g. attempting a container-style update against a systemd-managed process) is possible and would currently fail silently or claim success incorrectly.\n\n## Design (researched against prior art: restic, Tailscale, Docker/kubectl version output)\n\n**1. Stamp install type at build/release time — never probe for it at runtime.**\nAdd a small cross-cutting `internal/installtype` package: `var channel = \"unknown\"`, read via `Channel() string`. Stamp the real value per release artifact with `-ldflags \"-X .../installtype.channel=systemd\"` (native binary build) or `=container` (Docker image build) — one line per build target in the existing release pipeline, since `archied` and `archie-agent` are already built as separate artifacts for their respective channels.\n\nPrecedent: restic strips its `self-update` subcommand entirely via a build tag for distro-packaged builds — the wrong path isn't just mislabeled, it's absent. Tailscale, despite runtime-detecting almost everything else, treats Docker as an unconditional \"no self-update, manage via image tag\" — even the most sophisticated self-updater in this survey doesn't try to be clever about containers.\n\n**2. Fail closed, never guess.** The `/update` dispatcher must refuse to proceed if `installtype.Channel() == \"unknown\"` or doesn't match what the install/check command expects, with a clear operator-facing message. No fallback path.\n\n**3. Verify after, don't trust the exit code.** After `Installer.Install` returns success, re-check the *actual* running reference (binary path + hash, or container image digest) against the target version, and only then report success to the user. This is the concrete fix for the false-success bug. Tailscale's `confirm()` does the equivalent version comparison before/after in its own updater.\n\n**4. Extend `releaseupdate.Component`** (`internal/releaseupdate/service.go`) with `InstallType string` and `Reference string` fields (e.g. `\"container\"`, `\"ghcr.io/samcharles93/archie-agent:1.9.0@sha256:...\"`), populated by each component: `archied` reads its own compiled-in value; `archie-agent` reports its own the same way (already has a channel back to the daemon over NATS for logs — extend for a status/version response); third-party dependencies Archie doesn't build (e.g. NATS) can't self-report, so their `InstallType`/`Reference` comes from the deployment profile (`deployments/*.toml`) rather than detection.\n\n**5. Surface per-component status** on the Configuration page and in `/version`, structured as one block per component: `{install_type, running_version, reference, latest_available, status}`, where `status` is an enum (`ok` / `update_available` / `drift` / `unknown`) — not a bare color, with the actual comparison (e.g. running digest vs. latest digest) visible on hover/expand. Modeled on `docker version`'s Client/Server nested-block convention, which `kubectl version` independently converged on too.\n\n## Relates to\n\n- #468 (the fix this update-verification gap let slip through undetected)\n- #511 (update command UX — this issue is the underlying mechanism that makes accurate progress/success reporting possible; #511 shouldn't report a nicer-looking version of a still-unverified claim)","notes":"2026-08-21: design point 3 committed as c25799e on branch fix/522-verify-update-took-effect (not pushed).\n\nReport.Verify(running) partitions every claimed component into Confirmed/Drift/Unverified. Ground truth is the relaying process's own compiled-in gatewayVersion. Telegram now has three wordings: confirmed, 'could not confirm which version is actually running', and 'Update did NOT take effect' with per-component detail. Placeholders 'unknown' (watchdog default) and 'dev' (unstamped build) are unverifiable, never versions. Agent stays Unverified by design and is named as unchecked in the success message.\n\nGate: task check exit 0, golangci-lint 0 issues, gofumpt clean. Three adversarial review passes; all findings fixed. Regression tests proven to fail against pre-fix code; every new guard mutation-tested.\n\nSTILL OPEN on this issue:\n- point 4: Component.InstallType + Reference fields on releaseupdate.Component\n- point 5: per-component status block {install_type, running_version, reference, latest_available, status} on the Configuration page and in /version\n\nSplit out: archie-core-nln7 (dashboard updates get no phase-2 report, so the new verification never runs for them).\n--notes=2026-08-21: design point 3 MERGED to main as 3fb4857 (PR #530, squash of c25799e). Verified merged main passes task check exit 0.\n\nReport.Verify(running) partitions each claimed component into Confirmed/Drift/Unverified against the relaying process's own compiled-in gatewayVersion. Telegram has three wordings: confirmed, 'could not confirm which version is actually running', and 'Update did NOT take effect' with per-component detail. 'unknown' (watchdog default) and 'dev' (unstamped build) are unverifiable, never versions. Agent is Unverified by design and named as unchecked in the success message.\n\nSTILL OPEN, this issue stays in_progress:\n- point 4: Component.InstallType + Reference fields on releaseupdate.Component\n- point 5: per-component status block {install_type, running_version, reference, latest_available, status} on the Configuration page and in /version\n\nDependency note: archie-core-nln7 no longer depends on this issue. Its real prerequisite was the verification machinery, which landed in 3fb4857; it does not need points 4 or 5, so the blocking edge was removed to stop it sitting out of bd ready for no reason.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","created_at":"2026-08-14T23:55:31Z","updated_at":"2026-08-21T11:55:37Z","started_at":"2026-08-15T00:03:05Z","external_ref":"https://github.com/samcharles93/archie-core/issues/522","source_system":"github:https://github.com/samcharles93/archie-core/issues/522:522","metadata":null,"labels":["enhancement","webui"],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-1786751948782-3-837a8fd0","title":"Embed install-type at build time; verify updates against actual running state, not installer exit code","description":"## Problem\n\n`/update` and `/version` currently trust whatever the operator's external `update_check_command`/`update_install_command` reports (`internal/releaseupdate/command.go`). Nothing verifies that the reported version actually matches what's running. This already produced a false success: `/update` reported `archied`/`archie-agent` both updated to `v1.9.0` (the release containing the #468 fix), and a task run immediately after still hit the exact pre-fix failure — see #468 and #511 for the full evidence trail.\n\nSeparately, Archie ships in multiple install shapes (systemd-managed binary, Docker container via compose, possibly others). Nothing today tells the update mechanism which shape a given running component actually is, so a wrong-path update (e.g. attempting a container-style update against a systemd-managed process) is possible and would currently fail silently or claim success incorrectly.\n\n## Design (researched against prior art: restic, Tailscale, Docker/kubectl version output)\n\n**1. Stamp install type at build/release time — never probe for it at runtime.**\nAdd a small cross-cutting `internal/installtype` package: `var channel = \"unknown\"`, read via `Channel() string`. Stamp the real value per release artifact with `-ldflags \"-X .../installtype.channel=systemd\"` (native binary build) or `=container` (Docker image build) — one line per build target in the existing release pipeline, since `archied` and `archie-agent` are already built as separate artifacts for their respective channels.\n\nPrecedent: restic strips its `self-update` subcommand entirely via a build tag for distro-packaged builds — the wrong path isn't just mislabeled, it's absent. Tailscale, despite runtime-detecting almost everything else, treats Docker as an unconditional \"no self-update, manage via image tag\" — even the most sophisticated self-updater in this survey doesn't try to be clever about containers.\n\n**2. Fail closed, never guess.** The `/update` dispatcher must refuse to proceed if `installtype.Channel() == \"unknown\"` or doesn't match what the install/check command expects, with a clear operator-facing message. No fallback path.\n\n**3. Verify after, don't trust the exit code.** After `Installer.Install` returns success, re-check the *actual* running reference (binary path + hash, or container image digest) against the target version, and only then report success to the user. This is the concrete fix for the false-success bug. Tailscale's `confirm()` does the equivalent version comparison before/after in its own updater.\n\n**4. Extend `releaseupdate.Component`** (`internal/releaseupdate/service.go`) with `InstallType string` and `Reference string` fields (e.g. `\"container\"`, `\"ghcr.io/samcharles93/archie-agent:1.9.0@sha256:...\"`), populated by each component: `archied` reads its own compiled-in value; `archie-agent` reports its own the same way (already has a channel back to the daemon over NATS for logs — extend for a status/version response); third-party dependencies Archie doesn't build (e.g. NATS) can't self-report, so their `InstallType`/`Reference` comes from the deployment profile (`deployments/*.toml`) rather than detection.\n\n**5. Surface per-component status** on the Configuration page and in `/version`, structured as one block per component: `{install_type, running_version, reference, latest_available, status}`, where `status` is an enum (`ok` / `update_available` / `drift` / `unknown`) — not a bare color, with the actual comparison (e.g. running digest vs. latest digest) visible on hover/expand. Modeled on `docker version`'s Client/Server nested-block convention, which `kubectl version` independently converged on too.\n\n## Relates to\n\n- #468 (the fix this update-verification gap let slip through undetected)\n- #511 (update command UX — this issue is the underlying mechanism that makes accurate progress/success reporting possible; #511 shouldn't report a nicer-looking version of a still-unverified claim)","notes":"2026-08-21: design point 3 committed as c25799e on branch fix/522-verify-update-took-effect (not pushed).\n\nReport.Verify(running) partitions every claimed component into Confirmed/Drift/Unverified. Ground truth is the relaying process's own compiled-in gatewayVersion. Telegram now has three wordings: confirmed, 'could not confirm which version is actually running', and 'Update did NOT take effect' with per-component detail. Placeholders 'unknown' (watchdog default) and 'dev' (unstamped build) are unverifiable, never versions. Agent stays Unverified by design and is named as unchecked in the success message.\n\nGate: task check exit 0, golangci-lint 0 issues, gofumpt clean. Three adversarial review passes; all findings fixed. Regression tests proven to fail against pre-fix code; every new guard mutation-tested.\n\nSTILL OPEN on this issue:\n- point 4: Component.InstallType + Reference fields on releaseupdate.Component\n- point 5: per-component status block {install_type, running_version, reference, latest_available, status} on the Configuration page and in /version\n\nSplit out: archie-core-nln7 (dashboard updates get no phase-2 report, so the new verification never runs for them).\n--notes=2026-08-21: design point 3 MERGED to main as 3fb4857 (PR #530, squash of c25799e). Verified merged main passes task check exit 0.\n\nReport.Verify(running) partitions each claimed component into Confirmed/Drift/Unverified against the relaying process's own compiled-in gatewayVersion. Telegram has three wordings: confirmed, 'could not confirm which version is actually running', and 'Update did NOT take effect' with per-component detail. 'unknown' (watchdog default) and 'dev' (unstamped build) are unverifiable, never versions. Agent is Unverified by design and named as unchecked in the success message.\n\nSTILL OPEN, this issue stays in_progress:\n- point 4: Component.InstallType + Reference fields on releaseupdate.Component\n- point 5: per-component status block {install_type, running_version, reference, latest_available, status} on the Configuration page and in /version\n\nDependency note: archie-core-nln7 no longer depends on this issue. Its real prerequisite was the verification machinery, which landed in 3fb4857; it does not need points 4 or 5, so the blocking edge was removed to stop it sitting out of bd ready for no reason.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","created_at":"2026-08-14T23:55:31Z","updated_at":"2026-08-21T11:55:37Z","started_at":"2026-08-15T00:03:05Z","lease_expires_at":"2026-08-15T00:08:05Z","heartbeat_at":"2026-08-15T00:03:05Z","external_ref":"https://github.com/samcharles93/archie-core/issues/522","source_system":"github:https://github.com/samcharles93/archie-core/issues/522:522","metadata":null,"labels":["enhancement","webui"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786749700606-6-bf6aa32d","title":"agent containers: push fails with 'permission denied' reading .git/objects, distinct from #468","description":"## Problem\n\nTask `#445` (daemon: label dispatch trigger) parked at the `commit-push` stage with:\n\n```\npush fix/445-daemon-label-dispatch-trigger-with-empty-label-matches-every:\ngetting wanted object 295b030cc6face20f8a377e94076922c460576c1:\nopenat objects/29/5b030cc6face20f8a377e94076922c460576c1: permission denied\n```\n\nThis is a different failure mode than #468 (git's \"dubious ownership\" ownership *check*, resolved by `safe.directory`). Here git gets *past* whatever ownership check applies and fails on an actual filesystem permission bit when reading a loose object from the bind-mounted worktree's `.git/objects/`.\n\n## Why this is probably not fixed by #468\n\n`safe.directory` only tells git to trust a repo it doesn't own — it does not change the actual read/write permission bits on the files. If the object file was written by a process running as a different UID than the archie-agent container's process (e.g. daemon-side `worktree` package operations running as the host user, vs. the container process), a straightforward `openat ... permission denied` on a specific loose object is consistent with a UID mismatch on the bind mount that `safe.directory` does nothing for.\n\nNeither `Dockerfile` nor `docker-compose.yml` sets a `USER`/`user:` for the agent image, so the container should be running as root by default — worth confirming whether the deployment actually runs it as root (Docker `userns-remap` would explain root-inside behaving as an unprivileged UID on the host, which would produce exactly this symptom).\n\n## Ask\n\nConfirm the UID the archie-agent process actually runs as versus the UID that owns files under the worktree's `.git/objects/` on the host, and fix the mismatch (consistent UID, or `chown`/`chmod` the bind mount appropriately before handing it to the container).","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","created_at":"2026-08-14T23:18:58Z","updated_at":"2026-08-17T22:40:02Z","started_at":"2026-08-17T22:27:08Z","closed_at":"2026-08-17T22:40:02Z","close_reason":"Confirmed root cause: agent containers run as root (no USER in Dockerfile, no userns-remap anywhere in docker-compose.yml/internal/container/pool.go), so a commit the agent writes to the bind-mounted worktree lands owned by UID 0 on the host. The daemon later reads those same loose objects to push, running as its own non-root host user -- 'openat objects/../..: permission denied'. Fixed: containerEnv() now passes the daemon's own os.Getuid()/os.Getgid() as WORKTREE_UID/WORKTREE_GID; hybridTrees.Push (the single choke point before the push RPC) chowns the worktree back to that owner first. Adversarial review (fresh subagent) found one real bug in the first pass -- chownTree used os.Chown, which follows symlinks and fails on a legitimately-tracked-but-dangling symlink, which would have aborted a push that would otherwise have succeeded (worse than the original bug). Fixed with os.Lchown plus a regression test proving it against a dangling symlink. Full task check clean; all other review findings (full-tree walk cost, minor test-hygiene notes) were judged non-blocking by the reviewer.","external_ref":"https://github.com/samcharles93/archie-core/issues/520","source_system":"github:https://github.com/samcharles93/archie-core/issues/520:520","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786749700580-5-e3878224","title":"/stop does not kill an in-flight archie-agent NATS worker or its container — task keeps running","description":"## This is the most important finding from today's investigation.\n\n`/stop` is meant to be an emergency brake. It is not one: it reported success (\"🛑 Stopped task(s) #5\") while the task kept running, kept burning tokens, and kept flooding the logs with errors for at least the next 20+ minutes.\n\n## Root cause\n\n`/stop` → `Gateway.stopRunningTasks` → `router.Controller.StopRunning` (`internal/gateway/tasks.go:227`) → `Daemon.CancelRunningTasks` (`internal/daemon/running.go:114`) → `runningTasks.stopAll`, which cancels a `context.CancelFunc` registered in an in-process map (`internal/daemon/running.go:36-52`, populated by `Daemon.process` at `internal/daemon/daemon.go:800`).\n\nThat context governs only `archied`'s own orchestration goroutine for the task. In the NATS-dispatched execution model (`internal/app/agentworker`), the actual work happens in a **separate process** — the archie-agent worker — that pulled a stage request off NATS and is running it inside `handleSingleStageRequest` / `runMainLoopWithDelay` (`internal/app/agentworker/stage_loop.go`), driven by its own top-level context that has no connection whatsoever to the daemon's per-task cancel registry. Cancelling the daemon-side context does not reach it. There is currently no signal, subject, or mechanism by which `archied` can tell an already-dispatched archie-agent worker to stop.\n\nThis matches what was observed live: task `#1000000000000001` was reported stopped, remained `Working` in the dashboard 20+ minutes later, and its log showed 996 `handle failed err={}` entries in the minutes after the stop request — the worker was still very much alive and looping.\n\n## Expected behavior\n\n`/stop` (and task Cancel generally) should be a hard kill for both halves of the execution:\n1. `archied`'s own orchestration (already works, via the existing context cancellation).\n2. The archie-agent worker actually doing the work for that task.\n\n## Suggested fix\n\nContainers are per-task and Docker-managed by the daemon regardless of deployment shape (`internal/container/pool.go`). The most reliable \"dead in its tracks\" mechanism is for `/stop`/`Cancel` to kill the task's container directly via the Docker client the pool already holds, rather than relying on context propagation across a process boundary that current code has no way to cross. A NATS-side alternative (publish a cancellation event on a per-task subject that `stage_loop.go`'s loop checks between fetch and ack, or have the daemon revoke the task lease so the worker's next `Ack`/`Respond` fails) is a secondary/defense-in-depth improvement, but killing the container is what actually guarantees the work stops.\n\n## Related\n\nThe redelivery-storm behavior after a stop/nak (#517) and the swallowed error detail (#516) both make this worse in practice — an operator watching the logs after `/stop` sees hundreds of contentless error lines with no way to tell whether the stop is taking effect.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","created_at":"2026-08-14T23:18:46Z","updated_at":"2026-08-17T22:38:57Z","started_at":"2026-08-17T14:31:11Z","closed_at":"2026-08-17T22:38:57Z","close_reason":"Root cause found after Sam confirmed live testing still showed the task's in-flight tool calls/generation continuing tens of seconds to ~2 minutes after /stop reported success. internal/container/pool.go Release() always slept the configured GracePeriod and always used Docker's default ~10s graceful SIGTERM-then-SIGKILL timeout, even when the release was happening because the task's context had just been cancelled by /stop -- so a cancelled task's container (and the in-flight work inside it) could sit doing nothing for up to GracePeriod+~10s before actually dying. Fixed with a new releaseDecision(ctx, grace) helper: a cancelled ctx now skips the grace sleep entirely and requests an immediate SIGKILL (ContainerStopOptions.Timeout=0) instead of a graceful wait; a live ctx (normal completion) keeps the original behaviour byte-for-byte. Red-then-green with 3 new unit tests (internal/container/pool_test.go), task check clean, adversarially reviewed by a fresh subagent with zero blocking findings -- context-chain trace, Docker Timeout=0 semantics, and struct-equivalence for the unchanged path were all independently verified against the moby client source.","external_ref":"https://github.com/samcharles93/archie-core/issues/519","source_system":"github:https://github.com/samcharles93/archie-core/issues/519:519","metadata":null,"labels":["bug","gateway"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786749700549-4-d2331d9d","title":"dashboard: task timeline shows 'No events yet' for every task regardless of status or stage","description":"## Problem\n\nEvery task's expanded timeline on `/tasks` reads \"No events yet — This task has not recorded any transitions,\" regardless of status or how far the task progressed. Confirmed live across a `Working` task and multiple `Parked` tasks at different stages:\n\n- `#1000000000000001` — Working, implement/baseline, 20+ minutes in\n- `#1000000000000000` — Parked at implement/baseline (go build/VCS-stamp failure)\n- `#445` — Parked at tdd/commit-push (git push permission error)\n\nAll three show the identical empty-timeline message. This isn't isolated to the currently-stuck task — the timeline feature appears non-functional for the whole deployment, which means the dashboard's per-task \"what actually happened\" view (the thing an operator reaches for first when a task needs attention) carries no information at all.\n\n## Impact\n\nCombined with the logging defect in #516 (errors serialize to `{}`), this leaves an operator with almost no way to diagnose a stuck or parked task from the dashboard — no timeline, and the log detail that does exist is empty.\n\n## Ask\n\nFind where task transition events are supposed to be written (`store.Transition`, `d.emit(events.Event{...})`, etc.) versus what the timeline UI/API actually queries, and reconcile — either events aren't being persisted for these tasks, or the timeline endpoint is querying the wrong key/table.","status":"closed","priority":1,"issue_type":"bug","created_at":"2026-08-14T23:17:17Z","updated_at":"2026-08-15T00:35:51Z","started_at":"2026-08-15T00:03:04Z","closed_at":"2026-08-15T00:35:51Z","external_ref":"https://github.com/samcharles93/archie-core/issues/518","source_system":"github:https://github.com/samcharles93/archie-core/issues/518:518","metadata":null,"labels":["bug","webui"],"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -59,8 +59,8 @@ {"_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.","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-14T15:07:36Z","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-1786751948782-3-837a8fd0.2","title":"Add InstallType/Reference fields to releaseupdate.Component, populate from daemon/agent/deployment profile","description":"Part 2/3 of point 4 in archie-core-1786751948782-3-837a8fd0's design. releaseupdate.Component (internal/releaseupdate/service.go:35-41) has ID/Label/Installed/Available/Changelog but no InstallType or Reference fields. Add both, and populate: archied reads its own compiled-in installtype.Type(); archie-agent reports its own over the NATS status round-trip (depends on the sibling issue that adds that round-trip); third-party dependencies Archie doesn't build (e.g. NATS) can't self-report, so their InstallType/Reference should come from the deployment profile (deployments/*.toml) rather than detection -- add the relevant fields there. Reference is something like 'container' + 'ghcr.io/samcharles93/archie-agent:1.9.0@sha256:...', not just a bare install-type string.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-23T13:06:16Z","created_by":"Sam Catlow","updated_at":"2026-08-23T13:22:37Z","started_at":"2026-08-23T13:22:37Z","labels":["enhancement","webui"],"dependencies":[{"issue_id":"archie-core-1786751948782-3-837a8fd0.2","depends_on_id":"archie-core-1786751948782-3-837a8fd0.1","type":"blocks","created_at":"2026-08-23T23:06:19Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786751948782-3-837a8fd0.2","depends_on_id":"archie-core-1786751948782-3-837a8fd0","type":"parent-child","created_at":"2026-08-23T23:06:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-1786751948782-3-837a8fd0.3","title":"Surface per-component update status on Configuration page and /version","description":"Part 3/3, point 5 of archie-core-1786751948782-3-837a8fd0's design. Depends on the InstallType/Reference issue landing first -- there's nothing to surface otherwise. Add a /version endpoint and a per-component block on the Configuration page (internal/webui/api_config.go, ui/src/settings/), structured as {install_type, running_version, reference, latest_available, status} per component, where status is an enum (ok / update_available / drift / unknown) rather than a bare color. The actual comparison basis (e.g. running digest vs latest digest) should be visible on hover/expand, modeled on docker version's Client/Server nested-block convention per the original design doc.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-23T13:06:16Z","created_by":"Sam Catlow","updated_at":"2026-08-23T13:06:16Z","labels":["enhancement","webui"],"dependencies":[{"issue_id":"archie-core-1786751948782-3-837a8fd0.3","depends_on_id":"archie-core-1786751948782-3-837a8fd0","type":"parent-child","created_at":"2026-08-23T23:06:16Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786751948782-3-837a8fd0.3","depends_on_id":"archie-core-1786751948782-3-837a8fd0.2","type":"blocks","created_at":"2026-08-23T23:06:20Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-1786751948782-3-837a8fd0.2","title":"Add InstallType/Reference fields to releaseupdate.Component, populate from daemon/agent/deployment profile","description":"Part 2/3 of point 4 in archie-core-1786751948782-3-837a8fd0's design. releaseupdate.Component (internal/releaseupdate/service.go:35-41) has ID/Label/Installed/Available/Changelog but no InstallType or Reference fields. Add both, and populate: archied reads its own compiled-in installtype.Type(); archie-agent reports its own over the NATS status round-trip (depends on the sibling issue that adds that round-trip); third-party dependencies Archie doesn't build (e.g. NATS) can't self-report, so their InstallType/Reference should come from the deployment profile (deployments/*.toml) rather than detection -- add the relevant fields there. Reference is something like 'container' + 'ghcr.io/samcharles93/archie-agent:1.9.0@sha256:...', not just a bare install-type string.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-23T13:06:16Z","created_by":"Sam Catlow","updated_at":"2026-08-23T13:28:53Z","started_at":"2026-08-23T13:22:37Z","closed_at":"2026-08-23T13:28:53Z","close_reason":"Fixed: Component gained InstallType/Reference, populated via Service.Enrich from installtype.Type() (daemon), observed AgentStatus (agent), and [nats] config (third-party). Adversarial review clean (one lint-consistency nit fixed: use config.NATSMode* constants instead of raw strings).","labels":["enhancement","webui"],"dependencies":[{"issue_id":"archie-core-1786751948782-3-837a8fd0.2","depends_on_id":"archie-core-1786751948782-3-837a8fd0","type":"parent-child","created_at":"2026-08-23T23:06:15Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786751948782-3-837a8fd0.2","depends_on_id":"archie-core-1786751948782-3-837a8fd0.1","type":"blocks","created_at":"2026-08-23T23:06:19Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-1786751948782-3-837a8fd0.3","title":"Surface per-component update status on Configuration page and /version","description":"Part 3/3, point 5 of archie-core-1786751948782-3-837a8fd0's design. Depends on the InstallType/Reference issue landing first -- there's nothing to surface otherwise. Add a /version endpoint and a per-component block on the Configuration page (internal/webui/api_config.go, ui/src/settings/), structured as {install_type, running_version, reference, latest_available, status} per component, where status is an enum (ok / update_available / drift / unknown) rather than a bare color. The actual comparison basis (e.g. running digest vs latest digest) should be visible on hover/expand, modeled on docker version's Client/Server nested-block convention per the original design doc.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-23T13:06:16Z","created_by":"Sam Catlow","updated_at":"2026-08-23T13:29:01Z","started_at":"2026-08-23T13:29:01Z","labels":["enhancement","webui"],"dependencies":[{"issue_id":"archie-core-1786751948782-3-837a8fd0.3","depends_on_id":"archie-core-1786751948782-3-837a8fd0","type":"parent-child","created_at":"2026-08-23T23:06:16Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786751948782-3-837a8fd0.3","depends_on_id":"archie-core-1786751948782-3-837a8fd0.2","type":"blocks","created_at":"2026-08-23T23:06:20Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786751948782-3-837a8fd0.1","title":"Stamp archie-agent's install type and add NATS status round-trip","description":"Part 1/3 of point 4 in archie-core-1786751948782-3-837a8fd0's design. archied's own build is stamped with internal/installtype via -ldflags (Taskfile.yml:65, Dockerfile.archied:48-49), but archie-agent's build has no equivalent stamp -- Dockerfile:14 and Taskfile.yml:170 (agent build target) pass no -X installtype flag. Without it, an agent worker has nothing to self-report even once the daemon asks. Also add the NATS-side status/version request the daemon can send a running agentworker to get its install type + running version back (agentworker already has a NATS channel for logs; extend it for a status response rather than inventing a new transport). This is the prerequisite for archie-core-1786751948782-3-837a8fd0 point 4's 'archie-agent reports its own the same way' clause.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-23T13:06:14Z","created_by":"Sam Catlow","updated_at":"2026-08-23T13:18:03Z","started_at":"2026-08-23T13:06:41Z","closed_at":"2026-08-23T13:18:03Z","close_reason":"Fixed: archie-agent's build is now stamped (installtype + agentworker.Version), and it reports both back to the daemon in every taskrun.Response. daemon.AgentStatus records the latest observation; daemonRunningVersions includes the agent component once one lands. Adversarial review clean (one nice-to-have comment added).","labels":["enhancement","webui"],"dependencies":[{"issue_id":"archie-core-1786751948782-3-837a8fd0.1","depends_on_id":"archie-core-1786751948782-3-837a8fd0","type":"parent-child","created_at":"2026-08-23T23:06:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-w35v","title":"Workflows page 'Start work' form inputs unstyled (white boxes in dark theme)","description":"The Start work card on the Workflows dashboard page (ui/src/workflows/workflows.js renderStartWork) creates raw \u003cinput\u003e/\u003cselect\u003e/\u003ctextarea\u003e elements with no CSS class, so they fall back to browser default styling -- white background, black text -- against the rest of the dark-themed app. Every other form control in the app (e.g. Configuration's .kv-input in ui/src/settings/config-row.js) uses a themed class. Fix: style these form controls to match the app theme, either by reusing an existing input class or adding scoped rules in ui/src/workflows/workflows.css.","status":"closed","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-23T12:22:59Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:38Z","closed_at":"2026-08-23T12:23:14Z","close_reason":"Fixed: themed .wf-form input/select/textarea in workflows.css to match the dark theme.","external_ref":"https://github.com/samcharles93/archie-core/issues/593","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1787489597262-23-f61d8b1b","title":"Docs: promote the shipped review stage into docs/architecture and reconcile CLAUDE.md","description":"Under the scope-discipline rule merged as PR #533, a design is promoted into docs/architecture/ only once it is built and true. This is that promotion, and it is deliberately a separate bead so it is not lost when the feature lands and attention moves on.\n\nDo three things once the stage ships:\n\n1. Promote the docs/prds/ decision into docs/architecture/, describing the review stage as it actually works -- not as designed. Cut anything a reader could learn from the code.\n2. Update ARCHITECTURE.md's task lifecycle: queued -\u003e running(workflow:stage) -\u003e pr_open -\u003e merged|rejected gains a review stage that can divert to waiting_human before pr_open. The current text does not mention it.\n3. Reconcile CLAUDE.md's Development Protocol. It currently tells a human or agent contributor to run the adversarial pass by hand. Once archied does this for the PRs it opens, that section needs to say which path applies to whom, or it will read as describing a manual step that is now automatic.\n\nCLAUDE.md's own rule: a comment or doc that contradicts its code is worse than none, because the next reader trusts it.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-23T12:22:29Z","updated_at":"2026-08-23T12:22:29Z","external_ref":"https://github.com/samcharles93/archie-core/issues/586","source_system":"github:https://github.com/samcharles93/archie-core/issues/586:586","metadata":null,"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -78,11 +78,11 @@ {"_type":"issue","id":"archie-core-1ysw.6","title":"Do not report push failure after successful publication","description":"Push publishes the remote ref before writing unused local upstream metadata, then returns local config errors as if publication failed.","acceptance_criteria":"A post-publication metadata failure cannot park the task as an unsuccessful push; tests verify the remote ref and returned result remain consistent.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-22T11:01:46Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:42Z","external_ref":"https://github.com/samcharles93/archie-core/issues/600","dependencies":[{"issue_id":"archie-core-1ysw.6","depends_on_id":"archie-core-1ysw","type":"parent-child","created_at":"2026-08-22T21:01:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1ysw.4","title":"Fail refresh when the configured base cannot resolve","description":"Prepared worktrees currently swallow every resolveBase error and report successful refresh against stale history.","acceptance_criteria":"Prepared-worktree refresh returns a contextual error for a missing, renamed, or invalid base; fresh and reused Prepare paths have consistent tests.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-22T11:01:45Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:43Z","started_at":"2026-08-22T11:52:19Z","closed_at":"2026-08-22T11:55:20Z","close_reason":"Retry refresh now removes all non-HEAD worktree content including ignored output while preserving .git, tracked symlinks, and gitlinks; missing bases fail closed.","external_ref":"https://github.com/samcharles93/archie-core/issues/601","dependencies":[{"issue_id":"archie-core-1ysw.4","depends_on_id":"archie-core-1ysw","type":"parent-child","created_at":"2026-08-22T21:01:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-j8b4","title":"Implement persistent session memory and plugin storage","description":"Replace the PRD section 3 placeholder in internal/storage/storage.go with the specified persistent storage behavior for session.jsonl, memory.jsonl, and plugins.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-22T10:32:31Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:44Z","started_at":"2026-08-22T10:32:37Z","closed_at":"2026-08-22T10:56:59Z","close_reason":"Implemented persistent session transcript, cross-session memory, and staged plugin storage","external_ref":"https://github.com/samcharles93/archie-core/issues/602","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-t2db.6","title":"Docs: document playbooks, bindings and the intake threat model","description":"Separate so it is not lost when the feature lands.\n\n- The playbook/binding model in docs/architecture/: what a binding is, where it is persisted, how matchers resolve, how versioning works.\n- The threat model, written down plainly: this is a public intake surface that can start agents. Record what protects it and what does not.\n- ARCHITECTURE.md task lifecycle: a task started by a playbook binding has a different provenance from a forge-issue task, and the lifecycle section should say so.\n- Operator docs: how to point an external app at archie and build a first playbook, end to end.\n\nCLAUDE.md's rule: a doc that contradicts its code is worse than none.","acceptance_criteria":"The binding model and threat model are documented in docs/architecture/; ARCHITECTURE.md covers playbook-originated tasks; there is an end-to-end operator walkthrough for building a first playbook.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:46Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:29Z","external_ref":"https://github.com/samcharles93/archie-core/issues/553","dependencies":[{"issue_id":"archie-core-t2db.6","depends_on_id":"archie-core-t2db.4","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.6","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-t2db.6","title":"Docs: document playbooks, bindings and the intake threat model","description":"Separate so it is not lost when the feature lands.\n\n- The playbook/binding model in docs/architecture/: what a binding is, where it is persisted, how matchers resolve, how versioning works.\n- The threat model, written down plainly: this is a public intake surface that can start agents. Record what protects it and what does not.\n- ARCHITECTURE.md task lifecycle: a task started by a playbook binding has a different provenance from a forge-issue task, and the lifecycle section should say so.\n- Operator docs: how to point an external app at archie and build a first playbook, end to end.\n\nCLAUDE.md's rule: a doc that contradicts its code is worse than none.","acceptance_criteria":"The binding model and threat model are documented in docs/architecture/; ARCHITECTURE.md covers playbook-originated tasks; there is an end-to-end operator walkthrough for building a first playbook.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-21T13:45:46Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:29Z","external_ref":"https://github.com/samcharles93/archie-core/issues/553","dependencies":[{"issue_id":"archie-core-t2db.6","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-08-21T23:45:45Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.6","depends_on_id":"archie-core-t2db.4","type":"blocks","created_at":"2026-08-21T23:45:53Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-7d5u.6","title":"Docs: reconcile plugins-and-extensions.md and ARCHITECTURE.md with the shipped event model","description":"Separate bead so it is not lost once the feature lands.\n\n1. docs/architecture/plugins-and-extensions.md is an APPROVED foundation dated 2026-07-28 and currently describes only the plugin framework. If the design bead concluded that extensions may react to events, this doc has to say how -- and if it concluded that generic untyped dispatch is allowed after all, this doc must be amended deliberately rather than contradicted by code.\n\n2. ARCHITECTURE.md describes work intake as polling. Once webhook intake ships, that is no longer the whole picture, and the task lifecycle section needs the new entry path.\n\n3. CLAUDE.md's per-package traps section should gain whatever trap this work creates -- HMAC verification, replay windows, the poll/webhook double-dispatch hazard. That section exists precisely for things an agent will otherwise break.\n\n4. config.example.toml needs the intake flag documented with its default, alongside poll_interval.\n\nCLAUDE.md's own rule: a doc that contradicts its code is worse than none, because the next reader trusts it.","acceptance_criteria":"plugins-and-extensions.md reflects the decided extension model; ARCHITECTURE.md documents webhook intake alongside polling; config.example.toml documents the intake flag and default; any new trap is recorded in CLAUDE.md.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-21T13:26:52Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:30Z","external_ref":"https://github.com/samcharles93/archie-core/issues/554","dependencies":[{"issue_id":"archie-core-7d5u.6","depends_on_id":"archie-core-7d5u","type":"parent-child","created_at":"2026-08-21T23:26:51Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-7d5u.6","depends_on_id":"archie-core-7d5u.4","type":"blocks","created_at":"2026-08-21T23:26:58Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-h019.5","title":"Calibration: confirm findings adversarially before surfacing them","description":"The risk that kills this feature is a reviewer that cries wolf. A findings list padded with speculation trains the operator to skim past it, and then the feature is worse than nothing because it consumes attention while lowering trust.\n\nBefore a finding is surfaced, it must be independently checked and marked CONFIRMED or PLAUSIBLE, with only CONFIRMED able to block. The reviewer must also be able to return zero findings, and to state which properties it checked and cleared -- a review that reports nothing is a valid and welcome result, and saying so explicitly is what distinguishes 'I checked and it is fine' from 'I did not look'.\n\nPrior art from the 2026-08-20/21 sessions on PR #530: three passes each separated confirmed from plausible, one explicitly listed properties it had verified clean, and the confirmed findings were reproduced by mutation before being trusted. That calibration is the feature, not the finding count.","acceptance_criteria":"Only CONFIRMED findings block PR creation; a zero-finding review is representable and reported as such; the reviewer records which properties it checked and cleared; padding with style nits is explicitly out of contract.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:30Z","external_ref":"https://github.com/samcharles93/archie-core/issues/555","dependencies":[{"issue_id":"archie-core-h019.5","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.5","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.5","depends_on_id":"archie-core-h019.2","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-h019.6","title":"Surface findings on the PR body and the dashboard","description":"The output has to land where the operator already looks, or the review is invisible work.\n\nOn the PR archie opens: a findings section stating what was checked, what was found, what was fixed, and what survived. A PR with zero findings should say the review ran and found nothing -- silence is indistinguishable from the review not running, which is the same unverified-claim problem the update-verification work (PR #530) was about.\n\nOn the dashboard and /api/tasks: a parked-for-findings task must show why, the same way a park reason is already surfaced today. An operator seeing waiting_human needs the findings without digging through logs.","acceptance_criteria":"PR body carries a findings section including the zero-finding case; a task parked on a surviving finding shows the findings as its park reason in the dashboard and /api/tasks; nothing requires reading task logs to learn why a PR was withheld.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:31Z","external_ref":"https://github.com/samcharles93/archie-core/issues/556","dependencies":[{"issue_id":"archie-core-h019.6","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.6","depends_on_id":"archie-core-h019.2","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.6","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-h019.7","title":"Docs: promote the shipped review stage into docs/architecture and reconcile CLAUDE.md","description":"Under the scope-discipline rule merged as PR #533, a design is promoted into docs/architecture/ only once it is built and true. This is that promotion, and it is deliberately a separate bead so it is not lost when the feature lands and attention moves on.\n\nDo three things once the stage ships:\n\n1. Promote the docs/prds/ decision into docs/architecture/, describing the review stage as it actually works -- not as designed. Cut anything a reader could learn from the code.\n2. Update ARCHITECTURE.md's task lifecycle: queued -\u003e running(workflow:stage) -\u003e pr_open -\u003e merged|rejected gains a review stage that can divert to waiting_human before pr_open. The current text does not mention it.\n3. Reconcile CLAUDE.md's Development Protocol. It currently tells a human or agent contributor to run the adversarial pass by hand. Once archied does this for the PRs it opens, that section needs to say which path applies to whom, or it will read as describing a manual step that is now automatic.\n\nCLAUDE.md's own rule: a comment or doc that contradicts its code is worse than none, because the next reader trusts it.","acceptance_criteria":"docs/architecture/ describes the shipped stage; ARCHITECTURE.md's lifecycle includes the review stage and the waiting_human diversion; CLAUDE.md distinguishes the manual contributor pass from archied's automated one; no doc still claims review is only manual.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:32Z","external_ref":"https://github.com/samcharles93/archie-core/issues/557","dependencies":[{"issue_id":"archie-core-h019.7","depends_on_id":"archie-core-h019.4","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.7","depends_on_id":"archie-core-h019.6","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.7","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-h019.6","title":"Surface findings on the PR body and the dashboard","description":"The output has to land where the operator already looks, or the review is invisible work.\n\nOn the PR archie opens: a findings section stating what was checked, what was found, what was fixed, and what survived. A PR with zero findings should say the review ran and found nothing -- silence is indistinguishable from the review not running, which is the same unverified-claim problem the update-verification work (PR #530) was about.\n\nOn the dashboard and /api/tasks: a parked-for-findings task must show why, the same way a park reason is already surfaced today. An operator seeing waiting_human needs the findings without digging through logs.","acceptance_criteria":"PR body carries a findings section including the zero-finding case; a task parked on a surviving finding shows the findings as its park reason in the dashboard and /api/tasks; nothing requires reading task logs to learn why a PR was withheld.","status":"open","priority":2,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:31Z","external_ref":"https://github.com/samcharles93/archie-core/issues/556","dependencies":[{"issue_id":"archie-core-h019.6","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.6","depends_on_id":"archie-core-h019.1","type":"blocks","created_at":"2026-08-21T13:03:25Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.6","depends_on_id":"archie-core-h019.2","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":1,"comment_count":0} +{"_type":"issue","id":"archie-core-h019.7","title":"Docs: promote the shipped review stage into docs/architecture and reconcile CLAUDE.md","description":"Under the scope-discipline rule merged as PR #533, a design is promoted into docs/architecture/ only once it is built and true. This is that promotion, and it is deliberately a separate bead so it is not lost when the feature lands and attention moves on.\n\nDo three things once the stage ships:\n\n1. Promote the docs/prds/ decision into docs/architecture/, describing the review stage as it actually works -- not as designed. Cut anything a reader could learn from the code.\n2. Update ARCHITECTURE.md's task lifecycle: queued -\u003e running(workflow:stage) -\u003e pr_open -\u003e merged|rejected gains a review stage that can divert to waiting_human before pr_open. The current text does not mention it.\n3. Reconcile CLAUDE.md's Development Protocol. It currently tells a human or agent contributor to run the adversarial pass by hand. Once archied does this for the PRs it opens, that section needs to say which path applies to whom, or it will read as describing a manual step that is now automatic.\n\nCLAUDE.md's own rule: a comment or doc that contradicts its code is worse than none, because the next reader trusts it.","acceptance_criteria":"docs/architecture/ describes the shipped stage; ARCHITECTURE.md's lifecycle includes the review stage and the waiting_human diversion; CLAUDE.md distinguishes the manual contributor pass from archied's automated one; no doc still claims review is only manual.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","updated_at":"2026-08-22T09:25:32Z","external_ref":"https://github.com/samcharles93/archie-core/issues/557","dependencies":[{"issue_id":"archie-core-h019.7","depends_on_id":"archie-core-h019","type":"parent-child","created_at":"2026-08-21T13:03:15Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.7","depends_on_id":"archie-core-h019.4","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-h019.7","depends_on_id":"archie-core-h019.6","type":"blocks","created_at":"2026-08-21T13:03:26Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-nln7","title":"Dashboard-initiated updates get no phase-2 report, so they are never verified","description":"internal/webui/api_chat.go:497 starts an install with releaseupdate.InstallMeta{Channel: \"webui\"} and leaves ReportPath empty. CommandInstaller passes that through as ARCHIE_UPDATE_REPORT_PATH, and scripts/archie-update-watchdog's write_report() returns early when it is empty.\n\nConsequences: an operator who approves an update from the dashboard gets only the synchronous phase-1 result (build/install succeeded, restart queued) and never learns whether the daemon actually came back up, whether it was rolled back, or - since c25799e - whether the installed version is the one now running. Telegram gets all of that; the dashboard silently gets none of it.\n\nThe verification added in c25799e (releaseupdate.Report.Verify) is reached only from internal/channels/telegram/update.go, so this path is unverified regardless.\n\nFix needs two parts: give the webui install a ReportPath (updateReportPath in cmd/archied), and give the dashboard somewhere to relay a pending report on boot the way telegram's reportPendingUpdate does - today ReadPendingReport has exactly one caller, and a single report file shared by two relayers would race to clear it.","acceptance_criteria":"A dashboard-approved update produces a phase-2 report; the dashboard surfaces its outcome including version verification; two relayers cannot double-report or lose a report.","status":"closed","priority":2,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-20T14:04:33Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:58:07Z","started_at":"2026-08-23T12:56:47Z","closed_at":"2026-08-23T12:58:07Z","close_reason":"Fixed: dashboard installs now get a ReportPath, and Server.Run relays/verifies/clears the phase-2 report on boot via a new KindUpdateReport SSE event. Adversarial review clean.","external_ref":"https://github.com/samcharles93/archie-core/issues/531","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-qk8m","title":"MCP npm servers re-fetched from npm on every task container start","description":"## Problem\n\nd4bb914b/#64 fixed the daemon-side case: cmd/archied/main.go's\nconfiguredMCPProvider now points npx-launched MCP servers at a persistent\nNPM_CONFIG_CACHE under the daemon's own work_dir, so a daemon restart\nreuses a warm cache instead of re-resolving/re-downloading from the npm\nregistry.\n\ninternal/app/agentworker/mcp_providers.go builds the identical\nStdioTransportConfig for archie-agent's own per-task MCP servers, but was\ndeliberately left untouched -- it's not a separate code path, the exact\nsame cfg.Tools.MCPServers list (including any npx entries) is threaded\nthrough to every per-task NATS agent worker (bootstrap.go -\u003e NATSRunner.MCPServers\n-\u003e taskrun.Request -\u003e task_execution.go's startMCPProviders). Since each\ntask runs in a fresh ephemeral container, an npx-based MCP server\nconfigured for task use re-resolves/re-downloads on every task, not\njust every daemon restart -- more frequent, and thus a worse amplifier of\na registry outage than the bug already fixed.\n\n## Why this needs its own issue\n\nUnlike the daemon case, a bare NPM_CONFIG_CACHE=\u003cpath\u003e pointed at a host\ndirectory is meaningless inside an ephemeral container unless a\npersistent Docker volume is actually bind-mounted at that path. No such\nvolume currently exists for this purpose -- internal/container/pool.go's\nmounts are caller-provided, and nothing wires an npm-cache volume in.\nThat's real new infrastructure (a shared, persistent volume across\nper-task containers), not a parameter-threading fix like d4bb914b was.\n\n## Acceptance criteria\n\n- Task containers reuse a persistent npm cache across tasks, the same\n way the daemon now does across restarts.\n- The cache volume/mount is wired through internal/container/pool.go's\n Acquire (or equivalent) without weakening per-task filesystem isolation\n for anything other than the npm cache path itself.\n- Startup time for a task's npx-based MCP server no longer scales with\n package size once the cache is warm.\n","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-18T16:04:59Z","created_by":"Sam Catlow","updated_at":"2026-08-23T12:53:17Z","external_ref":"https://github.com/samcharles93/archie-core/issues/532","metadata":null,"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-q5w4","title":"secret engine plugin: age","description":"Resolve SecretRef values from an age-encrypted file of key=value lines. Env: AGE_FILE (encrypted file path), AGE_IDENTITY (age private key file). Resolve runs 'age -d -i \u003cidentity\u003e \u003cfile\u003e' and parses the plaintext. Fresh resolve per call (no cache) so updates are picked up without daemon restart. CLI-based, mirroring the bws engine; ship as a Yaegi plugin in examples/secret-engines/.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-08-17T14:22:03Z","created_by":"Sam Catlow","updated_at":"2026-08-17T22:27:53Z","started_at":"2026-08-17T14:22:10Z","closed_at":"2026-08-17T14:33:52Z","close_reason":"Shipped age engine plugin in examples/secret-engines/age.go (commit 24faf53): CLI-based, AGE_FILE/AGE_IDENTITY, key=value lines.","external_ref":"https://github.com/samcharles93/archie-core/issues/526","metadata":null,"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -110,7 +110,7 @@ {"_type":"issue","id":"archie-core-tje.1","title":"Extract archie-agent task subscription concern","description":"## Problem\\nmain.go owns boot task discovery and taskrun subscription selection in addition to process composition.\\n\\n## Scope\\nMove bootTaskID and subscribeTaskRuns into a concern-named cmd/archie-agent source file, preserving dedicated-container versus shared-queue behavior and existing tests.\\n\\n## Acceptance\\n- boot brief parsing and taskrun subscription selection are outside main.go\\n- behavior and logging remain unchanged\\n- focused tests and task check pass","acceptance_criteria":"Subscription concern is outside main.go with unchanged behavior; tests and task check pass","notes":"Implementation and validation are complete in /tmp/archie-core-agent-cleanup on branch refactor/archie-agent-main-cleanup, but delivery is pending: changes are uncommitted, not integrated into the target branch, and not pushed. Do not close until those delivery steps are complete.\n Validation completed: task subscription focused tests and fresh review clean.\nDelivered on review branch refactor/archie-agent-main-cleanup at de242f8; pending PR review/merge.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","updated_at":"2026-08-14T14:53:09Z","started_at":"2026-08-13T17:25:20Z","closed_at":"2026-08-14T14:53:09Z","close_reason":"Merged to main in PR #480 at 52738f5; implementation commit de242f8 passed task check, race tests, lint, and independent review","external_ref":"https://github.com/samcharles93/archie-core/issues/471","dependencies":[{"issue_id":"archie-core-tje.1","depends_on_id":"archie-core-tje","type":"parent-child","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-tje.2","title":"Extract archie-agent stage fetch loop","description":"## Problem\\nmain.go contains the stageBus contract and fetch-handle-ack loop, obscuring startup composition.\\n\\n## Scope\\nMove stageBus and runMainLoop into a stage-loop concern file without changing ack, nak, retry, cancellation, or shutdown semantics.\\n\\n## Acceptance\\n- stage loop is outside main.go\\n- all error and cancellation paths remain covered\\n- focused tests and task check pass","acceptance_criteria":"Stage loop is outside main.go with ack/nak/cancellation behavior preserved; tests and task check pass","notes":"Implementation and validation are complete in /tmp/archie-core-agent-cleanup on branch refactor/archie-agent-main-cleanup, but delivery is pending: changes are uncommitted, not integrated into the target branch, and not pushed. Do not close until those delivery steps are complete.\n Validation completed: stage-loop path tests, race tests, lint, task check, and fresh review clean.\nDelivered on review branch refactor/archie-agent-main-cleanup at de242f8; pending PR review/merge.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","updated_at":"2026-08-14T14:53:09Z","started_at":"2026-08-13T17:33:26Z","closed_at":"2026-08-14T14:53:09Z","close_reason":"Merged to main in PR #480 at 52738f5; implementation commit de242f8 passed task check, race tests, lint, and independent review","external_ref":"https://github.com/samcharles93/archie-core/issues/472","dependencies":[{"issue_id":"archie-core-tje.2","depends_on_id":"archie-core-tje","type":"parent-child","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-tje.3","title":"Extract archie-agent MCP provider lifecycle","description":"## Problem\\nmain.go contains MCP transport selection, provider startup/discovery, registry population, and cleanup alongside process wiring.\\n\\n## Scope\\nMove mcpProviderSet, startMCPProviders, and cleanup into an MCP-provider concern file. Preserve optional-provider failure isolation and transport behavior.\\n\\n## Acceptance\\n- MCP provider lifecycle is outside main.go\\n- optional failures and cleanup semantics remain unchanged and tested\\n- task check passes","acceptance_criteria":"MCP lifecycle is outside main.go with failure isolation and cleanup preserved; tests and task check pass","notes":"Implementation and validation are complete in /tmp/archie-core-agent-cleanup on branch refactor/archie-agent-main-cleanup, but delivery is pending: changes are uncommitted, not integrated into the target branch, and not pushed. Do not close until those delivery steps are complete.\n Validation completed: MCP lifecycle tests, lint, task check, and fresh review clean.\nDelivered on review branch refactor/archie-agent-main-cleanup at de242f8; pending PR review/merge.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","updated_at":"2026-08-14T14:53:09Z","started_at":"2026-08-13T17:04:26Z","closed_at":"2026-08-14T14:53:09Z","close_reason":"Merged to main in PR #480 at 52738f5; implementation commit de242f8 passed task check, race tests, lint, and independent review","external_ref":"https://github.com/samcharles93/archie-core/issues/473","dependencies":[{"issue_id":"archie-core-tje.3","depends_on_id":"archie-core-tje","type":"parent-child","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0} -{"_type":"issue","id":"archie-core-tje.4","title":"Extract archie-agent stage request handling","description":"## Problem\\nmain.go decodes, executes, and responds to single-stage requests in the same file as process startup.\\n\\n## Scope\\nMove handle and its request/response orchestration into a stage-handler concern file after the MCP lifecycle seam is available. Preserve reply-address validation, provider setup, response encoding, and logging.\\n\\n## Acceptance\\n- stage request handling is outside main.go\\n- decode, reply, provider, execution, encode, and publish error paths remain covered\\n- task check passes","acceptance_criteria":"Stage request handling is outside main.go with all boundary error semantics preserved; tests and task check pass","notes":"Implementation and validation are complete in /tmp/archie-core-agent-cleanup on branch refactor/archie-agent-main-cleanup, but delivery is pending: changes are uncommitted, not integrated into the target branch, and not pushed. Do not close until those delivery steps are complete.\n Validation completed: single-stage boundary/MCP assembly tests, task check, and fresh review clean.\nDelivered on review branch refactor/archie-agent-main-cleanup at de242f8; pending PR review/merge.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","updated_at":"2026-08-14T14:53:09Z","started_at":"2026-08-13T17:41:10Z","closed_at":"2026-08-14T14:53:09Z","close_reason":"Merged to main in PR #480 at 52738f5; implementation commit de242f8 passed task check, race tests, lint, and independent review","external_ref":"https://github.com/samcharles93/archie-core/issues/474","dependencies":[{"issue_id":"archie-core-tje.4","depends_on_id":"archie-core-tje.3","type":"blocks","created_at":"2026-08-13T16:10:54Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-tje.4","depends_on_id":"archie-core-tje","type":"parent-child","created_at":"2026-08-13T16:10:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-tje.4","title":"Extract archie-agent stage request handling","description":"## Problem\\nmain.go decodes, executes, and responds to single-stage requests in the same file as process startup.\\n\\n## Scope\\nMove handle and its request/response orchestration into a stage-handler concern file after the MCP lifecycle seam is available. Preserve reply-address validation, provider setup, response encoding, and logging.\\n\\n## Acceptance\\n- stage request handling is outside main.go\\n- decode, reply, provider, execution, encode, and publish error paths remain covered\\n- task check passes","acceptance_criteria":"Stage request handling is outside main.go with all boundary error semantics preserved; tests and task check pass","notes":"Implementation and validation are complete in /tmp/archie-core-agent-cleanup on branch refactor/archie-agent-main-cleanup, but delivery is pending: changes are uncommitted, not integrated into the target branch, and not pushed. Do not close until those delivery steps are complete.\n Validation completed: single-stage boundary/MCP assembly tests, task check, and fresh review clean.\nDelivered on review branch refactor/archie-agent-main-cleanup at de242f8; pending PR review/merge.","status":"closed","priority":2,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:44Z","created_by":"Sam Catlow","updated_at":"2026-08-14T14:53:09Z","started_at":"2026-08-13T17:41:10Z","closed_at":"2026-08-14T14:53:09Z","close_reason":"Merged to main in PR #480 at 52738f5; implementation commit de242f8 passed task check, race tests, lint, and independent review","external_ref":"https://github.com/samcharles93/archie-core/issues/474","dependencies":[{"issue_id":"archie-core-tje.4","depends_on_id":"archie-core-tje","type":"parent-child","created_at":"2026-08-13T16:10:45Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-tje.4","depends_on_id":"archie-core-tje.3","type":"blocks","created_at":"2026-08-13T16:10:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-tje","title":"Decompose cmd/archie-agent main.go by concern","description":"## Problem\\ncmd/archie-agent/main.go is 430 lines and mixes process startup, task subscription selection, stage-loop execution, MCP provider lifecycle, and request handling. This makes unrelated changes collide and obscures the composition boundary.\\n\\n## Scope\\nTrack small behavior-preserving extractions into concern-named files within cmd/archie-agent. Keep main.go focused on flags, startup ordering, construction, shutdown, and invoking the worker loop. No new packages or architecture changes.\\n\\n## Acceptance\\n- child tasks move one concern at a time with tests unchanged or improved\\n- main.go retains process-level input and composition only\\n- each child passes task check and fresh adversarial review","acceptance_criteria":"All child extractions complete; main.go contains process input and composition only; task check passes","notes":"Implementation and validation are complete in /tmp/archie-core-agent-cleanup on branch refactor/archie-agent-main-cleanup, but delivery is pending: changes are uncommitted, not integrated into the target branch, and not pushed. Do not close until those delivery steps are complete.\n Validation already completed: main.go reduced 430→136 lines; package tests/race/vet/build/lint pass; full task check passes; final fresh adversarial review reported zero findings.\nCorrected architecture migration pushed for review at commit de242f81c1b6309cdc984ded8e2f01fad89097b9 on branch refactor/archie-agent-main-cleanup. Rebased onto origin/main 58eae75. Focused tests, race, changed-line lint, full task check, and final independent review all pass. Keep in_progress until PR merge.","status":"closed","priority":2,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:24Z","created_by":"Sam Catlow","updated_at":"2026-08-14T14:53:09Z","started_at":"2026-08-13T17:57:45Z","closed_at":"2026-08-14T14:53:09Z","close_reason":"Merged to main in PR #480 at 52738f5; implementation commit de242f8 passed task check, race tests, lint, and independent review","external_ref":"https://github.com/samcharles93/archie-core/issues/475","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637501304-434-efae0b99","title":"agent containers: git dubious-ownership causes all gates to fail","description":"## Problem\n\nAgent containers bind-mount the worktree from the host at `/data/worktree`, where the owning UID differs from the container user's UID. Git refuses to operate in such directories (\"fatal: detected dubious ownership in repository\"), and the Go toolchain calls git for VCS status during `go build`/`go test`/`go vet`.\n\nThis means every gate — baseline gate, build gate, TDD repro gate — fails immediately, before any real work begins. Agents burn tokens trying to fix the environment instead of working on the assigned issue.\n\n## Evidence\n\n- Task for issue #441 burned 557K tokens across 29 iterations and parked with `gate_failed_final` — the agent never reached the actual multi-forge fix\n- `go build` within the container fails with `error obtaining VCS status: exit status 128`\n- The agent's uncommitted `build_test.go` recognized the real cause: \"A pre-existing git dubious-ownership issue causes the build to fail\"\n\n## Fix\n\nAdd `git config --global --add safe.directory /data/worktree` at archie-agent startup. The worktree mount path is always `/data/worktree` (storage.WorktreeMountDir). The command is best-effort: if git isn't installed, the agent logs a warning and continues — it remains usable for repos without gate commands.\n\n## Files\n\n- `cmd/archie-agent/main.go`: run git safe.directory config after logger init","status":"closed","priority":2,"issue_type":"bug","created_at":"2026-08-12T04:38:10Z","updated_at":"2026-08-15T12:57:37Z","closed_at":"2026-08-15T12:57:37Z","close_reason":"Fixed: internal/infrastructure/agentgit/safety.go's MarkSafe adds the mounted worktree to git's global safe.directory list, and it is wired into the actual agent-container startup path -- internal/app/agentworker/worker.go:63,84 calls dependencies.markSafe(ctx, workDir, log) unconditionally in run(), before NATS connect and before any gate executes. Confirmed by grep this is the only non-test call site (worker.go), so it isn't dead/unwired code. go test ./internal/infrastructure/agentgit/... and ./internal/app/agentworker/... -race -count=1 both pass, including worker_test.go coverage that exercises the run() path with markSafe wired in. This matches the exact fix archie-core-1786749700606-6-bf6aa32d already describes as done ('#468 ... resolved by safe.directory').","external_ref":"https://github.com/samcharles93/archie-core/issues/468","source_system":"github:https://github.com/samcharles93/archie-core/issues/468:468","metadata":null,"labels":["bug"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637501270-433-dc1a0bc2","title":"Telegram gateway: show tool calls inline during chat turns","description":"The Telegram chat agent returns only the final answer. The user cannot see which tools are being called, their parameters, or their results. This makes debugging agent behavior (hallucinations, wrong tool choices, footguns like `systemctl stop` vs `restart`) impossible from the chat side.\n\n## Desired behavior\n\nAfter each tool call completes, the gateway sends a compact inline message showing the tool name and a one-line summary of the result, before the next tool call or final answer. Similar to how Hermes surfaces tool calls in Telegram.\n\nExample format:\n```\n🔧 memory_edit — added entry\n🔧 terminal — systemctl --user stop archied (exit 0)\n🔧 terminal — systemctl --user start archied (exit 0)\n```\n\nThen the final answer.\n\n## Scope\n\n`internal/channels/telegram/` only. Behind a config flag `[chat.telegram] show_tool_calls = true` so it can be toggled.\n\n## Technical approach\n\nCurrently the call chain is:\n\n```\nsubmitTurn → router.RouteStream(turnCtx, gm, draft.onDelta)\n → r.LLMStream(ctx, msg, onDelta)\n → TurnRunner.Run(ctx, msg, onDelta)\n → prepared.Generate(ctx, req, onDelta)\n```\n\nOnly `onDelta` (text streaming) is threaded through. Tool calls happen inside `Generate` but there's no callback back to the gateway.\n\n### What needs to change\n\n1. **Add a tool-call observer callback** — either extend `LLMStreamResponder` signature or add a separate `OnToolCall` field to `gateway.Router` struct, plumbing it through `TurnRunner` → `TurnModel`/`PreparedTurnModel.Generate` so model providers can report tool invocations\n\n2. **Model provider integration** — the chat turn model (`cmd/archied/chat_turn_model.go`) and any provider-specific `Generate` implementations need to call the observer when a tool is executed, passing tool name + result summary\n\n3. **Telegram gateway wiring** — in `submitTurn` (`internal/channels/telegram/telegram.go`), if `show_tool_calls` config is true, wire the observer to send a compact inline message via `sendMessage` before the final reply\n\n4. **Config plumbing** — add `ShowToolCalls bool` to the Telegram gateway config struct and read it from `[chat.telegram] show_tool_calls` in `telegram_setup.go`\n\n### Key files\n\n| File | Role |\n|------|------|\n| `internal/gateway/gateway.go` | `RouteStream`, `Router` struct (add observer field) |\n| `internal/gateway/turn.go` | `TurnRunner.Run`, `PreparedTurnModel.Generate` signature |\n| `cmd/archied/chat_turn_model.go` | Model provider `Generate` — where tool calls execute |\n| `internal/channels/telegram/telegram.go` | `submitTurn` — wire observer + send messages |\n| `cmd/archied/telegram_setup.go` | Config reading + gateway construction |\n","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-12T04:20:52Z","updated_at":"2026-08-14T15:07:34Z","closed_at":"2026-08-14T15:07:34Z","external_ref":"https://github.com/samcharles93/archie-core/issues/467","source_system":"github:https://github.com/samcharles93/archie-core/issues/467:467","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -260,7 +260,7 @@ {"_type":"issue","id":"archie-core-1786637497395-289-8308ccd7","title":"Verify: WebhookAdapter: declarative filters","description":"### Acceptance Criteria\n\nIndependent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:28Z","updated_at":"2026-08-08T14:49:30Z","closed_at":"2026-08-08T14:49:31Z","external_ref":"https://github.com/samcharles93/archie-core/issues/310","source_system":"github:https://github.com/samcharles93/archie-core/issues/310:310","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637497373-288-22cb0426","title":"Verify: WebhookAdapter: HTTP server with per-route HMAC validation","description":"### Acceptance Criteria\n\nIndependent adversarial review by fresh agent. Verify: no dead code paths, no lint issues (golangci-lint run clean), tests pass (go test ./...), code is formatted (gofmt), no hardcoded values in tests. Review the implementation against the original acceptance criteria. Report findings or confirm clean.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:23Z","updated_at":"2026-08-08T14:49:25Z","closed_at":"2026-08-08T14:49:26Z","external_ref":"https://github.com/samcharles93/archie-core/issues/309","source_system":"github:https://github.com/samcharles93/archie-core/issues/309:309","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637497353-287-96a3e24c","title":"MS Graph webhook adapter: validationToken handshake","description":"Implement MS Graph webhook adapter with validationToken handshake for subscription verification, clientState verification, and CIDR IP allowlisting.","notes":"Not started. internal/channels/webhook/webhook.go has no MS-Graph-specific handling at all -- no validationToken query-param echo, no clientState check, no CIDR allowlist. This is likely a separate RouteConfig variant or a dedicated handler function, since MS Graph's subscription-verification handshake (echo validationToken as text/plain on subscribe) doesn't fit the existing POST-body-in/HMAC-out flow.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:20Z","updated_at":"2026-08-15T12:51:54Z","external_ref":"https://github.com/samcharles93/archie-core/issues/308","source_system":"github:https://github.com/samcharles93/archie-core/issues/308:308","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637497353-287-96a3e24c","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"related","created_at":"2026-08-15T12:52:04Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-1786637497328-286-9c985f28","title":"WebhookAdapter: idempotency cache","description":"Implement TTL-based idempotency cache to deduplicate retried webhook deliveries. Cache based on webhook event ID and route.","notes":"Not started. No cache of any kind in internal/channels/webhook/webhook.go. Needs a webhook event ID (route-scoped) -\u003e TTL cache; most platforms send a stable delivery/event ID header (e.g. GitHub's X-GitHub-Delivery) usable as the key. Related to the gateway-level archie-core-1786637492498-104-1bde76ae (MessageDeduplicator) which solves the same class of problem one layer up -- check whether one mechanism can serve both before building a second cache.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:17Z","updated_at":"2026-08-15T12:51:54Z","external_ref":"https://github.com/samcharles93/archie-core/issues/307","source_system":"github:https://github.com/samcharles93/archie-core/issues/307:307","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637497328-286-9c985f28","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"related","created_at":"2026-08-15T12:52:04Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786637497328-286-9c985f28","depends_on_id":"archie-core-1786637492498-104-1bde76ae","type":"related","created_at":"2026-08-15T12:52:03Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786637497328-286-9c985f28","depends_on_id":"archie-core-7d5u.5","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-1786637497328-286-9c985f28","title":"WebhookAdapter: idempotency cache","description":"Implement TTL-based idempotency cache to deduplicate retried webhook deliveries. Cache based on webhook event ID and route.","notes":"Not started. No cache of any kind in internal/channels/webhook/webhook.go. Needs a webhook event ID (route-scoped) -\u003e TTL cache; most platforms send a stable delivery/event ID header (e.g. GitHub's X-GitHub-Delivery) usable as the key. Related to the gateway-level archie-core-1786637492498-104-1bde76ae (MessageDeduplicator) which solves the same class of problem one layer up -- check whether one mechanism can serve both before building a second cache.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:17Z","updated_at":"2026-08-15T12:51:54Z","external_ref":"https://github.com/samcharles93/archie-core/issues/307","source_system":"github:https://github.com/samcharles93/archie-core/issues/307:307","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637497328-286-9c985f28","depends_on_id":"archie-core-1786637492498-104-1bde76ae","type":"related","created_at":"2026-08-15T12:52:03Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786637497328-286-9c985f28","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"related","created_at":"2026-08-15T12:52:04Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786637497328-286-9c985f28","depends_on_id":"archie-core-7d5u.5","type":"relates-to","created_at":"2026-08-21T23:27:06Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637497299-285-f4780816","title":"WebhookAdapter: deliver_only mode","description":"Implement deliver_only mode that skips agent processing and directly renders the prompt template as a deliverable (e.g. plain text, HTML, JSON response).","notes":"Not started, despite the package doc comment's claim: webhook.go:1-3 says 'Outbound delivery is not supported (deliver-only mode)' but handleWebhook() (webhook.go:120-183) unconditionally calls router.Route -- there is no branch that skips the agent and renders the template directly. RouteConfig.DeliverTo==\"origin\" only controls where the agent's reply goes, it doesn't skip the agent. Either the doc comment is aspirational (fix by implementing this issue) or describes a different, unbuilt code path -- don't trust the comment over the code.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:14Z","updated_at":"2026-08-15T12:51:54Z","external_ref":"https://github.com/samcharles93/archie-core/issues/306","source_system":"github:https://github.com/samcharles93/archie-core/issues/306:306","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637497299-285-f4780816","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"related","created_at":"2026-08-15T12:52:04Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637497271-284-573ca138","title":"WebhookAdapter: prompt templates with dot-notation","description":"Implement prompt template system with dot-notation variable interpolation ({pull_request.title}, {__raw__}) for building dynamic prompts from webhook payloads.","notes":"Partially done: internal/channels/webhook/webhook.go:243-264 extractText() does single-field dot-notation extraction (RouteConfig.Template = \"issue.title\"), not multi-variable interpolation. This issue wants a template string with multiple {field.path} placeholders plus a {__raw__} escape hatch -- extractText needs to become a real interpolation pass (parse placeholders, resolve each dot-path, substitute), not a single-path lookup. RouteConfig.Template's meaning would change from 'the one field to extract' to 'a template string' -- update its doc comment in the same change.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:10Z","updated_at":"2026-08-15T12:51:54Z","external_ref":"https://github.com/samcharles93/archie-core/issues/305","source_system":"github:https://github.com/samcharles93/archie-core/issues/305:305","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637497271-284-573ca138","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"related","created_at":"2026-08-15T12:52:04Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637497242-283-03662140","title":"WebhookAdapter: script transforms","description":"Support external script transforms per route. Allow bash/python scripts to transform incoming webhook payloads before processing.","notes":"Not started. No script/transform hook exists in internal/channels/webhook/webhook.go. Would sit between body read and text extraction in handleWebhook() (webhook.go:120-183), likely as a RouteConfig field naming an external command, invoked via os/exec on the raw body before extractText.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:49:07Z","updated_at":"2026-08-15T12:51:54Z","external_ref":"https://github.com/samcharles93/archie-core/issues/304","source_system":"github:https://github.com/samcharles93/archie-core/issues/304:304","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637497242-283-03662140","depends_on_id":"archie-core-1786637497036-275-8838629e","type":"related","created_at":"2026-08-15T12:52:04Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -408,7 +408,7 @@ {"_type":"issue","id":"archie-core-1786637493467-141-ffb91b17","title":"ToolEntry data type definition","description":"Design and implement the ToolEntry data type carrying: name, toolset (which tool group this belongs to), schema (JSON Schema for invocation), handler (function ref), check_fn (availability predicate), requires_env (env vars needed), is_async (async/sync distinction), description, emoji, max_result_size_chars (per-tool result cap), and dynamic_schema_overrides (runtime schema mutations). This is the foundational type that everything in the tools subsystem builds upon.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:14Z","updated_at":"2026-08-08T14:38:16Z","closed_at":"2026-08-08T14:38:17Z","external_ref":"https://github.com/samcharles93/archie-core/issues/162","source_system":"github:https://github.com/samcharles93/archie-core/issues/162:162","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493439-140-2cee2e9b","title":"[EPIC] Tools: central registry, MCP client, guardrails","description":"Central tool infrastructure to match Hermes parity:\n\n1. **Tool registry**: A central registry where tool modules register themselves with name, schema, handler, toolset membership, and availability check. Dynamic discovery of built-in tools. This replaces the current pattern of manually constructing core.ToolSet maps per invocation.\n\n2. **MCP client**: Connect to external MCP servers via stdio, HTTP/StreamableHTTP, or SSE transport. Discover their tools and register them into the tool registry. Support automatic reconnection with backoff, configurable timeouts, per-server parallel tool call opt-in.\n\n3. **Guardrails**: Tool-call loop detection (repeated calls, repeated failures, no-progress loops). Idempotent/mutating tool classification. Warning vs hard-stop decisions.\n\n4. **Progressive disclosure**: When tool schemas exceed a context-window threshold, replace them with bridge tools (tool_search/tool_describe/tool_call) and surface on demand. Core tools are always visible.\n\nRef: docs/prds/hermes-gap-analysis.md section 3\n\n### Acceptance Criteria\n\nMCP servers can be configured with a TOML block and their tools appear alongside built-ins. The agent loop is protected against tool-call loops. Tool schemas stay within context budget.\n","notes":"docs/prds/hermes-gap-analysis.md (referenced above) was intentionally deleted in commit 65aa5b4 ('chore: cleanup', 2026-07-28) after it had already spawned this and ~14 sibling beads issues from its 60 identified gaps — it is not a broken link to restore. This issue's description is the surviving record of its slice of that analysis.","status":"open","priority":2,"issue_type":"epic","created_at":"2026-08-08T14:38:11Z","updated_at":"2026-08-15T12:47:30Z","external_ref":"https://github.com/samcharles93/archie-core/issues/161","source_system":"github:https://github.com/samcharles93/archie-core/issues/161:161","metadata":null,"labels":["epic"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493413-139-d157cc71","title":"SessionSource struct for platform identity","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:06Z","updated_at":"2026-08-08T14:38:08Z","closed_at":"2026-08-08T14:38:09Z","external_ref":"https://github.com/samcharles93/archie-core/issues/160","source_system":"github:https://github.com/samcharles93/archie-core/issues/160:160","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-1786637493387-138-cad8e7a7","title":"Platform capability flags for adapters","description":"A capability-flag mechanism so callers can ask an adapter which optional features it supports (typing indicator, edit, delete, media send, clarify/approval/picker UI) instead of discovering support by a failed type assertion or a runtime error.\n\n### Context for implementers\n\nThis depends on the optional-method interfaces this issue is meant to describe: `archie-core-1786637493329-136-49b39c78` (typing/edit/delete/media) and `archie-core-1786637493357-137-35af7083` (clarify/approval/pickers). Implement after (or in close coordination with) those two, since the flag set should mirror whatever optional interfaces they land — don't invent a flag taxonomy ahead of the methods it describes.\n\n### Acceptance Criteria\n\n`BasePlatformAdapter` (`internal/gateway/adapter.go`) or a wrapping type exposes a capability query (e.g. `Capabilities() AdapterCapabilities`) that reports which optional methods an adapter implements. Every existing adapter's reported capabilities match its actual method set (a regression test should fail if an adapter claims a capability it doesn't implement, or vice versa).\n","notes":"Partial: the mechanism itself (gateway.CapabilityReporter, CapabilitiesOf, AdapterCapabilities) is built and covered by a regression test, scoped to Media only -- see archie-core-1786637493329-136-49b39c78 (closed, media portion). Still blocked on archie-core-1786637493357-137-35af7083 (clarify/approval/pickers) since AdapterCapabilities needs those flags added too before this is fully done.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:02Z","updated_at":"2026-08-23T12:53:18Z","started_at":"2026-08-22T11:53:10Z","external_ref":"https://github.com/samcharles93/archie-core/issues/159","source_system":"github:https://github.com/samcharles93/archie-core/issues/159:159","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637493387-138-cad8e7a7","depends_on_id":"archie-core-1786637493357-137-35af7083","type":"blocks","created_at":"2026-08-15T12:46:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786637493387-138-cad8e7a7","depends_on_id":"archie-core-1786637493329-136-49b39c78","type":"blocks","created_at":"2026-08-15T12:46:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-1786637493387-138-cad8e7a7","title":"Platform capability flags for adapters","description":"A capability-flag mechanism so callers can ask an adapter which optional features it supports (typing indicator, edit, delete, media send, clarify/approval/picker UI) instead of discovering support by a failed type assertion or a runtime error.\n\n### Context for implementers\n\nThis depends on the optional-method interfaces this issue is meant to describe: `archie-core-1786637493329-136-49b39c78` (typing/edit/delete/media) and `archie-core-1786637493357-137-35af7083` (clarify/approval/pickers). Implement after (or in close coordination with) those two, since the flag set should mirror whatever optional interfaces they land — don't invent a flag taxonomy ahead of the methods it describes.\n\n### Acceptance Criteria\n\n`BasePlatformAdapter` (`internal/gateway/adapter.go`) or a wrapping type exposes a capability query (e.g. `Capabilities() AdapterCapabilities`) that reports which optional methods an adapter implements. Every existing adapter's reported capabilities match its actual method set (a regression test should fail if an adapter claims a capability it doesn't implement, or vice versa).\n","notes":"Partial: the mechanism itself (gateway.CapabilityReporter, CapabilitiesOf, AdapterCapabilities) is built and covered by a regression test, scoped to Media only -- see archie-core-1786637493329-136-49b39c78 (closed, media portion). Still blocked on archie-core-1786637493357-137-35af7083 (clarify/approval/pickers) since AdapterCapabilities needs those flags added too before this is fully done.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:02Z","updated_at":"2026-08-23T12:53:18Z","started_at":"2026-08-22T11:53:10Z","external_ref":"https://github.com/samcharles93/archie-core/issues/159","source_system":"github:https://github.com/samcharles93/archie-core/issues/159:159","metadata":null,"labels":["task"],"dependencies":[{"issue_id":"archie-core-1786637493387-138-cad8e7a7","depends_on_id":"archie-core-1786637493329-136-49b39c78","type":"blocks","created_at":"2026-08-15T12:46:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-1786637493387-138-cad8e7a7","depends_on_id":"archie-core-1786637493357-137-35af7083","type":"blocks","created_at":"2026-08-15T12:46:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":2,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493357-137-35af7083","title":"BasePlatformAdapter interactive UX methods (clarify, approval, pickers)","description":"Add adapter-facing methods for interactive UX: presenting a clarifying question, an approval prompt, and a picker (multi-choice selection) natively on the platform, rather than as plain text the user has to reply to by hand.\n\n### Context for implementers\n\nThe approval *decision* plumbing already exists — `internal/tools/approval.go`, re-exported through `internal/gateway/approval.go` (`ApprovalRequester`, `ApprovalDecision`, `WithApprovalRequester`/`ApprovalFromContext`). What's missing is the adapter-side rendering: `BasePlatformAdapter` (`internal/gateway/adapter.go`) has no method for an adapter to display an approval/clarify/picker UI and report back a decision through that existing plumbing. This issue wires a new adapter method (or interface) into the existing `ApprovalRequester` flow — it should not duplicate or replace the decision model in `internal/tools/approval.go`. Sibling of `archie-core-1786637493329-136-49b39c78` (typing/edit/delete/media) — same \"optional adapter capability\" shape, different capability set.\n\n### Acceptance Criteria\n\nAn adapter can render a clarify/approval/picker prompt and the user's response is delivered back through the existing `ApprovalRequester`/`ApprovalDecision` flow in `internal/tools/approval.go`, not a parallel mechanism. Platforms without native UI (e.g. plain text-only channels) degrade to a text-based fallback rather than failing. Covered by a test double adapter, not a live platform.\n","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:37:59Z","updated_at":"2026-08-15T12:46:48Z","external_ref":"https://github.com/samcharles93/archie-core/issues/158","source_system":"github:https://github.com/samcharles93/archie-core/issues/158:158","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493329-136-49b39c78","title":"BasePlatformAdapter optional methods (typing, edit, delete, media)","description":"Extend adapter capability beyond the four required `BasePlatformAdapter` methods with optional per-platform methods: typing indicator, message edit, message delete, and media-specific send.\n\n### Context for implementers\n\n`internal/gateway/adapter.go` today defines `BasePlatformAdapter` with exactly four methods: `Connect`, `Disconnect`, `Send`, `ChatInfo` (see full listing — the file is 80 lines). Not every platform supports typing/edit/delete/media uniformly, so these should be a separate optional interface(s) that callers type-assert for, not additions to the required interface (that would break every existing adapter implementation). Pairs with `archie-core-1786637493387-138-cad8e7a7` (platform capability flags) — callers need a way to know *ahead of a type assertion* whether an adapter supports a given optional method, rather than probing via failed assertions at call time.\n\n### Acceptance Criteria\n\nOptional methods are defined on a separate interface (or interfaces) from `BasePlatformAdapter`, so existing adapters keep compiling unchanged. At least one adapter implementation exercises each optional method in a test. Callers that invoke an optional method on an adapter that doesn't implement it get a defined, non-panicking behavior.\n","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:37:57Z","updated_at":"2026-08-23T12:53:18Z","started_at":"2026-08-22T11:53:09Z","external_ref":"https://github.com/samcharles93/archie-core/issues/157","source_system":"github:https://github.com/samcharles93/archie-core/issues/157:157","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":1,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493304-135-95070200","title":"BasePlatformAdapter interface with required methods","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:37:51Z","updated_at":"2026-08-08T14:37:54Z","closed_at":"2026-08-08T14:37:55Z","external_ref":"https://github.com/samcharles93/archie-core/issues/156","source_system":"github:https://github.com/samcharles93/archie-core/issues/156:156","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -507,7 +507,7 @@ {"_type":"issue","id":"archie-core-1786637490896-42-a32bec11","title":"Web Chat: expose provider-aware active model and personality selectors","description":"Make the Web Chat selector state match Telegram: expose the active model/provider and the active personality for the current Web session, group models by provider when the manager supports it, and render those states in the UI. Preserve graceful fallback for managers without provider metadata.\n\n### Design\n\nUse the existing ModelManager, ProviderModelManager, and PersonaRegistry contracts. Keep the existing models/personas fields backward compatible while adding structured provider/active fields.\n\n### Acceptance Criteria\n\nSessions API returns active model/provider data and current-session personality state; provider-aware model options are grouped and selectable; selecting a provider/model/personality updates the shared gateway state; focused Go and UI/browser tests cover active and fallback states.","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:29:05Z","updated_at":"2026-08-08T14:31:21Z","closed_at":"2026-08-08T14:31:22Z","external_ref":"https://github.com/samcharles93/archie-core/issues/63","source_system":"github:https://github.com/samcharles93/archie-core/issues/63:63","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637490869-41-01cbe0c4","title":"Make activity and task context navigable","description":"The dashboard's live activity entries are not clickable, task detail does not provide a source-task/forge link, and the Tasks KPI strip sits directly against the table. Make activity events navigate to the relevant dashboard area, expose a clear source task action that opens the task's forge page when available, and restore visual separation between KPI cards and the task table. Add focused UI/runtime tests.","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:29:00Z","updated_at":"2026-08-08T14:31:23Z","closed_at":"2026-08-08T14:31:24Z","external_ref":"https://github.com/samcharles93/archie-core/issues/62","source_system":"github:https://github.com/samcharles93/archie-core/issues/62:62","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637490840-40-590ad4cb","title":"Discover user-installed global skills alongside project skills","description":"The Web UI currently scans only the daemon work directory, so skills installed under the user's global ~/.agents/skills are invisible. Add global-skill discovery alongside project skills, preserve deterministic precedence for duplicate names, expose source/path in the API/UI, and keep workflow activation using the same merged catalogue. Add tests for configured and default roots.","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:28:55Z","updated_at":"2026-08-08T14:31:25Z","closed_at":"2026-08-08T14:31:26Z","external_ref":"https://github.com/samcharles93/archie-core/issues/61","source_system":"github:https://github.com/samcharles93/archie-core/issues/61:61","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-1786637490815-39-45528ea3","title":"Restore compliance with the approved Archie visual design","description":"The current dashboard does not follow the supplied reference design. Rework the shell and page composition around the reference: a framed rounded workspace, compact top navigation, prominent welcome/header area, adjacent primary actions, getting-started panel, prominent status/compliance visualization, compact KPI strip with trend marks, forecast/projection panel, and live-runs table. Match the reference visual treatment: layered rounded surfaces, soft translucent panels, luminous abstract background treatment, compact information-dense cards, restrained status colours, and consistent icon/action placement. Do not reinterpret this as a generic dark admin console or as a light editorial marketing page. Capture desktop and narrow-viewport visual evidence before closing.","status":"open","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:28:52Z","updated_at":"2026-08-08T14:31:27Z","external_ref":"https://github.com/samcharles93/archie-core/issues/60","source_system":"github:https://github.com/samcharles93/archie-core/issues/60:60","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-1786637490815-39-45528ea3","title":"Restore compliance with the approved Archie visual design","description":"The current dashboard does not follow the supplied reference design. Rework the shell and page composition around the reference: a framed rounded workspace, compact top navigation, prominent welcome/header area, adjacent primary actions, getting-started panel, prominent status/compliance visualization, compact KPI strip with trend marks, forecast/projection panel, and live-runs table. Match the reference visual treatment: layered rounded surfaces, soft translucent panels, luminous abstract background treatment, compact information-dense cards, restrained status colours, and consistent icon/action placement. Do not reinterpret this as a generic dark admin console or as a light editorial marketing page. Capture desktop and narrow-viewport visual evidence before closing.","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:28:52Z","updated_at":"2026-08-23T13:33:21Z","closed_at":"2026-08-23T13:33:21Z","close_reason":"Closed","external_ref":"https://github.com/samcharles93/archie-core/issues/60","source_system":"github:https://github.com/samcharles93/archie-core/issues/60:60","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637490788-38-90d76956","title":"Add accessible interaction semantics across the dashboard","description":"Source review found navigation icons and a theme toggle that depend on visual glyphs or title text, and task rows are clickable table rows without keyboard semantics or an explicit expandable control. Audit the main pages for labels, focus visibility, keyboard operation, semantic headings and table behavior, status announcements, and sufficient non-color cues. Add automated DOM/accessibility-oriented regression tests for the critical controls.","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:28:47Z","updated_at":"2026-08-08T14:31:29Z","closed_at":"2026-08-08T14:31:30Z","external_ref":"https://github.com/samcharles93/archie-core/issues/59","source_system":"github:https://github.com/samcharles93/archie-core/issues/59:59","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637490760-37-147373cd","title":"Improve operator orientation and safe refresh behavior","description":"The current shell has a minimal brand/sidebar, repeated bare actions, and limited indication of data freshness or which filters are active. Define a small consistent page-toolbar pattern with last-updated/loading/error states, clearer action labels, and preserved filter/navigation state across refresh and route changes. Keep the visual system lightweight and consistent with the existing dark/light themes.","status":"open","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:28:43Z","updated_at":"2026-08-08T14:31:30Z","external_ref":"https://github.com/samcharles93/archie-core/issues/58","source_system":"github:https://github.com/samcharles93/archie-core/issues/58:58","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637490735-36-521c78cb","title":"Make dense dashboard views usable on narrow screens","description":"The responsive layout collapses the sidebar at 860px, but the dashboard relies on dense tables and multi-control filter rows without a documented table overflow/stacking treatment. Exercise dashboard, tasks, logs, workflows, settings, and channels at narrow viewport widths; fix clipping, horizontal scrolling ownership, control wrapping, and touch target sizing while preserving desktop density.","status":"closed","priority":2,"issue_type":"feature","created_at":"2026-08-08T14:28:38Z","updated_at":"2026-08-08T14:31:32Z","closed_at":"2026-08-08T14:31:33Z","external_ref":"https://github.com/samcharles93/archie-core/issues/57","source_system":"github:https://github.com/samcharles93/archie-core/issues/57:57","metadata":null,"labels":["enhancement"],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/internal/webui/api_version.go b/internal/webui/api_version.go new file mode 100644 index 000000000..8c1762769 --- /dev/null +++ b/internal/webui/api_version.go @@ -0,0 +1,101 @@ +package webui + +import ( + "net/http" + + "github.com/samcharles93/archie-core/internal/releaseupdate" +) + +// componentStatus is the per-component update status enum surfaced to the +// dashboard: an operator scanning this list needs "is this component fine, +// or does it need attention, and why" at a glance, not a bare color that +// means something different on every row. +const ( + // statusOK means the running version matches what the check command + // reports installed, and nothing newer is available. + statusOK = "ok" + // statusUpdateAvailable means a newer version exists and nothing + // contradicts the check command's claim of what's currently running. + statusUpdateAvailable = "update_available" + // statusDrift means a running version was actually observed and it + // does not match what the check command claims is installed -- the + // same false-success shape releaseupdate.Report.Verify catches after + // an update, but here for the steady-state view. + statusDrift = "drift" + // statusUnknown means no running version could be confirmed for this + // component, so neither ok nor drift can be asserted honestly. + statusUnknown = "unknown" +) + +// componentVersionStatus is one row of GET /api/version: what a component +// claims to have installed, what was actually observed running (if +// anything), what's available, how it's deployed, and the resulting status. +type componentVersionStatus struct { + ID string `json:"id"` + Label string `json:"label"` + InstallType string `json:"install_type,omitempty"` + Reference string `json:"reference,omitempty"` + RunningVersion string `json:"running_version,omitempty"` + InstalledClaim string `json:"installed_claim,omitempty"` + LatestAvailable string `json:"latest_available,omitempty"` + Status string `json:"status"` +} + +// versionStatusFor decides one component's status from its check-command +// claim (installed) against the version actually observed running (running, +// ok). Order matters: drift is checked before update_available because a +// claim the running system actively contradicts is a more fundamental +// problem than a newer release merely existing -- an operator who only +// sees "update available" on a component that is silently not running what +// it claims would look in the wrong place. +func versionStatusFor(component releaseupdate.Component, running string, ok bool) string { + if ok && component.Installed != "" && running != component.Installed { + return statusDrift + } + if !ok || component.Installed == "" { + // No baseline to compare against -- an empty Installed means the + // check command never reported one, so Available (if any) cannot + // be judged newer than nothing. Reporting update_available here + // would assert a comparison that was never actually made. + return statusUnknown + } + if component.Available != "" && component.Available != component.Installed { + return statusUpdateAvailable + } + return statusOK +} + +// handleVersion reports, per component, how it's deployed and whether what +// is actually running matches what the operator's update-check command +// claims -- the steady-state counterpart to the phase-2 update report +// (update_report.go), which only fires around an update itself. +func (s *Server) handleVersion(w http.ResponseWriter, r *http.Request) { + if s.Chat == nil || !chatUpdateServiceConfigured(s.Chat.Updates) { + http.Error(w, "updates are not configured", http.StatusNotImplemented) + return + } + snapshot, err := s.Chat.Updates.Check(r.Context(), 0) + if err != nil { + http.Error(w, err.Error(), http.StatusBadGateway) + return + } + running := map[string]string{} + if s.RunningVersions != nil { + running = s.RunningVersions() + } + components := make([]componentVersionStatus, 0, len(snapshot.Components)) + for _, component := range snapshot.Components { + runningVersion, ok := running[component.ID] + if ok && runningVersion == "" { + ok = false + } + components = append(components, componentVersionStatus{ + ID: component.ID, Label: component.Label, + InstallType: component.InstallType, Reference: component.Reference, + RunningVersion: runningVersion, InstalledClaim: component.Installed, + LatestAvailable: component.Available, + Status: versionStatusFor(component, runningVersion, ok), + }) + } + writeJSON(w, map[string]any{"components": components}) +} diff --git a/internal/webui/api_version_test.go b/internal/webui/api_version_test.go new file mode 100644 index 000000000..9be9f7e7f --- /dev/null +++ b/internal/webui/api_version_test.go @@ -0,0 +1,158 @@ +package webui + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + + "github.com/samcharles93/archie-core/internal/gateway" + "github.com/samcharles93/archie-core/internal/releaseupdate" +) + +func TestVersionStatusForCases(t *testing.T) { + tests := []struct { + name string + component releaseupdate.Component + running string + ok bool + want string + }{ + { + name: "matches, nothing newer", + component: releaseupdate.Component{Installed: "1.0.0"}, + running: "1.0.0", ok: true, + want: statusOK, + }, + { + name: "newer available, running matches installed claim", + component: releaseupdate.Component{Installed: "1.0.0", Available: "1.1.0"}, + running: "1.0.0", ok: true, + want: statusUpdateAvailable, + }, + { + name: "running contradicts the installed claim", + component: releaseupdate.Component{Installed: "1.1.0"}, + running: "1.0.0", ok: true, + want: statusDrift, + }, + { + name: "nothing observed running", + component: releaseupdate.Component{Installed: "1.0.0"}, + running: "", ok: false, + want: statusUnknown, + }, + { + name: "drift takes priority over update_available", + component: releaseupdate.Component{Installed: "1.1.0", Available: "1.2.0"}, + running: "1.0.0", ok: true, + want: statusDrift, + }, + { + name: "check command reported no installed claim -- nothing to compare against", + component: releaseupdate.Component{}, + running: "1.0.0", ok: true, + want: statusUnknown, + }, + { + name: "available with no installed claim must not read as an update, since nothing was compared", + component: releaseupdate.Component{Available: "1.0.0"}, + running: "1.0.0", ok: true, + want: statusUnknown, + }, + { + name: "installed equals available -- nothing new, matches Snapshot.Available's own semantics", + component: releaseupdate.Component{Installed: "1.0.0", Available: "1.0.0"}, + running: "1.0.0", ok: true, + want: statusOK, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + if got := versionStatusFor(test.component, test.running, test.ok); got != test.want { + t.Errorf("versionStatusFor(%+v, %q, %v) = %q, want %q", test.component, test.running, test.ok, got, test.want) + } + }) + } +} + +func TestHandleVersionComposesCheckAndRunningVersions(t *testing.T) { + sessions := gateway.NewSessionStoreMemory() + t.Cleanup(func() { _ = sessions.Close() }) + updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{ + {ID: "daemon", Label: "Gateway", Installed: "1.0.0", Available: "1.1.0", InstallType: "binary"}, + {ID: "agent", Label: "Runtime", Installed: "1.0.0", InstallType: "container", Reference: "img@sha256:abc"}, + }}} + server := &Server{ + Chat: &ChatService{Router: gateway.NewRouter(chatStatusStub{}, nil, "web"), Sessions: sessions, Updates: updates}, + RunningVersions: func() map[string]string { return map[string]string{"daemon": "1.0.0"} }, + } + + res := httptest.NewRecorder() + server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/version", nil)) + if res.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", res.Code, res.Body) + } + var got struct { + Components []componentVersionStatus `json:"components"` + } + if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if len(got.Components) != 2 { + t.Fatalf("components = %#v, want 2", got.Components) + } + daemon := got.Components[0] + if daemon.Status != statusUpdateAvailable || daemon.RunningVersion != "1.0.0" || daemon.InstallType != "binary" { + t.Errorf("daemon = %+v, want status=%q running_version=1.0.0 install_type=binary", daemon, statusUpdateAvailable) + } + agent := got.Components[1] + if agent.Status != statusUnknown || agent.RunningVersion != "" { + t.Errorf("agent = %+v, want status=%q with no observed running version (not wired into RunningVersions in this test)", agent, statusUnknown) + } + if agent.Reference != "img@sha256:abc" { + t.Errorf("agent.Reference = %q, want %q", agent.Reference, "img@sha256:abc") + } +} + +// TestHandleVersionTreatsPresentButEmptyRunningVersionAsUnobserved covers a +// map entry that IS present but holds "" -- distinct from a missing key, +// and reachable in production: a malformed or pre-this-change archie-agent +// build could self-report an empty AgentVersion, which daemon.AgentStatus +// would still record as observed=true, version="". An empty string is not +// a version any component is actually running, so it must read as +// unobserved rather than as a running value to compare against. +func TestHandleVersionTreatsPresentButEmptyRunningVersionAsUnobserved(t *testing.T) { + sessions := gateway.NewSessionStoreMemory() + t.Cleanup(func() { _ = sessions.Close() }) + updates := &chatUpdateStub{snapshot: releaseupdate.Snapshot{Components: []releaseupdate.Component{ + {ID: "agent", Label: "Runtime", Installed: "1.0.0"}, + }}} + server := &Server{ + Chat: &ChatService{Router: gateway.NewRouter(chatStatusStub{}, nil, "web"), Sessions: sessions, Updates: updates}, + RunningVersions: func() map[string]string { return map[string]string{"agent": ""} }, + } + + res := httptest.NewRecorder() + server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/version", nil)) + var got struct { + Components []componentVersionStatus `json:"components"` + } + if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Components[0].Status != statusUnknown { + t.Errorf("status = %q, want %q for a present-but-empty running version", got.Components[0].Status, statusUnknown) + } +} + +func TestHandleVersionUnconfigured(t *testing.T) { + server := &Server{} + + res := httptest.NewRecorder() + server.Handler().ServeHTTP(res, httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/api/version", nil)) + if res.Code != http.StatusNotImplemented { + t.Fatalf("status = %d, want %d", res.Code, http.StatusNotImplemented) + } +} diff --git a/internal/webui/server.go b/internal/webui/server.go index f28029f59..fe257b0ea 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -236,6 +236,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET /api/channels", s.handleChannels) mux.HandleFunc("POST /api/channels/{id}/reload", s.handleChannelReload) mux.HandleFunc("GET /api/config", s.handleConfig) + mux.HandleFunc("GET /api/version", s.handleVersion) mux.HandleFunc("PATCH /api/config", s.handleConfigUpdate) mux.HandleFunc("POST /api/config/reset", s.handleConfigReset) mux.HandleFunc("GET /api/logs", s.handleLogs) diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index f72f12fc7..edbf5ef34 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -1,12 +1,13 @@ (function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,captures:``,mappings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,help:``};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new p(`unauthorised`,401);if(!t.ok)throw new p(`${t.status} ${t.statusText}`,t.status);return t.json()}function d(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))r!==``&&r!=null&&t.set(n,r);let n=t.toString();return n?`?${n}`:``}async function f(e){try{let t=(await e.text()).trim();if(t)return t.split(` -`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),captures:e=>u(`/api/captures`+d({limit:e})),mappings:()=>u(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=` +`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),workRequest:async e=>{let t=await fetch(`/api/work-requests`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),channelReload:async e=>{let t=await fetch(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:`{}`,signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},config:()=>u(`/api/config`),version:()=>u(`/api/version`),configUpdate:async e=>{let t=await fetch(`/api/config`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({updates:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},configReset:async e=>{let t=await fetch(`/api/config/reset`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({key:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},logs:e=>u(`/api/logs`+d(e)),captures:e=>u(`/api/captures`+d({limit:e})),mappings:()=>u(`/api/mappings`),mappingCreate:async e=>{let t=await fetch(`/api/mappings`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},mappingUpdate:async(e,t)=>{let n=await fetch(`/api/mappings/${e}`,{method:`PATCH`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(t),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},mappingDelete:async e=>{let t=await fetch(`/api/mappings/${e}`,{method:`DELETE`,headers:{Accept:`application/json`,"X-Archie-CSRF":`1`},signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status)},mappingPreview:async(e,t)=>{let n=await fetch(`/api/mappings/preview`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify({capture_id:e,fields:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},memory:()=>u(`/api/memory`),chatSessions:()=>u(`/api/chat/sessions`),chatMessages:e=>u(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatCancel:async e=>{let t=await fetch(`/api/chat/cancel`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatMessage:async(e,t)=>{let n=await fetch(`/api/chat/message`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({channel_id:e,source_id:crypto.randomUUID(),text:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatPersona:async(e,t)=>{let n=await fetch(`/api/chat/persona`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({session_id:e,name:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatUpdate:()=>u(`/api/chat/update`),chatUpdateDefer:async e=>{let t=await fetch(`/api/chat/update/defer`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(15e3)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatUpdateInstall:async e=>{let t=await fetch(`/api/chat/update/install`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({snapshot:e}),signal:AbortSignal.timeout(12e4)});if(!t.ok)throw new p(await f(t),t.status);return t.json()},chatDangerous:()=>u(`/api/chat/dangerous`),chatDangerousRequest:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({spec:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},chatDangerousDecision:async(e,t)=>{let n=await fetch(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({decision:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()}};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function _({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&v(o,u===!1?`var(--danger)`:`var(--ok)`))}function v(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=``,u}function y({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=` `,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(e){return e==null||e===``?`—`:String(e)}function K(t,n,r){let i=ie(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`—`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>se(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>ae(f,u,r)),f}function ae(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,m.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,oe(e,String(n.message||n))})}function oe(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function se(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let h=()=>n(t,...a);f.addEventListener(`click`,h),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&h()}),d.addEventListener(`click`,async()=>{let e=ce(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await m.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}function le(){let t=e(`div.cfg-page`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},`Refresh`))),r)}async function a(){try{o(await m.config(),a)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function o(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,de(t.identity,a),fe(t.repositories),me(t.models,t.providers),ge(t.budgets,a),_e(t.agent,a),ye(t.storage,t.containers,a),xe(t.web,a),ue(t.provenance))}return t}function ue(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function de(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function fe(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,pe(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function pe(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function me(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(he(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function he(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function ge(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Max tokens`,t.max_tokens||`Unlimited`,{key:`budgets.max_tokens`,type:`int`,raw:t.max_tokens,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function _e(t,n){return t?q(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.kv-list`,K(`Execution mode`,ve(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),K(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),K(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):q(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function ve(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function ye(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,be(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function be(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function xe(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var Se=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function Ce(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function we(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...Se.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Ae(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(ke(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(Te(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(Te(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ee)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function Te(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ee(t){let n=t.fields||{};return e(`div.log-row.log-${Ce(t.level)}`,e(`span.log-time.mono`,Oe(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(De(n))))))}function De(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Oe(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function ke(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Ae(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function je(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Me(t)]:[o]}function Me(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Ne(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Ne(t.headers)))))}function Ne(t){return t?e(`pre.capture-payload`,Pe(t)):e(`div.capture-empty`,`(empty)`)}function Pe(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Fe(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>je(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Ie=[`string`,`number`,`bool`,`object`,`array`,`any`];function Le(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function Re(e,t){return e?`${e}.${t}`:t}function ze(e,t){return`${e}[${t}]`}function Be(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,ze(n,t)]):Object.entries(t).map(([e,t])=>[e,t,Re(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:Le(n),name:t})}},t),Be(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:Le(t),name:r})}},JSON.stringify(t))}function Ve(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Ie.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,He(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function He(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function Ue(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function We(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>Ue(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ve(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):Be(o.payload,{onPick:p})))}return t}function Ge(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Ke)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Ke(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,qe(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function qe(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Je=`
+ class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function b(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}var x=`archie.setup-complete.dismissed.v1`;function S(e,t=globalThis.localStorage){if(!e?.steps?.length)return{kind:`omit`,remaining:[]};let n=e.steps.filter(e=>!e.done);return n.length?(t?.removeItem?.(x),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function C(e=globalThis.localStorage){e?.setItem?.(x,`1`)}var w=new Set([`waiting_human`,`parked`]);function T(e=[]){let t=e.filter(e=>w.has(e.status)),n=e.filter(e=>e.status===`running`);return{attention:{count:t.length,href:t.length===1?`#/tasks?task=${encodeURIComponent(t[0].id)}`:`#/tasks?status=needs_you`},running:{count:n.length,href:`#/tasks?status=running`}}}function E(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,k()),v=r(`connecting`,`idle`),y=[],b=new Map;w(),O();let x=h(e=>{y.unshift(e),y.splice(50),E()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,x);function w(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),E()}function E(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>D(e,b)))}async function O(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);E(),N(r),g.textContent=t?.operator?`${k()}, ${t.operator}`:k(),P(e),F(t),I(e,n),L(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Retry`))}}function N(t){let r=T(t),i=r.attention.count,a=r.running.count;n(p,i>0&&e(`a.btn.btn-attention`,{href:r.attention.href},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:r.running.href},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:O},l(`refresh`,{size:15}),`Refresh`))}function P(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,_({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),_({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:M(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function F(t){let r=S(t),i=r.kind===`omit`||r.kind===`dismissed`;if(d.classList.toggle(`dash-top-standalone`,i),i)return n(c);let a=r.remaining;if(a.length){let r=Math.round((t.steps.length-a.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(R))));return}n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`div.setup-complete-actions`,e(`span.setup-pct`,l(`check`,{size:16})),e(`button.icon-btn.setup-dismiss`,{type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onclick:()=>{C(),F(t)}},`×`)))))}function I(e,t){A(u,e,t)}function L(e){j(f,e)}function R(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function D(t,n){let r=O(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function O(e,t){return Number(e.task_id)>0?Number(e.task_id):!e.repo||!e.issue?0:Number(t.get(`${e.repo}#${e.issue}`))||0}function k(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function A(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),y({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}function j(t,r){let i=r?.tokens_by_day||[],a=i.reduce((e,t)=>e+(t.tokens||0),0);if(!i.length){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Token outlook`)),s(`Nothing spent yet`,`Usage appears here once Archie runs its first task.`)));return}let c=a/i.length,l=Math.round(c*30),u=i.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Token outlook`),e(`p.card-sub`,`Next 30 days at the current rate`))),e(`div.forecast-value`,o(l)),e(`div.forecast-note`,`Based on ${o(Math.round(c))} per day over ${i.length} days`),b([{label:`Last 7 days (${o(u)})`,value:u,kind:`info`},{label:`Earlier (${o(a-u)})`,value:Math.max(a-u,0),kind:`idle`}])))}function M(e){if(e.length<4)return null;let t=Math.floor(e.length/2),n=e.slice(0,t).reduce((e,t)=>e+t,0),r=e.slice(t).reduce((e,t)=>e+t,0);return n?(r-n)/n*100:null}function N(e,t){let n=e.title||`untitled task`;return{"aria-expanded":String(t),"aria-controls":`task-timeline-${e.id}`,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${n}`}}var P=new Set([`waiting_human`,`parked`]),F=new Set([`needs_you`,`queued`,`running`,`waiting_human`,`pr_open`,`merged`,`parked`,`dead`,`rejected`,`closed_wont_do`]);function I(e){let t=e?.get?.(`status`)||``;return F.has(t)?t:``}function L(e,t){return t?t===`needs_you`?P.has(e.status):e.status===t:!0}var R={queued:`Queued`,running:`Working`,waiting_human:`Waiting for you`,pr_open:`In review`,merged:`Merged`,parked:`Parked`,dead:`Stopped (too many retries)`,rejected:`Rejected`,closed_wont_do:`Won't do`};function z(e){return R[e]||e||`Unknown`}function B(t=new URLSearchParams){let o=e(`div`),c=e(`div.grid.grid-4.task-summary`),l=e(`tbody`),u=[],d=I(t),f=``,p=Number(t.get(`task`)),h=Number.isFinite(p)&&p>0?p:null,g=h!==null,v=``,y=new Map,b=new Map,x=new Set,S=e(`input.task-search`,{type:`search`,placeholder:`Search by title or repo…`,oninput:e=>{f=e.target.value.trim().toLowerCase(),O()}}),C=e(`select.task-filter`,{onchange:e=>{d=e.target.value,O()}},e(`option`,{value:``},`All statuses`),e(`option`,{value:`needs_you`,selected:d===`needs_you`},`Needs you`),...Object.entries(R).map(([t,n])=>e(`option`,{value:t,selected:d===t},n)));w(),T();function w(){n(o,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Tasks`),e(`p.page-sub`,`Every issue archied has picked up, and where it stands.`)),e(`div.page-actions`,e(`button.btn`,{onclick:T},`Refresh`))),c,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`All tasks`),e(`p.card-sub`,`Click a row for its timeline`)),e(`div.task-filters`,S,C)),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(t=>e(`th`,t)))),l))))}async function T(){try{[u,v]=await Promise.all([m.tasks(),m.config().then(e=>e?.identity?.forge_host||``).catch(()=>``)]),E(),O(),h&&u.some(e=>String(e.id)===String(h))&&W(h),k()}catch(t){n(c,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(l,e(`tr`,e(`td`,{colspan:8},s(`Cannot reach archied`,String(t.message||t)))))}}function E(){let e=u.length,t={};for(let e of u)t[e.status]=(t[e.status]||0)+1;let r=t.running||0,i=(t.waiting_human||0)+(t.parked||0),a=(t.merged||0)+(t.pr_open||0);n(c,_({label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),_({label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),_({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),_({label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`}))}function D(){return u.filter(e=>L(e,d)?!f||`${e.title} ${e.repo}`.toLowerCase().includes(f):!1)}function O(){let t=D();if(!u.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No tasks yet`,`Tasks appear here once archied picks up an issue to work.`))));return}if(!t.length){n(l,e(`tr`,e(`td`,{colspan:8},s(`No matching tasks`,`Try a different search or status filter.`))));return}l.replaceChildren();for(let e of t)l.append(A(e)),h===e.id&&l.append(H(e));k()}function k(){!g||!h||(g=!1,requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${h}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))}function A(t){let n=h===t.id,o=`task-timeline-${t.id}`,s=e=>{e?.stopPropagation(),h=h===t.id?null:t.id,O(),h===t.id&&W(t.id)};return e(`tr.task-row`,{...N(t,n),id:`task-row-${t.id}`,tabindex:`0`,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),s(e))},onclick:s},e(`td.mono`,{"data-label":`Repository`},e(`button.task-expand`,{type:`button`,"aria-expanded":String(n),"aria-controls":o,"aria-label":`${n?`Collapse`:`Expand`} timeline for ${t.title||`untitled task`}`,onclick:s},n?`−`:`+`),B(t)??`${t.owner}/${t.repo}`),e(`td.mono`,{"data-label":`Issue`},V(t)??`#${t.issue_number}`),e(`td.strong`,{"data-label":`Title`},t.title||`(untitled)`),e(`td`,{"data-label":`Status`},r(z(t.status),i(t.status))),e(`td`,{"data-label":`Workflow`},t.workflow||`—`),e(`td`,{"data-label":`Stage`},t.stage||`—`),e(`td`,{"data-label":`Last activity`,title:t.created_at?`Created ${a(t.created_at)}`:``},a(t.updated_at)),e(`td`,{"data-label":`Actions`},j(t)))}function j(t){let n=b.get(t.id),r=n?e(`span.task-action-error`,n):null,i=x.has(t.id),a=(n,r,a,o)=>e(n,{type:`button`,disabled:i,onclick:e=>{e.stopPropagation(),!(o&&!window.confirm(o))&&M(t.id,r)}},a),o=(t.actions||[]).map(e=>{switch(e){case`cancel`:return a(`button.btn.btn-small.btn-quiet`,e,`Cancel`,`Cancel "${t.title||`this task`}"? This closes the forge issue.`);case`stop`:return a(`button.btn.btn-small`,e,`Stop`,`Stop "${t.title||`this task`}"? Recoverable work will remain parked.`);case`approve`:return a(`button.btn.btn-small`,e,`Approve`);case`reject`:return a(`button.btn.btn-small.btn-quiet`,e,`Reject`,`Reject "${t.title||`this task`}"? This closes the forge issue.`);case`retry`:return a(`button.btn.btn-small`,e,`Retry`);case`abandon`:return a(`button.btn.btn-small.btn-quiet`,e,`Abandon`,`Abandon "${t.title||`this task`}"? This closes the forge issue.`);case`archive`:return a(`button.btn.btn-small.btn-quiet`,e,`Archive`,`Archive the local record for "${t.title||`this task`}"?`);case`open_pr`:return F(t,`pulls`,t.pr_number,`Open PR`);case`open_issue`:return F(t,`issues`,t.issue_number,`Open issue`);default:return null}});return!o.length&&!r?`—`:e(`div.task-actions`,r,o)}async function M(e,t){b.delete(e),x.add(e),O();try{await m.taskAction(e,t),x.delete(e),t===`archive`&&(h=null),await T()}catch(t){x.delete(e),b.set(e,t.message||`Action failed`),O()}}function P(e){return!v||!e.owner||!e.repo?null:`${v.replace(/\/+$/,``)}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`}function F(t,n,r,i){let a=P(t);return!a||!r||n===`issues`&&t.source===`chat`?e(`button.btn.btn-small`,{type:`button`,disabled:!0,title:`${i} is unavailable`},i):e(`a.btn.btn-small`,{href:`${a}/${n}/${r}`,target:`_blank`,rel:`noreferrer`,onclick:e=>e.stopPropagation()},i)}function B(t){let n=P(t);return n?e(`a.task-source-link`,{href:n,target:`_blank`,rel:`noreferrer`,title:`Open ${t.owner}/${t.repo} on the forge`,onclick:e=>e.stopPropagation()},`${t.owner}/${t.repo}`):null}function V(t){let n=P(t);return t.source===`chat`||!n||!t.issue_number?null:e(`a.task-source-link`,{href:`${n}/issues/${t.issue_number}`,target:`_blank`,rel:`noreferrer`,title:`Open issue #${t.issue_number} on the forge`,onclick:e=>e.stopPropagation()},`#${t.issue_number}`)}function H(t){let n=y.get(t.id);return e(`tr.task-timeline-row`,{id:`task-timeline-${t.id}`},e(`td`,{colspan:8},e(`div.task-detail-actions`,e(`div.task-decision-title`,`Available actions`),j(t)),t.status===`waiting_human`&&t.plan?e(`div.task-decision`,e(`div.task-decision-title`,`Decision required`),e(`div.task-decision-plan`,t.plan)):t.status===`parked`&&t.park_reason?e(`div.task-decision`,e(`div.task-decision-title`,`Park reason`),e(`div.task-decision-plan`,t.park_reason)):null,n===void 0?e(`div.task-timeline-loading`,`Loading timeline…`):n===null?e(`div.task-timeline-error`,e(`div.task-timeline-title`,`Could not load timeline`),e(`div.task-timeline-detail`,`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`),e(`button.btn`,{onclick:()=>W(t.id)},`Retry`)):n.length?e(`ul.task-timeline`,...n.map(U)):s(`No events yet`,`This task has not recorded any transitions.`)))}function U(t){return e(`li.task-timeline-entry`,e(`span.task-timeline-dot`),e(`div`,e(`div.task-timeline-kind`,t.kind||t.type||`event`),t.detail&&e(`div.task-timeline-detail`,t.detail),e(`div.task-timeline-when`,a(t.at))))}async function W(e){try{let t=await m.task(e);y.set(e,t||[])}catch{y.set(e,null)}O()}return o}function V(){let t=e(`div`),r=e(`div.grid.grid-2`),i=e(`input.skill-search`,{type:`search`,placeholder:`Search skills…`,oninput:e=>{o=e.target.value.trim().toLowerCase(),d()}}),a=[],o=``,c=null;l(),u();function l(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Skills`),e(`p.page-sub`,`What Archie can do, in plain language.`)),e(`div.page-actions`,e(`button.btn`,{onclick:u},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Catalogue`),e(`p.card-sub`,`Project, shared, and user-global skills`)),i),r)),d()}async function u(){try{a=(await m.skills())?.skills||[],c=null}catch(e){a=[],c=String(e.message||e)}d()}function d(){if(c)return n(r,s(`Cannot reach archied`,c));if(!a.length)return n(r,s(`No skills discovered yet`,`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`));let e=a.filter(e=>f(e,o));if(!e.length)return n(r,s(`No skills match`,`Nothing found for "${o}".`));n(r,...e.map(p))}function f(e,t){return!t||`${e.name} ${e.description}`.toLowerCase().includes(t)}function p(t){return e(`div.card.skill-card`,e(`div.card-head`,e(`h3.card-title`,t.name||`Untitled skill`),t.workflow&&e(`span.pill.pill-info`,t.workflow)),e(`p.skill-desc`,t.description||`No description provided.`),e(`div.skill-source`,t.source||`Unknown source`))}return t}var H={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function U(e){return H[e]?H[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function W(e,t){return t?Math.round(e/t*100):0}function G(t,n=`ok`){return e(`div.wf-bar`,e(`div.wf-bar-fill.wf-bar-${n}`,{style:`width:${Math.min(100,Math.max(0,t))}%`}))}function ee(e){if(!e)return`—`;if(e<1e3)return`${e} ms`;let t=e/1e3;return t<60?`${t.toFixed(1)} s`:`${(t/60).toFixed(1)} min`}function te(){let t=e(`div`),r=e(`div`),i=e(`div`),a=e(`div`);o(),c();function o(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Workflows`),e(`p.page-sub`,`Run outcomes and spend per workflow, and where stages get stuck.`)),e(`div.page-actions`,e(`button.btn`,{onclick:c},`Refresh`))),a,r,i)}async function c(){try{let e=await m.workflows();l(e?.definitions||[]),u(e?.workflows||[],e?.definitions||[]),d(e?.stages||[])}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(i)}}function l(t){if(!t.length){n(a);return}let r=e(`input`,{placeholder:`Identity`,required:!0}),i=e(`input`,{placeholder:`owner/repository`,required:!0}),o=e(`select`,{required:!0},...t.filter(e=>e.enabled).map(t=>e(`option`,{value:t.id},U(t.name||t.id)))),s=e(`input`,{placeholder:`Short task title`,required:!0}),c=e(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3}),l=e(`p.card-sub`),u=e(`button.btn`,{type:`submit`},`Start work`),d=e(`form.wf-form`,{onsubmit:async e=>{e.preventDefault(),u.disabled=!0;try{let e=await m.workRequest({identity:r.value,repository:i.value,workflow:o.value,title:s.value,instructions:c.value});l.textContent=`Queued task #${e.task_id}.`,d.reset()}catch(e){l.textContent=String(e.message||e)}finally{u.disabled=!1}}},r,i,o,s,c,u,l);n(a,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Start work`),e(`p.card-sub`,`This enters Archie’s normal admitted task queue.`))),d))}function u(t,i){let a=new Map(t.map(e=>[e.workflow,e])),o=i.map(e=>({...e,...a.get(e.id)||{workflow:e.id,runs:0,merged:0}}));if(!o.length){n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`))),s(`No workflow runs yet`,`Stats appear here once a task has run through a workflow.`)));return}n(r,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per workflow`),e(`p.card-sub`,`Success rate is merged tasks over all runs`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Origin`,`Runs`,`Success rate`,`Avg tokens`,`Avg steps`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>{let n=W(t.merged,t.runs);return e(`tr`,e(`td.strong`,U(t.workflow)),e(`td.mono`,t.origin||`registry`),e(`td`,`${t.runs} run${t.runs===1?``:`s`}`),e(`td`,e(`div.wf-rate`,`${n}%`,e(`span.wf-rate-sub`,`${t.merged} of ${t.runs} merged`)),G(n,n>=50?`ok`:`warn`)),e(`td.mono`,t.avg_tokens?t.avg_tokens.toLocaleString():`—`),e(`td.mono`,t.avg_steps?t.avg_steps.toFixed(1):`—`))}))))))}function d(t){if(!t.length){n(i,e(`div.card.wf-stage-card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Per stage`))),s(`No stage data yet`,`Stage timing and failures appear here once workflows have run.`)));return}let r=Math.max(...t.map(e=>e.avg_ms||0),1),a=[...t].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),o=[...t].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);n(i,e(`div.grid.grid-2.wf-stage-card`,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Slowest stages`),e(`p.card-sub`,`Average duration, this workflow's stages`))),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Runs`,`Avg duration`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,`${t.runs}`),e(`td`,e(`div.wf-rate`,ee(t.avg_ms)),G(W(t.avg_ms,r),`info`)))))))),e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Most failures`),e(`p.card-sub`,`Stages that error out, over their runs`))),o.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Workflow`,`Stage`,`Failures`].map(t=>e(`th`,t)))),e(`tbody`,...o.map(t=>e(`tr`,e(`td`,U(t.workflow)),e(`td.strong`,t.stage),e(`td`,e(`div.wf-rate`,`${t.errors} of ${t.runs}`),G(W(t.errors,t.runs),`danger`))))))):s(`No failures recorded`,`Every stage has completed cleanly so far.`))))}return t}function ne(){let t=e(`div`),i=e(`div.grid.grid-2`);a(),o();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Channels`),e(`p.page-sub`,`The conversational front-ends Archie can be reached through.`)),e(`div.page-actions`,e(`button.btn`,{onclick:o},`Refresh`))),i)}async function o(){try{c((await m.channels())?.channels||[])}catch(e){n(i,s(`Cannot reach archied`,String(e.message||e)))}}function c(e){if(!e.length){n(i,s(`No channels configured`,`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`));return}n(i,...e.map(l))}function l(t){return e(`div.card.channel-card`,e(`div.card-head`,e(`h3.card-title`,t.name),r(t.state||(t.configured?`configured`:`stopped`),re(t.state,t.configured))),e(`p.channel-desc`,t.description),e(`p.channel-detail`,t.detail),t.reload_supported?e(`button.btn`,{onclick:async e=>{e.currentTarget.disabled=!0;try{await m.channelReload(t.id||t.name.toLowerCase()),await o()}catch{e.currentTarget.disabled=!1}}},`Reload`):e(`p.channel-detail`,`Reload requires a daemon restart for this adapter.`))}return t}function re(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function ie(e){return e==null||e===``?`—`:String(e)}function K(t,n,r){let i=ie(n),a=e(`span.kv-label`,t),o=e(`span.kv-value.mono${i===`—`?`.is-empty`:``}`,{title:i},i);if(!r?.key)return e(`div.kv`,a,o);let s=r.locked?.[r.key];if(s)return e(`div.kv.is-locked`,a,o,e(`span.kv-note`,s));let c=r.overridden?.includes(r.key),l=e(`button.kv-btn`,{type:`button`,title:`Edit ${t}`},`Edit`),u=c?e(`button.kv-btn`,{type:`button`,title:`Discard the dashboard value and fall back to the config file`},`Reset`):null,d=e(`div.kv-actions`,c&&e(`span.kv-flag`,{title:`Set from the dashboard; this shadows the value in the config file`},`overridden`),l,u),f=e(`div.kv`,a,o,d);return l.addEventListener(`click`,()=>se(f,t,r,[a,o,d])),u?.addEventListener(`click`,()=>ae(f,u,r)),f}function ae(e,t,n){let{key:r,onSaved:i}=n;t.disabled=!0,m.configReset(r).then(()=>i?.()).catch(n=>{t.disabled=!1,oe(e,String(n.message||n))})}function oe(t,n){let r=t.querySelector?.(`.kv-note`);r||(r=e(`span.kv-note.is-error`),t.appendChild(r)),r.classList.add(`is-error`),r.textContent=n}function se(t,r,i,a){let{key:o,type:s,raw:c,onSaved:l}=i,u=s===`bool`?e(`select.kv-input`,e(`option`,{value:`true`,selected:c===!0},`true`),e(`option`,{value:`false`,selected:c===!1},`false`)):e(`input.kv-input`,{type:`text`,value:String(c??``)}),d=e(`button.kv-save`,{type:`button`},`Save`),f=e(`button.kv-cancel`,{type:`button`},`Cancel`),p=e(`span.kv-note.is-error`);n(t,e(`span.kv-label`,r),u,e(`div.kv-actions`,d,f),p),u.focus?.(),u.select?.();let h=()=>n(t,...a);f.addEventListener(`click`,h),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault?.(),d.click()),e.key===`Escape`&&h()}),d.addEventListener(`click`,async()=>{let e=ce(s,u.value);if(e.error){p.textContent=e.error;return}d.disabled=!0;try{await m.configUpdate({[o]:e.value}),l?.()}catch(e){p.textContent=String(e.message||e),d.disabled=!1}})}function ce(e,t){switch(e){case`int`:{let e=parseInt(t,10);return Number.isNaN(e)?{error:`Enter a whole number`}:{value:e}}case`bool`:return{value:t===`true`};default:return{value:t}}}var le={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ue={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function de(t){return t.length?fe(`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Component`,`Install type`,`Running`,`Latest available`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,{title:[`Installed claim: ${t.installed_claim||`unknown`}`,`Running: ${t.running_version||`not observed`}`,t.reference?`Reference: ${t.reference}`:null].filter(Boolean).join(` +`)},e(`td.strong`,t.label||t.id),e(`td.mono`,t.install_type||`—`),e(`td.mono`,t.running_version||`—`),e(`td.mono`,t.latest_available||`—`),e(`td`,r(le[t.status]||t.status,ue[t.status]||`idle`)))))))):fe(`How each component is deployed, and whether what's running matches what's installed.`,s(`No components reported`,`The configured update-check command returned nothing.`))}function fe(t,...n){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Update status`),e(`p.card-sub`,t))),...n)}function pe(){let t=e(`div.cfg-page`),r=e(`div`),i=e(`div`);a(),o(),c();function a(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Configuration`),e(`p.page-sub`,`What archied is actually running with right now.`)),e(`div.page-actions`,e(`button.btn`,{onclick:()=>{o(),c()}},`Refresh`))),i,r)}async function o(){try{l(await m.config(),o)}catch(t){n(r,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}async function c(){try{let e=await m.version();n(i,de(e?.components||[]))}catch(t){if(t?.status===501){n(i);return}n(i,e(`div.card`,s(`Update status unavailable`,String(t.message||t))))}}function l(t,i){if(!t||Object.keys(t).length===0){n(r,e(`div.card`,s(`No configuration loaded`,`archied is running without a config file wired into the dashboard, so there is nothing to show.`)));return}let a={locked:t.locked||{},overridden:t.overridden||[],onSaved:i},o=[t.reload?.overlay_unavailable&&e(`div.card.cfg-notice`,e(`p`,`The runtime config overlay is not in effect: ${t.reload.overlay_unavailable}`)),t.reload?.last_error&&e(`div.card.cfg-notice`,e(`p`,`The last config reload failed; the running config is unchanged: ${t.reload.last_error}`))];n(r,...o,he(t.identity,a),ge(t.repositories),ve(t.models,t.providers),be(t.budgets,a),xe(t.agent,a),Ce(t.storage,t.containers,a),Te(t.web,a),me(t.provenance))}return t}function me(t){return t?.length?q(`Configuration sources`,`Applied from top to bottom; later entries take precedence over earlier ones.`,e(`div.kv-list`,...t.map(e=>K(`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,e.path)))):q(`Configuration sources`,`The files that supplied the running configuration.`,s(`Source provenance is unavailable.`))}function q(t,n,...r){return e(`div.card.cfg-section`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t),e(`p.card-sub`,n))),...r)}function he(t,n){return t?q(`Identity`,`Who Archie is on the forge, and how it addresses commits and comments.`,e(`div.kv-list`,K(`Bot account`,t.bot_user,{key:`bot_user`,type:`string`,raw:t.bot_user,...n}),K(`Commit author email`,t.bot_email,{key:`bot_email`,type:`string`,raw:t.bot_email,...n}),K(`Pickup label`,t.label,{key:`label`,type:`string`,raw:t.label,...n}),K(`Forge type`,t.forge_type,{key:`forge.type`,type:`string`,raw:t.forge_type,...n}),K(`Forge host`,t.forge_host,{key:`forge.host`,type:`string`,raw:t.forge_host,...n}),K(`Max diff size (lines)`,t.diff_cap_lines||`Unlimited`,{key:`diff_cap_lines`,type:`int`,raw:t.diff_cap_lines,...n}))):q(`Identity`,`Who Archie is on the forge.`,s(`Not available`))}function ge(t){return t?.length?q(`Repositories`,`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Repository`,`Base branch`,`Ecosystem`,`Quality gate`,`Protected paths`].map(t=>e(`th`,t)))),e(`tbody`,...t.map(t=>e(`tr`,e(`td.strong`,`${t.owner}/${t.name}`),e(`td.mono`,t.base),e(`td`,t.ecosystem||`go`),e(`td.mono`,_e(t.gate)),e(`td.mono`,t.protect?.length?t.protect.join(`, `):`—`))))))):q(`Repositories`,`The repositories Archie polls for work.`,s(`No repositories configured`,`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`))}function _e(e){return e?.length?e.map(e=>e.join(` `)).join(` → `):`—`}function ve(t,n){let i=Object.entries(t||{}),a=Object.entries(n||{}),o=i.length?e(`div.kv-list`,...i.map(([e,t])=>K(ye(e),t))):s(`No model roles configured`,`Assign a model to at least one role (e.g. "builder") in [models].`),c=a.length?e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Provider`,`Class`,`Base URL`,`API key env var`,`Status`].map(t=>e(`th`,t)))),e(`tbody`,...a.map(([t,n])=>e(`tr`,e(`td.strong`,t),e(`td`,n.class),e(`td.mono`,n.base_url||`default`),e(`td.mono`,n.api_key_env||`—`),e(`td`,n.configured?r(`configured`,`ok`):r(`missing credentials`,`warn`))))))):s(`No providers configured`,`Add a [providers.] entry so a model role above has something to run on.`);return q(`Models & providers`,`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,e(`h3.cfg-subhead`,`Model roles`),o,e(`h3.cfg-subhead`,`Providers`),c)}function ye(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function be(t,n){return t?q(`Budgets`,`The limits every autonomous stage runs under, so a stuck task cannot run forever.`,e(`div.kv-list`,K(`Max steps`,t.max_steps||`Unlimited`,{key:`budgets.max_steps`,type:`int`,raw:t.max_steps,...n}),K(`Max tokens`,t.max_tokens||`Unlimited`,{key:`budgets.max_tokens`,type:`int`,raw:t.max_tokens,...n}),K(`Wall clock`,t.wall_clock,{key:`budgets.wall_clock`,type:`string`,raw:t.wall_clock,...n}),K(`Max gate failures before parking`,t.gate_max_failures||`Unlimited`,{key:`budgets.gate_max_failures`,type:`int`,raw:t.gate_max_failures,...n}))):q(`Budgets`,`Limits on every agent stage.`,s(`Not available`))}function xe(t,n){return t?q(`Agent execution`,`How archied actually runs a stage of work.`,e(`div.kv-list`,K(`Execution mode`,Se(t.mode),{key:`agent.mode`,type:`string`,raw:t.mode,...n}),K(`Worker command`,t.command,{key:`agent.command`,type:`string`,raw:t.command,...n}),K(`Extra environment variables passed through`,t.env?.length?t.env.join(`, `):`None`))):q(`Agent execution`,`How Archie runs autonomous stages.`,s(`Not available`))}function Se(e){switch(e){case`inprocess`:return`In-process (same binary as the daemon)`;case`subprocess`:return`Subprocess (separate archie-agent process)`;case`nats`:return`NATS (dispatched to a worker over the message bus)`;default:return e||`Not set`}}function Ce(t,n,r){let i=[];return t&&i.push(e(`h3.cfg-subhead`,`Paths`),e(`div.kv-list`,K(`Work directory`,t.work_dir,{key:`work_dir`,type:`string`,...r}),K(`State path prefix`,t.db_path,{key:`db_path`,type:`string`,...r}),K(`Shared skills directory`,t.skills_dir||`None (uses the work directory)`,{key:`skills_dir`,type:`string`,raw:t.skills_dir,...r}),K(`Daemon plugin directory`,t.plugin_dir||`None`,{key:`plugin_dir`,type:`string`,raw:t.plugin_dir,...r}),K(`Secret engine plugin directory`,t.secret_engine_dir||`None (built-in engines only)`,{key:`secret_engine_dir`,type:`string`,raw:t.secret_engine_dir,...r}))),n&&i.push(e(`h3.cfg-subhead`,`Sandboxed containers`),e(`div.kv-list`,K(`Sandboxing enabled`,n.enabled?`Yes`:`No`,{key:`containers.enabled`,type:`bool`,raw:n.enabled,...r}),K(`Agent image`,n.image||`Not set`,{key:`containers.image`,type:`string`,raw:n.image,...r}),K(`Max concurrent tasks`,n.max_concurrency||`Unlimited`,{key:`containers.max_concurrency`,type:`int`,raw:n.max_concurrency,...r}),K(`Container max lifetime`,n.max_uptime,{key:`containers.max_uptime`,type:`string`,raw:n.max_uptime,...r}),K(`Persistent volume retention`,n.volume_ttl,{key:`containers.volume_ttl`,type:`string`,raw:n.volume_ttl,...r}),K(`How images are refreshed`,we(n.pull_policy),{key:`containers.pull_policy`,type:`string`,raw:n.pull_policy,...r}),K(`Docker network`,n.network||`Auto-detected`,{key:`containers.network`,type:`string`,raw:n.network,...r}))),i.length||i.push(s(`Not available`)),q(`Storage & sandboxing`,`Where archied keeps its state, and how it isolates task execution.`,...i)}function we(e){return e===`always`?`Always pull the latest image before running`:`Only pull when the image is missing locally`}function Te(t,n){return t?q(`Dashboard`,`This dashboard's own listen address.`,e(`div.kv-list`,K(`Listen address`,t.listen===`off`?`Disabled`:t.listen,{key:`web.listen`,type:`string`,raw:t.listen===`off`?``:t.listen,...n}))):q(`Dashboard`,`This dashboard's own listen address.`,s(`Not available`))}var Ee=[{value:``,label:`All levels`},{value:`ERROR`,label:`Errors`},{value:`WARN,ERROR`,label:`Warnings and errors`},{value:`INFO,WARN,ERROR`,label:`Info and above`},{value:`DEBUG`,label:`Debug only`}];function De(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Oe(){let t=e(`div`),i=e(`div.log-list`),a=r(`connecting`,`idle`),o=e(`span.log-meta`),c={level:``,component:``,q:``},l=!1,u=[],d=[],f=new Map,p=!1,h=e(`select.log-select`,{onchange:e=>x({level:e.target.value})},...Ee.map(t=>e(`option`,{value:t.value},t.label))),_=e(`select.log-select`,{onchange:e=>x({component:e.target.value})}),v=e(`input.log-search`,{type:`search`,placeholder:`Search messages and fields…`,oninput:Pe(e=>x({q:e.target.value}),250)}),y=e(`button.btn`,{onclick:S},`Pause`);C();let b=g(e=>E(e),e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,b),w();function x(e){c={...c,...e},w()}function S(){l=!l,y.textContent=l?`Resume`:`Pause`,y.classList.toggle(`btn-primary`,l)}function C(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Logs`),e(`p.page-sub`,`What Archie has been doing, newest last.`)),e(`div.page-actions`,y,e(`button.btn`,{onclick:w},`Refresh`))),e(`div.card`,e(`div.card-head`,e(`div.log-filters`,h,_,v),e(`div.log-status`,o,a)),i))}async function w(){o.textContent=`Refreshing…`;try{let e=await m.logs({level:c.level,component:c.component,q:c.q,limit:500});T(e.components||[]),p=!!e.disabled,o.textContent=e.disabled?`Durable history unavailable; live daemon logs continue.`:e.truncated?`showing the most recent matches from ${e.file}`:e.file||``,d=e.entries||[],D()}catch(e){n(i,s(`Cannot read logs`,String(e.message||e)))}}function T(t){if(Ne(t,u))return;u=t;let r=c.component;n(_,e(`option`,{value:``},`All components`),...t.map(t=>e(`option`,{value:t},t))),_.value=r}function E(e){if(l)return;let t=e;O(t)&&(f.set(ke(t),t),t.fields?.component&&T([...u,t.fields.component]),D())}function D(){let e=new Map;for(let t of d)e.set(ke(t),t);for(let[t,n]of f)e.set(t,n);let t=[...e.values()].filter(O).slice(-1e3);if(!t.length){n(i,s(p?`Durable history unavailable`:`Nothing matches`,p?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`));return}n(i,...t.map(Ae)),i.scrollTop=i.scrollHeight}function O(e){if(c.level&&!c.level.split(`,`).includes((e.level||``).toUpperCase())||c.component&&e.fields?.component!==c.component)return!1;if(c.q){let t=c.q.toLowerCase();if(!`${e.message||e.msg||``} ${JSON.stringify(e.fields||{})}`.toLowerCase().includes(t))return!1}return!0}return t}function ke(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Ae(t){let n=t.fields||{};return e(`div.log-row.log-${De(t.level)}`,e(`span.log-time.mono`,Me(t.time)),e(`span.log-level`,(t.level||`info`).toUpperCase()),e(`span.log-body`,e(`span.log-msg`,t.message||t.msg||``),...Object.entries(n).map(([t,n])=>e(`span.log-field`,e(`span.log-field-key`,t),String(je(n))))))}function je(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function Me(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function Ne(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function Pe(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}function Fe(t,{expanded:n,onToggle:i}){let o=e(`tr.capture-row`,{tabindex:`0`,"aria-expanded":String(n),onclick:i,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i(e))}},e(`td.mono`,t.source||`(unknown)`),e(`td`,{title:t.received_at||``},a(t.received_at)),e(`td`,r(`Unbound`,`idle`)),e(`td.mono`,t.content_type||`—`),e(`td`,e(`button.btn.btn-small`,{type:`button`},n?`Hide`:`View`)));return n?[o,Ie(t)]:[o]}function Ie(t){return e(`tr.capture-detail-row`,e(`td`,{colspan:5},e(`div.capture-detail`,e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Payload`),Le(t.body)),e(`div.capture-detail-section`,e(`div.capture-detail-title`,`Headers`),Le(t.headers)))))}function Le(t){return t?e(`pre.capture-payload`,Re(t)):e(`div.capture-empty`,`(empty)`)}function Re(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function ze(){let t=e(`div`),i=e(`div.card`),a=r(`connecting`,`idle`),o=[],c=null,l=null,u=!0;p(),f();let d=h(e=>{e.kind===`capture`&&f()},e=>{a.className=`pill pill-${e===`live`?`ok`:`warn`}`,a.textContent=e});t.addEventListener(`archie:teardown`,d);async function f(){try{let e=await m.captures(100);u=e.enabled!==!1,o=e.captures||[],l=null}catch(e){l=String(e.message||e)}g()}function p(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Event inspector`),e(`p.page-sub`,`Real inbound payloads archie has captured, most recent first.`)),e(`div.page-actions`,a,e(`button.btn`,{onclick:f},`Refresh`))),i),g()}function g(){if(l){n(i,s(`Cannot reach archied`,l));return}if(!u){n(i,s(`Capture is not configured`,`This deployment has no capture storage wired up.`));return}if(!o.length){n(i,s(`No captures yet`,`Point a webhook at /webhooks/capture/ and it will show up here.`));return}n(i,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Source`,`Received`,`Binding`,`Content type`,``].map(t=>e(`th`,t)))),e(`tbody`,...o.flatMap(e=>Fe(e,{expanded:c===e.id,onToggle:()=>{c=c===e.id?null:e.id,g()}}))))))}return t}var Be=[`string`,`number`,`bool`,`object`,`array`,`any`];function Ve(e){if(e==null)return`any`;if(Array.isArray(e))return`array`;switch(typeof e){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`bool`;case`object`:return`object`;default:return`any`}}function He(e,t){return e?`${e}.${t}`:t}function Ue(e,t){return`${e}[${t}]`}function We(t,{path:n=``,name:r=``,onPick:i}={}){return typeof t==`object`&&t?e(`ul.mapping-tree-list`,...(Array.isArray(t)?t.map((e,t)=>[String(t),e,Ue(n,t)]):Object.entries(t).map(([e,t])=>[e,t,He(n,e)])).map(([t,n,r])=>e(`li.mapping-tree-item`,e(`span.mapping-tree-key`,{onclick:e=>{e.stopPropagation(),i?.({path:r,type:Ve(n),name:t})}},t),We(n,{path:r,name:t,onPick:i})))):e(`span.mapping-tree-value`,{onclick:e=>{e.stopPropagation(),i?.({path:n,type:Ve(t),name:r})}},JSON.stringify(t))}function Ge(t,{preview:n,onRemove:r,onNameChange:i,onTypeChange:a,onRequiredChange:o}={}){if(!t.length)return e(`div.mapping-empty-fields`,`Click a value in the payload to bind a field.`);let s=new Map((n?.failures||[]).map(e=>[e.field_name,e]));return e(`table.table.mapping-fields-table`,e(`thead`,e(`tr`,...[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map(t=>e(`th`,t)))),e(`tbody`,...t.map((t,c)=>e(`tr`,e(`td`,e(`input.mapping-input`,{value:t.name,oninput:e=>i?.(c,e.target.value)})),e(`td.mono`,t.path),e(`td`,e(`select.mapping-select`,{onchange:e=>a?.(c,e.target.value)},...Be.map(n=>e(`option`,{value:n,selected:n===t.type},n)))),e(`td`,e(`input`,{type:`checkbox`,checked:t.required,onchange:e=>o?.(c,e.target.checked)})),e(`td`,Ke(t,n,s)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(c)},`Remove`))))))}function Ke(e,t,n){if(!t)return r(`not previewed`,`idle`);let i=n.get(e.name);return i?r(i.reason,`danger`):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?r(JSON.stringify(t.values[e.name]),`ok`):r(`skipped (optional)`,`idle`)}function qe(t,{onEdit:n,onDelete:r}){return e(`tr`,e(`td`,t.name),e(`td.mono`,t.source_hint||`—`),e(`td`,String(t.fields?.length??0)),e(`td`,e(`button.btn.btn-small`,{type:`button`,onclick:()=>n?.(t)},`Edit`),e(`button.btn.btn-small`,{type:`button`,onclick:()=>r?.(t)},`Delete`)))}function Je(){let t=e(`div`),r=[],i=[],a=null,o=null;C(),c();async function c(){try{let[e,t]=await Promise.all([m.mappings(),m.captures(100)]);r=e.mappings||[],i=t.captures||[],a=null}catch(e){a=String(e.message||e)}C()}function l(){o={id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}function u(e){o={id:e.id,name:e.name,sourceHint:e.source_hint||``,fields:(e.fields||[]).map(e=>({...e})),captureId:null,payload:null,payloadError:null,preview:null,actionError:null},C()}async function d(e){if(window.confirm(`Delete mapping "${e.name}"?`))try{await m.mappingDelete(e.id),await c()}catch(e){a=String(e.message||e),C()}}function f(e){let t=i.find(t=>String(t.id)===String(e));if(o.captureId=t?t.id:null,o.preview=null,!t)o.payload=null,o.payloadError=null;else try{o.payload=JSON.parse(t.body),o.payloadError=null}catch{o.payload=null,o.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}C()}function p({path:e,type:t,name:n}){let r=new Set(o.fields.map(e=>e.name)),i=n||`field`,a=1;for(;r.has(i);)i=`${n||`field`}_${++a}`;o.fields.push({name:i,path:e,type:t,required:!0}),o.preview=null,C()}function h(e){o.fields.splice(e,1),o.preview=null,C()}function g(e,t){Object.assign(o.fields[e],t),o.preview=null,C()}let _=(e,t)=>g(e,{name:t}),v=(e,t)=>g(e,{type:t}),y=(e,t)=>g(e,{required:t});async function b(){if(!o.captureId){o.actionError=`Pick a captured event to preview against.`,C();return}try{o.preview=await m.mappingPreview(o.captureId,o.fields),o.actionError=null}catch(e){o.actionError=String(e.message||e)}C()}async function x(){let e={name:o.name,source_hint:o.sourceHint,fields:o.fields};try{o.id?await m.mappingUpdate(o.id,e):await m.mappingCreate(e),o=null,await c()}catch(e){o.actionError=String(e.message||e),C()}}function S(){o=null,C()}function C(){n(t,o?T():w())}function w(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Field mappings`),e(`p.page-sub`,`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`)),e(`div.page-actions`,e(`button.btn.btn-primary`,{type:`button`,onclick:l},`New mapping`))),a?s(`Cannot reach archied`,a):r.length?e(`div.card`,e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Name`,`Source hint`,`Fields`,``].map(t=>e(`th`,t)))),e(`tbody`,...r.map(e=>qe(e,{onEdit:u,onDelete:d})))))):s(`No mappings yet`,`Create one from a captured event to reuse fields in a future playbook binding.`))}function T(){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,o.id?`Edit mapping`:`New mapping`)),e(`div.page-actions`,e(`button.btn`,{type:`button`,onclick:S},`Cancel`),e(`button.btn.btn-primary`,{type:`button`,onclick:x},`Save`))),o.actionError?e(`div.mapping-error`,o.actionError):null,e(`div.card.mapping-form`,e(`label.mapping-form-row`,`Name`,e(`input.mapping-input`,{value:o.name,oninput:e=>{o.name=e.target.value}})),e(`label.mapping-form-row`,`Source hint (organisational only)`,e(`input.mapping-input`,{value:o.sourceHint,oninput:e=>{o.sourceHint=e.target.value}})),e(`label.mapping-form-row`,`Preview against captured event`,e(`select.mapping-select`,{onchange:e=>f(e.target.value)},e(`option`,{value:``},`— pick a captured event —`),...i.map(t=>e(`option`,{value:t.id,selected:String(o.captureId)===String(t.id)},`${t.source||`(unknown)`} — ${t.received_at||``}`))))),e(`div.card.mapping-fields`,e(`div.mapping-section-title`,`Bound fields`),Ge(o.fields,{preview:o.preview,onRemove:h,onNameChange:_,onTypeChange:v,onRequiredChange:y}),e(`button.btn`,{type:`button`,onclick:b},`Preview`)),e(`div.card.mapping-payload`,e(`div.mapping-section-title`,`Payload — click a value to bind it`),o.payloadError?e(`div.mapping-error`,o.payloadError):o.payload===null?e(`div.mapping-empty-fields`,`Pick a captured event above to see its payload.`):We(o.payload,{onPick:p})))}return t}function Ye(){let t=e(`div`),r=e(`div`);i(),a();function i(){n(t,e(`div.page-head`,e(`div`,e(`h1.page-title`,`Memory`),e(`p.page-sub`,`What Archie can recall between conversations, and the tools it uses to do it.`)),e(`div.page-actions`,e(`button.btn`,{onclick:a},l(`refresh`,{size:15}),`Refresh`))),r)}async function a(){n(r,e(`div.card`,e(`div.mem-loading`,`Loading…`)));try{let t=await m.memory();if(!t.enabled||!t.providers?.length){n(r,e(`div.card`,s(`Memory is not configured`,`Without a provider, Archie starts every conversation with no recollection of earlier ones.`)));return}n(r,e(`div.grid.grid-2`,...t.providers.map(Xe)))}catch(t){n(r,e(`div.card`,s(`Cannot read memory providers`,String(t.message||t))))}}return t}function Xe(t){let n=t.tools||[];return e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,t.name||`provider`),e(`p.card-sub`,Ze(t.role))),t.available?r(`ready`,`ok`):r(`unavailable`,`danger`)),!t.available&&e(`p.mem-warning`,`Configured but not usable right now — a required binary or connection may be missing.`),n.length?e(`ul.mem-tools`,...n.map(t=>e(`li.mem-tool`,e(`div.mem-tool-name.mono`,t.name),t.description&&e(`div.mem-tool-desc`,t.description)))):e(`p.mem-warning`,`This provider exposes no tools, so the agent cannot use it.`))}function Ze(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}var Qe=`
ARCHIE WORKSPACE

Chat

@@ -71,10 +72,10 @@
-`;function Ye(){let e=document.createElement(`template`);e.innerHTML=Je.trim();let t=e.content.firstElementChild,n={};for(let e of t.querySelectorAll(`[data-chat-ref]`))n[e.dataset.chatRef]=e;return{root:t,refs:n}}function J(t){let n=document.createDocumentFragment(),r=/(~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\(https?:\/\/[^\s)]+\)|\*[^*]+\*|_[^_]+_)/g,i=0;for(let a of t.matchAll(r)){a.index>i&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return ii&&n.append(document.createTextNode(t.slice(i,a.index)));let r=a[0];if(r.startsWith(`~~`))n.append(e(`del`,r.slice(2,-2)));else if(r.startsWith(`**`)||r.startsWith(`__`))n.append(e(`strong`,r.slice(2,-2)));else if(r.startsWith("`"))n.append(e(`code`,r.slice(1,-1)));else if(r.startsWith(`[`)){let t=r.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)$/);n.append(e(`a`,{href:t[2],target:`_blank`,rel:`noreferrer`},t[1]))}else n.append(e(`em`,r.slice(1,-1)));i=a.index+r.length}return i{i.length&&(n.append(e(`p`,J(i.join(` `)))),i=[])},c=()=>{a&&n.append(a),a=null};for(let t=0;te(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` -`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function Ze(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function Qe(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function $e(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function et(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?Xe(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=Xe(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function tt(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),nt(t).append(o),o}function nt(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var rt=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(rt);return e||(e=crypto.randomUUID(),localStorage.setItem(rt,e)),e}function it(e){return{text:e,sourceID:crypto.randomUUID()}}function at(e){return{...e}}function ot(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?at(e.turn):it(r),isRetry:n}}function st({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,Qe(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ct(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,lt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function lt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function ut(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function dt(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function ft(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function pt(e){return e?.status===501?null:`Could not check for updates.`}function mt(){let{root:t,refs:n}=Ye(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(et(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1,_.children[A]?.scrollIntoView({block:`nearest`})}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,dt(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),dt(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=pt(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{ft(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,ct({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=ut(y,e.commands),st({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,st({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=ot(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:$e();l||i.append(u),u.querySelector(`.chat-retry`)?.remove(),u.querySelector(`.chat-tools`)?.replaceChildren();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` +`)))),o=null):o=[];continue}if(o){o.push(l);continue}let u=Y(l),d=t+1e(`td`,J(t)))));n.append(e(`table`,e(`thead`,e(`tr`,...u.map(t=>e(`th`,J(t))))),a));continue}if(!l.trim()){s(),c();continue}let f=l.match(/^(#{1,3})\s+(.+)$/);if(f){s(),c(),n.append(e(`h${f[1].length}`,J(f[2])));continue}let p=l.match(/^\s*[-*]\s+(.+)$/),m=l.match(/^\s*\d+[.)]\s+(.+)$/);if(p||m){s();let t=m?`ol`:`ul`;(!a||a.tagName.toLowerCase()!==t)&&(c(),a=e(t)),a.append(e(`li`,J((p||m)[1])));continue}if(l.startsWith(`>`)){s(),c(),n.append(e(`blockquote`,J(l.replace(/^>\s?/,``))));continue}i.push(l)}return s(),c(),o&&n.append(e(`pre`,e(`code`,o.join(` +`)))),n}function Y(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function tt(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}function nt(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function rt(){return e(`div.chat-bubble-row.assistant`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,`Archie`),e(`div.chat-tools`),e(`div.chat-bubble-text`)))}function it(t){let n=t.from??t.From??``,r=t.text??t.Text??``,i=n!==`web`;return e(`div.chat-bubble-row.${i?`assistant`:`user`}`,e(`div.chat-bubble`,e(`div.chat-bubble-meta`,i?`Archie`:`You`),i?et(r):e(`div.chat-bubble-text`,r)))}function X(e,t){let n=et(t);return typeof e?.replaceWith==`function`?e.replaceWith(n):e?.parentNode&&e.parentNode.replaceChild(n,e),n}function at(t,n){let r=n?.tool??``;if(!t||!r)return null;let i=n.parameters??``,a=n.text??``,o=e(`div.chat-tool`,e(`span.chat-tool-icon`,`🔧`),e(`span.chat-tool-name`,r),i&&e(`code.chat-tool-parameters`,i),e(`span.chat-tool-summary`,a));return n.failed&&(o.className=`chat-tool failed`),ot(t).append(o),o}function ot(t){let n=t.querySelector(`.chat-tools`);if(n)return n;let r=e(`div.chat-tools`);return t.append(r),r}var st=`archie.web.chat.channel`;function Z(){let e=localStorage.getItem(st);return e||(e=crypto.randomUUID(),localStorage.setItem(st,e)),e}function ct(e){return{text:e,sourceID:crypto.randomUUID()}}function lt(e){return{...e}}function ut(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?lt(e.turn):ct(r),isRetry:n}}function dt({sessionList:t,sessionTools:n,sessions:r,currentSession:i,onSelect:a}){if(t.replaceChildren(),n.hidden=!i,!r.length){t.append(e(`div.chat-empty`,`Your conversations will appear here.`));return}for(let n of r)t.append(e(`button.chat-session`,{class:i===n.session_id?`active`:``,onclick:()=>a(n.session_id)},e(`strong`,nt(n)),e(`span`,new Date(n.last_active_at).toLocaleString())))}function ft(t,n,r){t.persona.replaceChildren(e(`option`,{value:``},`Personality`));for(let r of n.personas||[])t.persona.append(e(`option`,{value:r},r));t.persona.value=n.active_persona||``;let i=n.providers||[];t.provider.hidden=i.length===0,t.provider.replaceChildren(e(`option`,{value:``},`Provider`));for(let n of i)t.provider.append(e(`option`,{value:n},n));t.provider.value=n.active_provider||i[0]||``,pt(t,n,t.provider.value),t.restart.hidden=!n.restart_available,t.dangerousPanel.hidden=!n.dangerous_available,n.dangerous_available&&r()}function pt(t,n,r){let i=n.models_by_provider||{},a=r&&i[r]?i[r]:n.models||[];t.model.replaceChildren(e(`option`,{value:``},`Model`));for(let n of a)t.model.append(e(`option`,{value:n},n));t.model.value=n.active_model||``}function mt(t,n){let r=(n||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e),i=e(`div.chat-command-list`);r.length||i.append(e(`span`,`Send a message to begin.`));for(let t of r)i.append(e(`div.chat-command-item`,e(`code`,t.usage||t.command),e(`span`,t.description||``)));return t.replaceChildren(e(`summary`,`Available commands (${r.length})`),i),r}function ht(t,n,{onDefer:r,onInstall:i}){t.replaceChildren();let a=n?.snapshot||null,o=n?.available||[];if(!o.length){t.append(e(`span`,a?.deferred?`Update deferred.`:`Archie is up to date.`));return}t.append(e(`div`,e(`strong`,`Update available`),e(`span`,o.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `))),e(`div.chat-update-actions`,e(`button.btn`,{onclick:r},`Defer`),n.can_install?e(`button.btn.btn-primary`,{onclick:i},`Install update`):null))}function gt(t,n,{onRequest:r,onDecision:i}){t.replaceChildren();let a=n?.checkpoints||[],o=n?.pending||[],s=e(`select.chat-select`,{"aria-label":`Checkpoint`},e(`option`,{value:``},`Select checkpoint`),...a.map(t=>e(`option`,{value:t.Number??t.number},`${t.Number??t.number} — ${t.Label??t.label??`checkpoint`}`))),c=e(`input.chat-dangerous-input`,{placeholder:`Process name or id`,"aria-label":`Process name or id`}),l=(e,t)=>()=>r(e,String(t.value||t).trim()),u=(t,n,r)=>e(`button.btn`,{onclick:()=>i(t,n)},r),d=o.length?o.map(t=>e(`div.chat-dangerous-pending`,e(`span`,t.description),e(`div.chat-update-actions`,u(t.id,`approve`,`Approve`),u(t.id,`permanent`,`Approve for 24h`),u(t.id,`deny`,`Deny`)))):[e(`span.chat-hint`,`No pending dangerous actions.`)];t.append(e(`div.chat-dangerous-head`,e(`strong`,`Dangerous actions`),e(`span.chat-hint`,`Every action requires approval.`)),e(`div.chat-dangerous-controls`,e(`div`,s,e(`button.btn`,{onclick:l(`rollback`,s)},`Request rollback`)),e(`div`,c,e(`button.btn`,{onclick:l(`stop`,c)},`Request stop`))),e(`div.chat-dangerous-pending-list`,...d))}function _t(e){return e?.status===501?null:`Could not check for updates.`}function vt(){let{root:t,refs:n}=$e(),{sessionList:r,transcript:i,composer:a,send:o,stop:s,status:c,persona:l,provider:u,model:d,restart:f,emptyState:p,updatePanel:h,dangerousPanel:g,commandMenu:_,sessionTools:v,commandHelp:y,checkUpdates:b,newChat:x}=n,S=``,C=[],w=!1,T=null,E=null,D={},O=[],k=[],A=0;f.onclick=()=>{window.confirm(`Reload the Telegram chat adapter?`)&&(a.value=`/restart`,H())},x.onclick=()=>{a.value=`/new`,H()};for(let e of t.querySelectorAll(`[data-chat-prompt]`))e.onclick=()=>{a.value=e.dataset.chatPrompt,a.focus()};function j(e){p.remove(),i.append(it(e)),i.scrollTop=i.scrollHeight}function M(){let e=a.value.slice(0,a.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);return e?e[1].toLowerCase():null}function N(){_.hidden=!0,k=[],A=0}function P(){let t=M();if(t===null){N();return}if(k=O.filter(e=>`${e.command} ${e.description}`.toLowerCase().includes(t)).slice(0,8),!k.length){N();return}A=Math.min(A,k.length-1),_.replaceChildren(...k.map((t,n)=>e(`button.chat-command-option`,{type:`button`,role:`option`,"aria-selected":String(n===A),onmousedown:e=>e.preventDefault(),onclick:()=>F(n)},e(`code`,t.command),e(`span`,t.description||t.usage||``)))),_.hidden=!1,_.children[A]?.scrollIntoView({block:`nearest`})}function F(e){let t=k[e];if(!t)return;let n=a.value.slice(0,a.selectionStart),r=a.value.slice(a.selectionStart),i=n.search(/(?:^|\s)\/[^\s]*$/),o=i<0?n.length:i+ +(n[i]===` `);a.value=`${n.slice(0,o)}${t.command} ${r}`;let s=o+t.command.length+1;a.setSelectionRange(s,s),N(),a.focus()}async function I(){try{let e=await m.chatUpdate();E=e?.snapshot||null,ht(h,e,{onDefer:async()=>{await m.chatUpdateDefer(E),ht(h,{snapshot:{deferred:!0},available:[]},{onDefer:()=>{},onInstall:()=>{}}),c.textContent=`Update deferred`},onInstall:async()=>{c.textContent=`Installing…`,await m.chatUpdateInstall(E),c.textContent=`Update started`,I()}})}catch(t){let n=_t(t);h.replaceChildren(...n?[e(`span`,n)]:[])}}async function L(){try{gt(g,await m.chatDangerous(),{onRequest:async(e,t)=>{if(t)try{await m.chatDangerousRequest(e,t),c.textContent=`Approval requested`,await L()}catch(e){c.textContent=e.message||`Could not request action`}},onDecision:async(e,t)=>{try{await m.chatDangerousDecision(e,t),c.textContent=t===`deny`?`Action denied`:`Action approved`,await L()}catch(e){c.textContent=e.message||`Approval failed`}}})}catch(t){g.replaceChildren(e(`span.chat-hint`,t.message||`Dangerous actions unavailable`))}}async function R(){let e=await m.chatSessions();C=e.sessions||[],D=e,ft({persona:l,provider:u,model:d,restart:f,dangerousPanel:g},e,L),O=mt(y,e.commands),dt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),!S&&C[0]&&await V(C[0].session_id)}async function z(e){if(S)try{c.textContent=`Working…`;let t=await m.chatMessage(Z(),e);t.session_id&&(S=t.session_id),c.textContent=t.reply||`Session updated`,await R(),S&&await V(S),v.open=!1}catch(e){c.textContent=e.message||`Session action failed`}}function B(e,t){let n=window.prompt(t);n?.trim()&&z(`${e} ${n.trim()}`)}async function V(e){S=e,dt({sessionList:r,sessionTools:v,sessions:C,currentSession:S,onSelect:V}),i.replaceChildren(),await m.chatMessage(Z(),`/resume ${e}`),l.value=D.active_personas?.[e]||D.active_persona||``;let t=await m.chatMessages(e);for(let e of t)j(e);i.children.length||i.append(p)}async function H(t=null){let{text:n,turn:r,isRetry:l}=ut(t,a.value);if(!n||w)return;N(),w=!0,o.disabled=!0,s.disabled=!1,a.disabled=!0,c.textContent=l?`Retrying…`:`Thinking…`,l||(j({from:`web`,text:n}),a.value=``);let u=l?t.replyBubble:rt();l||i.append(u),u.querySelector(`.chat-retry`)?.remove(),u.querySelector(`.chat-tools`)?.replaceChildren();let d=u.querySelector(`.chat-bubble-text`),f=``,p=!1,m=!1,h;try{T=new AbortController,h=setTimeout(()=>{m=!0,T.abort()},12e4);let e=await fetch(`/api/chat/stream`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify({channel_id:Z(),source_id:r.sourceID,text:r.text}),signal:T.signal});if(!e.ok)throw Error(await e.text()||`${e.status} ${e.statusText}`);let t=e.body.getReader(),n=new TextDecoder,i=``;for(;;){let{value:e,done:r}=await t.read();i+=n.decode(e||new Uint8Array,{stream:!r});let a=i.split(` `);i=a.pop()||``;for(let e of a){let t=e.split(` -`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&tt(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=at(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{lt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:mt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:we},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Fe},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:We},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ge},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:le}],ht=`archie.theme`;function gt(e){document.documentElement.dataset.theme=e,localStorage.setItem(ht,e)}function $(){return localStorage.getItem(ht)||`dark`}function _t(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{gt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function vt(){gt($());let t=e(`main.main`),r=_t(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):yt(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function yt(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}vt(); \ No newline at end of file +`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(S=n.session_id),n.type===`delta`&&(f+=n.text,d=X(d,f)),n.type===`tool`&&at(u.querySelector(`.chat-bubble`)??u,n),n.type===`done`&&(p=!0,f||(f=n.text,d=X(d,f))),n.type===`error`)throw Error(n.text)}if(r)break}if(!p)throw Error(`chat stream ended before completion`);d.isConnected&&(d=X(d,f)),c.textContent=`Ready`,await R()}catch(t){if(t.name===`AbortError`&&!m)d=X(d,`Turn stopped.`),c.textContent=`Stopped`;else{d=X(d,`Unable to complete that turn: ${t.message||t}`);let n=lt(r),i=e(`button.btn.chat-retry`,{type:`button`,onclick:()=>H({turn:n,replyBubble:u})},`Retry`);u.append(i),c.textContent=`Error — retry available`}}finally{clearTimeout(h),T=null,w=!1,o.disabled=!1,s.disabled=!0,a.disabled=!1,a.focus()}}o.onclick=()=>H(),s.onclick=()=>{let e=S;c.textContent=`Stopping…`,e&&m.chatCancel(e).catch(()=>{}),T?.abort()},a.oninput=P,a.onkeydown=e=>{if(!_.hidden&&k.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&k.some(e=>e.command===a.value.trim())){e.preventDefault(),N(),H();return}if(e.key===`ArrowDown`){e.preventDefault(),A=(A+1)%k.length,P();return}if(e.key===`ArrowUp`){e.preventDefault(),A=(A+k.length-1)%k.length,P();return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),F(A);return}if(e.key===`Escape`){e.preventDefault(),N();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())},l.onchange=async()=>{!S||!l.value||(await m.chatPersona(S,l.value),D.active_personas={...D.active_personas||{},[S]:l.value},c.textContent=`Personality: ${l.value}`)},u.onchange=async()=>{pt({model:d},D,u.value),u.value&&await U(`/model --provider ${u.value}`)},d.onchange=async()=>{d.value&&await U(`/model ${d.value}`)};async function U(e){try{let t=await m.chatMessage(Z(),e);c.textContent=t.reply||`Model updated`,await R()}catch(e){c.textContent=`Model update failed: ${e.message||e}`}}b.onclick=I;let W={retry:()=>z(`/retry`),undo:()=>z(`/undo`),title:()=>B(`/title`,`Session title`),branch:()=>B(`/branch`,`Branch name (optional)`),compress:()=>z(`/compress --preview`)};for(let e of t.querySelectorAll(`[data-chat-action]`))e.onclick=W[e.dataset.chatAction];return R().catch(e=>{c.textContent=e.message||`Chat unavailable`}),I(),t}var Q=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:E},{path:`/chat`,label:`Chat`,icon:`chat`,view:vt},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:B},{path:`/logs`,label:`Logs`,icon:`logs`,view:Oe},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:ze},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Je},{path:`/skills`,label:`Skills`,icon:`skills`,view:V},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:te},{path:`/memory`,label:`Memory`,icon:`memory`,view:Ye},{path:`/channels`,label:`Channels`,icon:`channels`,view:ne},{path:`/settings`,label:`Configuration`,icon:`settings`,view:pe}],yt=`archie.theme`;function bt(e){document.documentElement.dataset.theme=e,localStorage.setItem(yt,e)}function $(){return localStorage.getItem(yt)||`dark`}function xt(t){let r=new Map,i=e(`nav.nav`,...[null].flatMap(()=>[...Q.map(n=>{let i=e(`a.nav-item`,{href:`#${n.path}`,onclick:e=>{n.soon?e.preventDefault():t(n.path)},"aria-disabled":n.soon||void 0,title:n.soon?`Coming soon`:void 0},l(n.icon),e(`span.nav-label`,n.label),n.soon&&e(`span.nav-soon`,`soon`));return r.set(n.path,i),i})])),a=e(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{bt($()===`dark`?`light`:`dark`),n(a,l($()===`dark`?`moon`:`sun`))}});n(a,l($()===`dark`?`moon`:`sun`));let o,s=()=>{o?.classList.remove(`is-open`),c.setAttribute(`aria-expanded`,`false`)},c=e(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{o.classList.add(`is-open`),c.setAttribute(`aria-expanded`,`true`),u.focus()}},l(`search`,{size:15})),u=e(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:e=>{if(e.key===`Escape`){s(),e.target.blur();return}if(e.key!==`Enter`)return;let n=e.target.value.trim().toLowerCase(),r=Q.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(t(r.path),e.target.value=``,e.target.blur(),s())}});return o=e(`div.topbar-search`,e(`span.topbar-search-icon`,{"aria-hidden":`true`},l(`search`,{size:15})),c,u),{node:e(`header.topbar`,e(`div.brand`,e(`span.brand-mark`,`A`),`Archie`),i,e(`div.topbar-end`,o,e(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},l(`help`)),a,e(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,n]of r)t===e?n.setAttribute(`aria-current`,`page`):n.removeAttribute(`aria-current`)}}}function St(){bt($());let t=e(`main.main`),r=xt(i);n(document.getElementById(`app`),e(`div.shell`,r.node,t));function i(e){location.hash===`#${e}`?a(e):location.hash=e}function a(e){t.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[i,a=``]=e.split(`?`,2),o=Q.find(e=>e.path===i)||Q[0];r.highlight(o.path),n(t,o.view?o.view(new URLSearchParams(a)):Ct(o))}window.addEventListener(`hashchange`,()=>a(location.hash.slice(1)||`/`)),a(location.hash.slice(1)||`/`)}function Ct(t){return e(`div`,e(`div.page-head`,e(`div`,e(`h1.page-title`,t.label))),e(`div.card`,e(`div.empty`,e(`div.empty-title`,`${t.label} is not built yet`),e(`div`,`This section is next up. Nothing is broken.`))))}St(); \ No newline at end of file diff --git a/ui/src/base/api.js b/ui/src/base/api.js index 12c12795a..ded31fcac 100644 --- a/ui/src/base/api.js +++ b/ui/src/base/api.js @@ -86,6 +86,7 @@ export const api = { return res.json(); }, config: () => req("/api/config"), + version: () => req("/api/version"), configUpdate: async (updates) => { const res = await fetch("/api/config", { method: "PATCH", diff --git a/ui/src/settings/settings.js b/ui/src/settings/settings.js index 2e593392b..895de73b2 100644 --- a/ui/src/settings/settings.js +++ b/ui/src/settings/settings.js @@ -2,6 +2,7 @@ import "./settings.css"; import { api } from "../base/api.js"; import { el, empty, mount, pill } from "../base/dom.js"; import { row } from "./config-row.js"; +import { updateStatusCard } from "./update-status.js"; /** * A view of the config archied is actually running with, grouped by @@ -23,9 +24,11 @@ export function settingsPage() { // tables on one shared measure; see settings.css. const root = el("div.cfg-page"); const body = el("div"); + const versionSlot = el("div"); render(); load(); + loadVersionStatus(); function render() { mount( @@ -37,8 +40,9 @@ export function settingsPage() { el("h1.page-title", "Configuration"), el("p.page-sub", "What archied is actually running with right now."), ), - el("div.page-actions", el("button.btn", { onclick: load }, "Refresh")), + el("div.page-actions", el("button.btn", { onclick: () => { load(); loadVersionStatus(); } }, "Refresh")), ), + versionSlot, body, ); } @@ -52,6 +56,22 @@ export function settingsPage() { } } + async function loadVersionStatus() { + try { + const data = await api.version(); + mount(versionSlot, updateStatusCard(data?.components || [])); + } catch (err) { + // 501 means updates just aren't configured for this deployment -- + // that's the ordinary state for most installs, not a failure to + // report as loudly as an unreachable daemon. + if (err?.status === 501) { + mount(versionSlot); + return; + } + mount(versionSlot, el("div.card", empty("Update status unavailable", String(err.message || err)))); + } + } + function renderBody(cfg, reload) { if (!cfg || Object.keys(cfg).length === 0) { mount( diff --git a/ui/src/settings/update-status.js b/ui/src/settings/update-status.js new file mode 100644 index 000000000..b23699cbd --- /dev/null +++ b/ui/src/settings/update-status.js @@ -0,0 +1,73 @@ +import { el, empty, pill } from "../base/dom.js"; + +const STATUS_LABELS = { + ok: "OK", + update_available: "Update available", + drift: "Drift", + unknown: "Unknown", +}; + +const STATUS_KINDS = { + ok: "ok", + update_available: "info", + drift: "danger", + unknown: "idle", +}; + +/** + * Per-component deployment/update status (GET /api/version): how each + * component is installed, what's actually running, and whether that + * agrees with what the update-check command claims. The comparison basis + * -- the exact installed claim, running version and reference this status + * was computed from -- sits in the row's title attribute (a hover tooltip) + * rather than a separate expand control, since it's supplementary detail + * an operator wants on demand, not on every glance at the table. + * + * Split out from settings.js (which top-level imports settings.css) so it + * can be unit tested under plain node --test. + */ +export function updateStatusCard(components) { + if (!components.length) { + return section( + "How each component is deployed, and whether what's running matches what's installed.", + empty("No components reported", "The configured update-check command returned nothing."), + ); + } + return section( + "How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.", + el( + "div.table-scroll", + el( + "table.table", + el("thead", el("tr", ...["Component", "Install type", "Running", "Latest available", "Status"].map((h) => el("th", h)))), + el( + "tbody", + ...components.map((c) => { + const basis = [ + `Installed claim: ${c.installed_claim || "unknown"}`, + `Running: ${c.running_version || "not observed"}`, + c.reference ? `Reference: ${c.reference}` : null, + ].filter(Boolean).join("\n"); + return el( + "tr", + { title: basis }, + el("td.strong", c.label || c.id), + el("td.mono", c.install_type || "—"), + el("td.mono", c.running_version || "—"), + el("td.mono", c.latest_available || "—"), + el("td", pill(STATUS_LABELS[c.status] || c.status, STATUS_KINDS[c.status] || "idle")), + ); + }), + ), + ), + ), + ); +} + +function section(sub, ...children) { + return el( + "div.card.cfg-section", + el("div.card-head", el("div", el("h2.card-title", "Update status"), el("p.card-sub", sub))), + ...children, + ); +} diff --git a/ui/test/settings-update-status.test.js b/ui/test/settings-update-status.test.js new file mode 100644 index 000000000..57935424f --- /dev/null +++ b/ui/test/settings-update-status.test.js @@ -0,0 +1,37 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import "./shim.js"; +import { updateStatusCard } from "../src/settings/update-status.js"; + +test("update status card shows an empty state with no components", () => { + const card = updateStatusCard([]); + assert.equal(card.querySelector("table"), null); +}); + +test("update status card renders one row per component with its status pill", () => { + const card = updateStatusCard([ + { id: "daemon", label: "Gateway", install_type: "binary", running_version: "1.0.0", latest_available: "1.1.0", status: "update_available" }, + { id: "agent", label: "Runtime", install_type: "container", running_version: "1.0.0", status: "ok" }, + ]); + const rows = card.querySelector("tbody").children; + assert.equal(rows.length, 2); + assert.match(rows[0].textContent, /Gateway/); + assert.match(rows[0].textContent, /Update available/); + assert.match(rows[1].textContent, /OK/); +}); + +test("update status card's row title carries the comparison basis", () => { + const card = updateStatusCard([ + { id: "agent", label: "Runtime", installed_claim: "1.1.0", running_version: "1.0.0", reference: "img@sha256:abc", status: "drift" }, + ]); + const row = card.querySelector("tbody").children[0]; + assert.match(row.attrs.title, /Installed claim: 1\.1\.0/); + assert.match(row.attrs.title, /Running: 1\.0\.0/); + assert.match(row.attrs.title, /Reference: img@sha256:abc/); +}); + +test("update status card shows an unrecognised status as its own label rather than crashing", () => { + const card = updateStatusCard([{ id: "x", status: "something-new" }]); + const row = card.querySelector("tbody").children[0]; + assert.match(row.textContent, /something-new/); +});