diff --git a/Taskfile.yml b/Taskfile.yml index 31325af9a..f6497f410 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -192,6 +192,10 @@ tasks: proxying /api and /events through to archie-ui on :8484 + The gRPC ports come from [services.state].listen and [services.gateway].listen in + deployments/dev.toml, each paired with the target that dials it. Move them there + when the host already owns one: cockpit binds 9090 by default. + Open http://localhost:5173 -- not :8484. The Vite server is the one with hot reload; :8484 serves the last built dist/ and will look stale. diff --git a/cmd/archie-gateway/main.go b/cmd/archie-gateway/main.go index dfa6bd83c..e9c8c9989 100644 --- a/cmd/archie-gateway/main.go +++ b/cmd/archie-gateway/main.go @@ -24,7 +24,7 @@ func run() int { var options archied.GatewayOptions flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") - flag.StringVar(&options.Listen, "listen", "127.0.0.1:8585", "gateway gRPC listen address") + flag.StringVar(&options.Listen, "listen", "", "gateway gRPC listen address (defaults to [services.gateway].listen, else 127.0.0.1:8585)") flag.StringVar(&options.Token, "token", "", "Bearer [REDACTED] required for a non-loopback listener (defaults to [services.gateway].target_token)") flag.Parse() ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) diff --git a/cmd/archie-state-store/main.go b/cmd/archie-state-store/main.go index 7a1f27426..130956aad 100644 --- a/cmd/archie-state-store/main.go +++ b/cmd/archie-state-store/main.go @@ -31,7 +31,7 @@ func run() int { var options archied.StateStoreOptions flag.StringVar(&options.Config, "config", filepath.Join(base, "archie", "config.toml"), "configuration file or directory") flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory") - flag.StringVar(&options.Listen, "listen", "127.0.0.1:9090", "state store gRPC listen address") + flag.StringVar(&options.Listen, "listen", "", "state store gRPC listen address (defaults to [services.state].listen, else 127.0.0.1:9090)") flag.StringVar(&options.Token, "token", "", "bearer token required for a non-loopback listener (defaults to [services.state].target_token)") flag.StringVar(&options.ReadyAddr, "ready-addr", "", "optional readiness HTTP listen address (e.g. 127.0.0.1:9091)") flag.Parse() diff --git a/cmd/archie-state-store/main_test.go b/cmd/archie-state-store/main_test.go index 5be744ded..c844fbeb9 100644 --- a/cmd/archie-state-store/main_test.go +++ b/cmd/archie-state-store/main_test.go @@ -85,9 +85,10 @@ func buildBinary(t *testing.T, dir string) string { } // writeMinimalConfig writes a config.toml that passes configuration.Validate -// while keeping the process minimal: the standalone binary reads its gRPC -// listen address from -listen, not from [services.state].target, so the config -// only needs the fields validation requires plus the db_path it owns. The +// while keeping the process minimal: the standalone binary takes its gRPC +// listen address from -listen or [services.state].listen, never from the +// target, so the config only needs the fields validation requires plus the +// db_path it owns. The // forge token resolves from an env var, so no real credential is needed. func writeMinimalConfig(t *testing.T, dir string) string { t.Helper() @@ -108,6 +109,27 @@ name = "widget" return cfg } +// writeConfigWithServiceListen is writeMinimalConfig plus the +// [services.state] block that lets a test supply the listen address through +// configuration instead of the -listen flag. +func writeConfigWithServiceListen(t *testing.T, dir string) string { + t.Helper() + cfg := writeMinimalConfig(t, dir) + f, err := os.OpenFile(cfg, os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + t.Fatalf("open config to append: %v", err) + } + defer func() { + if err := f.Close(); err != nil { + t.Fatalf("close config: %v", err) + } + }() + if _, err := f.WriteString("\n[services.state]\nlisten = \"127.0.0.1:0\"\n"); err != nil { + t.Fatalf("append [services.state]: %v", err) + } + return cfg +} + // syncBuffer is a concurrency-safe buffer for a subprocess's stdout/stderr: // the os/exec goroutine writes while the test goroutine reads (to parse the // log and to report it on failure). A plain strings.Builder races under @@ -158,7 +180,12 @@ func startStateStoreProcess(t *testing.T, bin, cfg string) *stateStoreProcess { // credential interceptors on both the unary and the streaming surface. func startStateStore(t *testing.T, bin, cfg, listen, token string) *stateStoreProcess { t.Helper() - args := []string{"-config", cfg, "-listen", listen, "-ready-addr", "127.0.0.1:0"} + args := []string{"-config", cfg, "-ready-addr", "127.0.0.1:0"} + if listen != "" { + // An empty listen means "pass no -listen at all". A test uses that to + // prove the bound address came from [services.state].listen. + args = append(args, "-listen", listen) + } if token != "" { // An explicit -token wins over [services.state].target_token and the // STATE_STORE_TOKEN secret, so the process authenticates callers with @@ -291,14 +318,29 @@ func capture(source, body string) store.CapturedEvent { // adapter, error-sentinel fidelity across the wire, the not-found-as-(nil,nil) // convention, and single-owner SQLite (the binary owns the one archie.db file // and the consumer dials gRPC without opening any store file). +// +// It also takes its listen address from [services.state].listen rather than +// -listen, so the startup path every deployment uses is covered by the process +// that exercises the most: before that key existed the address came from a flag +// default with no config key, so a host that already owned the port (cockpit +// owns 9090 by default) could only be retargeted by passing -listen and +// hand-writing an overlay whose target matched -- and the failure read as a +// code fault, "address already in use" in the store and a gRPC handshake error +// in every client. func TestStateStoreRealProcessSmoke(t *testing.T) { if testing.Short() { t.Skip("real-process smoke test builds and execs the binary; skip under -short") } dir := t.TempDir() bin := buildBinary(t, dir) - cfg := writeMinimalConfig(t, dir) - st := startStateStoreProcess(t, bin, cfg) + cfg := writeConfigWithServiceListen(t, dir) + st := startStateStore(t, bin, cfg, "", "") + if st.addr == "" { + t.Fatalf("no bound gRPC address in the log:\n%s", st.log.String()) + } + if !strings.Contains(st.log.String(), `"listen":"127.0.0.1:0"`) { + t.Fatalf("the resolved listen was not the configured address:\n%s", st.log.String()) + } cl := dial(t, st.addr) ctx := t.Context() @@ -313,9 +355,23 @@ func TestStateStoreRealProcessSmoke(t *testing.T) { if err := cl.Transition(ctx, task.ID, task.Status, "running", "smoke started"); err != nil { t.Fatalf("Transition: %v", err) } - if _, err := cl.InsertEvent(ctx, events.Event{Kind: "stage_finish", TaskID: task.ID, Data: map[string]any{"duration_ms": 12.0}}); err != nil { + if _, err := cl.InsertEvent(ctx, events.Event{Kind: "stage_finish", TaskID: task.ID, Attempt: 1, Data: map[string]any{"duration_ms": 12.0}}); err != nil { t.Fatalf("InsertEvent: %v", err) } + // R4's document is stored as an event, so the real process must round-trip + // it with its nested structure and its attempt key intact: the standalone + // State Store owns the only copy, and a lost field here is a Config tab + // that reads a run it cannot describe. The key is the daemon's own + // (internal/daemon/daemon.go writes "document"), asserted by name below. + if _, err := cl.InsertEvent(ctx, events.Event{ + Kind: events.KindConfigCaptured, TaskID: task.ID, Attempt: 1, + Data: map[string]any{ + "schema": events.ConfigCapturedSchema, + "document": map[string]any{"bot_user": "archie", "models": map[string]any{"implement": "anthropic/claude"}}, + }, + }); err != nil { + t.Fatalf("InsertEvent config_captured: %v", err) + } if capID, err := cl.InsertCapture(ctx, capture("sentry", `{"id":1}`), 0, 0); err != nil || capID == 0 { t.Fatalf("InsertCapture = (%d, %v)", capID, err) } @@ -324,9 +380,25 @@ func TestStateStoreRealProcessSmoke(t *testing.T) { if err != nil || got == nil || got.ID != task.ID || got.Status != "running" { t.Fatalf("TaskByID after transition = %+v, %v", got, err) } - if evs, err := cl.TaskEvents(ctx, task.ID); err != nil || len(evs) != 1 || evs[0].Kind != "stage_finish" { + evs, err := cl.TaskEvents(ctx, task.ID) + if err != nil || len(evs) != 2 || evs[0].Kind != "stage_finish" { t.Fatalf("TaskEvents = %+v, %v", evs, err) } + if evs[0].Attempt != 1 { + t.Errorf("TaskEvents attempt = %d, want 1 across the real process", evs[0].Attempt) + } + if evs[1].Kind != events.KindConfigCaptured || evs[1].Attempt != 1 || evs[1].Data["schema"] != events.ConfigCapturedSchema { + t.Errorf("config_captured event = %+v, want its kind, attempt and schema preserved", evs[1]) + } + if _, renamed := evs[1].Data["config"]; renamed { + t.Error(`the document crossed under "config"; the producer writes it under "document"`) + } + if len(evs[1].Data) != 2 { + t.Errorf("config_captured data keys = %v, want exactly schema and document", evs[1].Data) + } + if doc, ok := evs[1].Data["document"].(map[string]any); !ok || doc["bot_user"] != "archie" { + t.Errorf("config_captured payload = %#v, want the decoded document under its own key", evs[1].Data) + } if caps, err := cl.ListCaptures(ctx, 10); err != nil || len(caps) != 1 || caps[0].Source != "sentry" { t.Fatalf("ListCaptures = %+v, %v", caps, err) } diff --git a/config.example.toml b/config.example.toml index f9f3efa89..c8a818558 100644 --- a/config.example.toml +++ b/config.example.toml @@ -304,6 +304,11 @@ gate_max_failures = 5 # docs/prds/state-store-contract.md). [services.gateway] target = "127.0.0.1:8585" # archie-gateway's gRPC address (always remote once set) +# listen = "127.0.0.1:8585" # The address archie-gateway BINDS. Read only by the +# # archie-gateway process; every client ignores it. Defaults +# # to the target above, so a default deployment's client and +# # server cannot drift onto different ports. Set it when the +# # host already owns that port. # target_token = "..." # Bearer [REDACTED] for a NON-loopback listener. A loopback listener # # (127.0.0.1/::1/localhost) needs no token. A non-loopback # # listener without a token fails closed, as does a @@ -316,6 +321,11 @@ target = "127.0.0.1:9090" # REQUIRED. The State Store gRPC address arch # # in-process: the standalone archie-state-store process # # owns the single SQLite file (docs/prds/state-store-contract.md # # §10/§12 step 7). An empty target is a startup error. +# listen = "127.0.0.1:9090" # The address archie-state-store BINDS. Read only by that +# # process; every client ignores it. Defaults to the target +# # above, so a default deployment's client and server cannot +# # drift onto different ports. Move it when the host already +# # owns 9090 (cockpit binds it by default). # target_token = "..." # bearer token for a NON-loopback target. A loopback target # # (127.0.0.1/::1/localhost) needs no token. A non-loopback # # target without a token fails closed (docs/prds/state-store-contract.md diff --git a/deployments/dev.toml b/deployments/dev.toml index 0e21a71e6..c03d4bc07 100644 --- a/deployments/dev.toml +++ b/deployments/dev.toml @@ -11,16 +11,20 @@ [web] listen = "127.0.0.1:8484" -# `task dev` also runs archie-state-store on its -listen default -# (127.0.0.1:9090, loopback, no token) via dev:state-store -- point archied, -# archie-gateway and archie-ui at it so a fresh dev checkout works without -# hand-editing the installed config.toml +# `task dev` runs archie-state-store via dev:state-store, which passes no +# -listen, so the listen below is the port the store binds. It must agree with +# the target: these two lines are the only place that pair is stated. Move them +# when the host already owns 9090 (cockpit binds it by default) -- before the +# listen key existed the collision could only be worked around by hand-writing +# a matching target and passing -listen, and it read as a code fault. # (docs/prds/state-store-contract.md §12 step 7). [services.state] target = "127.0.0.1:9090" +listen = "127.0.0.1:9090" -# `task dev` runs archie-gateway on its -listen default (127.0.0.1:8585, -# loopback, no token). Stated explicitly so the value archie-ui dials is -# visible next to the State Store one. +# `task dev` runs archie-gateway via dev:gateway, which also passes no -listen: +# the listen below is what it binds. Stated explicitly so the value archie-ui +# dials is visible next to the State Store one. [services.gateway] -target = "127.0.0.1:8585" \ No newline at end of file +target = "127.0.0.1:8585" +listen = "127.0.0.1:8585" \ No newline at end of file diff --git a/docs/architecture/configuration.md b/docs/architecture/configuration.md index 29d708155..4f7f90d0a 100644 --- a/docs/architecture/configuration.md +++ b/docs/architecture/configuration.md @@ -162,6 +162,7 @@ existing structure combines different owners. | listen/relay addresses | email config | Email adapter instance settings. | | webhook target | `Notify` | Notification adapter instance settings. | | web listen address | `Web` | Web transport settings. | +| `listen` under `[services.state]` and `[services.gateway]` | `ServiceConnection` | The bind address of the process that owns the service. Read only by that process, and defaulted to the address its clients dial so the pair cannot drift. | | index directory and database path | `Indexing` | Index infrastructure settings, derived from storage settings unless explicitly overridden. | | forge, dispatch, models, providers, containers, memory, tools, indexing and repositories | `IdentityConfig` | Existing composite duplicates unrelated settings. Replace it with associations from an `IdentityID` to independently owned configured instances. | | owner, name, base, gate, protection, ecosystem, preflight, storage, retry and concurrency | `Repo` | Split across work intake, workspace, workflow execution, policy, gate, and scheduling as described in Repository settings. | diff --git a/docs/architecture/migration-decisions.md b/docs/architecture/migration-decisions.md index 6c1e84825..43733161a 100644 --- a/docs/architecture/migration-decisions.md +++ b/docs/architecture/migration-decisions.md @@ -529,3 +529,19 @@ config DTO translation will land, so it unblocks the dissolution above. per area when the decisions are already dictated by `dependencies-and-contracts.md`. That is the ceremony pattern this project deliberately avoids. + +## OPEN — `[chat.*]` config section naming + +`configuration.md:160` already states the position: `ChatConfig` holds "separate +channel instance settings... there is no chat-wide settings owner". The config +section name has not followed, so a settings block named for a product surface +owns what the architecture calls channel state. + +Two candidates, neither settled: `[channel.*]` and `[messaging.channel.*]`. The +second reads as a domain path, and no config section in this repo is currently +named after a domain package, so adopting it sets a precedent for every other +section rather than fixing one name. + +Blocked on a maintainer decision, not on evidence. This is a rename with an +operator-visible TOML break, so it should land with the `internal/config` +dissolution recorded above rather than on its own. diff --git a/docs/architecture/observability.md b/docs/architecture/observability.md index 0a816a5c9..060716257 100644 --- a/docs/architecture/observability.md +++ b/docs/architecture/observability.md @@ -1,7 +1,8 @@ # Task Observability -**Status:** Implemented -**Date:** 2026-08-09 +**Status:** Implemented. The per-run detail surface was added on 2026-09-18 and +is described below. +**Date:** 2026-08-09 (revised 2026-09-18) ## Historical problem @@ -135,6 +136,183 @@ lifecycle rather than accumulating independently. Telegram or the webui chat — this is the surface that actually matters for the deployment model in `CLAUDE.md`, where an operator may not be looking at a dashboard at all. +- The per-attempt read surface described in the next section, on top of the + same task-scoped stream. + +## Per-run task detail (attempts, stages, changes, config) + +**Status:** landed, together with the change set that carries this revision +(workflow run `76f8e877`). The provenance half is in the tree: `events.Event.Attempt`, +the `changes_captured` and `config_captured` event kinds, and the two protobuf field +additions. So is the read half: the three per-attempt endpoints +(`/api/tasks/{id}/attempts`, `/changes`, `/debug`) and the dashboard run-detail page +that consumes them. The decision record, the rejected alternatives and the honest +limits are `docs/prds/task-run-detail.md`. + +The task log surface above answers *why did this park?*. This surface answers +*what did this run actually do?*, per attempt. + +### Attempt attribution + +One task can run many times, and the task's event stream is the durable record +of all of them. `events.Event.Attempt` attributes each event to one run; `0` +means **not attributable** — every event written before this change, plus the +deliberately task-agnostic producers. An unattributed event is reported as a +count and is never presented as an attempt. + +Attribution is a column, not a fold over `task_queued`/`task_retried`: a fold +would have to guess which side of a boundary an event belongs to across a daemon +restart, a stale-run recovery, or two interleaved attempts, and a guess rendered +as structure is exactly the false fidelity this surface exists to avoid. + +The column reaches an existing database through the presence-gated arm in +`internal/store`'s `migrateTasks` — `eventsSchema` is `CREATE TABLE IF NOT +EXISTS`, so on an existing database the migrator is the *only* thing that adds +it. `PRAGMA user_version` is unchanged because the loop is presence-gated +rather than version-gated, and nothing is backfilled. + +### Read surface + +The routes are registered beside the existing task routes in +`internal/webui`'s `registerTaskRoutes` and all resolve the task through the +store's `TaskByID`; a task that does not exist is a `404`, never a `200` with an +empty body. + +- `GET /api/tasks/{id}/attempts` — every attempt with its stages inline, so the + rail and the attempt selector can never disagree. Stages are ordered by + occurrence within their attempt. An attempt with no stages is legitimate and + renders as "no stages recorded", never as an unexplained empty rail. +- `GET /api/tasks/{id}/changes?attempt=N` — the change captures for one + attempt, ordered by capture time; more than one per attempt is normal (a + mid-workflow commit such as TDD's `commit-repro`, then `commit-push`, then a + final `open-pr` capture that carries the pull-request number). + `found: false` means no capture was recorded for that attempt, which is + **not** "no files changed"; a capture that was recorded but could not be read + is reported as exactly that, and never as a diffstat of zeroes. +- `GET /api/tasks/{id}` — unchanged: the raw event array, each event now + carrying `attempt`. The per-attempt configuration is read from this response, + selected by kind **and** attempt. +- `GET /api/tasks/{id}/logs` — gains `stage` beside its existing filters. The + match is exact and case-insensitive, and an entry that records no stage never + matches (see `logging.Query.Stage`). +- `GET /api/tasks/{id}/debug?attempt=N` — the stored task record and the task's + events, deliberately unfiltered, so an operator can attribute everything the + task did even when a panel has nothing to show. + +The `attempt` parameter follows one rule on every route: absent or `0` selects +the task's current attempt, and the resolved attempt is echoed in the response. + +### Stage status + +`stage_start` and `stage_finish` are the only inputs, so the derivation is +explicit and each case is pinned by a test: + +| Events seen for the stage | Reported | +| --- | --- | +| `stage_finish` with `data.error` | `failed`, with the error text | +| `stage_finish` with `data.interrupted` | `interrupted` | +| `stage_finish`, neither | `ok` — "returned without error" | +| `stage_start` unmatched, and this is the task's current in-flight attempt | `running` | +| `stage_start` unmatched on any dead attempt | `interrupted` — the run ended without finishing it | +| `stage_finish` with no matching start | the stage, with no start time invented | +| no stage information at all for that attempt | `unknown` | + +**There is no exit code.** `stage_finish` carries a duration and an optional +error string and nothing else, so no stage can be shown as pass/fail and the +page must not imply verification. A stage that finished cleanly and then parked +stays `ok` on a failed task, which is why the attempt status is read together +with the task status rather than on its own. + +### Changed files + +The change an attempt produced is read from the worktree at the moment it is +committed or pushed, and persisted as a `changes_captured` durable event — plus +one final capture when `OpenPR` records the pull-request number, which is the +only point at which a capture can carry one. It has to be captured there: the +worktree is deleted on merge, close and no-PR terminal states, a retry resets +the branch onto its base, and no forge contract exposes a changed-file read. +`internal/domain/workflow/task/changes.go` owns the value types and the status +strings they persist. + +- One capture carries per-file `added`/`modified`/`deleted`/`renamed`/ + `typechange` status with added and deleted line counts, and totals. +- Each capture names its schema (`archie/task-changes@1`, in `internal/events`) + and a reader refuses a payload whose schema or key set it does not know, + rather than rendering the zero value of every field it could not find. That + refusal surfaces as "a capture was recorded but could not be read", which is + a different statement from "no capture was recorded". +- `base_sha` is the merge base the file list was diffed against, not the base + branch's tip, so the pair describes one change set even when the base branch + moved during the run. +- `files` is capped; `totals` always covers the **full** set, and a truncated + capture says so rather than silently dropping entries. +- `binary` means "no textual hunks" — never a claim about the file's type on + disk — and a path the repository recorded as a rename pair is reported as the + repository recorded it. +- Capture **degrades and never parks**: an implementation without the capture + seam captures nothing, logs, and lets the run continue. + +### Per-attempt configuration + +The effective configuration an attempt ran under is persisted as a once-per- +attempt `config_captured` durable event carrying the schema constant +`archie/task-config@1` and the non-secret task-runtime subset from +`config.Config.ForTask()`. It is not stored in a table and has no endpoint of +its own: the dashboard reads it out of the events response it already fetches. +The single-row `config_snapshot` table is left alone — it answers what the +running configuration is now and is replaced on every publish. + +Redaction is proven positively by a test that builds a full configuration +containing canary values and asserts none of them survive serialising, rather +than being inferred from the producer's contract. The timeline carries one +human line for this kind; the document itself is rendered by the panel. + +**Trust boundary, stated honestly.** A task-scoped grant may insert events on +its own task ID — that is how `tool_call` and `agent_finish` already work — so a +task could in principle write its own `config_captured` event. This widens no +capability, because the grant could already insert arbitrary events on itself, +but it does mean this provenance is exactly as trustworthy as the rest of that +task's event stream, and no more. It is not tamper-proofing and must never be +described as such. + +### The wire + +The whole wire change is two fields on existing messages: `Event.attempt` +(field 11) and `ReadTaskLogRequest.stage` (field 9) in +`proto/state/v1/state.proto`. No RPC, no table and no configuration field was +added, so the ratified state-store contract in +`docs/prds/state-store-contract.md` rev 2c is unchanged. + +Version skew degrades instead of failing, and each degrade is a statement the +page has to make rather than hide: an old server makes `attempt` read as `0` and +`stage` match nothing, so the page says it cannot attribute events to attempts +instead of labelling the whole stream "attempt 1"; an old client sees +`config_captured` as an unfamiliar kind, and the panel must then say it cannot +read per-run configuration — a different claim from "not captured for this +attempt". + +### Rules the surface keeps + +- "No record" and "this deployment cannot read this" stay different answers, + for logs and for configuration alike. +- No run-duration figure is shown. A run can spend days in `waiting_human`, so + one number would understate wall time; per-stage durations only. +- No duration is invented for a stage with no start; it reads "not recorded". +- The stage filter is a narrowing, not a coverage claim: agent and tool output + carries no stage and is never matched, and the pane says so beside the + control. +- An attempt predating the change shows "not captured for this run" for its + configuration and its change capture, never an empty view that implies + defaults applied or nothing changed. + +### Failure and rollback + +Every part is additive. A capture or a configuration emit that cannot happen +leaves the run alone — reporting must never park a task. Reverting the change +set removes the endpoints and the page; the extra column and the extra event +kinds are inert to the previous revision (SQLite ignores a column no statement +names, and an unfamiliar event kind already renders as unfamiliar), and there is +no data transformation to undo. ## Dependency direction diff --git a/docs/prds/service-registry.md b/docs/prds/service-registry.md new file mode 100644 index 000000000..6afe622fc --- /dev/null +++ b/docs/prds/service-registry.md @@ -0,0 +1,112 @@ +# Service registry — one declaration per service + +**Status:** Design, pre-implementation. Supersedes `state-store-contract.md` §10's +`State ServiceConnection` struct-field instruction (revised to rev. 2d in the same change). + +**Base:** the `listen` field, `internal/app/archied/listen.go`, and the listen defaults cited +below exist on `feat/attempt-attribution`, not on `main`. This design therefore lands on top of +that branch: `RegisterService`'s `listen` argument has nothing to carry without it. + +## Problem + +A service is already one Go type, `config.ServiceConnection`. What is duplicated is its +**name**, in three layers: + +| Layer | Location | What is hard-coded | +|---|---|---| +| Declaration | `internal/config/services.go:4-14` | `Gateway` and `State` as struct fields | +| Defaulting | `internal/infrastructure/configuration/defaults.go:74-82` | three `if cfg.Services.X.Y == ""` branches | +| Consumption | `internal/app/archied/{bootstrap.go,state_store.go,gateway.go}`, `internal/app/archieui/config.go:80-81` | `cfg.Services.State` / `cfg.Services.Gateway` field access | + +Adding a service means editing all three. The drift this permits is already visible: +`stateStoreResolvedToken` (`state_store_client.go:17-23`) and `gatewayResolvedToken` +(`chat_service.go:20-26`) are byte-identical apart from the env var name, and +`gateway.Target` is defaulted while `state.Target` is a startup error, with nothing +stating that asymmetry in one place. + +`resolveServiceListen(service, flagValue, configured)` (`listen.go:24-34`) is already +name-parameterised. It is the shape the rest should follow. + +## Decision + +**Key services by name, and carry per-service asymmetry as registration data.** + +### 1. Declaration collapses to a map + +```go +// internal/config/services.go +type Services map[string]ServiceConnection +``` + +`ServiceConnection` is unchanged. The TOML shape is unchanged, so no deployment profile, +`config.example.toml`, or `install.sh` edit is required. An unrecognised `[services.foo]` +decodes without a code edit, satisfying criterion 5. + +### 2. Registration is the single entry point + +```go +// internal/config/servicespec.go +func RegisterService(context, name, target, listen, tokenEnv string) +``` + +registered once per service, at package init in `internal/config`: + +```go +RegisterService("both", "gateway", "127.0.0.1:8585", "127.0.0.1:8585", "GATEWAY_TOKEN") +RegisterService("client", "state", "", "127.0.0.1:9090", "STATE_STORE_TOKEN") +``` + +Positional, five strings, as the story specifies. Each argument is data the current code +states in prose or in a branch: + +- `context` is `client`, `server`, or `both`, and decides which fields must resolve + non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with + no default `listen`, panics at registration. Registrations come from this repository's + own `init()`, never from operator input, so an invalid one is a programming error with + no caller positioned to handle an error return. A documented-but-unread `Context` would + be worse than no field at all. +- `target` is the **default**, and an empty default means the operator must supply one. + That single convention replaces the `state.target` required / `gateway.target` defaulted + asymmetry with no branch: `state` registers `""`, `gateway` registers an address. +- `listen` is the default listen address, feeding the existing + flag → `[services.].listen` → default precedence unchanged. +- `tokenEnv` names the fallback env var, replacing the two copied resolvers with one. + +### 3. Defaulting and consumption become loops and lookups + +`applyDefaults` iterates the registry instead of naming services. Consumers read +`cfg.Services.Get("state")`, returning a `ServiceConnection` plus the spec, so +`stateStoreResolvedToken` and `gatewayResolvedToken` collapse into +`Services.ResolvedToken(name, secrets)`. + +## Criteria satisfied + +1. Declared once, in the `RegisterService` call. +2. No second location can contradict it; the map has no per-service fields to disagree with. +3. Registration is the entry point, with the five fields a service has. +4. A new service is one `RegisterService` line: no field, no default branch, no consumer edit. +5. The set of services is registry data, not a struct definition. + +## Scope and risk + +- `state-store-contract.md` §10 must be revised in the same change, or the tree contradicts + its own ratified authority. Its summary (`:7`) already says `[services.]`. +- A typo'd `[services.gatway]` is **reported today** (`UnknownKeys = [services.gatway, + services.gatway.target]`), because the struct form leaves it in `toml.MetaData.Undecoded()`. + A map decodes any section, so preserving that is a requirement, not an optional extra: + `unregisteredServiceKeys` asks the registry which names exist. This costs nothing in + extensibility, because the answer comes from registration data rather than a fixed list. + (An earlier draft of this document claimed the typo was silently ignored either way. It + was not; the behaviour was measured.) +- Existing tests reference `cfg.Services.State` directly (`state_store_client_test.go:82`, + `setup_test.go:278`, and others). They move to `Get`, mechanically. +- No wire contract, no RPC, and no persisted format is touched. The 42-RPC State Store + contract is unaffected. + +## Acceptance + +- Adding a third service is a one-line diff plus its consumer, proven by a test that + registers a throwaway service and asserts its defaults and token fallback resolve. +- `grep -rn 'Services\.\(State\|Gateway\)' --include='*.go'` returns nothing. +- The existing `services_test.go` default and precedence assertions pass unchanged in + behaviour, rewritten only to the new accessor. diff --git a/docs/prds/state-store-contract.md b/docs/prds/state-store-contract.md index b9ec56e97..f51cd95d3 100644 --- a/docs/prds/state-store-contract.md +++ b/docs/prds/state-store-contract.md @@ -1,6 +1,9 @@ # State Store — contract boundary & transport (ratification) -**Status:** Ratified (rev. 2c). Rev. 1 was marked *conditionally ratified*; the three +**Status:** Ratified (rev. 2d). Rev. 2d revises §10 only: the `State ServiceConnection` +struct-field instruction is withdrawn in favour of name-keyed services +(`docs/prds/service-registry.md`). The contract, its 42 RPCs, and the listener topology are +unchanged. Rev. 1 was marked *conditionally ratified*; the three reviewer conditions it raised are resolved (rev. 2), and the two third-pass findings are resolved here: (a) the stale Q3 migration wording in `service-decomposition.md` (`store.WorkflowStore`, `mode = "inproc" | "remote"`) now matches the ratified ownership split @@ -535,16 +538,17 @@ an explicit operator decision. **Follow the gateway's presence-based `target` seam, not the NATS `mode` enum.** -- `internal/config/services.go` gains a `State ServiceConnection` field: +- **Revised (rev. 2d).** This section previously instructed that + `internal/config/services.go` gain a `State ServiceConnection` *struct field*. That + instruction is withdrawn: naming each service as a field is the duplication + `docs/prds/service-registry.md` removes, and this document's own summary (`:7`) already + describes the seam as `[services.]`. Services are keyed by name: ```go - type Services struct { - Gateway ServiceConnection `toml:"gateway" yaml:"gateway"` - State ServiceConnection `toml:"state" yaml:"state"` - } - type ServiceConnection struct { - Target string `toml:"target" yaml:"target"` - } + type Services map[string]ServiceConnection ``` + registered once via `RegisterService(context, name, target, listen, tokenEnv)`. The TOML + shape below is unchanged, so nothing else in this section is affected; read + `cfg.Services.Get("state")` wherever it says `cfg.Services.State`. - **Empty `Target` → local** `*store.Store` adapter (the default; State Store not yet extracted). **Set `Target` → dial gRPC** and use `*staterpc.Client`. This differs from the gateway, where `Target` is always defaulted to `127.0.0.1:8585` because the gateway is already diff --git a/docs/prds/task-run-detail.md b/docs/prds/task-run-detail.md new file mode 100644 index 000000000..fe485d6d9 --- /dev/null +++ b/docs/prds/task-run-detail.md @@ -0,0 +1,291 @@ +# Per-run task detail: attempts, stages, changes, config, debug + +**Status:** Settled design, landing with this change set (workflow run +`76f8e877`). The persistence foundation is already in the tree +(`events.attempt`, the two new event kinds, the two proto fields); the read +endpoints and the page land with it. The surface contract itself is +`docs/architecture/observability.md`. +**Date:** 2026-09-18 +**Compounds with:** `docs/prds/task-logs-pagination.md` (a bounded read says +what it does not show), `docs/prds/status-health-surface.md` (no surface that +answers something already answered elsewhere). + +## Decision + +A task gets one detail page that answers "what did this run actually do?" per +**attempt**: an ordered stage rail, the change each commit/push produced, the +effective configuration the attempt ran under, the attempt's log, and the raw +record behind all of it. + +The single organising idea is **attempt attribution**. Today the dashboard +renders a task's whole event stream as one flat timeline, so a retried task +reads as one long run with two of everything. Every new panel is scoped to one +attempt and says which one. + +The second organising idea is **provenance, not re-derivation**. What a run +produced is captured at the producer, while the evidence exists, and persisted +durably. Nothing in this surface tries to reconstruct a past run from state +that has since moved on. + +## The requirement set + +| # | Requirement | Mechanism | +| --- | --- | --- | +| R1 | Per-attempt stage rail: stages with name, start, duration, terminal status and error, ordered within one attempt | `GET /api/tasks/{id}/attempts` reads the task's events and groups them by `attempt` | +| R2 | Events carry an attempt, migrated safely and carried on the wire | `events.attempt` column + presence-gated migrator arm; `Event.attempt = 11` | +| R3 | Changed files captured at commit/push, persisted per task, exposed, shown with repo/PR links | `changes_captured` durable event written by the commit/push steps; `GET /api/tasks/{id}/changes` | +| R4 | The effective configuration an attempt ran under, secrets redacted, shown | `config_captured` durable event written once per attempt; read from the events response the page already holds | +| R5 | Log pane filters by attempt, stage and level; absence stays distinct from an unreadable deployment | `logging.Query.Stage` + `ReadTaskLogRequest.stage = 9`; the pane keeps `disabled` and `found=false` apart | +| R6 | Retry is reachable from the run view and produces a new attempt shown as a new run | Existing retry action, labelled as a NEW run whose confirm states the previous attempt's commits are discarded | +| R7 | Raw JSON of the task record and its events for the selected attempt | `GET /api/tasks/{id}/debug` | +| R8 | Deep-linkable, reload-safe per-task detail page that keeps existing URLs working | `#/tasks/{id}` route beside the existing `#/tasks?task=N` and `#/tasks?status=...` | +| R9 | Design polish: hierarchy, tokens, both themes, responsive rail, a11y, loading/empty/error states | UI lane; measured at 480px and 700px in both themes | +| R10 | Documentation of record | This document plus `docs/architecture/observability.md` | +| R11 | Red-first tests for every new behaviour, full gate, `task ui`, forced `go build ./...`, `go test -race` on touched packages | Per lane; the anti-cost-cutting requirement lives here | + +## Attempt attribution: a column, not a guess + +`events.Event.Attempt`, persisted by `internal/store` as the `events.attempt` +column (`internal/store/events.go`, `eventsSchema`), is a real column, +`NOT NULL DEFAULT 0`. It was chosen over segmenting the stream on `task_queued` / +`task_retried` because a fold would have to guess which side of a boundary an +event belongs to when the daemon restarts mid-attempt, when `RecoverStale` +requeues, or when two attempts interleave across a crash. A guess rendered as +structure is exactly the false fidelity this surface exists to avoid; a column +is durable, queryable and ordered by construction. + +**`0` means "not attributable".** It is every row written before this change +plus the deliberately task-agnostic producers. It is not an attempt number and +is never rendered as one. The attempts endpoint reports the count of +unattributed events so the page can say so instead of presenting old history as +attempt 1. + +## Migration against an existing `archie.db` + +The store's migrator (`migrateTasks` in `internal/store/store.go`) already reads +`PRAGMA table_info` through `tableColumns` and applies a presence-gated +`ALTER TABLE ... ADD COLUMN` list. This change adds an `events` arm: a +`tableColumns(ctx, tx, "events")` read beside the other two, and the entry +`ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`. + +Three consequences a future maintainer must not get wrong: + +- `eventsSchema` is `CREATE TABLE IF NOT EXISTS` (`internal/store/events.go`), + so on an existing database it is a **no-op**. The migrator arm is the only + thing that adds the column there. This is why the red test builds a raw + SQLite file with the pre-change `events` DDL and must fail before the arm + exists: every temp-database test passes either way. +- **`user_version` stays 3.** The loop is presence-gated, not version-gated; + bumping it would force an edit to the test that exists to prove a newer + schema is refused. +- **No backfill, ever.** Existing rows keep `attempt = 0`. Inferring an attempt + number for them would be fabrication. + +## Changed files: captured at the producer + +The measurement is taken inside the shared step library immediately after a +successful commit and after a successful push (`StageCommit` and +`StageCommitPush` in `internal/domain/workflow/steps.go`) — the one place +where the worktree, the branch, the base, the task and the store are all in +scope, and the only place that knows a push actually happened. + +Both alternatives were rejected on evidence, not taste: + +- **Reading the diff on demand** is impossible. The worktree is deleted on + merge, close and no-PR terminal states (`internal/worktree.(*Manager).Cleanup`, + called from the daemon's terminal paths) and a retry resets the branch onto + its base (`internal/worktree.(*Manager).refresh` → `resetOnto`). There is + nothing left to read. +- **Reading it from the forge** is impossible today. The forge contract exposes + no changed-file capability, and adding one would cost three implementations + plus an RPC and would still fail for chat-sourced tasks with no PR. + +Binding consequences: + +- Capture **degrades, never parks**. A `Trees` implementation without the + capture seam captures nothing, logs, and lets the run continue. A reporting + failure must never fail a task. +- The value types live in `internal/domain/workflow/task` (`changes.go`), not in + package `workflow` and not in `internal/worktree`. Package `workflow` has no + import of `internal/worktree`, and this subpackage is not projected into the + interpreted-stage symbol table, so declaring the types here widens nothing and + needs no symbol-table regeneration. The capture method stays off that surface + entirely. +- `files` is capped at 200 entries because an event's `data` is not + length-limited by the store. `totals` always covers the **full** set and + `truncated: true` says when entries were dropped. +- `binary` means "no textual hunks", not "a binary file". Rename pairing is + go-git behaviour the lane pins with a test; where the repository records a + rename as add + delete, the surface reports what was recorded. + +## Per-run configuration: a durable event, not a table + +**Decision.** The effective configuration an attempt ran under is persisted as a +`config_captured` durable event (`internal/events.KindConfigCaptured`), on the +same attempt key R2 adds — not in a table, and not behind new RPCs. + +**Why.** Three reasons, in order of weight: + +1. Events are already this system's durable per-attempt provenance stream, and + they demonstrably carry aggregation (`StageStats`, `TokensByDay` both + aggregate over persisted events). R3 puts its diffstat there in this same + change. A table plus two RPCs would have given one feature **two provenance + mechanisms for one purpose**. +2. It adds no RPC, so the ratified state-store surface is untouched and nothing + in `docs/prds/state-store-contract.md` (rev 2c) changes. +3. The page already fetches the task's events to build the rail (R1) and to read + the diffstat (R3), so the document arrives in a fetch it already makes. There + is nothing to join. + +The single-row `config_snapshot` table is deliberately **left alone**. It +answers "what is the running configuration now", is replaced on every publish, +and is pinned to one row by a test. It could not answer "what did attempt 2 run +under" in any case. + +**Payload.** The result of `config.Config.ForTask()` — the non-secret +task-runtime subset — plus the schema constant `archie/task-config@1`. Not the +dashboard's configuration view: that is a larger projection carrying the full +schema catalog, and it is the wrong object for this. Stored shape and the tab's +read rule are in `docs/architecture/observability.md`. + +**Binding conditions.** It is emitted through the durable path, never the +lossy bus; it is written once per attempt, not once per stage; redaction is +proven **positively** by a canary-secrets test rather than assumed from the +producer's contract; the timeline gains one human line for it rather than +dumping a JSON blob; and an attempt with no such event renders "not captured for +this run", never an empty table implying defaults applied. + +**Documented residual — the honest trust claim.** A task-scoped grant may insert +events on its own task ID; that is how `tool_call` and `agent_finish` already +work, so a task can in principle write its own `config_captured` event. This +**widens no capability** — the grant could already insert arbitrary events on +itself — but it does mean this provenance is exactly as trustworthy as the rest +of that task's event stream, and no more. It is not tamper-proofing and must +never be described as such. + +## No new RPC and no new table + +The entire wire change is two fields on existing messages: + +```proto +// proto/state/v1/state.proto +message Event { int64 attempt = 11; } +message ReadTaskLogRequest { string stage = 9; } +``` + +No RPC was added, no store table was added, and no new configuration field was +introduced. `docs/prds/state-store-contract.md` is unchanged because no ratified +contract changed; the JSON document rides an existing `data` column over an +existing RPC. + +Both fields are tolerant in both directions, and the degrade is stated rather +than hidden: an old server makes `attempt` read as `0` and `stage` match +nothing, so the page must say the deployment cannot attribute events to attempts +rather than show one run labelled "attempt 1". An old client shows +`config_captured` as an unknown kind, and the Config tab must then say "this +deployment cannot read per-run configuration" — a different claim from "not +captured for this attempt". + +## Retry is a new run + +The retry action is reachable from the run view and produces a new attempt that +appears as a new run. It is a **fresh** run: it resets the branch onto +`origin/` (`internal/worktree.(*Manager).refresh` → `resetOnto`) and +**discards the previous attempt's commits**. Labelling it "restart" would imply +resumption that does not happen, so the control and its confirm copy say so. + +## Honest limits the surface carries + +These are the claims that would otherwise be overstated. Each is a copy or +rendering rule, not a caveat in a comment: + +- **There is no exit code, so no stage shows pass/fail.** `stage_finish` carries + a duration and an optional error string and nothing else. A stage `ok` means + "returned without error", not "the work was correct". The agent's own verdict + is shown separately from the rail. A stage that parks after finishing cleanly + leaves that stage `ok` on a failed task, so attempt status is read together + with task status. +- **The log stage filter only matches lines the workflow bound a stage to.** + Agent and tool output carries no stage and never matches. The pane states that + coverage limit next to the control rather than presenting a filtered view as + the whole story. +- **Absence and unreadability are different answers.** A deployment that cannot + read task logs says so; an attempt whose log does not exist says that. They + are never collapsed, in either direction, for logs or for configuration. +- **An empty changed-files view never means "nothing changed".** No capture + exists for runs predating this change and the forge cannot supply one, so the + empty state reads "not captured for this run". +- **No run-duration figure is shown.** Per-stage durations only: a run can spend + days in `waiting_human`, and one number would understate wall time. +- **No duration is invented** for a stage with no `stage_start`; it reads "not + recorded". +- **Unattributed history is never presented as an attempt.** Events with + `attempt = 0` are reported as a count, not guessed into a run. +- **The configuration shown is the attempt's non-secret task-runtime subset** — + bot identity, models, limits, budgets, dispatch, diff cap, notifications, + forge host, tool policy. It is not the full dashboard configuration and must + never imply it contains providers, repositories, identities or credentials. + +## Route and compatibility + +`#/tasks/{id}` is the detail route; it is deep-linkable and reload-safe. +`#/tasks?task=N` and `#/tasks?status=...` keep working and keep their existing +behaviour, including the nav highlight. The debug view is why the raw view +exists at all: the task list response is capped, so a client-side join has no +row for an older task, and a debug view that silently hid events would be worse +than useless. + +## What this deliberately does not do + +- **No new RPC, table, store interface or configuration field.** Nothing here + needed one, and each would have widened a ratified surface. +- **No exit status, no pass/fail gate badge, no "steps" in the CI sense.** The + reference layout is a CI pipeline; archie's stages are agent runs and the page + must not borrow CI's claims. +- **No backfill** of attempts, change captures or configurations onto runs that + predate the change. +- **No client-side join for configuration.** It arrives in the events response + the page already fetches; there is nothing to join. +- **No change to `docs/prds/state-store-contract.md`.** No ratified contract + moved. + +## Files this change touches + +- `internal/store/`: the `events.attempt` column, its migrator arm, and the + schema-presence test. +- `internal/events/`: `Event.Attempt`, `KindChangesCaptured`, + `KindConfigCaptured`, `ConfigCapturedSchema`. +- `internal/domain/workflow/task/changes.go`: the change value types. +- `internal/worktree/` + `internal/app/agentworker/`: the capture primitive and + its production forwarding. +- `internal/domain/workflow/steps.go`: the capture at commit and push. +- `internal/daemon/`: the per-attempt configuration emit at dispatch. +- `internal/logging/`: `Query.Stage`. +- `internal/webui/`: the three read endpoints and the `stage` log parameter. +- `proto/state/v1/state.proto` + generated stubs: the two field additions. +- `ui/src/`: the detail page, the tab primitive, the rail, and the panel copy. +- `docs/`: this document and `docs/architecture/observability.md`. + +## Acceptance + +1. Two attempts of one task render as two runs, and attempt 1's rail excludes + attempt 2's stages. +2. A task with no stages renders "no stages recorded", never an unexplained + empty rail. +3. A pre-change `archie.db` gains the `attempt` column with `user_version` + still 3, and its old events are reported as unattributed. +4. An attempt with a capture shows per-file added/deleted counts, status, repo + and PR links; an attempt without one says so and never says "no changes". +5. The Config tab shows the attempt's document for the selected attempt only, + with no secret value present in the serialized document. +6. Retry from the run view produces a new attempt shown as a new run, with copy + stating the previous attempt's commits are discarded. +7. The log stage filter narrows to stage-bound lines and the pane states the + coverage limit; `disabled` and `found=false` remain distinguishable. +8. `#/tasks/{id}` survives reload, and `#/tasks?task=N` / `#/tasks?status=...` + are unchanged. +9. The debug view returns the task record and its unfiltered events, each + carrying `attempt`. +10. Run the gate and the dashboard build: `task check` passes clean, `task ui` + has been run so `ui/dist` matches the sources, and every touched package + builds and passes under `-race`. diff --git a/internal/agentexec/taskevents_test.go b/internal/agentexec/taskevents_test.go index f82855014..0a6c0bfcf 100644 --- a/internal/agentexec/taskevents_test.go +++ b/internal/agentexec/taskevents_test.go @@ -46,9 +46,17 @@ func TestForwardTaskEventsPublishesEachEventOnItsTaskSubject(t *testing.T) { }() want := []events.Event{ - {Kind: events.KindStageStart, TaskID: 42, Stage: "baseline"}, - {Kind: events.KindStageFinish, TaskID: 42, Stage: "baseline", Data: map[string]any{"duration_ms": float64(120)}}, - {Kind: events.KindParked, TaskID: 42, Detail: "baseline red"}, + {Kind: events.KindStageStart, TaskID: 42, Stage: "baseline", Attempt: 1}, + {Kind: events.KindStageFinish, TaskID: 42, Stage: "baseline", Attempt: 1, Data: map[string]any{"duration_ms": float64(120)}}, + {Kind: events.KindParked, TaskID: 42, Attempt: 1, Detail: "baseline red"}, + // R4's document rides this bridge too: a worker captures its own + // effective configuration, and the daemon is a different process, so + // the payload has to survive the hop or the Config tab reads nothing. + // The daemon's own key for it is asserted below by name. + {Kind: events.KindConfigCaptured, TaskID: 42, Attempt: 1, Data: map[string]any{ + "schema": events.ConfigCapturedSchema, + "document": map[string]any{"bot_user": "archie"}, + }}, } for _, e := range want { bus.Publish(e) @@ -71,6 +79,21 @@ func TestForwardTaskEventsPublishesEachEventOnItsTaskSubject(t *testing.T) { if got.Kind != want[i].Kind || got.TaskID != want[i].TaskID || got.Stage != want[i].Stage || got.Detail != want[i].Detail { t.Errorf("event %d = %+v, want %+v", i, got, want[i]) } + if got.Attempt != want[i].Attempt { + t.Errorf("event %d attempt = %d, want %d (provenance must not be dropped on the hop)", i, got.Attempt, want[i].Attempt) + } + if got.Kind == events.KindConfigCaptured { + if got.Data["schema"] != events.ConfigCapturedSchema { + t.Errorf("event %d schema = %v, want %q", i, got.Data["schema"], events.ConfigCapturedSchema) + } + if _, renamed := got.Data["config"]; renamed { + t.Errorf(`event %d crossed under "config"; the producer writes the document under "document"`, i) + } + doc, ok := got.Data["document"].(map[string]any) + if !ok || doc["bot_user"] != "archie" { + t.Errorf("event %d document payload = %#v, want the decoded document under its own key", i, got.Data["document"]) + } + } if got.At.IsZero() { t.Errorf("event %d has zero At, want the bus-stamped publish time", i) } diff --git a/internal/app/agentworker/task_execution.go b/internal/app/agentworker/task_execution.go index 41cc0165b..b5832f16f 100644 --- a/internal/app/agentworker/task_execution.go +++ b/internal/app/agentworker/task_execution.go @@ -14,6 +14,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/workflow" "github.com/samcharles93/archie-core/internal/domain/workflow/skillbuild" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workflow/wfeval" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/installtype" @@ -111,6 +112,16 @@ func (h *hybridTrees) ChangedLines(ctx context.Context, dir, base string) (int, return h.local.ChangedLines(ctx, dir, base) } +// ChangedFileStats is the capability the workflow captures a change through. +// It is not part of workflow.Trees: it is asserted for as the unexported +// optional interface package workflow declares, so a Trees implementation +// without it degrades to no capture. Without this forwarder the in-container +// path -- which is every production run, archie-agent executing the whole +// workflow -- would be exactly that silent no-op. +func (h *hybridTrees) ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error) { + return h.local.ChangedFileStats(ctx, dir, base) +} + var _ workflow.Trees = (*hybridTrees)(nil) // chownTree recursively chowns dir to uid:gid so the daemon -- running as diff --git a/internal/app/agentworker/task_execution_test.go b/internal/app/agentworker/task_execution_test.go index 81d57b947..d9a1a203d 100644 --- a/internal/app/agentworker/task_execution_test.go +++ b/internal/app/agentworker/task_execution_test.go @@ -24,6 +24,7 @@ import ( "github.com/samcharles93/archie-core/internal/agentexec" "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" "github.com/samcharles93/archie-core/internal/domain/workintake" "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/forge" @@ -421,6 +422,74 @@ func TestRunTaskExecutesBootstrapWorkflowEndToEnd(t *testing.T) { t.Fatalf("commit identity = author %q <%s>, committer %q <%s>", commit.Author.Name, commit.Author.Email, commit.Committer.Name, commit.Committer.Email) } + + // The change the run produced is captured at the push, through the + // container's hybridTrees, and persisted as durable provenance attributed + // to the attempt -- and captured once more by OpenPR, the first moment a + // capture can carry the pull-request number the view links. This is the + // only end-to-end path that matters: every production workflow.Run executes + // here. + timeline, err := st.TaskEvents(ctx, task.ID) + if err != nil { + t.Fatalf("TaskEvents: %v", err) + } + var captured []events.Event + for _, e := range timeline { + if e.Kind == events.KindChangesCaptured { + captured = append(captured, e) + } + } + if len(captured) != 2 { + t.Fatalf("changes_captured events = %d, want the push capture and the one OpenPR takes (%d)", len(captured), stored.PRNumber) + } + for i, e := range captured { + if e.Attempt != task.Attempt || task.Attempt == 0 { + t.Errorf("capture %d attempt = %d, want the task's own attempt %d", i, e.Attempt, task.Attempt) + } + } + if captured[0].Stage != "commit-push" { + t.Errorf("capture stage = %q, want the capturing stage", captured[0].Stage) + } + data, err := json.Marshal(captured[0].Data) + if err != nil { + t.Fatal(err) + } + var payload struct { + CapturedAfter string `json:"captured_after"` + PRNumber int `json:"pr_number"` + Files []struct { + Path string `json:"path"` + Status string `json:"status"` + } `json:"files"` + } + if err := json.Unmarshal(data, &payload); err != nil { + t.Fatalf("decode capture: %v", err) + } + if payload.CapturedAfter != "commit-push" { + t.Errorf("captured_after = %q, want commit-push", payload.CapturedAfter) + } + if payload.PRNumber != 0 { + t.Errorf("the push capture carries pr_number %d, want 0: no PR existed when it was taken", payload.PRNumber) + } + if len(payload.Files) != 1 || payload.Files[0].Path != ".archie/bootstrap.md" || payload.Files[0].Status != "added" { + t.Errorf("captured files = %+v, want the bootstrap marker as an added file", payload.Files) + } + + finalData, err := json.Marshal(captured[1].Data) + if err != nil { + t.Fatal(err) + } + var final struct { + CapturedAfter string `json:"captured_after"` + PRNumber int `json:"pr_number"` + } + if err := json.Unmarshal(finalData, &final); err != nil { + t.Fatalf("decode the final capture: %v", err) + } + if final.CapturedAfter != "open-pr" || final.PRNumber != stored.PRNumber || final.PRNumber == 0 { + t.Errorf("final capture = %q pr %d, want open-pr carrying the stored PR number %d, without which the changed-files view has nothing to link", + final.CapturedAfter, final.PRNumber, stored.PRNumber) + } } // TestRunTaskRestoresWorktreeOwnershipOnEveryExit pins the half of the @@ -768,3 +837,64 @@ func TestRouteTaskUsesRequestLabelOverride(t *testing.T) { t.Fatalf("routeTask() = %q, want %q (request label override not applied)", wf.Name, "security-review") } } + +// changeStatsReader mirrors the unexported optional interface package workflow +// type-asserts on TaskContext.Trees to capture what an attempt changed. It is +// restated here because an unexported interface cannot be named from this +// package; the assertion below is therefore the only way this side can pin +// that the in-container Trees is capable at all. +type changeStatsReader interface { + ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error) +} + +// TestHybridTreesCanReportWhatChanged is the in-container half of the change +// capture. Every production workflow.Run executes in archie-agent against a +// hybridTrees, so a Trees without this capability would make the capture a +// silent no-op in exactly the deployment that produces all the real data -- +// the daemon-side manager being capable would prove nothing. +func TestHybridTreesCanReportWhatChanged(t *testing.T) { + var trees any = &hybridTrees{local: &worktree.Manager{}} + if _, ok := trees.(changeStatsReader); !ok { + t.Fatal("hybridTrees cannot report a diffstat; every capture inside a container would silently no-op") + } +} + +// TestHybridTreesForwardsChangedFileStatsToItsLocalManager drives the +// capability against a real worktree, so satisfaction of the interface is not +// mistaken for a working forwarder. +func TestHybridTreesForwardsChangedFileStatsToItsLocalManager(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not installed") + } + ctx := t.Context() + host := newLocalRemote(t, "acme", "diffstat") + manager := &worktree.Manager{ + WorkDir: t.TempDir(), Token: "unused", + BotUser: "archie-bot", BotEmail: "archie-bot@example.com", BaseURL: "file://" + host, + } + dir, branch, err := manager.Prepare(ctx, "acme", "diffstat", "main", 4, "feat: widget", "", "") + if err != nil { + t.Fatalf("prepare: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, "widget.txt"), []byte("one\ntwo\n"), 0o644); err != nil { + t.Fatal(err) + } + if _, err := manager.CommitAll(ctx, dir, "feat: widget"); err != nil { + t.Fatalf("commit: %v", err) + } + + trees := &hybridTrees{local: manager, localDir: dir, branch: branch} + stats, err := trees.ChangedFileStats(ctx, dir, "main") + if err != nil { + t.Fatalf("ChangedFileStats: %v", err) + } + if len(stats.Files) != 1 || stats.Files[0].Path != "widget.txt" { + t.Fatalf("files = %+v, want the one committed file", stats.Files) + } + if stats.Totals != (task.ChangeTotals{Files: 1, Additions: 2}) { + t.Errorf("totals = %+v, want the file's two added lines", stats.Totals) + } + if stats.HeadSHA == "" || stats.BaseSHA == "" { + t.Errorf("SHAs = (%q, %q), want both resolved", stats.BaseSHA, stats.HeadSHA) + } +} diff --git a/internal/app/archied/bootstrap.go b/internal/app/archied/bootstrap.go index d9df7d48f..2b42570c1 100644 --- a/internal/app/archied/bootstrap.go +++ b/internal/app/archied/bootstrap.go @@ -346,18 +346,18 @@ func (b *boot) openStores(ctx context.Context) error { // the STATE_STORE_TOKEN secret (§10). It runs after openStores has resolved // b.secrets, and before setupObservability / buildDaemon wire consumers. func (b *boot) openStateStoreAdapter() error { - target := strings.TrimSpace(b.cfg.Services.State.Target) + target := strings.TrimSpace(b.cfg.Services.Get(config.ServiceNameState).Target) if target == "" { return fmt.Errorf("services.state.target is required: archied/archie-gateway no longer own archie.db; the standalone archie-state-store process owns it (docs/prds/state-store-contract.md §12 step 7)") } - client, cleanup, err := composeStateStoreClient(b.cfg.Services.State, b.secrets) + client, cleanup, err := composeStateStoreClient(b.cfg.Services, b.secrets) if err != nil { b.log.Error("state store adapter", "err", err) return err } b.stateStore = client b.stateStoreGrants = &staterpc.GrantIssuer{Client: client} - b.stateStoreToken = stateStoreResolvedToken(b.cfg.Services.State, b.secrets) + b.stateStoreToken = b.cfg.Services.ResolvedToken(config.ServiceNameState, b.secrets.Getenv) b.addCleanup(cleanup) return nil } @@ -617,7 +617,7 @@ func (b *boot) setupLLMAndChat() error { b.setupChatRuntime(cfg) b.setupEmbeddings(cfg, log) - contract, cleanup, err := composeChatContract(cfg.Services.Gateway, b.secrets) + contract, cleanup, err := composeChatContract(cfg.Services, b.secrets) if err != nil { return err } @@ -1427,7 +1427,7 @@ func (b *boot) buildDaemon() { b.d = &daemon.Daemon{ Cfg: b.cfgHolder, ConnectedNATS: daemon.NATSEndpoint{URL: b.natsURL, Token: b.natsToken}, - ConnectedStateStore: daemon.StateStoreEndpoint{URL: strings.TrimSpace(b.cfg.Services.State.Target), Token: b.stateStoreToken}, + ConnectedStateStore: daemon.StateStoreEndpoint{URL: strings.TrimSpace(b.cfg.Services.Get(config.ServiceNameState).Target), Token: b.stateStoreToken}, Store: b.stateStore, Bus: b.bus, Forge: b.forgeClient, diff --git a/internal/app/archied/chat_service.go b/internal/app/archied/chat_service.go index 85bb6d2ef..0fd194303 100644 --- a/internal/app/archied/chat_service.go +++ b/internal/app/archied/chat_service.go @@ -1,9 +1,6 @@ package archied import ( - "fmt" - "strings" - "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/config" @@ -12,32 +9,20 @@ import ( "github.com/samcharles93/archie-core/internal/secret" ) -// gatewayResolvedToken returns the Bearer [REDACTED] a Gateway client -// presents: the explicit [services.gateway].target_token key, then the -// GATEWAY_TOKEN secret/env. The server side (RunGateway) resolves the same -// value, so a distributed consumer and the gateway agree without sharing -// any other configuration. -func gatewayResolvedToken(settings config.ServiceConnection, secrets *secret.Registry) string { - token := settings.TargetToken - if token == "" { - token = secrets.Getenv("GATEWAY_TOKEN") - } - return token -} - // composeChatContract dials the standalone archie-gateway, the sole owner of // ChatContract, from the daemon's own configuration key. Token resolution is // the daemon's (it owns the config keys and the secret registry); the dial // itself and the fail-closed non-loopback rule belong to the transport, so // they come from gatewayrpc.Dial. -func composeChatContract(settings config.ServiceConnection, secrets *secret.Registry, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { - if strings.TrimSpace(settings.Target) == "" { - return nil, nil, fmt.Errorf("services.gateway.target is required") +func composeChatContract(services config.Services, secrets *secret.Registry, options ...grpc.DialOption) (gateway.ChatContract, func(), error) { + target, err := services.RequireTarget(config.ServiceNameGateway) + if err != nil { + return nil, nil, err } // Assigned through a typed variable rather than returned directly: a // direct forward would hand a failed dial's nil *Client back as a // non-nil ChatContract interface. - client, cleanup, err := gatewayrpc.Dial(settings.Target, gatewayResolvedToken(settings, secrets), options...) + client, cleanup, err := gatewayrpc.Dial(target, services.ResolvedToken(config.ServiceNameGateway, secrets.Getenv), options...) if err != nil { return nil, nil, err } diff --git a/internal/app/archied/chat_service_test.go b/internal/app/archied/chat_service_test.go index d4540341b..8bac5cdfd 100644 --- a/internal/app/archied/chat_service_test.go +++ b/internal/app/archied/chat_service_test.go @@ -19,10 +19,10 @@ import ( func TestComposeChatContractRejectsInvalidSettings(t *testing.T) { for _, tt := range []struct { name string - settings config.ServiceConnection + settings config.Services }{ - {name: "missing target", settings: config.ServiceConnection{}}, - {name: "blank target", settings: config.ServiceConnection{Target: " \t\n"}}, + {name: "missing target", settings: config.Services{}}, + {name: "blank target", settings: config.Services{config.ServiceNameGateway: {Target: " \t\n"}}}, } { t.Run(tt.name, func(t *testing.T) { chat, cleanup, err := composeChatContract(tt.settings, &secret.Registry{}) @@ -41,7 +41,7 @@ func TestComposeChatContractRejectsInvalidSettings(t *testing.T) { func TestComposeChatContractNonLoopbackFailsClosed(t *testing.T) { _, _, err := composeChatContract( - config.ServiceConnection{Target: "gateway.example.com:8585"}, + config.Services{config.ServiceNameGateway: {Target: "gateway.example.com:8585"}}, &secret.Registry{}, ) if err == nil { @@ -67,7 +67,7 @@ func TestComposeChatContractRemoteAndCleanup(t *testing.T) { }) chat, cleanup, err := composeChatContract( - config.ServiceConnection{Target: listener.Addr().String()}, + config.Services{config.ServiceNameGateway: {Target: listener.Addr().String()}}, &secret.Registry{}, ) if err != nil { @@ -95,18 +95,22 @@ func TestComposeChatContractRemoteAndCleanup(t *testing.T) { } } +// TestGatewayResolvedToken pins the daemon-side wiring rather than the +// precedence rule itself: config.Services.ResolvedToken owns the rule and is +// tested there, but only this level proves the gateway reads it through the +// secret registry and lands on the env var its registration names. func TestGatewayResolvedToken(t *testing.T) { - if got := gatewayResolvedToken(config.ServiceConnection{TargetToken: "file-token"}, &secret.Registry{}); got != "file-token" { + secrets := &secret.Registry{} + explicit := config.Services{config.ServiceNameGateway: {TargetToken: "file-token"}} + if got := explicit.ResolvedToken(config.ServiceNameGateway, secrets.Getenv); got != "file-token" { t.Fatalf("resolved token = %q, want file-token", got) } t.Setenv("GATEWAY_TOKEN", "environment-token") - if got := gatewayResolvedToken(config.ServiceConnection{}, &secret.Registry{}); got != "environment-token" { + empty := config.Services{config.ServiceNameGateway: {}} + if got := empty.ResolvedToken(config.ServiceNameGateway, secrets.Getenv); got != "environment-token" { t.Fatalf("resolved token = %q, want environment-token", got) } - if got := gatewayResolvedToken( - config.ServiceConnection{TargetToken: "file-token"}, - &secret.Registry{}, - ); got != "file-token" { + if got := explicit.ResolvedToken(config.ServiceNameGateway, secrets.Getenv); got != "file-token" { t.Fatalf("explicit target_token should win over the environment, got %q", got) } } diff --git a/internal/app/archied/chat_store_composition_test.go b/internal/app/archied/chat_store_composition_test.go index 28b358516..8165ff00f 100644 --- a/internal/app/archied/chat_store_composition_test.go +++ b/internal/app/archied/chat_store_composition_test.go @@ -11,8 +11,10 @@ import ( ) func TestRemoteChatCompositionPreservesChannelTurnLedger(t *testing.T) { - cfg := config.Config{DBPath: filepath.Join(t.TempDir(), "tasks.db")} - cfg.Services.Gateway.Target = "127.0.0.1:1" + cfg := config.Config{ + DBPath: filepath.Join(t.TempDir(), "tasks.db"), + Services: config.Services{config.ServiceNameGateway: {Target: "127.0.0.1:1"}}, + } st, err := store.Open(t.Context(), filepath.Join(t.TempDir(), "state-store.db")) if err != nil { t.Fatal(err) diff --git a/internal/app/archied/gateway.go b/internal/app/archied/gateway.go index dc9398a04..49d94d4a4 100644 --- a/internal/app/archied/gateway.go +++ b/internal/app/archied/gateway.go @@ -29,6 +29,24 @@ type GatewayOptions struct { Token string } +// gatewayListenAndToken resolves the two per-listener inputs RunGateway needs: +// the address it binds and the bearer token a non-loopback bind validates. +// +// Both are flag-first and config-second, and both fail closed rather than +// inventing a value -- resolveServiceListen explains why an empty address is an +// error rather than a default. +func gatewayListenAndToken(b *boot, options GatewayOptions) (listen, token string, err error) { + listen, err = resolveServiceListen("gateway", options.Listen, b.cfg.Services.Get(config.ServiceNameGateway).Listen) + if err != nil { + return "", "", err + } + token = options.Token + if token == "" { + token = b.cfg.Services.ResolvedToken(config.ServiceNameGateway, b.secrets.Getenv) + } + return listen, token, nil +} + // RunGateway owns conversation persistence, model runtime and tool-provider // lifecycles. Task-store adapters access the State Store contract (remote // *staterpc.Client via [services.state].target), not archie.db directly: the @@ -85,16 +103,16 @@ func RunGateway(ctx context.Context, options GatewayOptions) error { if err != nil { return err } - gatewayToken := options.Token - if gatewayToken == "" { - gatewayToken = gatewayResolvedToken(b.cfg.Services.Gateway, b.secrets) - } - //nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; gatewayrpc.StreamServerInterceptor derives its context from stream.Context() instead - opts, loopback, err := gatewayServerOpts(options.Listen, gatewayToken) + listen, gatewayToken, err := gatewayListenAndToken(b, options) if err != nil { return err } - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", options.Listen) + //nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; gatewayrpc.StreamServerInterceptor derives its context from stream.Context() instead + opts, loopback, err := gatewayServerOpts(listen, gatewayToken) + if err != nil { + return err + } + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen) if err != nil { return fmt.Errorf("listen for gateway: %w", err) } diff --git a/internal/app/archied/listen.go b/internal/app/archied/listen.go new file mode 100644 index 000000000..d8a5fa3b0 --- /dev/null +++ b/internal/app/archied/listen.go @@ -0,0 +1,34 @@ +package archied + +import ( + "fmt" + "strings" +) + +// resolveServiceListen picks the address a service listener binds: the -listen +// flag when it was given, else the address the configuration names. +// +// Both services this repository runs used to take their address from a flag +// default alone, with no config key. The port a service binds and the port its +// clients dial were therefore two separate facts -- the flag default (or a +// hand-passed -listen) and [services.].target -- with nothing keeping +// them in step. On a host that already owned the default (cockpit owns 9090) +// retargeting meant hand-writing an overlay and passing a matching flag, and +// the failure looked like a code fault: the listener died with "address already +// in use" while every client reported a gRPC handshake error against whatever +// else held the port. +// +// An empty result is an error, never a fallback: net.Listen treats "" as "any +// free port", so defaulting here would bind the service somewhere its clients +// do not look and report success while doing it. +func resolveServiceListen(service, flagValue, configured string) (string, error) { + if v := strings.TrimSpace(flagValue); v != "" { + return v, nil + } + if v := strings.TrimSpace(configured); v != "" { + return v, nil + } + return "", fmt.Errorf( + "%s: no listen address: pass -listen or set [services.%s].listen", service, service, + ) +} diff --git a/internal/app/archied/listen_test.go b/internal/app/archied/listen_test.go new file mode 100644 index 000000000..8fc22ed95 --- /dev/null +++ b/internal/app/archied/listen_test.go @@ -0,0 +1,58 @@ +package archied + +import "testing" + +// TestResolveServiceListen pins the precedence: an explicit -listen wins, else +// the configured address, and an address is never invented. +// +// The error cases are the ones that matter. net.Listen reads "" as "any free +// port", so defaulting here would bind the service somewhere its clients do not +// look and report success while doing it -- the exact failure this helper exists +// to make impossible. +func TestResolveServiceListen(t *testing.T) { + for _, tt := range []struct { + name, flagValue, configured, want string + wantErr bool + }{ + { + name: "the flag wins over the configured address", + flagValue: "127.0.0.1:9191", configured: "127.0.0.1:9090", + want: "127.0.0.1:9191", + }, + { + name: "the configured address is used when no flag was passed", + configured: "127.0.0.1:9191", + want: "127.0.0.1:9191", + }, + { + name: "a whitespace flag is not an address", + flagValue: " ", configured: "127.0.0.1:9191", + want: "127.0.0.1:9191", + }, + { + name: "both empty is an error, never a silent ephemeral port", + wantErr: true, + }, + { + name: "whitespace on both sides is an error too", + flagValue: " ", configured: "\t", + wantErr: true, + }, + } { + t.Run(tt.name, func(t *testing.T) { + got, err := resolveServiceListen("state", tt.flagValue, tt.configured) + if tt.wantErr { + if err == nil { + t.Fatalf("err = nil, want an error; got %q", got) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if got != tt.want { + t.Fatalf("listen = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/app/archied/setup_test.go b/internal/app/archied/setup_test.go index c3348e084..7e9e69e6f 100644 --- a/internal/app/archied/setup_test.go +++ b/internal/app/archied/setup_test.go @@ -275,7 +275,7 @@ func TestRunSetup_GeneratedConfigSatisfiesDaemonRequirements(t *testing.T) { } // openStateStoreAdapter refuses an empty target, so this is the difference // between a config that boots and one that does not. - if doc.Config.Services.State.Target == "" { + if doc.Config.Services.Get(config.ServiceNameState).Target == "" { t.Error("generated config leaves services.state.target empty; the daemon would not boot") } if doc.Config.BotUser == "" { diff --git a/internal/app/archied/state_store.go b/internal/app/archied/state_store.go index d2f2eea3f..4602e9620 100644 --- a/internal/app/archied/state_store.go +++ b/internal/app/archied/state_store.go @@ -19,6 +19,7 @@ import ( "google.golang.org/grpc" + "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/storecontract" "github.com/samcharles93/archie-core/internal/infrastructure/readiness" @@ -56,22 +57,26 @@ func RunStateStore(ctx context.Context, options StateStoreOptions) error { if err := b.loadConfig(ctx, options.Config, options.Overlay, false); err != nil { return err } - b.log = b.log.With("component", "state-store") + listen, err := resolveServiceListen("state", options.Listen, b.cfg.Services.Get(config.ServiceNameState).Listen) + if err != nil { + return err + } + b.log = b.log.With("component", "state-store", "listen", listen) if err := b.openStateStore(ctx); err != nil { return err } token := options.Token if token == "" { - token = stateStoreResolvedToken(b.cfg.Services.State, b.secrets) + token = b.cfg.Services.ResolvedToken(config.ServiceNameState, b.secrets.Getenv) } grants := &staterpc.TaskGrants{} //nolint:contextcheck // grpc.StreamServerInterceptor has no context.Context parameter; TaskGrants.StreamInterceptor derives its context from stream.Context() instead - opts, loopback, err := stateStoreServerOpts(options.Listen, token, grants) + opts, loopback, err := stateStoreServerOpts(listen, token, grants) if err != nil { return err } - listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", options.Listen) + listener, err := (&net.ListenConfig{}).Listen(ctx, "tcp", listen) if err != nil { return fmt.Errorf("listen for state store: %w", err) } diff --git a/internal/app/archied/state_store_client.go b/internal/app/archied/state_store_client.go index 3e5c31694..d8e8e4a96 100644 --- a/internal/app/archied/state_store_client.go +++ b/internal/app/archied/state_store_client.go @@ -1,36 +1,20 @@ package archied import ( - "fmt" - "strings" - "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" "github.com/samcharles93/archie-core/internal/secret" ) -// stateStoreResolvedToken returns the bearer token a State Store client -// presents: the explicit [services.state].target_token key, then the -// STATE_STORE_TOKEN secret/env. The daemon injects the same token into agent -// containers as STATE_STORE_TOKEN so the agent authenticates to the same -// remote store the daemon dials. -func stateStoreResolvedToken(settings config.ServiceConnection, secrets *secret.Registry) string { - token := settings.TargetToken - if token == "" { - token = secrets.Getenv("STATE_STORE_TOKEN") - } - return token -} - // composeStateStoreClient dials the State Store gRPC service the daemon's own // capture/mapping/binding consumers call. Token resolution is the daemon's // (it owns the config keys and the secret registry); the dial itself and the // fail-closed non-loopback rule (§9) belong to the transport, so they come // from staterpc.Dial. -func composeStateStoreClient(settings config.ServiceConnection, secrets *secret.Registry) (*staterpc.Client, func(), error) { - target := strings.TrimSpace(settings.Target) - if target == "" { - return nil, nil, fmt.Errorf("services.state.target is required") +func composeStateStoreClient(services config.Services, secrets *secret.Registry) (*staterpc.Client, func(), error) { + target, err := services.RequireTarget(config.ServiceNameState) + if err != nil { + return nil, nil, err } - return staterpc.Dial(target, stateStoreResolvedToken(settings, secrets)) + return staterpc.Dial(target, services.ResolvedToken(config.ServiceNameState, secrets.Getenv)) } diff --git a/internal/app/archied/state_store_client_test.go b/internal/app/archied/state_store_client_test.go index 780859524..5fabfd7e4 100644 --- a/internal/app/archied/state_store_client_test.go +++ b/internal/app/archied/state_store_client_test.go @@ -9,7 +9,7 @@ import ( ) func TestComposeStateStoreClientRequiresTarget(t *testing.T) { - _, _, err := composeStateStoreClient(config.ServiceConnection{}, &secret.Registry{}) + _, _, err := composeStateStoreClient(config.Services{}, &secret.Registry{}) if err == nil { t.Fatal("empty target should error") } @@ -29,7 +29,7 @@ func TestComposeStateStoreClientNonLoopbackFailsClosed(t *testing.T) { {name: "hostname without token", target: "store.example.com:9090"}, } { t.Run(tt.name, func(t *testing.T) { - _, _, err := composeStateStoreClient(config.ServiceConnection{Target: tt.target}, &secret.Registry{}) + _, _, err := composeStateStoreClient(config.Services{config.ServiceNameState: {Target: tt.target}}, &secret.Registry{}) if err == nil { t.Fatalf("non-loopback %q without a token should fail closed (docs/prds/state-store-contract.md §9)", tt.target) } @@ -38,7 +38,7 @@ func TestComposeStateStoreClientNonLoopbackFailsClosed(t *testing.T) { } func TestComposeStateStoreClientLoopbackSucceeds(t *testing.T) { - st, cleanup, err := composeStateStoreClient(config.ServiceConnection{Target: "127.0.0.1:9090"}, &secret.Registry{}) + st, cleanup, err := composeStateStoreClient(config.Services{config.ServiceNameState: {Target: "127.0.0.1:9090"}}, &secret.Registry{}) if err != nil { t.Fatalf("loopback without token should succeed: %v", err) } @@ -54,7 +54,7 @@ func TestComposeStateStoreClientLoopbackSucceeds(t *testing.T) { func TestComposeStateStoreClientTokenFromTargetToken(t *testing.T) { // Non-loopback with a configured token must not fail closed; the interceptor // is what carries it, so the client is dialable. - st, _, err := composeStateStoreClient(config.ServiceConnection{Target: "0.0.0.0:9090", TargetToken: "secret"}, &secret.Registry{}) + st, _, err := composeStateStoreClient(config.Services{config.ServiceNameState: {Target: "0.0.0.0:9090", TargetToken: "secret"}}, &secret.Registry{}) if err != nil { t.Fatalf("non-loopback with a token should succeed: %v", err) } @@ -79,7 +79,7 @@ func TestOpenStateStoreAdapterRemoteFailsClosed(t *testing.T) { t.Setenv("STATE_STORE_TOKEN", "") b := newBootstrap() b.secrets = &secret.Registry{} - b.cfg.Services.State = config.ServiceConnection{Target: "0.0.0.0:9090"} + b.cfg.Services = config.Services{config.ServiceNameState: {Target: "0.0.0.0:9090"}} if err := b.openStateStoreAdapter(); err == nil { t.Fatal("non-loopback without a token should fail closed") } diff --git a/internal/app/archied/state_store_regression_test.go b/internal/app/archied/state_store_regression_test.go index 6c5ae8005..7410709fc 100644 --- a/internal/app/archied/state_store_regression_test.go +++ b/internal/app/archied/state_store_regression_test.go @@ -44,7 +44,7 @@ func TestExternalServicesDoNotRequireBridgeNetwork(t *testing.T) { cfg := config.Config{} cfg.NATS.Mode = config.NATSModeExternal cfg.Containers.Network = "host" - cfg.Services.State.Target = "state.example.test:9090" + cfg.Services = config.Services{config.ServiceNameState: {Target: "state.example.test:9090"}} pool, _, cleanup := startContainers(t.Context(), cfg, slog.New(slog.DiscardHandler)) defer cleanup() if pool == nil { diff --git a/internal/app/archieui/config.go b/internal/app/archieui/config.go index 343b7a5d4..bd4776755 100644 --- a/internal/app/archieui/config.go +++ b/internal/app/archieui/config.go @@ -77,8 +77,8 @@ func project(cfg config.Config) projection { return projection{ listen: cfg.Web.Listen, trustForwardedHeaders: cfg.Web.TrustForwardedHeaders, - gateway: ServiceTarget{Target: cfg.Services.Gateway.Target, Token: cfg.Services.Gateway.TargetToken}, - state: ServiceTarget{Target: cfg.Services.State.Target, Token: cfg.Services.State.TargetToken}, + gateway: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameGateway).Target, Token: cfg.Services.Get(config.ServiceNameGateway).TargetToken}, + state: ServiceTarget{Target: cfg.Services.Get(config.ServiceNameState).Target, Token: cfg.Services.Get(config.ServiceNameState).TargetToken}, capture: CaptureOptions{ Retention: cfg.Capture.Retention.Std(), MaxEvents: cfg.Capture.MaxEvents, diff --git a/internal/app/archieui/config_test.go b/internal/app/archieui/config_test.go index c70dc1bf6..5c495530a 100644 --- a/internal/app/archieui/config_test.go +++ b/internal/app/archieui/config_test.go @@ -47,7 +47,7 @@ target_token = "state-token" // TestResolveReadsOnlyTheAllowlistedConfigProjection pins the maintainer's // decision for this bead: the UI process does read config.toml, but only -// Services.Gateway.{Target,TargetToken}, Services.State.{Target,TargetToken} +// Services.Get("gateway").{Target,TargetToken} and the same for "state" // and Web.{Listen,TrustForwardedHeaders}. Options has no field that could // carry anything else, so this asserts the six values arrive and the daemon's // own settings have nowhere to land. diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go index f33d87109..38b5a16a5 100644 --- a/internal/app/archieui/run_test.go +++ b/internal/app/archieui/run_test.go @@ -9,13 +9,16 @@ import ( "net/http" "net/http/httptest" "path/filepath" + "strconv" "strings" "testing" + "time" "google.golang.org/grpc" "github.com/samcharles93/archie-core/internal/domain/health" "github.com/samcharles93/archie-core/internal/domain/messaging" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gateway" "github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc" "github.com/samcharles93/archie-core/internal/infrastructure/staterpc" @@ -100,13 +103,16 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { t.Fatalf("open temp store: %v", err) } defer st.Close() - if _, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "remote summary", "body", "implement", ""); err != nil { + seeded, err := st.EnqueueChatTask(t.Context(), "acme", "widget", "remote summary", "body", "implement", "") + if err != nil { t.Fatalf("seed task: %v", err) } // The daemon publishes the configuration page's projection; this process - // only renders it (archie-core-ymut). + // only renders it (archie-core-ymut). The forge host is published too: it + // is what the run-detail reads resolve their repository and pull-request + // links from, the same projection the task list uses. published, err := json.Marshal(webui.ConfigView{ - Identity: webui.IdentityView{BotUser: "archie", ForgeType: "github"}, + Identity: webui.IdentityView{BotUser: "archie", ForgeType: "github", ForgeHost: "https://forge.example"}, Editable: true, }) if err != nil { @@ -118,6 +124,32 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { t.Fatalf("publish config snapshot: %v", err) } + // The other half of the configuration page is per-attempt provenance, and + // the three run-detail reads are backed by the same State Store contract as + // the rest of the task surface. The statements below are what other + // processes write in production -- the daemon's dispatch capture, the + // worker's change capture -- attributed to one attempt, so the assertions + // further down read them back through the real client rather than a fake. + seedAt := time.Now().UTC() + for _, e := range []events.Event{ + {Kind: events.KindStageStart, TaskID: seeded.ID, Attempt: 1, Stage: "prepare", At: seedAt}, + {Kind: events.KindStageFinish, TaskID: seeded.ID, Attempt: 1, Stage: "prepare", At: seedAt.Add(time.Second), Data: map[string]any{"duration_ms": 1000}}, + {Kind: events.KindConfigCaptured, TaskID: seeded.ID, Attempt: 1, At: seedAt, Data: map[string]any{ + "schema": events.ConfigCapturedSchema, "document": map[string]any{"bot_user": "archie"}, + }}, + {Kind: events.KindChangesCaptured, TaskID: seeded.ID, Attempt: 1, Stage: "open-pr", At: seedAt, Data: map[string]any{ + "schema": events.ChangesCapturedSchema, "owner": "acme", "repo": "widget", + "base": "main", "branch": "feat/1-widget", "head_sha": "head-sha", "base_sha": "base-sha", + "pr_number": 7, "captured_after": "open-pr", "truncated": false, + "files": []any{map[string]any{"path": "internal/x.go", "old_path": "", "status": "modified", "additions": 12, "deletions": 3, "binary": false}}, + "totals": map[string]any{"files": 1, "additions": 12, "deletions": 3}, + }}, + } { + if _, err := st.InsertEvent(t.Context(), e); err != nil { + t.Fatalf("seed %s event: %v", e.Kind, err) + } + } + stateTarget, stopState := serveGRPC(t, func(r grpc.ServiceRegistrar) { staterpc.RegisterServer(r, staterpc.Deps{Tasks: st, Captures: st, BindingDispatcher: st, ConfigSnapshots: st, Log: slog.New(slog.DiscardHandler)}) }) @@ -240,6 +272,96 @@ func TestUIServesDashboardAgainstRemoteContracts(t *testing.T) { t.Errorf("PATCH /api/config = %d, want 503: the daemon stays the configuration writer (PRD lines 95-96)", resp.StatusCode) } + // The run-detail reads. These three routes have no fake behind them: the + // rail, the capture and the raw event list all come back over the State + // Store listener the UI dialled, so each assertion below is the real + // client's answer about the attempt-attributed set seeded above. + taskPath := "/api/tasks/" + strconv.FormatInt(seeded.ID, 10) + code, body = get(taskPath + "/attempts") + if code != http.StatusOK { + t.Fatalf("GET /attempts = %d (%s), want 200", code, body) + } + var rail struct { + Attempts []struct { + Attempt int `json:"attempt"` + Status string `json:"status"` + Stages []struct { + Name string `json:"name"` + Status string `json:"status"` + } `json:"stages"` + } `json:"attempts"` + } + if err := json.Unmarshal(body, &rail); err != nil { + t.Fatalf("decode attempts: %v (%s)", err, body) + } + if len(rail.Attempts) != 1 || rail.Attempts[0].Attempt != 1 || rail.Attempts[0].Status != "ok" { + t.Fatalf("attempts = %s, want exactly the seeded attempt 1 recorded ok", body) + } + if len(rail.Attempts[0].Stages) != 1 || rail.Attempts[0].Stages[0].Name != "prepare" || rail.Attempts[0].Stages[0].Status != "ok" { + t.Fatalf("stage rail = %s, want the attempt's own prepare stage", body) + } + + code, body = get(taskPath + "/changes?attempt=1") + if code != http.StatusOK { + t.Fatalf("GET /changes = %d (%s), want 200", code, body) + } + var changes struct { + Found bool `json:"found"` + Captures []struct { + PRNumber int `json:"pr_number"` + PRURL string `json:"pr_url"` + Files []struct { + Path string `json:"path"` + } `json:"files"` + } `json:"captures"` + } + if err := json.Unmarshal(body, &changes); err != nil { + t.Fatalf("decode changes: %v (%s)", err, body) + } + if !changes.Found || len(changes.Captures) != 1 { + t.Fatalf("changes = %s, want the one capture recorded for the attempt", body) + } + if changes.Captures[0].PRNumber != 7 || changes.Captures[0].PRURL != "https://forge.example/acme/widget/pull/7" { + t.Errorf("capture = pr %d %q, want #7 linked through the published forge projection (%s)", + changes.Captures[0].PRNumber, changes.Captures[0].PRURL, body) + } + if len(changes.Captures[0].Files) != 1 || changes.Captures[0].Files[0].Path != "internal/x.go" { + t.Errorf("capture files = %s, want the file the attempt changed", body) + } + + code, body = get(taskPath + "/debug?attempt=1") + if code != http.StatusOK { + t.Fatalf("GET /debug = %d (%s), want 200", code, body) + } + var debug struct { + Attempt int `json:"attempt"` + Task struct { + ID int64 `json:"id"` + } `json:"task"` + Events []struct { + Kind string `json:"kind"` + Attempt int `json:"attempt"` + } `json:"events"` + } + if err := json.Unmarshal(body, &debug); err != nil { + t.Fatalf("decode debug: %v (%s)", err, body) + } + if debug.Task.ID != seeded.ID || debug.Attempt != 1 { + t.Errorf("debug = task %d attempt %d, want the seeded task and attempt 1 (%s)", debug.Task.ID, debug.Attempt, body) + } + kinds := map[string]int{} + for _, e := range debug.Events { + kinds[e.Kind]++ + if e.Attempt != 1 { + t.Errorf("debug event %s carries attempt %d, want 1: attribution must survive the store it was read from", e.Kind, e.Attempt) + } + } + for _, kind := range []string{events.KindStageStart, events.KindStageFinish, events.KindConfigCaptured, events.KindChangesCaptured} { + if kinds[kind] != 1 { + t.Errorf("debug events = %s, want exactly one %s", body, kind) + } + } + // Routes with no contract behind them degrade rather than panic. code, body = get("/api/logs") if code != http.StatusOK { diff --git a/internal/config/services.go b/internal/config/services.go index 6f9e03057..eda25ffb2 100644 --- a/internal/config/services.go +++ b/internal/config/services.go @@ -1,23 +1,75 @@ package config -// Services selects contract adapters at application composition time. -type Services struct { - Gateway ServiceConnection `toml:"gateway" yaml:"gateway"` - // State selects the State Store contract adapter. The State Store is its - // own process (cmd/archie-state-store) and owns archie.db; an empty Target - // is a startup error in archied/archie-gateway, which no longer serve a - // local store (docs/prds/state-store-contract.md §12 step 7). The daemon - // and agent dial the remote StateStoreService and present target_token - // when the target is non-loopback. Token resolution mirrors the daemon's: - // the explicit key, then the STATE_STORE_TOKEN secret/env var. - State ServiceConnection `toml:"state" yaml:"state"` +import ( + "fmt" + "strings" +) + +// Services maps a registered service name to its connection settings, keyed by +// the [services.] section it was decoded from. +// +// It was a struct with one field per service. That stated each service's name +// three times over -- here, in the loader's defaulting branches, and at every +// consumer's field access -- so a new service meant editing all three and +// nothing prevented them disagreeing. Which names are legitimate now comes +// from RegisterService; see ServiceSpec. +type Services map[string]ServiceConnection + +// Get returns the connection configured for name, or the zero value when the +// configuration carries no section for it. A registered service always has an +// entry once defaults have been applied. +func (s Services) Get(name string) ServiceConnection { + return s[name] } -// ServiceConnection is a contract adapter's gRPC address plus the bearer -// token a client presents when the target is non-loopback. It does not -// register services or start listeners. Changes require a daemon restart. +// ResolvedToken is the bearer token a client presents when dialling name: the +// explicit target_token if set, otherwise the environment variable the service +// registered. getenv is passed in rather than read directly so this stays free +// of internal/secret, which imports this package. +// +// This replaces two resolvers that were identical apart from the variable name +// each hard-coded. +func (s Services) ResolvedToken(name string, getenv func(string) string) string { + if token := s[name].TargetToken; token != "" { + return token + } + spec, ok := LookupService(name) + if !ok || spec.TokenEnv == "" { + return "" + } + return getenv(spec.TokenEnv) +} + +// RequireTarget returns the dial address for name, or an error naming the +// config key when the operator has not supplied one. +// +// A service registered with an empty default target is one the operator must +// configure, so this is the registry's own contract rather than a consumer's +// private rule. It stays a lazy check at composition time, not a load-time +// validation: a process that never dials a given service must still be able to +// load a configuration that omits it. +func (s Services) RequireTarget(name string) (string, error) { + target := strings.TrimSpace(s[name].Target) + if target == "" { + return "", fmt.Errorf("services.%s.target is required", name) + } + return target, nil +} + +// ServiceConnection is a service's gRPC addresses plus the bearer token a +// client presents when the target is non-loopback. A client reads only Target +// and TargetToken; Listen belongs to the process that owns the service. The +// struct does not itself register services or start listeners. Changes require +// a daemon restart. type ServiceConnection struct { Target string `toml:"target" yaml:"target"` + // Listen is the address the process that OWNS this service binds + // (archie-state-store, archie-gateway). It is read only by that process; + // every client ignores it. Defaulted from the service's registration, so + // a loaded config is never empty here -- an empty address reaches + // net.Listen as "any free port", which would silently move the service + // off the address its clients dial. + Listen string `toml:"listen" yaml:"listen"` // TargetToken is the bearer token a client (daemon or agent) presents // when dialing a non-loopback service target, and the standalone // archie-state-store server validates. Empty means no token, which is diff --git a/internal/config/services_test.go b/internal/config/services_test.go new file mode 100644 index 000000000..10325fbbe --- /dev/null +++ b/internal/config/services_test.go @@ -0,0 +1,225 @@ +package config_test + +import ( + "fmt" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/config" +) + +// TestRegisterServiceIsTheSingleDeclaration pins criterion 3 of +// docs/prds/service-registry.md: a service is declared by one call carrying the +// five fields it actually has, and every later layer reads that declaration +// rather than restating the name. +func TestRegisterServiceIsTheSingleDeclaration(t *testing.T) { + config.RegisterService(config.ServiceBoth, "widget", "127.0.0.1:7001", "127.0.0.1:7002", "WIDGET_TOKEN") + + spec, ok := config.LookupService("widget") + if !ok { + t.Fatal("LookupService(widget) = false, want the service just registered") + } + if spec.Context != config.ServiceBoth { + t.Errorf("Context = %q, want %q", spec.Context, config.ServiceBoth) + } + if spec.Target != "127.0.0.1:7001" { + t.Errorf("Target = %q, want the registered default", spec.Target) + } + if spec.Listen != "127.0.0.1:7002" { + t.Errorf("Listen = %q, want the registered default", spec.Listen) + } + if spec.TokenEnv != "WIDGET_TOKEN" { + t.Errorf("TokenEnv = %q, want the registered env var", spec.TokenEnv) + } +} + +// TestBuiltInServicesAreRegistered pins that the two services the daemon ships +// are declared through the same entry point as any other, with the asymmetry +// the old struct form left unstated: state has no default target, so the +// operator must supply one, while gateway does. +func TestBuiltInServicesAreRegistered(t *testing.T) { + state, ok := config.LookupService("state") + if !ok { + t.Fatal("LookupService(state) = false, want the State Store registered") + } + if state.Target != "" { + t.Errorf("state Target default = %q, want empty: services.state.target is operator-supplied", state.Target) + } + if state.Listen == "" { + t.Error("state Listen default is empty, want an address: an empty listen reaches net.Listen as any free port") + } + if state.TokenEnv != "STATE_STORE_TOKEN" { + t.Errorf("state TokenEnv = %q, want STATE_STORE_TOKEN", state.TokenEnv) + } + + gateway, ok := config.LookupService("gateway") + if !ok { + t.Fatal("LookupService(gateway) = false, want the Gateway registered") + } + if gateway.Target == "" { + t.Error("gateway Target default is empty, want an address: the gateway target is defaulted, not operator-supplied") + } + if gateway.TokenEnv != "GATEWAY_TOKEN" { + t.Errorf("gateway TokenEnv = %q, want GATEWAY_TOKEN", gateway.TokenEnv) + } +} + +// TestUnregisteredServiceIsNotFound keeps the registry the authority on which +// names exist, which is what lets the loader report a typo'd [services.gatway] +// as an unknown key once Services is a map that would otherwise swallow it. +func TestUnregisteredServiceIsNotFound(t *testing.T) { + if _, ok := config.LookupService("gatway"); ok { + t.Error("LookupService(gatway) = true, want false for an unregistered name") + } +} + +// TestServicesGetReturnsTheNamedConnection pins lookup by name, which replaced +// per-service struct field access, so adding a service needs no new field. +func TestServicesGetReturnsTheNamedConnection(t *testing.T) { + services := config.Services{ + "state": {Target: "10.0.0.1:9090", Listen: "0.0.0.0:9090", TargetToken: "explicit"}, + } + got := services.Get("state") + if got.Target != "10.0.0.1:9090" { + t.Errorf("Get(state).Target = %q, want the configured target", got.Target) + } + if services.Get("absent") != (config.ServiceConnection{}) { + t.Error("Get(absent) returned a non-zero connection, want the zero value") + } +} + +// TestResolvedTokenPrefersTheExplicitKey pins the precedence the two +// hand-copied resolvers used: the config key wins, and the registered env var +// is only a fallback. +func TestResolvedTokenPrefersTheExplicitKey(t *testing.T) { + config.RegisterService(config.ServiceClient, "widget-explicit", "", "127.0.0.1:7003", "WIDGET_EXPLICIT_TOKEN") + services := config.Services{"widget-explicit": {TargetToken: "from-config"}} + + getenv := func(string) string { return "from-env" } + if got := services.ResolvedToken("widget-explicit", getenv); got != "from-config" { + t.Errorf("ResolvedToken = %q, want the explicit target_token to win", got) + } +} + +// TestResolvedTokenFallsBackToTheRegisteredEnvVar is the half that the old +// stateStoreResolvedToken and gatewayResolvedToken duplicated, differing only +// in the env var name they hard-coded. +func TestResolvedTokenFallsBackToTheRegisteredEnvVar(t *testing.T) { + config.RegisterService(config.ServiceClient, "widget-env", "", "127.0.0.1:7004", "WIDGET_ENV_TOKEN") + services := config.Services{"widget-env": {}} + + var asked string + getenv := func(name string) string { + asked = name + return "from-env" + } + if got := services.ResolvedToken("widget-env", getenv); got != "from-env" { + t.Errorf("ResolvedToken = %q, want the env fallback", got) + } + if asked != "WIDGET_ENV_TOKEN" { + t.Errorf("read env var %q, want the name from the registration", asked) + } +} + +// TestResolvedTokenOfUnregisteredServiceHasNoEnvFallback keeps an unknown name +// from reaching os.Getenv("") and returning something surprising. +func TestResolvedTokenOfUnregisteredServiceHasNoEnvFallback(t *testing.T) { + services := config.Services{"gatway": {}} + getenv := func(string) string { + t.Error("getenv called for an unregistered service, want no env fallback") + return "leaked" + } + if got := services.ResolvedToken("gatway", getenv); got != "" { + t.Errorf("ResolvedToken = %q, want empty", got) + } +} + +// mustPanic runs fn and returns the recovered value, or fails if fn returned +// normally. Registration errors are programming errors in this repository's +// own init(), not operator input, so they abort the process rather than +// returning an error nobody is positioned to handle. +func mustPanic(t *testing.T, fn func()) (recovered any) { + t.Helper() + defer func() { recovered = recover() }() + fn() + t.Fatal("RegisterService returned normally, want a panic") + return nil +} + +// TestRegisterServiceRejectsAnUnknownContext makes Context load-bearing. It +// documented which addresses a service must end up with, but nothing read it, +// so a typo'd context was accepted and silently meant nothing. +func TestRegisterServiceRejectsAnUnknownContext(t *testing.T) { + got := mustPanic(t, func() { + config.RegisterService("clientt", "widget-badcontext", "", "127.0.0.1:7005", "T") + }) + if !strings.Contains(fmt.Sprint(got), "clientt") { + t.Errorf("panic = %v, want it to name the invalid context", got) + } +} + +// TestRegisterServiceRejectsAHostedServiceWithNoListen pins the requirement +// Context exists to express: a service this repository hosts must have a +// default bind address, because an empty one reaches net.Listen as "any free +// port". +func TestRegisterServiceRejectsAHostedServiceWithNoListen(t *testing.T) { + for _, hosted := range []string{config.ServiceServer, config.ServiceBoth} { + t.Run(hosted, func(t *testing.T) { + got := mustPanic(t, func() { + config.RegisterService(hosted, "widget-nolisten-"+hosted, "127.0.0.1:1", "", "T") + }) + if !strings.Contains(fmt.Sprint(got), "listen") { + t.Errorf("panic = %v, want it to name the missing listen address", got) + } + }) + } +} + +// TestRegisterServiceAcceptsAClientWithNoTargetDefault keeps the State Store's +// own shape legal: a dialled-only service may register an empty target, which +// is how "the operator must supply this" is stated. +func TestRegisterServiceAcceptsAClientWithNoTargetDefault(t *testing.T) { + defer func() { + if r := recover(); r != nil { + t.Fatalf("RegisterService panicked on a legal client registration: %v", r) + } + }() + config.RegisterService(config.ServiceClient, "widget-clientok", "", "127.0.0.1:7006", "T") +} + +// TestRequireTargetReportsAnAbsentOperatorSuppliedTarget moves the "target is +// required" check off two hand-written consumer copies and onto the registry, +// which is what declared the target operator-supplied in the first place. +func TestRequireTargetReportsAnAbsentOperatorSuppliedTarget(t *testing.T) { + for _, tt := range []struct { + name string + target string + want string + wantErr bool + }{ + {name: "absent", wantErr: true}, + {name: "blank", target: " \t\n", wantErr: true}, + {name: "set", target: "10.0.0.1:9090", want: "10.0.0.1:9090"}, + {name: "set with padding", target: " 10.0.0.1:9090 ", want: "10.0.0.1:9090"}, + } { + t.Run(tt.name, func(t *testing.T) { + services := config.Services{config.ServiceNameState: {Target: tt.target}} + got, err := services.RequireTarget(config.ServiceNameState) + if tt.wantErr { + if err == nil { + t.Fatal("RequireTarget returned no error for an empty target") + } + if !strings.Contains(err.Error(), "services.state.target") { + t.Errorf("error = %v, want it to name the config key", err) + } + return + } + if err != nil { + t.Fatalf("RequireTarget: %v", err) + } + if got != tt.want { + t.Errorf("RequireTarget = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/internal/config/servicespec.go b/internal/config/servicespec.go new file mode 100644 index 000000000..900aebf01 --- /dev/null +++ b/internal/config/servicespec.go @@ -0,0 +1,130 @@ +package config + +import ( + "fmt" + "sort" + "strings" + "sync" +) + +// Service contexts. The context decides which addresses a service must end up +// with: a process that owns a service needs a listen address, and a process +// that dials one needs a target. +const ( + // ServiceClient is dialled but not hosted by this repository. + ServiceClient = "client" + // ServiceServer is hosted but not dialled. + ServiceServer = "server" + // ServiceBoth is hosted by one of our processes and dialled by others. + ServiceBoth = "both" +) + +// ServiceSpec is everything the codebase knows about one service that is not +// operator input. It exists so a service is declared once: the name, its +// defaults, and the environment variable its token falls back to were +// previously a struct field, a defaulting branch, and a hand-copied resolver +// in three separate packages, with nothing keeping them in step. +type ServiceSpec struct { + // Context is ServiceClient, ServiceServer, or ServiceBoth. + Context string + // Name is the [services.] section and the key callers look up. + Name string + // Target is the default dial address. Empty means there is no default + // and the operator must supply one, which is how "services.state.target + // is required" is stated without a branch that names the service. + Target string + // Listen is the default bind address for the process that owns the + // service. It is never empty for a hosted service: an empty address + // reaches net.Listen as "any free port", silently moving the service + // off the address its clients dial. + Listen string + // TokenEnv names the environment variable a client falls back to when + // [services.].target_token is empty. + TokenEnv string +} + +// Registered service names. They live beside the registrations below so the +// spelling a consumer looks up and the spelling that was registered are the +// same token, not two string literals that a typo can separate. +const ( + ServiceNameGateway = "gateway" + ServiceNameState = "state" +) + +var ( + serviceRegistryMu sync.RWMutex + serviceRegistry = map[string]ServiceSpec{} +) + +// RegisterService declares one service. It is the single entry point the +// design calls for: adding a service is this call plus its consumer, with no +// new struct field, defaulting branch, or accessor anywhere else. +// +// Re-registering a name replaces the previous spec, so a test can install a +// throwaway service without disturbing the built-ins. +// +// It panics on a registration that cannot be honoured. Registrations come from +// this repository's own init(), never from operator input, so an invalid one is +// a programming error: there is no caller positioned to handle an error return, +// and failing at process start is better than a service that binds somewhere +// nobody dials. Context is enforced here rather than merely documented, so +// "hosted" genuinely implies a bind address. +func RegisterService(context, name, target, listen, tokenEnv string) { + switch context { + case ServiceClient, ServiceServer, ServiceBoth: + default: + panic(fmt.Sprintf( + "config.RegisterService(%q): unknown context %q, want %q, %q or %q", + name, context, ServiceClient, ServiceServer, ServiceBoth, + )) + } + if context != ServiceClient && strings.TrimSpace(listen) == "" { + panic(fmt.Sprintf( + "config.RegisterService(%q): a %q service needs a default listen address; "+ + "an empty one reaches net.Listen as \"any free port\"", + name, context, + )) + } + serviceRegistryMu.Lock() + defer serviceRegistryMu.Unlock() + serviceRegistry[name] = ServiceSpec{ + Context: context, + Name: name, + Target: target, + Listen: listen, + TokenEnv: tokenEnv, + } +} + +// LookupService returns the spec registered for name. The registry is the +// authority on which service names exist, which is what lets the loader still +// report a typo'd [services.gatway] once Services is a map that would +// otherwise decode any section at all. +func LookupService(name string) (ServiceSpec, bool) { + serviceRegistryMu.RLock() + defer serviceRegistryMu.RUnlock() + spec, ok := serviceRegistry[name] + return spec, ok +} + +// RegisteredServices returns every spec, ordered by name so defaulting and +// validation run in a stable order regardless of map iteration. +func RegisteredServices() []ServiceSpec { + serviceRegistryMu.RLock() + defer serviceRegistryMu.RUnlock() + out := make([]ServiceSpec, 0, len(serviceRegistry)) + for _, spec := range serviceRegistry { + out = append(out, spec) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out +} + +func init() { + // The two services this repository ships. Everything that differs + // between them is an argument here, not a branch somewhere else: the + // gateway's target is defaulted while the State Store's is supplied by + // the operator, and each falls back to its own token variable. + RegisterService(ServiceBoth, ServiceNameGateway, "127.0.0.1:8585", "127.0.0.1:8585", "GATEWAY_TOKEN") + RegisterService(ServiceClient, ServiceNameState, "", "127.0.0.1:9090", "STATE_STORE_TOKEN") +} diff --git a/internal/contracts/state/v1/state.pb.go b/internal/contracts/state/v1/state.pb.go index 7b59d9eaa..cbc486d12 100644 --- a/internal/contracts/state/v1/state.pb.go +++ b/internal/contracts/state/v1/state.pb.go @@ -448,17 +448,22 @@ func (x *Task) GetUpdatedAt() *timestamppb.Timestamp { // string (matching the store's own on-disk representation) rather than // google.protobuf.Struct, to stay a direct mirror of the existing column. type Event struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` - At *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=at,proto3" json:"at,omitempty"` - Kind string `protobuf:"bytes,3,opt,name=kind,proto3" json:"kind,omitempty"` - TaskId int64 `protobuf:"varint,4,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` - Repo string `protobuf:"bytes,5,opt,name=repo,proto3" json:"repo,omitempty"` - Issue int64 `protobuf:"varint,6,opt,name=issue,proto3" json:"issue,omitempty"` - Workflow string `protobuf:"bytes,7,opt,name=workflow,proto3" json:"workflow,omitempty"` - Stage string `protobuf:"bytes,8,opt,name=stage,proto3" json:"stage,omitempty"` - Detail string `protobuf:"bytes,9,opt,name=detail,proto3" json:"detail,omitempty"` - DataJson string `protobuf:"bytes,10,opt,name=data_json,json=dataJson,proto3" json:"data_json,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` + At *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=at,proto3" json:"at,omitempty"` + Kind string `protobuf:"bytes,3,opt,name=kind,proto3" json:"kind,omitempty"` + TaskId int64 `protobuf:"varint,4,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + Repo string `protobuf:"bytes,5,opt,name=repo,proto3" json:"repo,omitempty"` + Issue int64 `protobuf:"varint,6,opt,name=issue,proto3" json:"issue,omitempty"` + Workflow string `protobuf:"bytes,7,opt,name=workflow,proto3" json:"workflow,omitempty"` + Stage string `protobuf:"bytes,8,opt,name=stage,proto3" json:"stage,omitempty"` + // attempt is the run this event belongs to. Zero means UNATTRIBUTED, not a + // first attempt: rows written before the field existed, and the deliberately + // task-agnostic producers, all carry zero. A reader must report those as + // unattributable rather than presenting them as one run. + Attempt int64 `protobuf:"varint,11,opt,name=attempt,proto3" json:"attempt,omitempty"` + Detail string `protobuf:"bytes,9,opt,name=detail,proto3" json:"detail,omitempty"` + DataJson string `protobuf:"bytes,10,opt,name=data_json,json=dataJson,proto3" json:"data_json,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -549,6 +554,13 @@ func (x *Event) GetStage() string { return "" } +func (x *Event) GetAttempt() int64 { + if x != nil { + return x.Attempt + } + return 0 +} + func (x *Event) GetDetail() string { if x != nil { return x.Detail @@ -3629,15 +3641,19 @@ func (x *TaskLogEntry) GetFieldsJson() string { // working by crossing the boundary. limit is caller-capped // (docs/prds/state-store-contract.md §8: the log cap is 2000). type ReadTaskLogRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` - Attempt int64 `protobuf:"varint,2,opt,name=attempt,proto3" json:"attempt,omitempty"` - Limit int64 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"` - Levels []string `protobuf:"bytes,4,rep,name=levels,proto3" json:"levels,omitempty"` - Component string `protobuf:"bytes,5,opt,name=component,proto3" json:"component,omitempty"` - Contains string `protobuf:"bytes,6,opt,name=contains,proto3" json:"contains,omitempty"` - Since *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=since,proto3" json:"since,omitempty"` - Until *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=until,proto3" json:"until,omitempty"` + state protoimpl.MessageState `protogen:"open.v1"` + TaskId int64 `protobuf:"varint,1,opt,name=task_id,json=taskId,proto3" json:"task_id,omitempty"` + Attempt int64 `protobuf:"varint,2,opt,name=attempt,proto3" json:"attempt,omitempty"` + Limit int64 `protobuf:"varint,3,opt,name=limit,proto3" json:"limit,omitempty"` + Levels []string `protobuf:"bytes,4,rep,name=levels,proto3" json:"levels,omitempty"` + Component string `protobuf:"bytes,5,opt,name=component,proto3" json:"component,omitempty"` + Contains string `protobuf:"bytes,6,opt,name=contains,proto3" json:"contains,omitempty"` + Since *timestamppb.Timestamp `protobuf:"bytes,7,opt,name=since,proto3" json:"since,omitempty"` + Until *timestamppb.Timestamp `protobuf:"bytes,8,opt,name=until,proto3" json:"until,omitempty"` + // stage filters on an entry's own "stage" field. Only entries a stage + // tagged carry one -- agent and tool output is logged without a stage, so a + // stage filter narrows the file rather than covering it. Empty means any. + Stage string `protobuf:"bytes,9,opt,name=stage,proto3" json:"stage,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -3728,6 +3744,13 @@ func (x *ReadTaskLogRequest) GetUntil() *timestamppb.Timestamp { return nil } +func (x *ReadTaskLogRequest) GetStage() string { + if x != nil { + return x.Stage + } + return "" +} + // found=false is not an error: the task has no log file for that attempt. // That is a different condition from a process that cannot read logs at all // (codes.Unavailable), and the dashboard reports them differently. @@ -5720,7 +5743,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\n" + "created_at\x18\x19 \x01(\v2\x1a.google.protobuf.TimestampR\tcreatedAt\x129\n" + "\n" + - "updated_at\x18\x1a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\x81\x02\n" + + "updated_at\x18\x1a \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\"\x9b\x02\n" + "\x05Event\x12\x0e\n" + "\x02id\x18\x01 \x01(\x03R\x02id\x12*\n" + "\x02at\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\x02at\x12\x12\n" + @@ -5729,7 +5752,8 @@ const file_state_v1_state_proto_rawDesc = "" + "\x04repo\x18\x05 \x01(\tR\x04repo\x12\x14\n" + "\x05issue\x18\x06 \x01(\x03R\x05issue\x12\x1a\n" + "\bworkflow\x18\a \x01(\tR\bworkflow\x12\x14\n" + - "\x05stage\x18\b \x01(\tR\x05stage\x12\x16\n" + + "\x05stage\x18\b \x01(\tR\x05stage\x12\x18\n" + + "\aattempt\x18\v \x01(\x03R\aattempt\x12\x16\n" + "\x06detail\x18\t \x01(\tR\x06detail\x12\x1b\n" + "\tdata_json\x18\n" + " \x01(\tR\bdataJson\"\x8c\x02\n" + @@ -5926,7 +5950,7 @@ const file_state_v1_state_proto_rawDesc = "" + "\x05level\x18\x03 \x01(\tR\x05level\x12\x10\n" + "\x03msg\x18\x04 \x01(\tR\x03msg\x12\x1f\n" + "\vfields_json\x18\x05 \x01(\tR\n" + - "fieldsJson\"\x93\x02\n" + + "fieldsJson\"\xa9\x02\n" + "\x12ReadTaskLogRequest\x12\x17\n" + "\atask_id\x18\x01 \x01(\x03R\x06taskId\x12\x18\n" + "\aattempt\x18\x02 \x01(\x03R\aattempt\x12\x14\n" + @@ -5935,7 +5959,8 @@ const file_state_v1_state_proto_rawDesc = "" + "\tcomponent\x18\x05 \x01(\tR\tcomponent\x12\x1a\n" + "\bcontains\x18\x06 \x01(\tR\bcontains\x120\n" + "\x05since\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\x05since\x120\n" + - "\x05until\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x05until\"\xc9\x01\n" + + "\x05until\x18\b \x01(\v2\x1a.google.protobuf.TimestampR\x05until\x12\x14\n" + + "\x05stage\x18\t \x01(\tR\x05stage\"\xc9\x01\n" + "\x13ReadTaskLogResponse\x120\n" + "\aentries\x18\x01 \x03(\v2\x16.state.v1.TaskLogEntryR\aentries\x12\x1c\n" + "\ttruncated\x18\x02 \x01(\bR\ttruncated\x12\x18\n" + diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 6ac79c1dc..6cfe23d36 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -1027,6 +1027,14 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { d.Log.Warn("PR state check failed", "pr", t.PRNumber, "err", err) continue } + // OpenPRs returns a deliberately narrow projection of a pr_open task + // (id/owner/repo/issue/pr/status/source/identity) that does not carry + // the attempt, so the outcome event below reads it from the task's own + // row. A failed lookup costs attribution and never the merge handling: + // the status transition and the worktree cleanup still run. OpenPRs + // carries attempt, so these events are attributed without a second + // read per open PR on every reconcile tick. + attempt := t.Attempt switch state { case "merged": _ = d.Store.Transition(ctx, t.ID, workflow.StatusPROpen, workflow.StatusMerged, "") @@ -1043,7 +1051,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { )) d.Log.Info("PR merged", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber) d.emit(events.Event{ - Kind: events.KindPRMerged, TaskID: t.ID, + Kind: events.KindPRMerged, TaskID: t.ID, Attempt: attempt, Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Data: map[string]any{"pr": t.PRNumber}, }) @@ -1052,7 +1060,7 @@ func (d *Daemon) reconcilePRs(ctx context.Context) { _ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber) d.Log.Info("PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber) d.emit(events.Event{ - Kind: events.KindPRRejected, TaskID: t.ID, + Kind: events.KindPRRejected, TaskID: t.ID, Attempt: attempt, Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Data: map[string]any{"pr": t.PRNumber}, }) @@ -1086,7 +1094,7 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) { } d.recordPark(ctx, task.ID, reason) d.emit(events.Event{ - Kind: events.KindParked, TaskID: task.ID, + Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt, Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason, }) return @@ -1100,7 +1108,7 @@ func (d *Daemon) process(ctx context.Context, task *workflow.Task) { } d.recordPark(ctx, task.ID, reason) d.emit(events.Event{ - Kind: events.KindParked, TaskID: task.ID, + Kind: events.KindParked, TaskID: task.ID, Attempt: task.Attempt, Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason, }) return @@ -1364,12 +1372,15 @@ func (d *Daemon) runViaAgent(ctx context.Context, task *workflow.Task, repo conf return } defer revoke() + cfg := d.configFor(task) + taskCfg := cfg.ForTask() + d.captureAttemptConfig(ctx, task, taskCfg) req := taskrun.Request{ Task: task, Repo: repo, - Cfg: d.configFor(task).ForTask(), - Providers: agentexec.ProvidersFromConfig(d.configFor(task).Providers), - MCPServers: d.configFor(task).Tools.MCPServers, + Cfg: taskCfg, + Providers: agentexec.ProvidersFromConfig(cfg.Providers), + MCPServers: cfg.Tools.MCPServers, WorktreeGrant: grant, KindWorkflows: d.KindWorkflows, LabelWorkflows: d.LabelWorkflows, @@ -1532,6 +1543,52 @@ func (d *Daemon) configFor(task *workflow.Task) config.Config { return d.Cfg.Get() } +// captureAttemptConfig persists the effective task configuration this attempt +// runs under, as a durable event on the attempt's own key. +// +// It is written where the configuration is materialised for the dispatch, so +// the document is exactly what the run received. The published configuration +// snapshot cannot answer this: it is the CURRENT configuration, replaced on +// every publish, so a run that finished last week has no record anywhere else. +// +// Fail-open by construction: a configuration that could not be recorded is +// worth a log line and nothing more. Parking a task over a reporting failure +// would trade the run for the receipt. +func (d *Daemon) captureAttemptConfig(ctx context.Context, task *workflow.Task, cfg config.TaskConfig) { + if d.Store == nil { + return + } + document, err := json.Marshal(cfg) + if err != nil { + d.Log.Warn("attempt configuration not captured", "task", task.ID, "attempt", task.Attempt, "err", err) + return + } + event := events.Event{ + At: time.Now().UTC(), + Kind: events.KindConfigCaptured, + TaskID: task.ID, + Repo: task.Owner + "/" + task.Repo, + Issue: task.IssueNumber, + Workflow: task.Workflow, + Attempt: task.Attempt, + Data: map[string]any{ + "schema": events.ConfigCapturedSchema, + // Raw so the document is embedded once, as it was encoded, rather + // than as a string a reader would have to decode again. + "document": json.RawMessage(document), + }, + } + id, err := d.Store.InsertEvent(ctx, event) + if err != nil { + d.Log.Warn("attempt configuration not captured", "task", task.ID, "attempt", task.Attempt, "err", err) + return + } + // The assigned ID tells the event sink to broadcast without inserting a + // duplicate row. + event.ID = id + d.emit(event) +} + func configForIdentity(root config.Config, identity config.IdentityConfig) config.Config { root.BotUser = identity.BotUser root.BotEmail = identity.BotEmail diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index 2ce250463..d2bbbe13d 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -7,6 +7,7 @@ import ( "log/slog" "os" "slices" + "sort" "strings" "sync" "sync/atomic" @@ -1739,3 +1740,333 @@ func TestReconcilePRsSkipsChatTasks(t *testing.T) { t.Errorf("CloseIssue called for a chat task: issue number is synthetic") } } + +// daemonCanarySecrets are recognisable secret references and values that must +// never appear in a captured configuration document. The event this capture +// writes is readable by anyone who can read the task's timeline, so the +// document is a disclosure boundary, not just a convenience. +const ( + canaryForgeToken = "ghp_DAEMONCANARYFORGETOKEN01" + canaryWebhookSecret = "CANARY-WEBHOOK-SECRET-02" + canaryIdentityToken = "ghp_DAEMONCANARYIDENTITY03" + canaryProviderKey = "sk-DAEMONCANARYPROVIDERKEY04" + canaryBWSKeyName = "DAEMON-CANARY-BWS-KEY-NAME-05" + canaryTelegramToken = "tg-DAEMONCANARYTELEGRAMTOKEN06" + canaryNATSTokenEnv = "DAEMON_CANARY_NATS_TOKEN_ENV_07" + canaryStateStoreToken = "DAEMON-CANARY-STATE-STORE-TOKEN-08" +) + +// configWithCanarySecrets is a fully populated configuration carrying +// recognisable secrets in every place a deployment keeps one: the root forge, +// an identity's forge, the model providers, the chat channel, the state store +// and the NATS credential. A capture that serialized the wrong object -- the +// whole config, or a projection that forgot to drop a secret -- would carry +// one of them. +func configWithCanarySecrets() config.Config { + return config.Config{ + WorkDir: "/work/archie", + DBPath: "/work/archie/archie.db", + BotUser: "archie-bot", + BotEmail: "archie@example.com", + Label: "archie", + Forge: config.Forge{ + Type: "gitea", Host: "gitea.example.com", TokenEnv: "GITEA_TOKEN", + Token: secret.SecretRef{Engine: "bws", Key: canaryForgeToken}, + WebhookSecret: secret.SecretRef{Engine: "bws", Key: canaryWebhookSecret}, + Intake: "webhook", + }, + Models: map[string]string{"builder": "openai/gpt-4", "planner": "openai/gpt-4"}, + Providers: map[string]config.Provider{ + "openai": { + Class: "openai", APIKeyEnv: "OPENAI_API_KEY", BaseURL: "https://api.openai.com/v1", + APIKey: secret.SecretRef{Engine: "bws", Key: canaryBWSKeyName}, + }, + "custom": { + Class: "custom", APIKey: secret.SecretRef{Engine: "literal", Key: canaryProviderKey}, + }, + }, + Budgets: config.Budgets{MaxSteps: 40, GateMaxFailures: 2}, + DiffCapLines: 800, + Dispatch: config.Dispatch{ + Trigger: "either", AckReaction: "eyes", + Labels: map[string]string{"queued": "archie:queued"}, + }, + Notify: config.Notify{Webhook: "https://hooks.example.com/notify"}, + Tools: config.ToolsConfig{Policy: config.ToolPolicy{MaxResultChars: 12000, SpillDir: "/tmp/spill"}}, + NATS: config.NATSConfig{Mode: "external", URL: "nats://127.0.0.1:4222", TokenEnv: canaryNATSTokenEnv}, + Chat: config.ChatConfig{Operator: "sam", Telegram: config.TelegramConfig{TokenEnv: "TELEGRAM_TOKEN", Token: secret.SecretRef{Engine: "bws", Key: canaryTelegramToken}}}, + Services: config.Services{config.ServiceNameState: {Target: "127.0.0.1:50051", TargetToken: canaryStateStoreToken}}, + ModelLimits: map[string]config.ModelLimits{ + "openai/gpt-4": {ContextWindow: 128000, MaxOutputTokens: 4096}, + }, + Identities: []config.IdentityConfig{ + { + Name: "gitea-bot", BotUser: "gitea-bot", BotEmail: "gitea-bot@example.com", + Forge: config.Forge{Type: "gitea", Host: "gitea.example.com", Token: secret.SecretRef{Engine: "bws", Key: canaryIdentityToken}}, + Models: map[string]string{"builder": "openai/gpt-4"}, + Budgets: config.Budgets{MaxSteps: 40}, + }, + }, + } +} + +// TestDispatchCapturesTheAttemptsEffectiveConfig is R4's producer half: the +// configuration an attempt ran under is retrievable for that attempt. +// +// It asserts three separate claims rather than one: the event is durable and +// attributed to the attempt, the document is the dispatch's own TaskConfig, +// and no secret value anywhere in the configuration reaches it. +func TestDispatchCapturesTheAttemptsEffectiveConfig(t *testing.T) { + d, s, busClient := daemonWithNATS(t) + d.Cfg.Set(configWithCanarySecrets()) + ctx := context.Background() + + if _, err := s.EnqueueIssue(ctx, "acme", "widget", 5, "t", "b", "", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + if task.Attempt == 0 { + t.Fatal("claimed task has attempt 0; the event below could not be attributed to a run") + } + + sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) { + data, _ := json.Marshal(taskrun.Response{Status: workflow.StatusPROpen}) + _ = msg.Respond(data) + }) + if err != nil { + t.Fatalf("subscribe: %v", err) + } + t.Cleanup(func() { _ = sub.Unsubscribe() }) + + d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}) + + timeline, err := s.TaskEvents(ctx, task.ID) + if err != nil { + t.Fatal(err) + } + var captures []events.Event + for _, e := range timeline { + if e.Kind == events.KindConfigCaptured { + captures = append(captures, e) + } + } + if len(captures) != 1 { + t.Fatalf("config_captured events = %d, want exactly 1 for the attempt", len(captures)) + } + captured := captures[0] + if captured.Attempt != task.Attempt { + t.Errorf("capture attempt = %d, want the dispatched attempt %d", captured.Attempt, task.Attempt) + } + + encoded, err := json.Marshal(captured) + if err != nil { + t.Fatal(err) + } + document := string(encoded) + for _, leak := range []string{ + canaryForgeToken, canaryWebhookSecret, canaryIdentityToken, canaryProviderKey, + canaryBWSKeyName, canaryTelegramToken, canaryNATSTokenEnv, canaryStateStoreToken, + } { + if strings.Contains(document, leak) { + t.Errorf("captured configuration document leaked %q:\n%s", leak, document) + } + } + + var data struct { + Schema string `json:"schema"` + Document json.RawMessage `json:"document"` + } + if err := json.Unmarshal(encoded, &data); err != nil { + t.Fatal(err) + } + // The event wrapper carries kind/stage/attempt; the document itself is + // what the Config tab renders. + var wrapper struct { + Data struct { + Schema string `json:"schema"` + Document json.RawMessage `json:"document"` + } `json:"data"` + } + if err := json.Unmarshal(encoded, &wrapper); err != nil { + t.Fatal(err) + } + if wrapper.Data.Schema != events.ConfigCapturedSchema { + t.Errorf("schema = %q, want %q", wrapper.Data.Schema, events.ConfigCapturedSchema) + } + var doc map[string]any + if err := json.Unmarshal(wrapper.Data.Document, &doc); err != nil { + t.Fatalf("document is not a JSON object: %v", err) + } + + // The document is exactly TaskConfig's field set, not the larger dashboard + // projection: a reader must be able to trust that it carries no providers, + // repositories, identities or lock state. + wantKeys := []string{ + "bot_email", "bot_user", "budgets", "diff_cap_lines", "dispatch", + "forge", "model_limits", "models", "notify", "tool_policy", + } + gotKeys := make([]string, 0, len(doc)) + for key := range doc { + gotKeys = append(gotKeys, key) + } + sort.Strings(gotKeys) + if !slices.Equal(gotKeys, wantKeys) { + t.Errorf("document keys = %v, want exactly %v", gotKeys, wantKeys) + } + if doc["forge"] == nil || !strings.Contains(document, "gitea.example.com") { + t.Error("document is missing the non-secret forge host the Config tab renders") + } + + // The size decides whether a per-attempt document belongs in an event at + // all; recorded so the number is reviewable, not assumed. + t.Logf("serialized config document: %d bytes for a fully populated deployment", len(wrapper.Data.Document)) + if len(wrapper.Data.Document) == 0 { + t.Error("document is empty; the Config tab would render nothing") + } + + // Models and ModelLimits are the only two fields whose size is set by the + // deployment rather than by the struct, so the growth factor gets measured + // too instead of assumed. + scaled := configWithCanarySecrets() + scaled.Models = map[string]string{} + scaled.ModelLimits = map[string]config.ModelLimits{} + for i := range 20 { + ref := fmt.Sprintf("openai/model-%d", i) + scaled.Models[fmt.Sprintf("role-%d", i)] = ref + scaled.ModelLimits[ref] = config.ModelLimits{ContextWindow: 128000, MaxOutputTokens: 4096} + } + scaledDoc, err := json.Marshal(scaled.ForTask()) + if err != nil { + t.Fatal(err) + } + t.Logf("serialized config document with 20 named models: %d bytes", len(scaledDoc)) +} + +// failingEventStore is the daemon's store surface with an event insert that +// always fails, so the fail-open policy of the capture can be observed without +// breaking everything else the dispatch needs. +type failingEventStore struct { + *store.Store +} + +func (f failingEventStore) InsertEvent(context.Context, events.Event) (int64, error) { + return 0, fmt.Errorf("events table unavailable") +} + +// TestCaptureAttemptConfigFailureDoesNotStopTheDispatch: a provenance record +// that could not be written must not cost the run. The taskrun request has to +// go out anyway, and nothing may park. +func TestCaptureAttemptConfigFailureDoesNotStopTheDispatch(t *testing.T) { + d, s, busClient := daemonWithNATS(t) + d.Store = failingEventStore{Store: s} + ctx := context.Background() + + if _, err := s.EnqueueIssue(ctx, "acme", "widget", 6, "t", "b", "", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("claim: (%v, %v)", task, err) + } + + dispatched := make(chan struct{}, 1) + sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) { + dispatched <- struct{}{} + data, _ := json.Marshal(taskrun.Response{Status: workflow.StatusPROpen}) + _ = msg.Respond(data) + }) + if err != nil { + t.Fatalf("subscribe: %v", err) + } + t.Cleanup(func() { _ = sub.Unsubscribe() }) + + d.runViaAgent(ctx, task, config.Repo{Owner: "acme", Name: "widget", Base: "main"}) + + select { + case <-dispatched: + case <-time.After(time.Second): + t.Fatal("the taskrun request was never published; a failed config capture stopped the dispatch") + } + + got, err := s.TaskByIssue(ctx, "acme", "widget", 6) + if err != nil || got == nil { + t.Fatalf("TaskByIssue: (%+v, %v)", got, err) + } + if got.Status == workflow.StatusParked { + t.Errorf("task parked with reason %q; a failed config capture must not park a run", got.ParkReason) + } +} + +// TestTaskAgnosticDaemonEventsCarryNoAttempt pins the other half of the +// attribution rule: an event produced before any task row exists has no +// attempt to name, and inventing one -- the deployment's "current" attempt, a +// zero-that-means-first -- would be a fabricated claim. It stays 0, which the +// reader reports as unattributed. +func TestTaskAgnosticDaemonEventsCarryNoAttempt(t *testing.T) { + d := &Daemon{Bus: events.NewBus(), Log: slog.New(slog.DiscardHandler)} + sub := d.Bus.Subscribe(4) + t.Cleanup(sub.Close) + + d.acknowledge(context.Background(), &recordingForge{}, config.Config{}, + config.Repo{Owner: "acme", Name: "widget"}, forge.Issue{Number: 3, Title: "a task"}) + + select { + case e := <-sub.C: + if e.Kind != events.KindTaskQueued { + t.Fatalf("kind = %q, want %q", e.Kind, events.KindTaskQueued) + } + if e.Attempt != 0 { + t.Errorf("queued event attempt = %d, want 0 (no task exists yet to attribute it to)", e.Attempt) + } + case <-time.After(time.Second): + t.Fatal("no queued event was published") + } +} + +// TestReconcilePRsAttributesTheOutcomeToTheTasksAttempt: a PR is merged or +// rejected against the attempt whose task recorded that PR number, so the +// timeline can attribute the outcome to the run that produced it instead of +// leaving it unattributed. +func TestReconcilePRsAttributesTheOutcomeToTheTasksAttempt(t *testing.T) { + d, s, fg := testDaemon(t, 3, 0) + ctx := context.Background() + d.Bus = events.NewBus() + sub := d.Bus.Subscribe(8) + t.Cleanup(sub.Close) + + if _, err := s.EnqueueIssue(ctx, "acme", "widget", 42, "a task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := s.ClaimNext(ctx) + if err != nil || task == nil { + t.Fatalf("ClaimNext = (%+v, %v)", task, err) + } + if task.Attempt == 0 { + t.Fatal("claimed task has attempt 0; this test could not tell a stamp from a coincidence") + } + task.PRNumber = 7 + if err := s.Update(ctx, task); err != nil { + t.Fatal(err) + } + if err := s.Transition(ctx, task.ID, workflow.StatusRunning, workflow.StatusPROpen, ""); err != nil { + t.Fatal(err) + } + fg.prStates = map[int]string{7: "merged"} + + d.reconcilePRs(ctx) + + select { + case e := <-sub.C: + if e.Kind != events.KindPRMerged { + t.Fatalf("kind = %q, want %q", e.Kind, events.KindPRMerged) + } + if e.Attempt != task.Attempt { + t.Errorf("pr_merged attempt = %d, want the task's attempt %d", e.Attempt, task.Attempt) + } + case <-time.After(time.Second): + t.Fatal("reconcilePRs published no merge event") + } +} diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index c28113228..047a80b50 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -22,6 +22,11 @@ type Task struct { Owner, Repo, Identity, Status, Stage, ParkReason string IssueNumber, RetryCount int ForgeBacked bool + // Attempt is the run the operator acted on. It is stamped onto the event + // this action records so an intervention is attributable to the run it + // changed course -- without it a retry or a stop is indistinguishable + // between attempts on the timeline. + Attempt int } type Store interface { @@ -85,7 +90,7 @@ func (s Service) apply(ctx context.Context, task *Task, identity *string, action if identity != nil { source = "chat" } - o := outcome{event: events.Event{TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber}} + o := outcome{event: events.Event{TaskID: task.ID, Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Attempt: task.Attempt}} switch action { case taskstate.ActionApprove: err := s.Store.Requeue(ctx, task.ID, "waiting_human", "implement") diff --git a/internal/domain/workflow/changes_test.go b/internal/domain/workflow/changes_test.go new file mode 100644 index 000000000..2af734bb2 --- /dev/null +++ b/internal/domain/workflow/changes_test.go @@ -0,0 +1,588 @@ +package workflow + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/samcharles93/archie-core/internal/agentexec" + "github.com/samcharles93/archie-core/internal/config" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/logging" +) + +// recordingStore is the narrow Store the engine calls mid-run, keeping the +// events it was asked to persist. A capture is durable provenance, so the +// assertions below read this and not the lossy bus. +type recordingStore struct { + events []events.Event + transitions []transition + insertEr error +} + +// transition is one status change the engine asked the store for. Parking is +// observable only through these, which is what makes "a reporting failure +// never parks the task" a test rather than a reading of the code. +type transition struct{ from, to, detail string } + +func (s *recordingStore) Update(context.Context, *Task) error { return nil } + +func (s *recordingStore) Transition(_ context.Context, _ int64, from, to, detail string) error { + s.transitions = append(s.transitions, transition{from: from, to: to, detail: detail}) + return nil +} + +func (s *recordingStore) InsertEvent(_ context.Context, e events.Event) (int64, error) { + if s.insertEr != nil { + return 0, s.insertEr + } + s.events = append(s.events, e) + return int64(len(s.events)), nil +} + +func (s *recordingStore) ofKind(kind string) []events.Event { + var out []events.Event + for _, e := range s.events { + if e.Kind == kind { + out = append(out, e) + } + } + return out +} + +// capturingTrees is a Trees implementation that can also report what changed. +// fakeTrees deliberately stays without the capability, so every existing test +// that drives a stage through it exercises the degrade path. +type capturingTrees struct { + fakeTrees + stats task.ChangeStats + err error + calls int + dir string + base string +} + +func (c *capturingTrees) ChangedFileStats(_ context.Context, dir, base string) (task.ChangeStats, error) { + c.calls++ + c.dir, c.base = dir, base + return c.stats, c.err +} + +var ( + _ Trees = (*fakeTrees)(nil) + _ Trees = (*capturingTrees)(nil) + _ changeStatsReader = (*capturingTrees)(nil) + _ task.Store = (*recordingStore)(nil) +) + +// capturePayload mirrors the frozen persisted shape of a changes_captured +// event. Decoding the event's data through it is what proves the field names +// a reader depends on. +type capturePayload struct { + Schema string `json:"schema"` + Owner string `json:"owner"` + Repo string `json:"repo"` + Base string `json:"base"` + Branch string `json:"branch"` + HeadSHA string `json:"head_sha"` + BaseSHA string `json:"base_sha"` + PRNumber int `json:"pr_number"` + CapturedAfter string `json:"captured_after"` + Files []task.FileChange `json:"files"` + Totals task.ChangeTotals `json:"totals"` + Truncated bool `json:"truncated"` +} + +func decodeCapture(t *testing.T, e events.Event) capturePayload { + t.Helper() + raw, err := json.Marshal(e.Data) + if err != nil { + t.Fatalf("marshal capture data: %v", err) + } + var payload capturePayload + if err := json.Unmarshal(raw, &payload); err != nil { + t.Fatalf("decode capture data: %v", err) + } + return payload +} + +func sampleStats() task.ChangeStats { + return task.ChangeStats{ + BaseSHA: strings.Repeat("a", 40), + HeadSHA: strings.Repeat("b", 40), + Files: []task.FileChange{ + {Path: "internal/x.go", Status: task.ChangeModified, Additions: 12, Deletions: 3}, + {Path: "docs/y.md", OldPath: "docs/z.md", Status: task.ChangeRenamed}, + }, + Totals: task.ChangeTotals{Files: 2, Additions: 12, Deletions: 3}, + } +} + +func captureTaskContext(t *testing.T, trees Trees, store Store) *TaskContext { + t.Helper() + return &TaskContext{ + Task: &Task{ + ID: 11, Attempt: 2, Owner: "acme", Repo: "widget", IssueNumber: 7, + Stage: "commit-push", Branch: "feat/7-widget", + }, + Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, + Trees: trees, + Store: store, + Dir: "/worktree", + Branch: "feat/7-widget", + Log: slog.New(slog.DiscardHandler), + } +} + +// TestRunStampsTheAttemptOnEveryEventItEmits is R2's producer half. The +// attempt is read from the task record the run holds, so an event +// is attributable to one attempt without segmenting the stream by stage order, +// and nothing here guesses an attempt it does not have. +func TestRunStampsTheAttemptOnEveryEventItEmits(t *testing.T) { + bus := events.NewBus() + sub := bus.Subscribe(32) + t.Cleanup(sub.Close) + + tc := &TaskContext{ + Task: &Task{ID: 4, Attempt: 3, Owner: "o", Repo: "r", IssueNumber: 1, Status: StatusRunning}, + Repo: config.Repo{Owner: "o", Name: "r"}, + Store: &recordingStore{}, + Bus: bus, + Log: slog.New(slog.DiscardHandler), + } + Run(context.Background(), Workflow{Name: "w", Stages: []Stage{{Name: "build", Run: func(context.Context, *TaskContext) error { + return fmt.Errorf("boom") + }}}}, tc) + + var emitted []events.Event + for { + select { + case e := <-sub.C: + emitted = append(emitted, e) + default: + if len(emitted) == 0 { + t.Fatal("run emitted no events at all; the assertion below would be vacuous") + } + for _, e := range emitted { + if e.Attempt != 3 { + t.Errorf("event %s attempt = %d, want 3", e.Kind, e.Attempt) + } + } + return + } + } +} + +// TestRunBindsTheStageOntoTheTaskLoggerOnlyForTheStage is R5's producer half: +// a line a stage's own code writes must be selectable by stage, and a line +// written outside any stage must not be attributed to one. +// +// It asserts against the logging entry the reader actually filters on +// (internal/logging.Query.Stage matches Entry.Fields["stage"]) rather than +// against a rendered line, so a change in the handler cannot make this pass +// while the filter stays broken. +func TestRunBindsTheStageOntoTheTaskLoggerOnlyForTheStage(t *testing.T) { + feed := logging.NewFeed(32) + outer := slog.New(logging.NewFeedHandler(slog.NewJSONHandler(discardSink{}, nil), feed)) + tc := &TaskContext{ + Task: &Task{ID: 4, Attempt: 1, Owner: "o", Repo: "r", IssueNumber: 1, Status: StatusRunning}, + Repo: config.Repo{Owner: "o", Name: "r"}, + Store: &recordingStore{}, + Log: outer, + } + Run(context.Background(), Workflow{Name: "w", Stages: []Stage{{Name: "build", Run: func(_ context.Context, tc *TaskContext) error { + tc.Log.Info("inside the stage") + return nil + }}}}, tc) + + stages := map[string]string{} + for _, entry := range feed.Snapshot() { + stage, _ := entry.Fields["stage"].(string) + stages[entry.Message] = stage + } + starting, ok := stages["stage starting"] + if !ok { + t.Fatalf("no stage-start line was logged at all: %v", stages) + } + if starting != "build" { + t.Errorf("stage starting carries stage %q, want build", starting) + } + if got := stages["inside the stage"]; got != "build" { + t.Errorf("a line logged by the stage's own code carries stage %q, want build", got) + } + + // Restored afterwards: a line the engine writes outside a stage is not + // attributable to one, and claiming it were would make a stage filter lie. + if tc.Log != outer { + t.Error("tc.Log was not restored after the stage; the next stage's lines would inherit a stale stage") + } + outer.Info("after the run") + entries := feed.Snapshot() + last := entries[len(entries)-1] + if last.Message != "after the run" { + t.Fatalf("last entry = %q, want the line logged after the run", last.Message) + } + if stage, ok := last.Fields["stage"]; ok { + t.Errorf("a line logged after the run carries stage %v, want none", stage) + } +} + +// discardSink absorbs what the wrapped JSON handler renders, so this test's +// assertions read the feed and never a terminal. It cannot be io.Discard or +// slog.DiscardHandler: FeedHandler.Enabled delegates to the wrapped handler, +// and slog.DiscardHandler reports every record as disabled, which leaves the +// feed empty and the assertions below vacuous. +type discardSink struct{} + +func (discardSink) Write(p []byte) (int, error) { return len(p), nil } + +func TestStageCommitCapturesTheChangedFiles(t *testing.T) { + trees := &capturingTrees{commitAllChanged: true, stats: sampleStats()} + store := &recordingStore{} + tc := captureTaskContext(t, trees, store) + tc.Task.Stage = "commit-repro" + + if err := StageCommit("commit-repro", func(*TaskContext) string { return "msg" }).Run(context.Background(), tc); err != nil { + t.Fatalf("StageCommit.Run() = %v, want nil", err) + } + + captures := store.ofKind(events.KindChangesCaptured) + if len(captures) != 1 { + t.Fatalf("changes_captured events = %d, want exactly 1", len(captures)) + } + got := captures[0] + if got.Attempt != 2 { + t.Errorf("capture attempt = %d, want the task's own attempt 2", got.Attempt) + } + if got.Stage != "commit-repro" { + t.Errorf("capture stage = %q, want the capturing stage", got.Stage) + } + if got.TaskID != tc.Task.ID || got.Repo != "acme/widget" || got.Workflow != tc.Task.Workflow { + t.Errorf("capture identity = (%d, %q, %q), want the task's", got.TaskID, got.Repo, got.Workflow) + } + if trees.dir != tc.Dir || trees.base != "main" { + t.Errorf("diffstat read (%q, %q), want the worktree and the repo's base branch", trees.dir, trees.base) + } + + payload := decodeCapture(t, got) + if payload.Schema != events.ChangesCapturedSchema { + t.Errorf("payload schema = %q, want %q: a reader refuses a capture it cannot name", + payload.Schema, events.ChangesCapturedSchema) + } + if payload.Owner != "acme" || payload.Repo != "widget" || payload.Base != "main" || payload.Branch != "feat/7-widget" { + t.Errorf("payload coordinates = %+v", payload) + } + if payload.CapturedAfter != capturedAfterCommit { + t.Errorf("captured_after = %q, want %q", payload.CapturedAfter, capturedAfterCommit) + } + if payload.HeadSHA != strings.Repeat("b", 40) || payload.BaseSHA != strings.Repeat("a", 40) { + t.Errorf("payload SHAs = (%q, %q), want the measured pair", payload.BaseSHA, payload.HeadSHA) + } + if len(payload.Files) != 2 || payload.Files[0].Path != "internal/x.go" || payload.Files[1].OldPath != "docs/z.md" { + t.Errorf("payload files = %+v", payload.Files) + } + if payload.Totals != (task.ChangeTotals{Files: 2, Additions: 12, Deletions: 3}) { + t.Errorf("payload totals = %+v", payload.Totals) + } +} + +// TestStageCommitPushCapturesOnlyAfterThePush pins the second capture point: +// a push that failed is not a change that landed, and a capture claiming one +// would be worse than no capture. +func TestStageCommitPushCapturesOnlyAfterThePush(t *testing.T) { + tests := []struct { + name string + pushShares bool + }{ + {name: "after a successful push", pushShares: true}, + {name: "not after a failed push", pushShares: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + trees := &capturingTrees{commitAllChanged: true, stats: sampleStats()} + if !tt.pushShares { + trees.pushErr = fmt.Errorf("push refused") + } + store := &recordingStore{} + tc := captureTaskContext(t, trees, store) + + err := StageCommitPush(func(*TaskContext) string { return "msg" }).Run(context.Background(), tc) + captures := store.ofKind(events.KindChangesCaptured) + if !tt.pushShares { + if err == nil { + t.Fatal("StageCommitPush.Run() = nil on a failed push, want the push error") + } + if len(captures) != 0 { + t.Fatalf("captures = %d after a failed push, want none", len(captures)) + } + return + } + if err != nil { + t.Fatalf("StageCommitPush.Run() = %v, want nil", err) + } + if len(captures) != 1 { + t.Fatalf("changes_captured events = %d, want exactly 1", len(captures)) + } + if got := decodeCapture(t, captures[0]).CapturedAfter; got != capturedAfterCommitPush { + t.Errorf("captured_after = %q, want %q", got, capturedAfterCommitPush) + } + }) + } +} + +// TestChangeCaptureDegradesWithoutTheCapability: the capture is an optional +// capability, so a Trees implementation that cannot report a diffstat must +// lose the record and nothing else. fakeTrees is exactly that implementation. +func TestChangeCaptureDegradesWithoutTheCapability(t *testing.T) { + trees := &fakeTrees{commitAllChanged: true} + store := &recordingStore{} + tc := captureTaskContext(t, trees, store) + + if err := StageCommit("commit", func(*TaskContext) string { return "msg" }).Run(context.Background(), tc); err != nil { + t.Fatalf("StageCommit.Run() = %v, want the stage to succeed without a capture", err) + } + if got := len(store.ofKind(events.KindChangesCaptured)); got != 0 { + t.Errorf("changes_captured events = %d, want none", got) + } +} + +// TestChangeCaptureFailureNeverFailsTheStage: reporting is not the work. A +// worktree that cannot be measured, and a store that rejects the write, must +// both leave the stage's own result untouched. +func TestChangeCaptureFailureNeverFailsTheStage(t *testing.T) { + tests := []struct { + name string + trees Trees + store Store + reason string + }{ + { + name: "the diffstat could not be read", + trees: &capturingTrees{commitAllChanged: true, err: fmt.Errorf("worktree vanished")}, + store: &recordingStore{}, + reason: "a worktree the daemon already deleted", + }, + { + name: "the capture could not be persisted", + trees: &capturingTrees{commitAllChanged: true, stats: sampleStats()}, + store: &recordingStore{insertEr: fmt.Errorf("store unavailable")}, + reason: "a store that refused the row", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tc := captureTaskContext(t, tt.trees, tt.store) + if err := StageCommit("commit", func(*TaskContext) string { return "msg" }).Run(context.Background(), tc); err != nil { + t.Fatalf("StageCommit.Run() = %v, want nil despite %s", err, tt.reason) + } + }) + } +} + +// TestOpenPRCapturesThePullRequestNumber is R3's link requirement at the +// producer. The captures taken at commit and push time run before the PR +// exists, so their pr_number is necessarily 0; OpenPR captures once more as +// soon as the number is recorded, which is what lets the changed-files view +// link the pull request. +func TestOpenPRCapturesThePullRequestNumber(t *testing.T) { + trees := &capturingTrees{stats: sampleStats()} + store := &recordingStore{} + forgeClient := &fakeForge{} + tc := captureTaskContext(t, trees, store) + tc.Forge = forgeClient + tc.Task.Stage = "open-pr" + tc.Task.Title = "widget fails" + + if err := OpenPR(context.Background(), tc, "body"); err != nil { + t.Fatalf("OpenPR() = %v, want nil", err) + } + if tc.Task.PRNumber == 0 { + t.Fatal("OpenPR recorded no PR number; the assertion below would be vacuous") + } + + captures := store.ofKind(events.KindChangesCaptured) + if len(captures) != 1 { + t.Fatalf("changes_captured events = %d, want the capture OpenPR records once the PR number exists", len(captures)) + } + payload := decodeCapture(t, captures[0]) + if payload.CapturedAfter != capturedAfterOpenPR { + t.Errorf("captured_after = %q, want %q", payload.CapturedAfter, capturedAfterOpenPR) + } + if payload.PRNumber != tc.Task.PRNumber { + t.Errorf("pr_number = %d, want the number OpenPR recorded (%d)", payload.PRNumber, tc.Task.PRNumber) + } + if captures[0].Stage != "open-pr" { + t.Errorf("capture stage = %q, want the capturing stage", captures[0].Stage) + } +} + +// TestChangeCaptureTruncatesTheFileListButNotTheTotals: one large refactor +// must not write an unbounded payload, and a capture that dropped entries must +// still report how much the attempt actually changed. +func TestChangeCaptureTruncatesTheFileListButNotTheTotals(t *testing.T) { + files := make([]task.FileChange, 0, task.MaxCapturedFiles+5) + for i := range task.MaxCapturedFiles + 5 { + files = append(files, task.FileChange{ + Path: fmt.Sprintf("file-%03d.go", i), Status: task.ChangeAdded, Additions: 1, + }) + } + stats := task.ChangeStats{ + Files: files, + Totals: task.ChangeTotals{Files: len(files), Additions: len(files)}, + } + trees := &capturingTrees{commitAllChanged: true, stats: stats} + store := &recordingStore{} + tc := captureTaskContext(t, trees, store) + + if err := StageCommit("commit", func(*TaskContext) string { return "msg" }).Run(context.Background(), tc); err != nil { + t.Fatal(err) + } + captures := store.ofKind(events.KindChangesCaptured) + if len(captures) != 1 { + t.Fatalf("changes_captured events = %d, want 1", len(captures)) + } + payload := decodeCapture(t, captures[0]) + if len(payload.Files) != task.MaxCapturedFiles { + t.Errorf("payload carries %d files, want the cap of %d", len(payload.Files), task.MaxCapturedFiles) + } + if !payload.Truncated { + t.Error("truncated = false, want true when entries were dropped") + } + if payload.Totals != (task.ChangeTotals{Files: len(files), Additions: len(files)}) { + t.Errorf("totals = %+v, want the full set %d", payload.Totals, len(files)) + } + if payload.Totals.Files == len(payload.Files) { + t.Error("totals were recomputed over the truncated list; a reader would understate the change") + } +} + +// TestBaselineFixCapturesItsOwnCommit pins the third capture point: the +// baseline repair is a real, gate-verified commit of its own, and it is the +// only record of that intermediate state once the later push capture folds it +// into one bigger change. +func TestBaselineFixCapturesItsOwnCommit(t *testing.T) { + dir := t.TempDir() + script := filepath.Join(dir, "gate.sh") + if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { + t.Fatal(err) + } + runner := agentRunnerFunc(func(context.Context, string, agentexec.Request, agentexec.ToolCallReporter) (agentexec.Result, error) { + return agentexec.Result{Version: agentexec.ProtocolVersion, Status: agentexec.StatusPassed}, nil + }) + + tests := []struct { + name string + changed bool + want int + }{ + {name: "a real fix is captured", changed: true, want: 1}, + {name: "a commit that produced nothing is not", changed: false, want: 0}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + trees := &capturingTrees{commitAllChanged: tt.changed, stats: sampleStats()} + store := &recordingStore{} + tc := &TaskContext{ + Task: &Task{ID: 9, Attempt: 1, Owner: "o", Repo: "r", Status: StatusRunning}, + Repo: config.Repo{Owner: "o", Name: "r", Gate: [][]string{{"sh", script}}}, + Cfg: config.Config{Models: map[string]string{"builder": "provider/model"}}, + Agent: runner, + Trees: trees, + Store: store, + Dir: dir, + Branch: "feat/9-x", + Log: slog.New(slog.DiscardHandler), + } + if err := StageBaselineGate().Run(context.Background(), tc); err != nil { + t.Fatalf("StageBaselineGate.Run() = %v", err) + } + captures := store.ofKind(events.KindChangesCaptured) + if len(captures) != tt.want { + t.Fatalf("changes_captured events = %d, want %d", len(captures), tt.want) + } + if tt.want == 0 { + return + } + if got := decodeCapture(t, captures[0]).CapturedAfter; got != capturedAfterBaselineFix { + t.Errorf("captured_after = %q, want %q", got, capturedAfterBaselineFix) + } + if !tc.BaselineFixed { + t.Error("BaselineFixed = false after a captured baseline commit") + } + }) + } +} + +// TestCaptureIsNeverCallableFromTrees makes the constraint explicit in code, +// next to the type that must not grow past it: the capture is an optional, +// unexported capability, and Trees -- the surface interpreted stage code is +// handed -- must not name it. wfextract's reachability test proves the same +// thing from the interpreted side. +func TestCaptureIsNeverCallableFromTrees(t *testing.T) { + if _, ok := any((*fakeTrees)(nil)).(changeStatsReader); ok { + t.Error("fakeTrees satisfies the capture capability; the degrade test above would be vacuous") + } + if _, ok := any(Trees(nil)).(changeStatsReader); ok { + t.Error("Trees names the capture capability; interpreted stage code could call it") + } +} + +// TestAFailedCaptureNeverParksTheTask runs the whole engine, not just the +// step: the only way a capture failure could reach the operator as a parked +// task is through Run's own error path, so the assertion has to be made +// against Run's transitions. +func TestAFailedCaptureNeverParksTheTask(t *testing.T) { + tests := []struct { + name string + trees Trees + }{ + { + name: "the diffstat could not be read", + trees: &capturingTrees{commitAllChanged: true, err: fmt.Errorf("worktree vanished")}, + }, + { + name: "the capture could not be persisted", + trees: &capturingTrees{commitAllChanged: true, stats: sampleStats()}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + store := &recordingStore{} + if tt.name == "the capture could not be persisted" { + // Only the capture's own insert fails; every other write the + // engine makes still has to succeed for the run to finish. + store = &recordingStore{insertEr: fmt.Errorf("store unavailable")} + } + tc := captureTaskContext(t, tt.trees, store) + tc.Task.Status = StatusRunning + + Run(context.Background(), Workflow{Name: "implement", Stages: []Stage{ + StageCommitPush(func(*TaskContext) string { return "msg" }), + {Name: "open-pr", Run: func(_ context.Context, tc *TaskContext) error { + tc.Outcome = Outcome{Status: StatusPROpen, Detail: "PR #1"} + return nil + }}, + }}, tc) + + for _, tr := range store.transitions { + if tr.to == StatusParked { + t.Fatalf("task parked (%s -> %s: %s); a change capture must never park a run that succeeded", + tr.from, tr.to, tr.detail) + } + } + if tc.Outcome.Status != StatusPROpen { + t.Errorf("outcome = %q, want the stage's own %q", tc.Outcome.Status, StatusPROpen) + } + }) + } +} diff --git a/internal/domain/workflow/implement.go b/internal/domain/workflow/implement.go index 32e79ef1d..74a489b1b 100644 --- a/internal/domain/workflow/implement.go +++ b/internal/domain/workflow/implement.go @@ -111,6 +111,7 @@ func StageBaselineGate() Stage { if changed { tc.BuildSummary = res.Summary tc.BaselineFixed = true + tc.captureChanges(ctx, capturedAfterBaselineFix) } } return nil diff --git a/internal/domain/workflow/implement_test.go b/internal/domain/workflow/implement_test.go index e74d6458a..2859a61fc 100644 --- a/internal/domain/workflow/implement_test.go +++ b/internal/domain/workflow/implement_test.go @@ -382,6 +382,7 @@ func TestOpenPRLinksSourceBranchBeforeCreatingPR(t *testing.T) { Task: &Task{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 42, Title: "Fix bug"}, Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, Branch: "fix/42-bug", + Log: slog.New(slog.DiscardHandler), } if err := OpenPR(context.Background(), tc, "summary"); err != nil { t.Fatal(err) @@ -420,10 +421,15 @@ func TestStageCommitPushDoesNotUseSyntheticIssueForChatNoOp(t *testing.T) { // fakeTrees implements Trees, tracking calls without touching a real // worktree. commitAllChanged controls what CommitAll reports. +// +// It deliberately does NOT implement the unexported changeStatsReader +// capability: every stage test that drives a fake tree therefore also covers +// the path where a capture cannot be taken at all. type fakeTrees struct { commitAllChanged bool pushed bool pushBranch string + pushErr error } func (f *fakeTrees) Prepare(context.Context, string, string, string, int, string, string, string) (string, string, error) { @@ -435,6 +441,9 @@ func (f *fakeTrees) CommitAll(context.Context, string, string) (bool, error) { } func (f *fakeTrees) Push(_ context.Context, _, branch string) error { + if f.pushErr != nil { + return f.pushErr + } f.pushed = true f.pushBranch = branch return nil @@ -464,6 +473,7 @@ func TestStageCommitPushPushesBaselineFixEvenWithNothingNewToCommit(t *testing.T Dir: "/tmp/test", Branch: "archie/issue-1", Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 1}, + Log: slog.New(slog.DiscardHandler), } if err := stage.Run(context.Background(), tc); err != nil { @@ -488,6 +498,7 @@ func TestStageCommitPushStillErrorsOnEmptyTreeWithoutBaselineFix(t *testing.T) { Dir: "/tmp/test", Branch: "archie/issue-1", Task: &Task{ID: 1, Owner: "o", Repo: "r", IssueNumber: 1}, + Log: slog.New(slog.DiscardHandler), } if err := stage.Run(context.Background(), tc); err == nil { @@ -595,6 +606,7 @@ func TestOpenPRSurvivesALinkBranchFailure(t *testing.T) { Task: &Task{ID: 1, Owner: "acme", Repo: "widget", IssueNumber: 42, Title: "Fix bug"}, Repo: config.Repo{Owner: "acme", Name: "widget", Base: "main"}, Branch: "fix/42-bug", + Log: slog.New(slog.DiscardHandler), } if err := OpenPR(context.Background(), taskCtx, "summary"); err != nil { diff --git a/internal/domain/workflow/steps.go b/internal/domain/workflow/steps.go index ea5d41e0f..d4cd15997 100644 --- a/internal/domain/workflow/steps.go +++ b/internal/domain/workflow/steps.go @@ -8,6 +8,8 @@ import ( "strings" "time" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" "github.com/samcharles93/archie-core/internal/gate" "github.com/samcharles93/archie-core/internal/gate/gateeval" ) @@ -15,6 +17,91 @@ import ( // Shared step library. Every workflow composes these; workflow-specific // stages live next to their workflow definition. +// The captured_after values recorded inside a changes_captured event. They +// are part of the on-disk payload: a reader distinguishes a mid-workflow +// commit from the push that ended the run, so renaming one is a migration, +// not a rename. +const ( + capturedAfterCommit = "commit" + capturedAfterCommitPush = "commit-push" + capturedAfterBaselineFix = "baseline-fix" + // capturedAfterOpenPR is the final capture of a run: OpenPR takes it the + // moment the PR number is recorded, because that is the only point at which + // a capture can carry one. + capturedAfterOpenPR = "open-pr" +) + +// changeStatsReader is the optional capability through which a Trees +// implementation reports what an attempt changed. It is deliberately +// unexported, and deliberately NOT a method on Trees: Trees is projected into +// the interpreted-stage symbol table, so declaring it there would widen what +// repository-authored .archie/stages/*.go may call (pinned by +// wfextract/reachability_test.go). A Trees implementation without it degrades +// to no capture rather than failing the stage. +type changeStatsReader interface { + ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error) +} + +// captureChanges records what this attempt has changed, read off the worktree +// at the moment it was committed or pushed -- the only point where the +// worktree still holds the change and a commit or push is known to have +// happened. A retry resets the branch onto its base and a terminal state +// deletes the worktree, so nothing can re-derive this afterwards. +// +// Capturing is reporting, not work: every failure path here logs and returns, +// because a provenance record that could not be written must never park or +// fail a run that otherwise succeeded. +func (tc *TaskContext) captureChanges(ctx context.Context, after string) { + if tc.Dir == "" { + tc.Log.Warn("change capture skipped: no worktree to read", "captured_after", after) + return + } + reader, ok := tc.Trees.(changeStatsReader) + if !ok { + tc.Log.Warn("change capture unavailable: this worktree implementation cannot report a diffstat", + "captured_after", after) + return + } + stats, err := reader.ChangedFileStats(ctx, tc.Dir, tc.Repo.BaseBranch()) + if err != nil { + tc.Log.Warn("change capture failed", "captured_after", after, "err", err) + return + } + // Durable, never bus-only: the worktree this was measured from is gone by + // the time anyone reads it, so a capture that only reached the live feed + // would be lost with the process. + if err := tc.EmitDurable(ctx, events.KindChangesCaptured, tc.Task.Stage, "", changeCaptureData(tc, after, stats)); err != nil { + tc.Log.Warn("change capture not persisted", "captured_after", after, "err", err) + } +} + +// changeCaptureData builds the persisted payload for one capture. Totals are +// taken over the FULL set of changed files, so a capture truncated at +// task.MaxCapturedFiles still reports how much the attempt changed -- only the +// per-file breakdown is bounded. +func changeCaptureData(tc *TaskContext, after string, stats task.ChangeStats) map[string]any { + files := stats.Files + truncated := false + if len(files) > task.MaxCapturedFiles { + files = files[:task.MaxCapturedFiles] + truncated = true + } + return map[string]any{ + "schema": events.ChangesCapturedSchema, + "owner": tc.Task.Owner, + "repo": tc.Task.Repo, + "base": tc.Repo.BaseBranch(), + "branch": tc.Branch, + "head_sha": stats.HeadSHA, + "base_sha": stats.BaseSHA, + "pr_number": tc.Task.PRNumber, + "captured_after": after, + "files": files, + "totals": stats.Totals, + "truncated": truncated, + } +} + // StagePrepareWorktree clones the repo fresh and checks out the task // branch. Skips if the daemon already prepared the worktree (Docker // containers require the tree before acquire). @@ -42,6 +129,7 @@ func StageCommit(name string, message func(*TaskContext) string) Stage { if !changed { return fmt.Errorf("worktree has no changes to commit") } + tc.captureChanges(ctx, capturedAfterCommit) return nil }} } @@ -69,7 +157,11 @@ func StageCommitPush(message func(*TaskContext) string) Stage { if !changed && !tc.BaselineFixed { return fmt.Errorf("worktree has no changes to commit") } - return tc.Trees.Push(ctx, tc.Dir, tc.Branch) + if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil { + return err + } + tc.captureChanges(ctx, capturedAfterCommitPush) + return nil }} } @@ -211,6 +303,12 @@ func OpenPR(ctx context.Context, tc *TaskContext, body string) error { } t.PRNumber = num tc.Outcome = Outcome{Status: StatusPROpen, Detail: fmt.Sprintf("PR #%d", num)} + // The captures taken while committing and pushing ran before this PR + // existed, so they carry no number and the changed-files view cannot link + // it. This is the one point where the number is known and the worktree is + // still there to measure, so it is captured here rather than left for a + // read to reconstruct. Reporting only: captureChanges never fails the stage. + tc.captureChanges(ctx, capturedAfterOpenPR) return nil } diff --git a/internal/domain/workflow/task/changes.go b/internal/domain/workflow/task/changes.go new file mode 100644 index 000000000..df4a895c9 --- /dev/null +++ b/internal/domain/workflow/task/changes.go @@ -0,0 +1,67 @@ +package task + +// ChangeStats is the change one attempt produced, measured at the moment it +// was committed or pushed. +// +// It is a measurement, not a view: the worktree it was read from is deleted on +// merge, close and no-PR terminal states, and a retry resets the branch onto +// its base, so this is the only record of what an attempt actually changed. +// Nothing re-derives it after the fact. +// +// The value types live in this subpackage rather than in package workflow or +// internal/worktree, for two reasons that were checked rather than assumed. +// Package workflow must never import internal/worktree -- it has no such +// import today -- so a shared value cannot live there. And this subpackage is +// not projected into the interpreted-stage symbol table (the generated +// wfextract table names no type from here), whereas a new exported type in +// package workflow would be reachable from repository-authored +// `.archie/stages/*.go`. Declaring it here widens nothing and needs no +// symbol-table regeneration. +type ChangeStats struct { + BaseSHA string `json:"base_sha"` + HeadSHA string `json:"head_sha"` + Files []FileChange `json:"files"` + Totals ChangeTotals `json:"totals"` +} + +// FileChange is one file's contribution to a change. +type FileChange struct { + Path string `json:"path"` + // OldPath is the pre-change path, populated only for a rename. + OldPath string `json:"old_path"` + // Status is one of the Change* values below. + Status string `json:"status"` + Additions int `json:"additions"` + Deletions int `json:"deletions"` + // Binary reports that the file produced no textual hunks. It is NOT a + // claim that the file is binary on disk: an empty or otherwise chunkless + // edit reports this too, so it must never be rendered as a file type. + Binary bool `json:"binary"` +} + +// ChangeTotals summarises a change. Totals always cover the FULL set of +// changed files, even when FileChange entries were dropped by the +// MaxCapturedFiles cap, so a truncated capture still reports honest totals. +type ChangeTotals struct { + Files int `json:"files"` + Additions int `json:"additions"` + Deletions int `json:"deletions"` +} + +// Change status values as they are persisted inside a changes_captured +// event's data. Like the task lifecycle statuses, these strings are part of +// the on-disk format: renaming one is a migration, not a rename. +const ( + ChangeAdded = "added" + ChangeModified = "modified" + ChangeDeleted = "deleted" + ChangeRenamed = "renamed" + ChangeTypeChanged = "typechange" +) + +// MaxCapturedFiles caps how many file entries one capture persists. Unlike +// Event.Detail, an event's data is not length-limited by the store, so this cap +// is what keeps one large refactor from writing an unbounded payload. A capture +// that dropped entries keeps the totals of the full set and reports itself as +// truncated. +const MaxCapturedFiles = 200 diff --git a/internal/domain/workflow/task/changes_test.go b/internal/domain/workflow/task/changes_test.go new file mode 100644 index 000000000..29c01ac73 --- /dev/null +++ b/internal/domain/workflow/task/changes_test.go @@ -0,0 +1,29 @@ +package task + +import "testing" + +// TestChangeStatusesAreSpelledAsPersisted pins the five status strings as +// literals. They are the on-disk vocabulary of a changes_captured payload and +// the dashboard mirrors them as its own key set +// (ui/src/tasks/changed-files.jsx FILE_STATUS), so renaming one here without +// the matching dashboard change renders raw status codes instead of words -- +// with both suites still green unless each side pins the literal. +func TestChangeStatusesAreSpelledAsPersisted(t *testing.T) { + statuses := []struct { + name string + got string + want string + }{ + {name: "ChangeAdded", got: ChangeAdded, want: "added"}, + {name: "ChangeModified", got: ChangeModified, want: "modified"}, + {name: "ChangeDeleted", got: ChangeDeleted, want: "deleted"}, + {name: "ChangeRenamed", got: ChangeRenamed, want: "renamed"}, + {name: "ChangeTypeChanged", got: ChangeTypeChanged, want: "typechange"}, + } + + for _, s := range statuses { + if s.got != s.want { + t.Errorf("%s = %q, want %q", s.name, s.got, s.want) + } + } +} diff --git a/internal/domain/workflow/wfextract/reachability_test.go b/internal/domain/workflow/wfextract/reachability_test.go index 48993ec26..d6d03384d 100644 --- a/internal/domain/workflow/wfextract/reachability_test.go +++ b/internal/domain/workflow/wfextract/reachability_test.go @@ -2,6 +2,7 @@ package wfextract import ( "context" + "reflect" "testing" "github.com/traefik/yaegi/interp" @@ -109,3 +110,69 @@ func TestWrapperNilGuardsPreserved(t *testing.T) { t.Errorf("ChangedLines on nil WChangedLines = %v, want nil", err) } } + +// TestChangeCaptureIsNotCallableFromInterpretedCode is the acceptance test for +// "the sandbox surface did not widen", in the same shape as the reachability +// test above and with the opposite assertion. +// +// An attempt's changed files are captured through an UNEXPORTED optional +// interface asserted on TaskContext.Trees, precisely so that the capability is +// not part of workflow.Trees: Trees is projected into this symbol table, so a +// method added to it would become callable by every repository-authored +// .archie/stages/*.go file. Both halves are asserted here -- the interface's +// method set, and the interpreted call that must not resolve -- because the +// second alone would be weaker: it would still pass if the symbol table lost +// Trees altogether. +func TestChangeCaptureIsNotCallableFromInterpretedCode(t *testing.T) { + trees := reflect.TypeFor[workflow.Trees]() + if _, ok := trees.MethodByName("ChangedFileStats"); ok { + t.Fatalf("workflow.Trees gained ChangedFileStats; interpreted stage code can now read a diffstat the engine only meant to capture") + } + + // The control first: an interpreted call to a method Trees really has must + // resolve, so the refusal below is the missing method and not a broken + // harness. + const control = `package main + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/workflow" +) + +func UseTrees(t workflow.Trees) { + _, _ = t.Diff(context.Background(), "", "") +} +` + const probe = `package main + +import ( + "context" + + "github.com/samcharles93/archie-core/internal/domain/workflow" +) + +// CaptureDiffstat is an interpreted stage trying to reach the engine's +// change capture through the surface TaskContext hands it. +func CaptureDiffstat(t workflow.Trees) { + stats, err := t.ChangedFileStats(context.Background(), "", "") + _, _ = stats.HeadSHA, err +} +` + + i, err := yaegiutil.New(interp.Options{}, Symbols) + if err != nil { + t.Fatalf("New: %v", err) + } + if _, err := yaegiutil.Resolve[func(workflow.Trees)](i, control, "main.UseTrees"); err != nil { + t.Fatalf("the control call Trees.Diff did not resolve (%v); this test cannot tell a missing capability from a broken symbol table", err) + } + + j, err := yaegiutil.New(interp.Options{}, Symbols) + if err != nil { + t.Fatalf("New: %v", err) + } + if _, err := yaegiutil.Resolve[func(workflow.Trees)](j, probe, "main.CaptureDiffstat"); err == nil { + t.Error("interpreted stage code resolved Trees.ChangedFileStats; the capture capability leaked into the projected surface") + } +} diff --git a/internal/domain/workflow/workflow.go b/internal/domain/workflow/workflow.go index 3cff53eb8..5054ac1cc 100644 --- a/internal/domain/workflow/workflow.go +++ b/internal/domain/workflow/workflow.go @@ -134,7 +134,13 @@ type TaskContext struct { } // Emit publishes an observability event stamped with the task's -// identity. Safe on a nil bus. +// identity and the attempt that produced it. Safe on a nil bus. +// +// The attempt comes from the task record this context runs against, so a +// reader can attribute the event to one run without segmenting the task's +// stream by stage order. It is never guessed: a producer with no attempt +// (the deliberately task-agnostic daemon events) leaves it zero, which reads +// as unattributed rather than as a first run. func (tc *TaskContext) Emit(kind, stage, detail string, data map[string]any) { if tc.Bus == nil { return @@ -145,6 +151,7 @@ func (tc *TaskContext) Emit(kind, stage, detail string, data map[string]any) { Repo: tc.Task.Owner + "/" + tc.Task.Repo, Issue: tc.Task.IssueNumber, Workflow: tc.Task.Workflow, + Attempt: tc.Task.Attempt, Stage: stage, Detail: detail, Data: data, @@ -161,7 +168,8 @@ func (tc *TaskContext) EmitDurable(ctx context.Context, kind, stage, detail stri } event := events.Event{ At: time.Now().UTC(), Kind: kind, TaskID: tc.Task.ID, Repo: tc.Task.Owner + "/" + tc.Task.Repo, - Issue: tc.Task.IssueNumber, Workflow: tc.Task.Workflow, Stage: stage, Detail: detail, Data: data, + Issue: tc.Task.IssueNumber, Workflow: tc.Task.Workflow, Attempt: tc.Task.Attempt, + Stage: stage, Detail: detail, Data: data, } id, err := tc.Store.InsertEvent(ctx, event) if err != nil { @@ -293,7 +301,17 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) { for _, stage := range wf.Stages { t.Stage = stage.Name _ = tc.Store.Update(ctx, t) - log.Info("stage starting", "stage", stage.Name) + // The stage is bound onto the task logger for exactly the stage's own + // execution and removed afterwards, so every line a stage's code writes + // is selectable by stage (internal/logging.Query.Stage). It is restored + // rather than left in place because a line written outside any stage is + // not attributable to one. Agent and tool output is logged by the runtime + // that produced it, which never sees this logger, so it carries no stage: + // the stage filter narrows the log, it does not cover it. + previousLog := tc.Log + stageLog := previousLog.With("stage", stage.Name) + tc.Log = stageLog + stageLog.Info("stage starting") tc.Emit(events.KindStageStart, stage.Name, "", nil) started := time.Now() @@ -306,13 +324,14 @@ func Run(ctx context.Context, wf Workflow, tc *TaskContext) { } } tc.Emit(events.KindStageFinish, stage.Name, "", data) + tc.Log = previousLog if err != nil { // Daemon shutdown is not a workflow failure. Leave the task running // so Startup's existing crash recovery requeues it; parking here // would publish a false failure and require manual intervention. if ctx.Err() != nil { - log.Info("stage interrupted", "stage", stage.Name, "err", err) + stageLog.Info("stage interrupted", "err", err) return } t.ParkReason = fmt.Sprintf("stage %s: %v", stage.Name, err) diff --git a/internal/events/events.go b/internal/events/events.go index c735892ab..959024a2d 100644 --- a/internal/events/events.go +++ b/internal/events/events.go @@ -50,6 +50,26 @@ const ( KindWorkRequestSubmitted = "work_request_submitted" KindLog = "log" // data: level, msg + // KindChangesCaptured records the change one attempt produced, read off + // the worktree at the moment it was committed or pushed, plus a final + // capture once OpenPR knows the number. It is durable + // provenance, not a live view: the worktree is deleted on merge, close + // and no-PR terminal states, and a retry resets the branch onto its base, + // so nothing can re-derive this after the fact. data: schema + // (ChangesCapturedSchema), owner, repo, base, branch, head_sha, base_sha, + // pr_number, captured_after, files[], totals, truncated. + KindChangesCaptured = "changes_captured" + + // KindConfigCaptured records the effective configuration one attempt ran + // under, captured where it is materialised for the dispatch. It is durable + // by requirement, not convenience: the published configuration snapshot is + // the CURRENT configuration and is replaced on every publish, so it cannot + // answer what a run that finished last week was configured with. This is + // the only record of that. data: schema (ConfigCapturedSchema) and document + // (the JSON encoding of the dispatch's config.TaskConfig, non-secret by + // construction and by test). + KindConfigCaptured = "config_captured" + // Curator family activity (epic archie-core-yp9). Curator runs ride // the same bus so background agents mutating memory stay observable: // what ran, when, what changed, and why (archie-core-114). @@ -79,20 +99,39 @@ const ( KindUpdateReport = "update_report" ) +// ConfigCapturedSchema is the schema name carried inside a config_captured +// event's data. It is named on the wire so a reader can refuse a document it +// does not understand rather than rendering it as though it did. +const ConfigCapturedSchema = "archie/task-config@1" + +// ChangesCapturedSchema is the schema name carried inside a changes_captured +// event's data, for the same reason as ConfigCapturedSchema: a capture read by +// a build that does not know its shape is a read failure, and the dashboard has +// a state for that distinct from a capture it rendered as zeroes. +const ChangesCapturedSchema = "archie/task-changes@1" + // Event is the single wire type: task lifecycle, stage progress, agent // stats, and log lines all flow through it -- every consumer (SQLite // sink, SSE fan-out, future aggregators) is just another subscriber. type Event struct { - ID int64 `json:"id,omitempty"` // set by the store sink - At time.Time `json:"at"` - Kind string `json:"kind"` - TaskID int64 `json:"task_id,omitempty"` - Repo string `json:"repo,omitempty"` - Issue int `json:"issue,omitempty"` - Workflow string `json:"workflow,omitempty"` - Stage string `json:"stage,omitempty"` - Detail string `json:"detail,omitempty"` - Data map[string]any `json:"data,omitempty"` + ID int64 `json:"id,omitempty"` // set by the store sink + At time.Time `json:"at"` + Kind string `json:"kind"` + TaskID int64 `json:"task_id,omitempty"` + Repo string `json:"repo,omitempty"` + Issue int `json:"issue,omitempty"` + Workflow string `json:"workflow,omitempty"` + Stage string `json:"stage,omitempty"` + // Attempt attributes the event to one run of the task. Zero means + // UNATTRIBUTED, not "attempt zero": every row written before this field + // existed, and the deliberately task-agnostic producers, carry 0. A + // reader must report those as unattributable rather than presenting them + // as a first run. The tag is deliberately not omitempty so that + // unattributed and absent stay distinguishable on the wire and in the + // array the dashboard renders. + Attempt int `json:"attempt"` + Detail string `json:"detail,omitempty"` + Data map[string]any `json:"data,omitempty"` } // Sub is one subscriber: a bounded channel plus a drop counter. diff --git a/internal/events/events_test.go b/internal/events/events_test.go index 1cc805327..00bd9daa6 100644 --- a/internal/events/events_test.go +++ b/internal/events/events_test.go @@ -199,3 +199,18 @@ func TestPublishDoesNotOverwritePreSetAt(t *testing.T) { t.Errorf("At = %v, want %v (preset should not be overwritten)", e.At, preset) } } + +// TestCapturedSchemasAreSpelledAsTheDashboardExpects pins the two schema names +// as literals. They are wire vocabulary: the dashboard mirrors them +// (ui/src/tasks/attempt-config.jsx, and api_tasks_changes.go for the changes +// one), so changing a name here without changing the reader turns every +// capture into "recorded but could not be read". The literal assertion is what +// makes that a failing test rather than a silent one. +func TestCapturedSchemasAreSpelledAsTheDashboardExpects(t *testing.T) { + if ConfigCapturedSchema != "archie/task-config@1" { + t.Errorf("ConfigCapturedSchema = %q, want archie/task-config@1", ConfigCapturedSchema) + } + if ChangesCapturedSchema != "archie/task-changes@1" { + t.Errorf("ChangesCapturedSchema = %q, want archie/task-changes@1", ChangesCapturedSchema) + } +} diff --git a/internal/infrastructure/configuration/defaults.go b/internal/infrastructure/configuration/defaults.go index 396eb038c..a60cd2512 100644 --- a/internal/infrastructure/configuration/defaults.go +++ b/internal/infrastructure/configuration/defaults.go @@ -62,9 +62,7 @@ const ( // input was to not call them. Splitting them means defaults can be applied, // inspected, and reasoned about independently of whether the result is valid. func (l *Loader) applyDefaults(cfg *config.Config) { - if cfg.Services.Gateway.Target == "" { - cfg.Services.Gateway.Target = "127.0.0.1:8585" - } + applyServiceDefaults(cfg) if cfg.Health.Listen == "" { cfg.Health.Listen = defaultHealthListen } @@ -79,6 +77,31 @@ func (l *Loader) applyDefaults(cfg *config.Config) { applyMemoryDefaults(cfg) } +// applyServiceDefaults fills each registered service's absent addresses from +// its registration. It iterates the registry rather than naming services, so a +// new service needs no branch here -- only its RegisterService call. +// +// A registered service always ends with an entry, so later code can read +// cfg.Services.Get(name) without distinguishing "absent section" from +// "section with every field defaulted". An empty registered Target is a +// service whose target the operator must supply, and stays empty for +// validation to reject rather than being defaulted to something dialable. +func applyServiceDefaults(cfg *config.Config) { + if cfg.Services == nil { + cfg.Services = config.Services{} + } + for _, spec := range config.RegisteredServices() { + conn := cfg.Services[spec.Name] + if conn.Target == "" { + conn.Target = spec.Target + } + if conn.Listen == "" { + conn.Listen = spec.Listen + } + cfg.Services[spec.Name] = conn + } +} + // applyMemoryDefaults fills an absent engine choice with the builtin // engine, so "nothing configured" and "explicitly builtin" are the same // resolved state everywhere after this point -- validateMemory and every diff --git a/internal/infrastructure/configuration/loader.go b/internal/infrastructure/configuration/loader.go index 2ad08f4cb..d64e52fb5 100644 --- a/internal/infrastructure/configuration/loader.go +++ b/internal/infrastructure/configuration/loader.go @@ -210,6 +210,23 @@ func unknownKeys(a, b []string) []string { return out } +// unregisteredServiceKeys reports [services.] sections naming a service +// nobody registered. +// +// Undecoded() cannot see these. Services is a map, so TOML decodes any section +// under [services] into it successfully, and a typo'd [services.gatway] would +// load clean where the previous struct form reported it. The registry is the +// authority on which names exist, so ask it. +func unregisteredServiceKeys(services config.Services) []string { + var out []string + for name := range services { + if _, ok := config.LookupService(name); !ok { + out = append(out, "services."+name) + } + } + return out +} + // sortedUnique returns keys sorted and de-duplicated, so Document.UnknownKeys // is deterministic across a base+overlay load that happens to name the same // stray key in both files. @@ -322,7 +339,7 @@ func (l *Loader) decodeMain(doc *Document, path string, isYAMLFile bool) error { // judges the effective configuration, including values the operator never // wrote. func (l *Loader) finalize(doc *Document) (*Document, error) { - doc.UnknownKeys = sortedUnique(doc.UnknownKeys) + doc.UnknownKeys = sortedUnique(append(doc.UnknownKeys, unregisteredServiceKeys(doc.Config.Services)...)) l.applyDefaults(&doc.Config) if err := Validate(&doc.Config); err != nil { return nil, err diff --git a/internal/infrastructure/configuration/services_test.go b/internal/infrastructure/configuration/services_test.go index b5e1efd7c..b4896d045 100644 --- a/internal/infrastructure/configuration/services_test.go +++ b/internal/infrastructure/configuration/services_test.go @@ -3,7 +3,11 @@ package configuration import ( "os" "path/filepath" + "slices" + "strings" "testing" + + "github.com/samcharles93/archie-core/internal/config" ) func TestLoadGatewayServiceTarget(t *testing.T) { @@ -22,8 +26,50 @@ func TestLoadGatewayServiceTarget(t *testing.T) { if err != nil { t.Fatal(err) } - if cfg.Services.Gateway.Target != tt.wantTarget { - t.Fatalf("target = %q, want %q", cfg.Services.Gateway.Target, tt.wantTarget) + if cfg.Services.Get(config.ServiceNameGateway).Target != tt.wantTarget { + t.Fatalf("target = %q, want %q", cfg.Services.Get(config.ServiceNameGateway).Target, tt.wantTarget) + } + }) + } +} + +// TestLoadServiceListens: both gRPC services this repository runs bind an +// address the configuration names. They used to be flag-only, so a host that +// already owned the default port (cockpit owns 9090) could only be retargeted +// by passing -listen and hand-writing an overlay whose target matched -- two +// files to keep in step, and nothing to keep them there. +func TestLoadServiceListens(t *testing.T) { + for _, tt := range []struct { + name, section, wantState, wantGateway string + }{ + {name: "defaults", wantState: "127.0.0.1:9090", wantGateway: "127.0.0.1:8585"}, + { + name: "explicit listens", + section: "[services.state]\nlisten = '127.0.0.1:9191'\n[services.gateway]\nlisten = '127.0.0.1:8686'", + wantState: "127.0.0.1:9191", + wantGateway: "127.0.0.1:8686", + }, + { + name: "state listen alone leaves the gateway default", + section: "[services.state]\nlisten = '127.0.0.1:9191'", + wantState: "127.0.0.1:9191", + wantGateway: "127.0.0.1:8585", + }, + } { + t.Run(tt.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"+tt.section), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := loadFile(path) + if err != nil { + t.Fatal(err) + } + if cfg.Services.Get(config.ServiceNameState).Listen != tt.wantState { + t.Fatalf("state listen = %q, want %q", cfg.Services.Get(config.ServiceNameState).Listen, tt.wantState) + } + if cfg.Services.Get(config.ServiceNameGateway).Listen != tt.wantGateway { + t.Fatalf("gateway listen = %q, want %q", cfg.Services.Get(config.ServiceNameGateway).Listen, tt.wantGateway) } }) } @@ -56,3 +102,85 @@ func TestLoadHealthListen(t *testing.T) { }) } } + +// TestRegisteredServiceDefaultsNeedNoLoaderEdit pins criterion 4 of +// docs/prds/service-registry.md. A service registered anywhere gets its +// defaults applied here without this package naming it, which is the whole +// point of iterating the registry instead of writing one branch per service. +func TestRegisteredServiceDefaultsNeedNoLoaderEdit(t *testing.T) { + config.RegisterService(config.ServiceBoth, "loadertest", "127.0.0.1:7101", "127.0.0.1:7102", "LOADERTEST_TOKEN") + + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := loadFile(path) + if err != nil { + t.Fatal(err) + } + got := cfg.Services.Get("loadertest") + if got.Target != "127.0.0.1:7101" { + t.Errorf("target = %q, want the registered default", got.Target) + } + if got.Listen != "127.0.0.1:7102" { + t.Errorf("listen = %q, want the registered default", got.Listen) + } +} + +// TestStateTargetIsNotDefaulted keeps the asymmetry the registry now carries as +// data: the gateway's target is defaulted, the State Store's is operator +// input, and defaulting it to something dialable would turn a missing +// required value into a connection attempt against the wrong host. +func TestStateTargetIsNotDefaulted(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + if err := os.WriteFile(path, []byte("bot_user = 'widget'\n"), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := loadFile(path) + if err != nil { + t.Fatal(err) + } + if got := cfg.Services.Get(config.ServiceNameState).Target; got != "" { + t.Errorf("state target = %q, want empty", got) + } +} + +// TestUnregisteredServiceSectionIsReported is the regression this change had to +// avoid introducing. Services was a struct, so [services.gatway] landed in +// Undecoded() and was reported. As a map it decodes cleanly, so without the +// registry check a typo'd service section would load silently and the daemon +// would dial the default instead. +func TestUnregisteredServiceSectionIsReported(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + src := minimalValidConfigTOML + "[services.gatway]\ntarget = '127.0.0.1:1'\n" + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { + t.Fatal(err) + } + doc, err := New(nil).File(path) + if err != nil { + t.Fatalf("File: %v (an unknown key must not fail the load)", err) + } + if !slices.Contains(doc.UnknownKeys, "services.gatway") { + t.Errorf("UnknownKeys = %v, want it to contain %q", doc.UnknownKeys, "services.gatway") + } +} + +// TestRegisteredServiceSectionIsNotReported is the other half: a real service +// section must not be flagged just because the map would accept anything. +func TestRegisteredServiceSectionIsNotReported(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.toml") + src := minimalValidConfigTOML + "[services.state]\ntarget = '127.0.0.1:9090'\n" + if err := os.WriteFile(path, []byte(src), 0o600); err != nil { + t.Fatal(err) + } + doc, err := New(nil).File(path) + if err != nil { + t.Fatal(err) + } + for _, k := range doc.UnknownKeys { + if strings.HasPrefix(k, "services.") { + t.Errorf("UnknownKeys = %v, want no services.* entry for a registered service", doc.UnknownKeys) + break + } + } +} diff --git a/internal/infrastructure/configuration/validate_test.go b/internal/infrastructure/configuration/validate_test.go index 993e71dd9..79b4972d8 100644 --- a/internal/infrastructure/configuration/validate_test.go +++ b/internal/infrastructure/configuration/validate_test.go @@ -27,7 +27,7 @@ func minimalValidConfig() config.Config { Image: "ghcr.io/samcharles93/archie-agent:latest", }, Services: config.Services{ - Gateway: config.ServiceConnection{Target: "127.0.0.1:8585"}, + config.ServiceNameGateway: {Target: "127.0.0.1:8585"}, }, } } diff --git a/internal/infrastructure/staterpc/conformance_test.go b/internal/infrastructure/staterpc/conformance_test.go index 90d1a9f92..2325a0808 100644 --- a/internal/infrastructure/staterpc/conformance_test.go +++ b/internal/infrastructure/staterpc/conformance_test.go @@ -96,10 +96,26 @@ func TestStateStoreConformance(t *testing.T) { if err := c.Update(ctx, task); err != nil { t.Fatalf("Update: %v", err) } - eventID, err := c.InsertEvent(ctx, events.Event{Kind: "stage_finish", TaskID: task.ID, Data: map[string]any{"duration_ms": 12.0}}) + eventID, err := c.InsertEvent(ctx, events.Event{Kind: "stage_finish", TaskID: task.ID, Attempt: 2, Data: map[string]any{"duration_ms": 12.0}}) if err != nil || eventID == 0 { t.Fatalf("InsertEvent: %v %v", eventID, err) } + // R4's wire acceptance: the per-attempt configuration document IS an + // event, so it has to survive the same hop an event does, including + // its nested structure and the attempt key that attributes it to one + // run. A payload that arrives flattened reads as a config with no + // fields at all. The document rides under the daemon's own key + // (internal/daemon/daemon.go), asserted by name below. + _, err = c.InsertEvent(ctx, events.Event{ + Kind: events.KindConfigCaptured, TaskID: task.ID, Attempt: 2, + Data: map[string]any{ + "schema": events.ConfigCapturedSchema, + "document": map[string]any{"bot_user": "archie", "models": map[string]any{"implement": "anthropic/claude"}}, + }, + }) + if err != nil { + t.Fatalf("InsertEvent config_captured: %v", err) + } // Stale transition: from no longer matches current status. err = c.Transition(ctx, task.ID, "queued", "merged", "") @@ -131,9 +147,26 @@ func TestStateStoreConformance(t *testing.T) { } // TaskEvents / EventsSince / stats. - if evs, err := c.TaskEvents(ctx, task.ID); err != nil || len(evs) != 1 || evs[0].Data["duration_ms"] != 12.0 { + evs, err := c.TaskEvents(ctx, task.ID) + if err != nil || len(evs) != 2 || evs[0].Data["duration_ms"] != 12.0 { t.Fatalf("TaskEvents: %+v %v", evs, err) } + if evs[0].Attempt != 2 { + t.Errorf("TaskEvents attempt = %d, want 2 (provenance must survive the wire)", evs[0].Attempt) + } + if evs[1].Kind != events.KindConfigCaptured || evs[1].Attempt != 2 || evs[1].Data["schema"] != events.ConfigCapturedSchema { + t.Errorf("config_captured event = %+v, want its kind, attempt and schema preserved", evs[1]) + } + if _, renamed := evs[1].Data["config"]; renamed { + t.Error(`the document crossed under "config"; the producer writes it under "document"`) + } + if len(evs[1].Data) != 2 { + t.Errorf("config_captured data keys = %v, want exactly schema and document", evs[1].Data) + } + doc, ok := evs[1].Data["document"].(map[string]any) + if !ok || doc["bot_user"] != "archie" { + t.Errorf("config_captured payload = %#v, want the decoded document under its own key", evs[1].Data) + } if _, err := c.EventsSince(ctx, 0, 10); err != nil { t.Fatalf("EventsSince: %v", err) } diff --git a/internal/infrastructure/staterpc/task_grants_test.go b/internal/infrastructure/staterpc/task_grants_test.go index 8a4c9b174..c3eca39bc 100644 --- a/internal/infrastructure/staterpc/task_grants_test.go +++ b/internal/infrastructure/staterpc/task_grants_test.go @@ -167,6 +167,41 @@ func TestTaskGrantScopesWorkerToItsOwnThreeRPCs(t *testing.T) { if _, err := workerA.InsertEvent(ctx, events.Event{TaskID: taskA.ID, Kind: "log"}); err != nil { t.Fatalf("task grant should authorize InsertEvent on its own task: %v", err) } + // The documented residual of R4, pinned rather than hidden: a task grant + // may insert events on its OWN task -- that is how tool_call and agent_finish + // already work -- so a task can write its own config_captured provenance, + // and only its own. The permission is the existing InsertEvent permission, + // not a new surface, which is why the provenance is exactly as trustworthy + // as the rest of that task's event stream. + configEvent := events.Event{ + TaskID: taskA.ID, Kind: events.KindConfigCaptured, Attempt: 1, + Data: map[string]any{"schema": events.ConfigCapturedSchema, "document": map[string]any{"bot_user": "archie"}}, + } + if _, err := workerA.InsertEvent(ctx, configEvent); err != nil { + t.Fatalf("task grant should authorize its own config_captured event: %v", err) + } + configEvent.TaskID = taskB.ID + if _, err := workerA.InsertEvent(ctx, configEvent); err == nil { + t.Fatal("task grant must not authorize a config_captured event on another task") + } + // The document rides under the producer's own key (internal/daemon/daemon.go + // writes "document"), so the fixture above is read back and asserted by key + // rather than trusted: a rename would otherwise leave this test green. + stored, err := admin.TaskEvents(ctx, taskA.ID) + if err != nil { + t.Fatalf("TaskEvents: %v", err) + } + for _, e := range stored { + if e.Kind != events.KindConfigCaptured { + continue + } + if _, renamed := e.Data["config"]; renamed { + t.Error(`the document crossed under "config"; the producer writes it under "document"`) + } + if _, ok := e.Data["document"].(map[string]any); !ok { + t.Errorf("config_captured data = %#v, want the document under the producer's key", e.Data) + } + } if err := workerA.Update(ctx, &workflow.Task{ID: taskA.ID, Owner: "acme", Repo: "widget"}); err != nil { t.Fatalf("task grant should authorize Update on its own task: %v", err) } diff --git a/internal/infrastructure/staterpc/values.go b/internal/infrastructure/staterpc/values.go index 91bec136c..4e82be238 100644 --- a/internal/infrastructure/staterpc/values.go +++ b/internal/infrastructure/staterpc/values.go @@ -113,8 +113,8 @@ func eventDataValue(s string) map[string]any { func eventProto(e events.Event) *pb.Event { return &pb.Event{ Id: e.ID, At: timestamp(e.At), Kind: e.Kind, TaskId: e.TaskID, Repo: e.Repo, - Issue: int64(e.Issue), Workflow: e.Workflow, Stage: e.Stage, Detail: e.Detail, - DataJson: eventDataJSON(e.Data), + Issue: int64(e.Issue), Workflow: e.Workflow, Stage: e.Stage, Attempt: int64(e.Attempt), + Detail: e.Detail, DataJson: eventDataJSON(e.Data), } } @@ -124,8 +124,8 @@ func eventValue(e *pb.Event) events.Event { } return events.Event{ ID: e.Id, At: timeValue(e.At), Kind: e.Kind, TaskID: e.TaskId, Repo: e.Repo, - Issue: int(e.Issue), Workflow: e.Workflow, Stage: e.Stage, Detail: e.Detail, - Data: eventDataValue(e.DataJson), + Issue: int(e.Issue), Workflow: e.Workflow, Stage: e.Stage, Attempt: int(e.Attempt), + Detail: e.Detail, Data: eventDataValue(e.DataJson), } } @@ -426,7 +426,7 @@ func taskLogEntryValue(e *pb.TaskLogEntry) logging.Entry { func taskLogRequestProto(taskID int64, attempt int, q logging.Query) *pb.ReadTaskLogRequest { return &pb.ReadTaskLogRequest{ TaskId: taskID, Attempt: int64(attempt), Limit: int64(q.Limit), - Levels: q.Levels, Component: q.Component, Contains: q.Contains, + Levels: q.Levels, Component: q.Component, Stage: q.Stage, Contains: q.Contains, Since: timestamp(q.Since), Until: timestamp(q.Until), } } @@ -435,6 +435,7 @@ func taskLogQueryValue(r *pb.ReadTaskLogRequest) logging.Query { return logging.Query{ Levels: r.Levels, Component: r.Component, + Stage: r.Stage, Contains: r.Contains, Limit: int(r.Limit), Since: timeValue(r.Since), diff --git a/internal/infrastructure/staterpc/values_test.go b/internal/infrastructure/staterpc/values_test.go index 8d06c201d..03875ca61 100644 --- a/internal/infrastructure/staterpc/values_test.go +++ b/internal/infrastructure/staterpc/values_test.go @@ -4,8 +4,95 @@ import ( "encoding/json" "fmt" "testing" + + "github.com/samcharles93/archie-core/internal/events" + "github.com/samcharles93/archie-core/internal/logging" ) +func TestEventAttemptSurvivesTheWire(t *testing.T) { + // attempt is provenance, so it must cross the boundary or the dashboard + // cannot attribute an event to a run. Zero must survive too: it is the + // unattributed marker, and a mapping that turned it into an absent field + // would make "unattributed" unrepresentable. + for _, attempt := range []int{0, 1, 7} { + t.Run(fmt.Sprintf("attempt=%d", attempt), func(t *testing.T) { + original := events.Event{ + Kind: events.KindStageFinish, TaskID: 42, Stage: "implement", + Attempt: attempt, Detail: "done", + Data: map[string]any{"duration_ms": float64(1200)}, + } + got := eventValue(eventProto(original)) + if got.Attempt != attempt { + t.Fatalf("attempt round-trip = %d, want %d", got.Attempt, attempt) + } + if got.Kind != original.Kind || got.TaskID != original.TaskID || got.Stage != original.Stage { + t.Fatalf("event round-trip = %+v, want %+v", got, original) + } + if got.Data["duration_ms"] != float64(1200) { + t.Fatalf("data round-trip = %v", got.Data) + } + }) + } +} + +func TestConfigCapturedPayloadSurvivesTheWire(t *testing.T) { + // R4's document is a nested JSON object inside the event's data, so the + // round trip has to keep its structure rather than flattening it to a + // string: the Config tab reads fields out of it. The key is the daemon's own + // -- internal/daemon/daemon.go writes the document under "document" -- and + // is asserted by name here so a rename cannot ride along unnoticed. + document := map[string]any{ + "schema": events.ConfigCapturedSchema, + "document": map[string]any{ + "bot_user": "archie", + "diff_cap_lines": float64(4000), + "models": map[string]any{"implement": "anthropic/claude"}, + }, + } + got := eventValue(eventProto(events.Event{ + Kind: events.KindConfigCaptured, TaskID: 42, Attempt: 2, Data: document, + })) + if got.Kind != events.KindConfigCaptured || got.Attempt != 2 { + t.Fatalf("config event = %+v", got) + } + if _, renamed := got.Data["config"]; renamed { + t.Error(`the document crossed under "config"; the producer writes it under "document"`) + } + if len(got.Data) != 2 { + t.Errorf("data keys = %v, want exactly schema and document", got.Data) + } + doc, ok := got.Data["document"].(map[string]any) + if !ok { + t.Fatalf("document payload = %#v, want a decoded object under the producer's own key", got.Data) + } + if doc["bot_user"] != "archie" { + t.Errorf("document.bot_user = %v, want archie", doc["bot_user"]) + } + models, ok := doc["models"].(map[string]any) + if !ok || models["implement"] != "anthropic/claude" { + t.Errorf("document.models = %#v, want the nested map preserved", doc["models"]) + } + if got.Data["schema"] != events.ConfigCapturedSchema { + t.Errorf("schema = %v, want %q", got.Data["schema"], events.ConfigCapturedSchema) + } +} + +func TestTaskLogStageFilterSurvivesTheWire(t *testing.T) { + // The stage filter is only useful if it reaches the reader, and the wire + // mirrors the whole logging.Query for exactly that reason: a filter that + // silently stops working at the boundary looks like "no matches". + query := logging.Query{ + Levels: []string{"ERROR"}, Component: "daemon", Stage: "implement", Contains: "parked", Limit: 50, + } + got := taskLogQueryValue(taskLogRequestProto(42, 3, query)) + if got.Stage != "implement" { + t.Fatalf("stage round-trip = %q, want implement", got.Stage) + } + if got.Component != "daemon" || got.Contains != "parked" || got.Limit != 50 { + t.Fatalf("query round-trip = %+v, want the whole filter preserved", got) + } +} + // TestEventDataJSONPreservesMarshalErrorMarker pins §11's conformance // invariant: the local store (internal/store/events.go) records a // {"marshal_error":%q} marker when json.Marshal of event Data fails, so the diff --git a/internal/infrastructure/taskactions/store.go b/internal/infrastructure/taskactions/store.go index 085e5cec5..9ebae24e7 100644 --- a/internal/infrastructure/taskactions/store.go +++ b/internal/infrastructure/taskactions/store.go @@ -16,7 +16,7 @@ func (s Store) TaskByID(ctx context.Context, id int64) (*taskactions.Task, error if err != nil || t == nil { return nil, err } - return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, Stage: t.Stage, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, ForgeBacked: t.IsForgeBacked()}, nil + return &taskactions.Task{ID: t.ID, Owner: t.Owner, Repo: t.Repo, Identity: t.Identity, Status: t.Status, Stage: t.Stage, ParkReason: t.ParkReason, IssueNumber: t.IssueNumber, RetryCount: t.RetryCount, Attempt: t.Attempt, ForgeBacked: t.IsForgeBacked()}, nil } func MaxRetries(cfg *config.Holder) func(*taskactions.Task) int { diff --git a/internal/logging/reader.go b/internal/logging/reader.go index 5d6a6df6e..6c1c0303e 100644 --- a/internal/logging/reader.go +++ b/internal/logging/reader.go @@ -38,6 +38,15 @@ type Query struct { Levels []string // Component matches the "component" field exactly. Empty means any. Component string + // Stage matches the entry's own "stage" field exactly (case-insensitive). + // Empty means any. + // + // Only entries a stage tagged carry that field. Agent and tool output is + // logged by the runtime that produced it and carries no stage, so a stage + // filter NARROWS the file rather than covering it: the caller is obliged to + // say that, because an honest-looking filter over a partial field is worse + // than no filter. An entry with no stage never matches. + Stage string // Contains matches the message or any field value, case-insensitively. Contains string // Limit caps returned entries. Zero selects DefaultTailLines; values @@ -563,6 +572,12 @@ func (q Query) matches(e Entry) bool { return false } } + if q.Stage != "" { + got, _ := e.Fields["stage"].(string) + if !strings.EqualFold(got, q.Stage) { + return false + } + } if !q.withinTimeBounds(e.Time) { return false } diff --git a/internal/logging/reader_test.go b/internal/logging/reader_test.go index 8aec0e8e6..698cfdaea 100644 --- a/internal/logging/reader_test.go +++ b/internal/logging/reader_test.go @@ -29,6 +29,52 @@ func line(level, msg string, extra ...string) string { return s.String() + "}" } +func TestTailStageFilter(t *testing.T) { + path := writeLog( + t, + line("INFO", "stage starting", `"stage":"prepare"`), + line("INFO", "stage finished", `"stage":"prepare"`, `"component":"daemon"`), + line("INFO", "stage starting", `"stage":"implement"`), + line("INFO", "agent turn", `"component":"daemon"`), + line("INFO", "stage starting", `"stage":"PREPARE"`), + ) + + tests := []struct { + name string + query Query + want []string + }{ + {"stage selects only that stage's entries", Query{Stage: "prepare"}, []string{"stage starting", "stage finished", "stage starting"}}, + {"stage match is case-insensitive", Query{Stage: "Implement"}, []string{"stage starting"}}, + {"an entry with no stage never matches", Query{Stage: "prepare"}, []string{"stage starting", "stage finished", "stage starting"}}, + {"stage combines with level", Query{Stage: "prepare", Levels: []string{"INFO"}}, []string{"stage starting", "stage finished", "stage starting"}}, + {"stage combines with component", Query{Stage: "prepare", Component: "daemon"}, []string{"stage finished"}}, + {"a stage nothing carries is empty, not an error", Query{Stage: "nonexistent"}, nil}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + res, err := Tail(path, tc.query) + if err != nil { + t.Fatalf("Tail: %v", err) + } + got := make([]string, 0, len(res.Entries)) + for _, e := range res.Entries { + got = append(got, e.Message) + } + if len(got) != len(tc.want) { + t.Fatalf("got %v, want %v", got, tc.want) + } + for i := range got { + if got[i] != tc.want[i] { + t.Errorf("got %v, want %v", got, tc.want) + break + } + } + }) + } +} + func TestTailFilters(t *testing.T) { path := writeLog( t, diff --git a/internal/store/events.go b/internal/store/events.go index 94a734dde..aabca3ddf 100644 --- a/internal/store/events.go +++ b/internal/store/events.go @@ -22,6 +22,7 @@ CREATE TABLE IF NOT EXISTS events ( issue INTEGER NOT NULL DEFAULT 0, workflow TEXT NOT NULL DEFAULT '', stage TEXT NOT NULL DEFAULT '', + attempt INTEGER NOT NULL DEFAULT 0, detail TEXT NOT NULL DEFAULT '', data TEXT NOT NULL DEFAULT '{}' ); @@ -47,10 +48,10 @@ func insertEvent(ctx context.Context, execer eventExecer, e events.Event) (int64 data = fmt.Appendf(nil, `{"marshal_error":%q}`, err.Error()) } res, err := execer.ExecContext(ctx, ` - INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, detail, data) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + INSERT INTO events (at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, e.At.UTC().Format(time.RFC3339Nano), e.Kind, e.TaskID, e.Repo, e.Issue, - e.Workflow, e.Stage, clip(e.Detail, 4000), string(data)) + e.Workflow, e.Stage, e.Attempt, clip(e.Detail, 4000), string(data)) if err != nil { return 0, err } @@ -65,7 +66,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) { var e events.Event var at, data string if err := rows.Scan(&e.ID, &at, &e.Kind, &e.TaskID, &e.Repo, &e.Issue, - &e.Workflow, &e.Stage, &e.Detail, &data); err != nil { + &e.Workflow, &e.Stage, &e.Attempt, &e.Detail, &data); err != nil { return nil, err } e.At, _ = time.Parse(time.RFC3339Nano, at) @@ -75,7 +76,7 @@ func scanEvents(rows *sql.Rows) (out []events.Event, retErr error) { return out, rows.Err() } -const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, detail, data" +const eventCols = "id, at, kind, task_id, repo, issue, workflow, stage, attempt, detail, data" // EventsSince returns up to limit events with id > sinceID, oldest // first -- SSE catch-up and the live feed. diff --git a/internal/store/store.go b/internal/store/store.go index 82d4ad348..b88494cf2 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -95,6 +95,15 @@ func migrateTasks(ctx context.Context, db *sql.DB) error { if err != nil { return err } + // events is created by `CREATE TABLE IF NOT EXISTS` (eventsSchema), which + // is a no-op against a database that already has the table. On an existing + // archie.db this read plus the `events` arm below is therefore the ONLY + // thing that adds events.attempt; without it the first insert fails with + // `table events has no column named attempt`. + eventsColumns, err := tableColumns(ctx, tx, "events") + if err != nil { + return err + } migrations := []struct { table string @@ -109,11 +118,15 @@ func migrateTasks(ctx context.Context, db *sql.DB) error { {"tasks", "binding_version", `ALTER TABLE tasks ADD COLUMN binding_version INTEGER NOT NULL DEFAULT 0`}, {"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`}, {"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`}, + {"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`}, } for _, migration := range migrations { present := columns - if migration.table == "bindings" { + switch migration.table { + case "bindings": present = bindingColumns + case "events": + present = eventsColumns } if present[migration.column] { continue @@ -544,9 +557,14 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) { } // OpenPRs returns tasks whose PR state should be reconciled with GitHub. +// +// It carries attempt deliberately: the reconcile loop attributes pr_merged and +// pr_rejected to the attempt that opened the PR, and it reaches the state store +// over the wire, so the row must carry the value for taskProto to publish it. +// Narrowing this projection back silently sends those events out unattributed. func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr error) { rows, err := s.db.QueryContext(ctx, ` - SELECT id, owner, repo, issue_number, pr_number, status, source, identity + SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt FROM tasks WHERE status=?`, workflow.StatusPROpen) if err != nil { return nil, err @@ -557,7 +575,7 @@ func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr erro for rows.Next() { var t workflow.Task if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.PRNumber, - &t.Status, &t.Source, &t.Identity); err != nil { + &t.Status, &t.Source, &t.Identity, &t.Attempt); err != nil { return nil, err } tasks = append(tasks, t) diff --git a/internal/store/store_test.go b/internal/store/store_test.go index 697710e44..e6a93c96e 100644 --- a/internal/store/store_test.go +++ b/internal/store/store_test.go @@ -111,6 +111,85 @@ func TestOpenMigratesUnversionedTaskSchemas(t *testing.T) { } } +// TestOpenMigratesLegacyEventsAttemptColumn covers the highest-risk step in +// attempt provenance: adding events.attempt to a database that predates it. +// eventsSchema is CREATE TABLE IF NOT EXISTS, so against an existing +// archie.db that statement is a no-op and the migrator arm is the ONLY thing +// that adds the column. A test that opens a fresh tempdir passes whether or +// not the arm exists, so the failure this pins is the one production would +// hit: `table events has no column named attempt`. +func TestOpenMigratesLegacyEventsAttemptColumn(t *testing.T) { + path := filepath.Join(t.TempDir(), "legacy.db") + raw, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + _, err = raw.ExecContext(t.Context(), ` + CREATE TABLE events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + at TEXT NOT NULL, + kind TEXT NOT NULL, + task_id INTEGER NOT NULL DEFAULT 0, + repo TEXT NOT NULL DEFAULT '', + issue INTEGER NOT NULL DEFAULT 0, + workflow TEXT NOT NULL DEFAULT '', + stage TEXT NOT NULL DEFAULT '', + detail TEXT NOT NULL DEFAULT '', + data TEXT NOT NULL DEFAULT '{}' + ); + INSERT INTO events (at, kind, task_id, stage, detail) + VALUES ('2026-01-01T00:00:00Z', 'stage_start', 7, 'prepare', 'pre-existing row'); + PRAGMA user_version = 3`) + if err != nil { + t.Fatal(err) + } + if err := raw.Close(); err != nil { + t.Fatal(err) + } + + s, err := Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = s.Close() }) + + // The row written before the column existed survives and reads as + // unattributed -- zero is not a first attempt. + legacy, err := s.TaskEvents(t.Context(), 7) + if err != nil { + t.Fatalf("TaskEvents after legacy migration: %v", err) + } + if len(legacy) != 1 || legacy[0].Detail != "pre-existing row" { + t.Fatalf("legacy events = %+v, want the preserved row", legacy) + } + if legacy[0].Attempt != 0 { + t.Errorf("legacy event attempt = %d, want 0 (unattributed)", legacy[0].Attempt) + } + + // Writing the new column is what actually fails in production when the + // migrator arm is missing. + if _, err := s.InsertEvent(t.Context(), events.Event{ + Kind: "stage_finish", TaskID: 7, Stage: "prepare", Attempt: 2, + Data: map[string]any{"duration_ms": 1200}, + }); err != nil { + t.Fatalf("InsertEvent with attempt after legacy migration: %v", err) + } + + timeline, err := s.TaskEvents(t.Context(), 7) + if err != nil { + t.Fatalf("TaskEvents after insert: %v", err) + } + if len(timeline) != 2 { + t.Fatalf("TaskEvents = %d events, want 2", len(timeline)) + } + if got := timeline[1].Attempt; got != 2 { + t.Errorf("attempt round-trip after legacy migration = %d, want 2", got) + } + if got := timeline[0].Attempt; got != 0 { + t.Errorf("legacy row attempt changed to %d, want 0", got) + } +} + func TestOpenRejectsNewerSchemaVersion(t *testing.T) { path := filepath.Join(t.TempDir(), "tasks.db") db, err := sql.Open("sqlite", path) @@ -526,12 +605,12 @@ func TestEventLogRoundTrip(t *testing.T) { s := openTest(t) ctx := context.Background() - id1, err := s.InsertEvent(ctx, events.Event{Kind: "stage_start", TaskID: 1, Stage: "plan"}) + id1, err := s.InsertEvent(ctx, events.Event{Kind: "stage_start", TaskID: 1, Stage: "plan", Attempt: 1}) if err != nil || id1 == 0 { t.Fatalf("insert = (%d, %v)", id1, err) } id2, err := s.InsertEvent(ctx, events.Event{ - Kind: "stage_finish", TaskID: 1, Workflow: "implement", Stage: "plan", + Kind: "stage_finish", TaskID: 1, Workflow: "implement", Stage: "plan", Attempt: 2, Data: map[string]any{"duration_ms": 1200}, }) if err != nil || id2 <= id1 { @@ -545,11 +624,18 @@ func TestEventLogRoundTrip(t *testing.T) { if evs[0].Data["duration_ms"] != float64(1200) { t.Fatalf("data round-trip = %v", evs[0].Data) } + if evs[0].Attempt != 2 { + t.Fatalf("EventsSince attempt round-trip = %d, want 2", evs[0].Attempt) + } timeline, err := s.TaskEvents(ctx, 1) if err != nil || len(timeline) != 2 { t.Fatalf("TaskEvents = (%d, %v)", len(timeline), err) } + // Two attempts of one task must stay distinguishable in its timeline. + if timeline[0].Attempt != 1 || timeline[1].Attempt != 2 { + t.Fatalf("TaskEvents attempts = (%d, %d), want (1, 2)", timeline[0].Attempt, timeline[1].Attempt) + } stats, err := s.StageStats(ctx) if err != nil || len(stats) != 1 || stats[0].AvgMs != 1200 || stats[0].Stage != "plan" { diff --git a/internal/webui/api_tasks_attempts.go b/internal/webui/api_tasks_attempts.go new file mode 100644 index 000000000..1882307dd --- /dev/null +++ b/internal/webui/api_tasks_attempts.go @@ -0,0 +1,343 @@ +package webui + +import ( + "net/http" + "sort" + "strconv" + "strings" + "time" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +// Stage/attempt statuses the attempt rail reports. They are one vocabulary +// because the rail renders one status per stage and one for the attempt it +// belongs to; "unknown" exists only for an attempt whose events carry no stage +// information at all, so a rail never claims a verdict it did not observe. +const ( + attemptStatusOK = "ok" + attemptStatusFailed = "failed" + attemptStatusInterrupted = "interrupted" + attemptStatusRunning = "running" + attemptStatusUnknown = "unknown" +) + +// taskAttemptsView is GET /api/tasks/{id}/attempts: every attempt of one task +// with its stages inline, so the rail and the attempt selector cannot disagree +// and the page makes no per-attempt calls of its own. +type taskAttemptsView struct { + TaskID int64 `json:"task_id"` + // CurrentAttempt is the task's own attempt, echoed so the page can show + // which run the daemon is on even when that attempt has no events yet. + CurrentAttempt int `json:"current_attempt"` + // UnattributedEvents counts events whose attempt is 0. It exists so the + // page can say honestly that older activity cannot be attributed instead + // of presenting it as a first run. + UnattributedEvents int `json:"unattributed_events"` + Attempts []taskAttemptView `json:"attempts"` +} + +// taskAttemptView is one attempt's rail entry. The bounds and duration are +// measured from the attempt's own events: the span between its first and last +// recorded event, which therefore includes any waiting-for-a-human gap rather +// than understating wall time (design AMENDMENTS 0.1, F3). Every optional +// field is omitted when it is not known rather than sent as a zero. +type taskAttemptView struct { + Attempt int `json:"attempt"` + Status string `json:"status"` + StartedAt *time.Time `json:"started_at,omitempty"` + FinishedAt *time.Time `json:"finished_at,omitempty"` + DurationMS *int64 `json:"duration_ms,omitempty"` + EventCount int `json:"event_count"` + Stages []taskStageView `json:"stages"` +} + +// taskStageView is one stage occurrence within an attempt. Error is always +// present (empty when the stage recorded none) so a consumer can tell "no error +// text" from a field it did not receive. +type taskStageView struct { + Name string `json:"name"` + Seq int `json:"seq"` + Status string `json:"status"` + StartedAt *time.Time `json:"started_at,omitempty"` + DurationMS *int64 `json:"duration_ms,omitempty"` + Error string `json:"error"` +} + +// handleTaskAttempts serves the stage rail: one task's attempts, each with the +// stages it recorded. +func (s *Server) handleTaskAttempts(w http.ResponseWriter, r *http.Request) { + t, ok := s.taskByPathID(w, r) + if !ok { + return + } + evs, err := s.Store.TaskEvents(r.Context(), t.ID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + attempts, unattributed := attemptsFromEvents(evs, t.Status, t.Attempt) + writeJSON(w, taskAttemptsView{ + TaskID: t.ID, + CurrentAttempt: t.Attempt, + UnattributedEvents: unattributed, + Attempts: attempts, + }) +} + +// taskByPathID resolves a task route's {id} to the task it names, answering the +// request itself and reporting false when it cannot. An unknown task is 404 +// plain text -- TaskByID says "no such row" the same way it says "here is the +// row", so the distinction is drawn here rather than leaked to the page. +func (s *Server) taskByPathID(w http.ResponseWriter, r *http.Request) (*task.Task, bool) { + id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) + if err != nil { + http.Error(w, "bad id", http.StatusBadRequest) + return nil, false + } + t, err := s.Store.TaskByID(r.Context(), id) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return nil, false + } + if t == nil { + http.Error(w, "task not found", http.StatusNotFound) + return nil, false + } + return t, true +} + +// taskAttemptTarget resolves a per-attempt read: the task its {id} names and the +// attempt it asks for. An absent or zero "attempt" parameter selects the task's +// current attempt, which is what a human means by "why did this park?" -- the +// most recent run, not an arbitrary earlier retry. Zero is not an attempt: it is +// the value that means "unattributed" on an event, so reading "attempt zero" +// would read a bucket rather than a run. +func (s *Server) taskAttemptTarget(w http.ResponseWriter, r *http.Request) (*task.Task, int, bool) { + t, ok := s.taskByPathID(w, r) + if !ok { + return nil, 0, false + } + attempt := t.Attempt + raw := strings.TrimSpace(r.URL.Query().Get("attempt")) + if raw == "" { + return t, attempt, true + } + parsed, err := strconv.Atoi(raw) + if err != nil { + http.Error(w, "bad attempt", http.StatusBadRequest) + return nil, 0, false + } + if parsed != 0 { + attempt = parsed + } + return t, attempt, true +} + +// attemptsFromEvents folds a task's timeline into its rail: one entry per +// attempt the events attribute to, ordered by attempt, plus the number of events +// that carry no attempt at all. +// +// Events with attempt 0 are counted and then dropped, never grouped. Zero means +// unattributed -- every row written before the column existed and every +// deliberately task-agnostic producer carries it -- so grouping them would +// present unrelated activity as attempt zero's rail. +func attemptsFromEvents(evs []events.Event, taskStatus string, currentAttempt int) ([]taskAttemptView, int) { + grouped := make(map[int][]events.Event) + numbers := make([]int, 0, 4) + unattributed := 0 + for _, e := range evs { + if e.Attempt == 0 { + unattributed++ + continue + } + if _, seen := grouped[e.Attempt]; !seen { + numbers = append(numbers, e.Attempt) + } + grouped[e.Attempt] = append(grouped[e.Attempt], e) + } + sort.Ints(numbers) + + attempts := make([]taskAttemptView, 0, len(numbers)) + for _, number := range numbers { + attempts = append(attempts, attemptRail(number, grouped[number], taskStatus, currentAttempt)) + } + return attempts, unattributed +} + +// attemptRail derives one attempt's status, bounds and stages from its events. +func attemptRail(number int, evs []events.Event, taskStatus string, currentAttempt int) taskAttemptView { + // The task's own record is the only honest source for "is this still + // happening": an unpaired start on any other attempt ended without + // finishing -- parked, retried, crashed or restarted -- so it is reported + // as interrupted rather than left looking permanently in flight. + inFlight := number == currentAttempt && taskStatus == task.StatusRunning + + first, last := attemptBounds(evs) + stages := foldStages(evs, inFlight) + attempt := taskAttemptView{ + Attempt: number, + Status: attemptStatus(stages, inFlight), + EventCount: len(evs), + Stages: stages, + } + if !first.IsZero() { + attempt.StartedAt = &first + } + // A finished_at is only claimed for an attempt that has an end: a running + // one has none yet, and an unknown one never had stage information to time. + if !last.IsZero() && attempt.Status != attemptStatusRunning && attempt.Status != attemptStatusUnknown { + attempt.FinishedAt = &last + if !first.IsZero() { + span := last.Sub(first).Milliseconds() + attempt.DurationMS = &span + } + } + return attempt +} + +// attemptBounds is the span of an attempt's own recorded events: the earliest +// and latest timestamp any of them carries. A zero time contributes nothing -- a +// record whose timestamp did not parse is not evidence of when it happened. +func attemptBounds(evs []events.Event) (first, last time.Time) { + for _, e := range evs { + if e.At.IsZero() { + continue + } + if first.IsZero() || e.At.Before(first) { + first = e.At + } + if last.IsZero() || e.At.After(last) { + last = e.At + } + } + return first, last +} + +// foldStages builds an attempt's ordered stage occurrences. A stage start is +// folded as an OPEN stage (status empty) until a matching finish closes it; +// resolving what is left needs the task's own record, so an open stage is +// running only while the daemon is executing this attempt and interrupted +// otherwise. +func foldStages(evs []events.Event, inFlight bool) []taskStageView { + stages := []taskStageView{} + for _, e := range evs { + switch e.Kind { + case events.KindStageStart: + started := e.At + stages = append(stages, taskStageView{Name: e.Stage, Seq: len(stages), StartedAt: &started}) + case events.KindStageFinish: + stages = finishStage(stages, e) + } + } + for i := range stages { + if stages[i].Status != "" { + continue + } + stages[i].Status = attemptStatusInterrupted + if inFlight { + stages[i].Status = attemptStatusRunning + } + } + return stages +} + +// attemptStatus reads one status off an attempt's stages. The task's own record +// outranks the events: an attempt the daemon is executing right now is running +// whatever its events have recorded so far -- including the ones that have +// recorded no stages at all. Otherwise no stage is left RUNNING to read: every +// stage still open when the daemon is not executing this attempt is folded as +// interrupted, which is what the next case reports. +func attemptStatus(stages []taskStageView, inFlight bool) string { + if inFlight { + return attemptStatusRunning + } + switch { + case anyStageStatus(stages, attemptStatusFailed): + return attemptStatusFailed + case anyStageStatus(stages, attemptStatusInterrupted): + return attemptStatusInterrupted + case len(stages) == 0: + // The attempt exists only because events attributed to it do; if none + // of them recorded a stage there is no verdict to report. + return attemptStatusUnknown + default: + return attemptStatusOK + } +} + +// finishStage applies one stage_finish event, closing the earliest still-open +// stage of the same name. A finish with no matching start still yields the +// stage -- with no start time rather than an invented one -- because the stage +// demonstrably ran and dropping it would hide a failure. +func finishStage(stages []taskStageView, e events.Event) []taskStageView { + status, errText := stageOutcome(e.Data) + recorded, hasRecorded := durationMillis(e.Data["duration_ms"]) + + idx := -1 + for i := range stages { + if stages[i].Name == e.Stage && stages[i].Status == "" { + idx = i + break + } + } + if idx < 0 { + stages = append(stages, taskStageView{Name: e.Stage, Seq: len(stages)}) + idx = len(stages) - 1 + } + stages[idx].Status = status + stages[idx].Error = errText + switch { + case hasRecorded: + // The producer's own measurement of the stage body, preferred over the + // gap between two event timestamps. + stages[idx].DurationMS = &recorded + case stages[idx].StartedAt != nil && !e.At.IsZero(): + span := e.At.Sub(*stages[idx].StartedAt).Milliseconds() + stages[idx].DurationMS = &span + } + return stages +} + +// stageOutcome reads a stage_finish event's own verdict. An interrupted finish +// is interrupted even though it also carries the cancellation error text; a +// non-empty error is a failure; anything else is ok. There is no exit code +// anywhere in this system, so no stage is ever badged as passing -- the status +// reports how the stage ended, not how well it went. +func stageOutcome(data map[string]any) (status, errText string) { + errText, _ = data["error"].(string) + if interrupted, _ := data["interrupted"].(bool); interrupted { + return attemptStatusInterrupted, errText + } + if errText != "" { + return attemptStatusFailed, errText + } + return attemptStatusOK, "" +} + +// durationMillis reads a millisecond duration a producer recorded in an event's +// data. A value that crossed JSON is float64 and one built in this process is +// an integer, so both spellings are accepted; anything else is reported as "not +// recorded" rather than as zero. +func durationMillis(v any) (int64, bool) { + switch n := v.(type) { + case int: + return int64(n), true + case int64: + return n, true + case float64: + return int64(n), true + default: + return 0, false + } +} + +func anyStageStatus(stages []taskStageView, status string) bool { + for _, s := range stages { + if s.Status == status { + return true + } + } + return false +} diff --git a/internal/webui/api_tasks_attempts_test.go b/internal/webui/api_tasks_attempts_test.go new file mode 100644 index 000000000..7e7aa168f --- /dev/null +++ b/internal/webui/api_tasks_attempts_test.go @@ -0,0 +1,536 @@ +package webui + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/events" +) + +// railBase is the fixed clock the rail fixtures hang off, so every timestamp +// and duration asserted below is a literal rather than a tolerance. +var railBase = time.Date(2026, 9, 18, 7, 0, 0, 0, time.UTC) + +func stageStartEvent(taskID int64, attempt int, stage string, at time.Time) events.Event { + return events.Event{Kind: events.KindStageStart, TaskID: taskID, Attempt: attempt, Stage: stage, At: at} +} + +func stageFinishEvent(taskID int64, attempt int, stage string, at time.Time, data map[string]any) events.Event { + return events.Event{Kind: events.KindStageFinish, TaskID: taskID, Attempt: attempt, Stage: stage, At: at, Data: data} +} + +func insertTaskEvent(t *testing.T, srv *Server, ev events.Event) { + t.Helper() + if _, err := srv.Store.InsertEvent(t.Context(), ev); err != nil { + t.Fatalf("insert %s event: %v", ev.Kind, err) + } +} + +// getTaskAPI issues one task-detail request through the real mux. A route that +// is not registered falls through to the SPA asset handler and answers 200 with +// an HTML page, so using the mux makes a missing registration fail the shape +// assertions below rather than passing quietly. +func getTaskAPI(t *testing.T, srv *Server, url string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, url, nil) + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, req) + return w +} + +func taskRoute(id int64, suffix string) string { + return "/api/tasks/" + strconv.FormatInt(id, 10) + suffix +} + +// twoAttemptTask drives one task through the lifecycle the rail has to read: +// claim (attempt 1), park, retry, claim (attempt 2), leaving the task running +// on its second attempt. No test writes an attempt number directly, so the +// attempt under test is the one the real lifecycle produced. +func twoAttemptTask(t *testing.T, srv *Server) *workflow.Task { + t.Helper() + ctx := t.Context() + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + first, err := srv.Store.ClaimNext(ctx) + if err != nil { + t.Fatal(err) + } + if first == nil { + t.Fatal("ClaimNext returned no task") + } + if first.Attempt != 1 { + t.Fatalf("first claim attempt = %d, want 1", first.Attempt) + } + if err := srv.Store.Transition(ctx, first.ID, workflow.StatusRunning, workflow.StatusParked, "stage implement: builder exited 1"); err != nil { + t.Fatal(err) + } + if err := srv.Store.RetryTask(ctx, first.ID, workflow.StatusParked, ""); err != nil { + t.Fatal(err) + } + second, err := srv.Store.ClaimNext(ctx) + if err != nil { + t.Fatal(err) + } + if second == nil { + t.Fatal("second claim returned no task") + } + if second.Attempt != 2 || second.Status != workflow.StatusRunning { + t.Fatalf("second claim = attempt %d status %q, want attempt 2 running", second.Attempt, second.Status) + } + return second +} + +// summarizeAttemptRail renders a folded rail as one line per attempt so a table +// case states the derivation it expects without a struct literal per stage: +// "attempt:status[name:status:duration[#error][@nostart],...] duration". +func summarizeAttemptRail(attempts []taskAttemptView) string { + lines := make([]string, 0, len(attempts)) + for _, a := range attempts { + stages := make([]string, 0, len(a.Stages)) + for _, s := range a.Stages { + stage := s.Name + ":" + s.Status + ":" + durationToken(s.DurationMS) + if s.StartedAt == nil { + stage += "@nostart" + } + if s.Error != "" { + stage += "#" + s.Error + } + stages = append(stages, stage) + } + line := strconv.Itoa(a.Attempt) + ":" + a.Status + "[" + strings.Join(stages, ",") + "] " + durationToken(a.DurationMS) + lines = append(lines, line) + } + return strings.Join(lines, " | ") +} + +func durationToken(ms *int64) string { + if ms == nil { + return "?" + } + return strconv.FormatInt(*ms, 10) +} + +// TestAttemptsFromEventsDerivesEveryRailRule is the table behind R1: every +// status rule the attempt rail depends on, one case each, plus the cases that +// would otherwise be answered by inventing data (a finish with no start, an +// event set with no stage information, events carrying no attempt at all). +func TestAttemptsFromEventsDerivesEveryRailRule(t *testing.T) { + at := railBase.Add + duration := func(ms int64) map[string]any { return map[string]any{"duration_ms": ms} } + + tests := []struct { + name string + taskStatus string + currentAttempt int + evs []events.Event + want string + wantUnattributed int + }{ + { + name: "a finished stage is ok and the attempt reports its measured span", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + stageStartEvent(1, 1, "prepare", at(0)), + stageFinishEvent(1, 1, "prepare", at(time.Second), duration(1000)), + }, + want: "1:ok[prepare:ok:1000] 1000", + }, + { + name: "a failed stage fails the attempt and carries the error text", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + stageStartEvent(1, 1, "implement", at(0)), + stageFinishEvent(1, 1, "implement", at(2*time.Second), map[string]any{ + "duration_ms": int64(2000), + "error": "stage implement: builder exited 1", + }), + }, + want: "1:failed[implement:failed:2000#stage implement: builder exited 1] 2000", + }, + { + name: "an interrupted stage reads interrupted even though the error text is recorded", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + stageStartEvent(1, 1, "implement", at(0)), + stageFinishEvent(1, 1, "implement", at(time.Second), map[string]any{ + "duration_ms": int64(1000), + "error": "context canceled", + "interrupted": true, + }), + }, + want: "1:interrupted[implement:interrupted:1000#context canceled] 1000", + }, + { + name: "a failed stage outranks an interrupted one", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + stageStartEvent(1, 1, "a", at(0)), + stageFinishEvent(1, 1, "a", at(time.Second), map[string]any{"duration_ms": int64(1000), "error": "boom"}), + stageStartEvent(1, 1, "b", at(2*time.Second)), + stageFinishEvent(1, 1, "b", at(3*time.Second), map[string]any{ + "duration_ms": int64(1000), "error": "canceled", "interrupted": true, + }), + }, + want: "1:failed[a:failed:1000#boom,b:interrupted:1000#canceled] 3000", + }, + { + name: "an unpaired start on the task's current in-flight attempt is running", + taskStatus: workflow.StatusRunning, currentAttempt: 2, + evs: []events.Event{stageStartEvent(1, 2, "implement", at(0))}, + want: "2:running[implement:running:?] ?", + }, + { + name: "an unpaired start on a superseded attempt is interrupted", + taskStatus: workflow.StatusRunning, currentAttempt: 2, + evs: []events.Event{stageStartEvent(1, 1, "implement", at(0))}, + want: "1:interrupted[implement:interrupted:?] 0", + }, + { + name: "an unpaired start on a parked task's own attempt is interrupted", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{stageStartEvent(1, 1, "implement", at(0))}, + want: "1:interrupted[implement:interrupted:?] 0", + }, + { + name: "a finish with no start yields the stage without an invented start time", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + stageFinishEvent(1, 1, "commit", at(0), duration(4000)), + }, + want: "1:ok[commit:ok:4000@nostart] 0", + }, + { + name: "a finish without a recorded duration derives it from its own start", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + stageStartEvent(1, 1, "prepare", at(0)), + stageFinishEvent(1, 1, "prepare", at(10*time.Second), nil), + }, + want: "1:ok[prepare:ok:10000] 10000", + }, + { + name: "a repeated stage name yields one rail entry per occurrence", + taskStatus: workflow.StatusRunning, currentAttempt: 1, + evs: []events.Event{ + stageStartEvent(1, 1, "implement", at(0)), + stageFinishEvent(1, 1, "implement", at(time.Second), duration(1000)), + stageStartEvent(1, 1, "implement", at(2*time.Second)), + }, + want: "1:running[implement:ok:1000,implement:running:?] ?", + }, + { + name: "a later attempt does not absorb the earlier attempt's stages", + taskStatus: workflow.StatusRunning, currentAttempt: 2, + evs: []events.Event{ + stageStartEvent(1, 1, "prepare", at(0)), + stageFinishEvent(1, 1, "prepare", at(time.Second), duration(1000)), + stageStartEvent(1, 2, "implement", at(2*time.Second)), + }, + want: "1:ok[prepare:ok:1000] 1000 | 2:running[implement:running:?] ?", + }, + { + name: "events carrying no attempt are counted, never grouped", + taskStatus: workflow.StatusQueued, currentAttempt: 0, + evs: []events.Event{ + {Kind: events.KindStageStart, TaskID: 1, Stage: "prepare", At: at(0)}, + {Kind: events.KindStageFinish, TaskID: 1, Stage: "prepare", At: at(time.Second), Data: duration(1000)}, + }, + wantUnattributed: 2, + }, + { + name: "a task with no events has no attempts and nothing unattributed", + taskStatus: workflow.StatusQueued, currentAttempt: 0, + want: "", + }, + { + name: "an attempt whose events carry no stage information is unknown", + taskStatus: workflow.StatusParked, currentAttempt: 1, + evs: []events.Event{ + {Kind: events.KindAgentFinish, TaskID: 1, Attempt: 1, At: at(0), Data: map[string]any{"status": "ok"}}, + }, + want: "1:unknown[] ?", + }, + { + name: "the task's own record keeps the current attempt running with no stage events", + taskStatus: workflow.StatusRunning, currentAttempt: 1, + evs: []events.Event{ + {Kind: events.KindAgentFinish, TaskID: 1, Attempt: 1, At: at(0), Data: map[string]any{"status": "ok"}}, + }, + want: "1:running[] ?", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + attempts, unattributed := attemptsFromEvents(tt.evs, tt.taskStatus, tt.currentAttempt) + if got := summarizeAttemptRail(attempts); got != tt.want { + t.Errorf("rail = %q, want %q", got, tt.want) + } + if unattributed != tt.wantUnattributed { + t.Errorf("unattributed = %d, want %d", unattributed, tt.wantUnattributed) + } + }) + } +} + +// TestHandleTaskAttemptsRendersBothAttemptsOfARetry pins the wire shape: an +// attempt's ordered stages with name, start time, duration, terminal status and +// error text, the task's current attempt, and attempt 1's rail excluding +// attempt 2's stages. +func TestHandleTaskAttemptsRendersBothAttemptsOfARetry(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + at := railBase.Add + + insertTaskEvent(t, srv, stageStartEvent(current.ID, 1, "prepare", at(0))) + insertTaskEvent(t, srv, stageFinishEvent(current.ID, 1, "prepare", at(1200*time.Millisecond), + map[string]any{"duration_ms": int64(1200)})) + insertTaskEvent(t, srv, stageStartEvent(current.ID, 1, "implement", at(1323*time.Millisecond))) + insertTaskEvent(t, srv, stageFinishEvent(current.ID, 1, "implement", at(231323*time.Millisecond), + map[string]any{"duration_ms": int64(230000), "error": "stage implement: builder exited 1"})) + insertTaskEvent(t, srv, stageStartEvent(current.ID, 2, "implement", at(time.Hour))) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/attempts")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + if raw := w.Body.String(); !strings.Contains(raw, `"error":""`) { + t.Errorf("body = %s, want the ok stage's error field present and empty rather than omitted", raw) + } + + var body struct { + TaskID int64 `json:"task_id"` + CurrentAttempt int `json:"current_attempt"` + UnattributedEvents int `json:"unattributed_events"` + Attempts []struct { + Attempt int `json:"attempt"` + Status string `json:"status"` + StartedAt *time.Time `json:"started_at"` + FinishedAt *time.Time `json:"finished_at"` + DurationMS *int64 `json:"duration_ms"` + EventCount int `json:"event_count"` + Stages []struct { + Name string `json:"name"` + Seq int `json:"seq"` + Status string `json:"status"` + StartedAt *time.Time `json:"started_at"` + DurationMS *int64 `json:"duration_ms"` + Error string `json:"error"` + } `json:"stages"` + } `json:"attempts"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, w.Body) + } + if body.TaskID != current.ID || body.CurrentAttempt != 2 || body.UnattributedEvents != 0 { + t.Fatalf("envelope = task %d, current attempt %d, unattributed %d; want %d, 2, 0", + body.TaskID, body.CurrentAttempt, body.UnattributedEvents, current.ID) + } + if len(body.Attempts) != 2 { + t.Fatalf("attempts = %d, want 2 (%s)", len(body.Attempts), w.Body) + } + + first := body.Attempts[0] + if first.Attempt != 1 || first.Status != "failed" { + t.Errorf("attempt 1 = %d/%q, want 1/failed", first.Attempt, first.Status) + } + if first.EventCount != 4 { + t.Errorf("attempt 1 event_count = %d, want 4", first.EventCount) + } + if first.StartedAt == nil || !first.StartedAt.Equal(at(0)) { + t.Errorf("attempt 1 started_at = %v, want %v", first.StartedAt, at(0)) + } + if first.FinishedAt == nil || !first.FinishedAt.Equal(at(231323*time.Millisecond)) { + t.Errorf("attempt 1 finished_at = %v, want %v", first.FinishedAt, at(231323*time.Millisecond)) + } + if first.DurationMS == nil || *first.DurationMS != 231323 { + t.Errorf("attempt 1 duration_ms = %v, want 231323", first.DurationMS) + } + if len(first.Stages) != 2 { + t.Fatalf("attempt 1 stages = %d, want 2 (%s)", len(first.Stages), w.Body) + } + prepare := first.Stages[0] + if prepare.Name != "prepare" || prepare.Seq != 0 || prepare.Status != "ok" || prepare.Error != "" { + t.Errorf("stage 0 = %+v, want prepare/0/ok with no error", prepare) + } + if prepare.DurationMS == nil || *prepare.DurationMS != 1200 { + t.Errorf("stage 0 duration_ms = %v, want 1200", prepare.DurationMS) + } + if prepare.StartedAt == nil || !prepare.StartedAt.Equal(at(0)) { + t.Errorf("stage 0 started_at = %v, want %v", prepare.StartedAt, at(0)) + } + implement := first.Stages[1] + if implement.Name != "implement" || implement.Seq != 1 || implement.Status != "failed" { + t.Errorf("stage 1 = %+v, want implement/1/failed", implement) + } + if implement.Error != "stage implement: builder exited 1" { + t.Errorf("stage 1 error = %q, want the recorded error text", implement.Error) + } + if implement.DurationMS == nil || *implement.DurationMS != 230000 { + t.Errorf("stage 1 duration_ms = %v, want 230000", implement.DurationMS) + } + + second := body.Attempts[1] + if second.Attempt != 2 || second.Status != "running" || second.EventCount != 1 { + t.Errorf("attempt 2 = %d/%q with %d events, want 2/running with 1", second.Attempt, second.Status, second.EventCount) + } + if second.FinishedAt != nil || second.DurationMS != nil { + t.Errorf("attempt 2 finished_at = %v, duration_ms = %v; both must be omitted for a running attempt", + second.FinishedAt, second.DurationMS) + } + if len(second.Stages) != 1 || second.Stages[0].Name != "implement" || second.Stages[0].Status != "running" { + t.Fatalf("attempt 2 stages = %+v, want one running implement", second.Stages) + } + if second.Stages[0].Error != "" { + t.Errorf("attempt 2 stage error = %q, want empty", second.Stages[0].Error) + } +} + +// TestHandleTaskAttemptsSeparatesUnattributedEventsFromAFirstRun pins the +// honesty requirement: events that carry no attempt cannot be presented as +// attempt 1, and a task with nothing recorded at all is a different answer from +// a task whose events predate attribution. +func TestHandleTaskAttemptsSeparatesUnattributedEventsFromAFirstRun(t *testing.T) { + t.Run("a task with no events at all", func(t *testing.T) { + srv := newTestServer(t) + if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + + w := getTaskAPI(t, srv, taskRoute(task.ID, "/attempts")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + raw := w.Body.String() + if !strings.Contains(raw, `"attempts":[]`) { + t.Errorf("body = %s, want an empty attempts array rather than null", raw) + } + if !strings.Contains(raw, `"unattributed_events":0`) { + t.Errorf("body = %s, want unattributed_events 0 for a task with nothing recorded", raw) + } + }) + + t.Run("events that carry no attempt", func(t *testing.T) { + srv := newTestServer(t) + if _, err := srv.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(t.Context(), "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + insertTaskEvent(t, srv, stageStartEvent(task.ID, 0, "prepare", railBase)) + insertTaskEvent(t, srv, stageFinishEvent(task.ID, 0, "prepare", railBase.Add(time.Second), + map[string]any{"duration_ms": int64(1000)})) + + w := getTaskAPI(t, srv, taskRoute(task.ID, "/attempts")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + var body struct { + UnattributedEvents int `json:"unattributed_events"` + Attempts []struct { + Attempt int `json:"attempt"` + } `json:"attempts"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, w.Body) + } + if body.UnattributedEvents != 2 { + t.Errorf("unattributed_events = %d, want 2", body.UnattributedEvents) + } + if len(body.Attempts) != 0 { + t.Errorf("attempts = %+v, want none: events carrying no attempt must never be presented as a run", body.Attempts) + } + }) +} + +// TestTaskDetailRoutesRejectUnknownTasksAndStoreFailures keeps the three new +// reads on the existing task-route conventions: an unknown task is 404 plain +// text (never 200 with an empty body), a store failure is 500, and a +// non-numeric id is 400. +func TestTaskDetailRoutesRejectUnknownTasksAndStoreFailures(t *testing.T) { + base := newTestServer(t) + if _, err := base.Store.EnqueueIssue(t.Context(), "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + existing, err := base.Store.TaskByIssue(t.Context(), "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + + eventsBroken := &Server{ + Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")}, + Log: base.Log, + } + lookupBroken := &Server{ + Store: &stubStore{TaskStore: base.Store, taskByIDErr: fmt.Errorf("db locked")}, + Log: base.Log, + } + + tests := []struct { + name string + srv *Server + id int64 + suffix string + wantStatus int + }{ + {"attempts unknown task", base, 999, "/attempts", http.StatusNotFound}, + {"changes unknown task", base, 999, "/changes", http.StatusNotFound}, + {"debug unknown task", base, 999, "/debug", http.StatusNotFound}, + {"attempts events failure", eventsBroken, existing.ID, "/attempts", http.StatusInternalServerError}, + {"changes events failure", eventsBroken, existing.ID, "/changes", http.StatusInternalServerError}, + {"debug events failure", eventsBroken, existing.ID, "/debug", http.StatusInternalServerError}, + {"attempts lookup failure", lookupBroken, existing.ID, "/attempts", http.StatusInternalServerError}, + {"changes lookup failure", lookupBroken, existing.ID, "/changes", http.StatusInternalServerError}, + {"debug lookup failure", lookupBroken, existing.ID, "/debug", http.StatusInternalServerError}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := getTaskAPI(t, tt.srv, taskRoute(tt.id, tt.suffix)) + if w.Code != tt.wantStatus { + t.Errorf("GET %s = %d (%s), want %d", tt.suffix, w.Code, w.Body, tt.wantStatus) + } + }) + } + + for _, suffix := range []string{"/attempts", "/changes", "/debug"} { + t.Run("non-numeric id "+suffix, func(t *testing.T) { + w := getTaskAPI(t, base, "/api/tasks/not-a-number"+suffix) + if w.Code != http.StatusBadRequest { + t.Errorf("GET %s = %d (%s), want 400", suffix, w.Code, w.Body) + } + }) + } + + // The attempt parameter belongs to the per-attempt reads: /attempts returns + // every attempt of the task, so it does not consume the parameter at all, + // while /changes and /debug resolve it and must refuse a value that is not + // an attempt number rather than silently read the current one. + t.Run("non-numeric attempt on /attempts is not a parameter of that read", func(t *testing.T) { + w := getTaskAPI(t, base, taskRoute(existing.ID, "/attempts?attempt=later")) + if w.Code != http.StatusOK { + t.Errorf("GET /attempts?attempt=later = %d (%s), want 200", w.Code, w.Body) + } + }) + for _, suffix := range []string{"/changes", "/debug"} { + t.Run("non-numeric attempt "+suffix, func(t *testing.T) { + w := getTaskAPI(t, base, taskRoute(existing.ID, suffix+"?attempt=later")) + if w.Code != http.StatusBadRequest { + t.Errorf("GET %s?attempt=later = %d (%s), want 400", suffix, w.Code, w.Body) + } + }) + } +} diff --git a/internal/webui/api_tasks_changes.go b/internal/webui/api_tasks_changes.go new file mode 100644 index 000000000..95e2fb32a --- /dev/null +++ b/internal/webui/api_tasks_changes.go @@ -0,0 +1,201 @@ +package webui + +import ( + "encoding/json" + "net/http" + "reflect" + "strings" + "time" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +// taskChangesView is GET /api/tasks/{id}/changes: the change captures recorded +// for one attempt. Found reports that a capture was recorded at all -- an empty +// captures list without it would tell an operator that nothing changed, which is +// not a claim this system can make about a run whose diffstat was never read. +type taskChangesView struct { + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Found bool `json:"found"` + Captures []changeCaptureView `json:"captures"` +} + +// changeCaptureView is one capture: the diffstat measured at the moment the run +// was committed or pushed, plus the repository and pull-request links the page +// renders beside it. The URLs are filled from the same forge projection the task +// list uses, so a capture links exactly where its task does. +type changeCaptureView struct { + CapturedAt time.Time `json:"captured_at"` + CapturedAfter string `json:"captured_after"` + Stage string `json:"stage"` + Owner string `json:"owner"` + Repo string `json:"repo"` + Base string `json:"base"` + Branch string `json:"branch"` + HeadSHA string `json:"head_sha"` + BaseSHA string `json:"base_sha"` + PRNumber int `json:"pr_number"` + RepoURL string `json:"repo_url,omitempty"` + PRURL string `json:"pr_url,omitempty"` + Totals task.ChangeTotals `json:"totals"` + Truncated bool `json:"truncated"` + Files []task.FileChange `json:"files"` +} + +// capturePayload is one changes_captured event's data as the producer persists +// it. The measured change itself reuses the shared task.ChangeStats identity the +// producer writes with, so the two sides cannot drift into two spellings of one +// diffstat. +type capturePayload struct { + Schema string `json:"schema"` + Owner string `json:"owner"` + Repo string `json:"repo"` + Base string `json:"base"` + Branch string `json:"branch"` + PRNumber int `json:"pr_number"` + CapturedAfter string `json:"captured_after"` + Truncated bool `json:"truncated"` + task.ChangeStats +} + +// capturePayloadKeys is the exact key set one capture carries, derived from +// capturePayload's own json tags rather than restated beside them: the reader +// and the key set cannot disagree. A payload that renamed, dropped or added a +// key is refused, because reading it leniently is how a lost truncation marker +// becomes "not truncated" and a dropped file list becomes "nothing changed". +var capturePayloadKeys = structKeys(reflect.TypeFor[capturePayload]()) + +// structKeys collects the JSON key names a struct declares, recursing into the +// embedded value structs a decoder flattens. +func structKeys(t reflect.Type) map[string]struct{} { + keys := make(map[string]struct{}, t.NumField()) + for field := range t.Fields() { + if field.Anonymous { + for key := range structKeys(field.Type) { + keys[key] = struct{}{} + } + continue + } + if name, _, _ := strings.Cut(field.Tag.Get("json"), ","); name != "" && name != "-" { + keys[name] = struct{}{} + } + } + return keys +} + +// handleTaskChanges serves the changed files one attempt produced. +func (s *Server) handleTaskChanges(w http.ResponseWriter, r *http.Request) { + t, attempt, ok := s.taskAttemptTarget(w, r) + if !ok { + return + } + evs, err := s.Store.TaskEvents(r.Context(), t.ID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + captures, recorded := capturedChanges(evs, attempt) + + // The links come from the task's own forge resolution, reused rather than + // re-derived: the capture's own owner/repo/pr decide the URL, so a capture + // taken before the PR existed has no pull-request link instead of one + // pointing at a later attempt's PR. + forge := s.resolveForge(r.Context()) + for i := range captures { + target := task.Task{ + Owner: captures[i].Owner, Repo: captures[i].Repo, + PRNumber: captures[i].PRNumber, Identity: t.Identity, + } + captures[i].RepoURL, _, captures[i].PRURL = taskURLs(target, forge(target)) + } + + writeJSON(w, taskChangesView{TaskID: t.ID, Attempt: attempt, Found: recorded, Captures: captures}) +} + +// capturedChanges folds a task's events into the captures recorded for one +// attempt, oldest first (events are read in insert order, which is capture +// order). +// +// recorded reports that the attempt has at least one capture event even when its +// payload could not be read: a capture that happened is provenance whether or not +// this read can decode it, and answering "no capture was recorded" would be a +// false statement about it. A payload that is absent, in a schema this build does +// not read, or otherwise malformed is skipped rather than failing the read. +func capturedChanges(evs []events.Event, attempt int) (captures []changeCaptureView, recorded bool) { + captures = []changeCaptureView{} + for _, e := range evs { + if e.Kind != events.KindChangesCaptured || e.Attempt != attempt { + continue + } + recorded = true + capture, ok := decodeCapture(e) + if !ok { + continue + } + captures = append(captures, capture) + } + return captures, recorded +} + +// decodeCapture reads one capture event. It reports false when the event carries +// no data, when its payload is not in the schema this build reads, when its key +// set is not exactly the one this reader declares, or when the payload is +// malformed. The totals are passed through as recorded and never recomputed from +// the file entries, because the producer's totals cover the full change set even +// when the entries were capped. +func decodeCapture(e events.Event) (changeCaptureView, bool) { + if len(e.Data) == 0 { + return changeCaptureView{}, false + } + raw, err := json.Marshal(e.Data) + if err != nil { + return changeCaptureView{}, false + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(raw, &keys); err != nil { + return changeCaptureView{}, false + } + if len(keys) != len(capturePayloadKeys) { + return changeCaptureView{}, false + } + for key := range capturePayloadKeys { + if _, ok := keys[key]; !ok { + return changeCaptureView{}, false + } + } + var payload capturePayload + if err := json.Unmarshal(raw, &payload); err != nil { + return changeCaptureView{}, false + } + if payload.Schema != events.ChangesCapturedSchema { + return changeCaptureView{}, false + } + files := payload.Files + if len(files) > task.MaxCapturedFiles { + // The producer bounds the list at task.MaxCapturedFiles and reports the + // drop with truncated. More entries than the shared cap means the cap + // was lost, and rendering them would present the loss as a complete + // capture. + return changeCaptureView{}, false + } + if files == nil { + files = []task.FileChange{} + } + return changeCaptureView{ + CapturedAt: e.At, + CapturedAfter: payload.CapturedAfter, + Stage: e.Stage, + Owner: payload.Owner, + Repo: payload.Repo, + Base: payload.Base, + Branch: payload.Branch, + HeadSHA: payload.HeadSHA, + BaseSHA: payload.BaseSHA, + PRNumber: payload.PRNumber, + Totals: payload.Totals, + Truncated: payload.Truncated, + Files: files, + }, true +} diff --git a/internal/webui/api_tasks_changes_test.go b/internal/webui/api_tasks_changes_test.go new file mode 100644 index 000000000..b109635f7 --- /dev/null +++ b/internal/webui/api_tasks_changes_test.go @@ -0,0 +1,460 @@ +package webui + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +// captureData is the shape the producer persists for one capture: the diffstat +// measured at the moment a run was committed or pushed. The reader's fixtures +// are built here; nothing in this file re-derives a capture. +func captureData(files []any, totals map[string]any) map[string]any { + return map[string]any{ + "schema": events.ChangesCapturedSchema, + "owner": "acme", "repo": "widget", "base": "main", "branch": "feat/2-x", + "head_sha": "head-sha", "base_sha": "base-sha", "pr_number": 0, + "captured_after": "commit-push", + "files": files, "totals": totals, "truncated": false, + } +} + +func modifiedFile(path string, additions, deletions int) map[string]any { + return map[string]any{ + "path": path, "old_path": "", "status": "modified", + "additions": additions, "deletions": deletions, "binary": false, + } +} + +func insertCapture(t *testing.T, srv *Server, taskID int64, attempt int, stage string, data map[string]any) { + t.Helper() + insertTaskEvent(t, srv, events.Event{ + Kind: events.KindChangesCaptured, TaskID: taskID, Attempt: attempt, Stage: stage, + At: railBase.Add(time.Duration(attempt) * time.Minute), Data: data, + }) +} + +// changesResponse is the endpoint's body as the page consumes it, decoded by +// field name so the contract is asserted rather than substring-matched. +type changesResponse struct { + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Found bool `json:"found"` + Captures []captureViewJSON `json:"captures"` +} + +type captureViewJSON struct { + CapturedAt time.Time `json:"captured_at"` + CapturedAfter string `json:"captured_after"` + Stage string `json:"stage"` + Owner string `json:"owner"` + Repo string `json:"repo"` + Base string `json:"base"` + Branch string `json:"branch"` + HeadSHA string `json:"head_sha"` + BaseSHA string `json:"base_sha"` + PRNumber int `json:"pr_number"` + RepoURL string `json:"repo_url"` + PRURL string `json:"pr_url"` + Totals changeTotalsJSON `json:"totals"` + Truncated bool `json:"truncated"` + Files []fileChangeJSON `json:"files"` +} + +type changeTotalsJSON struct { + Files int `json:"files"` + Additions int `json:"additions"` + Deletions int `json:"deletions"` +} + +type fileChangeJSON struct { + Path string `json:"path"` + OldPath string `json:"old_path"` + Status string `json:"status"` + Additions int `json:"additions"` + Deletions int `json:"deletions"` + Binary bool `json:"binary"` +} + +func decodeChanges(t *testing.T, body []byte) changesResponse { + t.Helper() + var decoded changesResponse + if err := json.Unmarshal(body, &decoded); err != nil { + t.Fatalf("decode response: %v (%s)", err, body) + } + return decoded +} + +// TestHandleTaskChangesKeepsFoundFalseApartFromAnEmptyFileList pins the +// distinction the changed-files view depends on: "no capture was recorded for +// this attempt" is not "no files changed". +func TestHandleTaskChangesKeepsFoundFalseApartFromAnEmptyFileList(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + insertCapture(t, srv, current.ID, 2, "commit", + captureData([]any{}, map[string]any{"files": 0, "additions": 0, "deletions": 0})) + + recorded := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if recorded.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", recorded.Code, recorded.Body) + } + if raw := recorded.Body.String(); !strings.Contains(raw, `"files":[]`) { + t.Errorf("body = %s, want an empty files array rather than null", raw) + } + body := decodeChanges(t, recorded.Body.Bytes()) + if !body.Found || body.Attempt != 2 { + t.Fatalf("found = %v, attempt = %d; want true, 2", body.Found, body.Attempt) + } + if len(body.Captures) != 1 { + t.Fatalf("captures = %d, want 1 (%s)", len(body.Captures), recorded.Body) + } + if len(body.Captures[0].Files) != 0 { + t.Errorf("files = %+v, want none: a capture with an empty diff is still a capture", body.Captures[0].Files) + } + if body.Captures[0].Totals.Files != 0 { + t.Errorf("totals.files = %d, want 0", body.Captures[0].Totals.Files) + } + + unrecorded := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=1")) + if unrecorded.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", unrecorded.Code, unrecorded.Body) + } + if raw := unrecorded.Body.String(); !strings.Contains(raw, `"captures":[]`) { + t.Errorf("body = %s, want an empty captures array rather than null", raw) + } + if got := decodeChanges(t, unrecorded.Body.Bytes()); got.Found || len(got.Captures) != 0 || got.Attempt != 1 { + t.Errorf("attempt 1 = found %v with %d captures at attempt %d, want found false, none, attempt 1", + got.Found, len(got.Captures), got.Attempt) + } +} + +// TestHandleTaskChangesResolvesTheCurrentAttemptAndCarriesTheRecordedFields +// pins the wire shape field by field, and that an absent attempt parameter +// selects the task's current attempt. +func TestHandleTaskChangesResolvesTheCurrentAttemptAndCarriesTheRecordedFields(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + data := captureData([]any{modifiedFile("internal/x.go", 12, 3)}, + map[string]any{"files": 1, "additions": 12, "deletions": 3}) + data["pr_number"] = 7 + insertCapture(t, srv, current.ID, 2, "commit-push", data) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + body := decodeChanges(t, w.Body.Bytes()) + if body.TaskID != current.ID || body.Attempt != 2 || !body.Found { + t.Fatalf("envelope = task %d attempt %d found %v; want %d, 2, true", + body.TaskID, body.Attempt, body.Found, current.ID) + } + if len(body.Captures) != 1 { + t.Fatalf("captures = %d, want 1 (%s)", len(body.Captures), w.Body) + } + capture := body.Captures[0] + if !capture.CapturedAt.Equal(railBase.Add(2 * time.Minute)) { + t.Errorf("captured_at = %v, want the capture event's own time", capture.CapturedAt) + } + if capture.CapturedAfter != "commit-push" || capture.Stage != "commit-push" { + t.Errorf("captured_after = %q, stage = %q; want commit-push, commit-push", capture.CapturedAfter, capture.Stage) + } + if capture.Owner != "acme" || capture.Repo != "widget" || capture.Base != "main" || capture.Branch != "feat/2-x" { + t.Errorf("repository fields = %q/%q base %q branch %q", capture.Owner, capture.Repo, capture.Base, capture.Branch) + } + if capture.HeadSHA != "head-sha" || capture.BaseSHA != "base-sha" || capture.PRNumber != 7 { + t.Errorf("shas = %q/%q pr %d, want head-sha/base-sha/7", capture.HeadSHA, capture.BaseSHA, capture.PRNumber) + } + if capture.Totals.Files != 1 || capture.Totals.Additions != 12 || capture.Totals.Deletions != 3 { + t.Errorf("totals = %+v, want 1/12/3", capture.Totals) + } + if capture.Truncated { + t.Error("truncated = true for a capture that was not truncated") + } + if len(capture.Files) != 1 { + t.Fatalf("files = %+v, want one", capture.Files) + } + file := capture.Files[0] + if file.Path != "internal/x.go" || file.Status != "modified" || file.Additions != 12 || file.Deletions != 3 || file.Binary { + t.Errorf("file = %+v, want internal/x.go modified +12 -3, not binary", file) + } + if file.OldPath != "" { + t.Errorf("old_path = %q, want empty for a modify", file.OldPath) + } +} + +// TestHandleTaskChangesKeepsTheFullTotalsOfATruncatedCapture pins that totals +// are the producer's measurement of the whole change set, not a re-count of the +// file entries this read happens to carry. +func TestHandleTaskChangesKeepsTheFullTotalsOfATruncatedCapture(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + data := captureData([]any{modifiedFile("internal/x.go", 1, 1)}, + map[string]any{"files": 250, "additions": 900, "deletions": 10}) + data["truncated"] = true + insertCapture(t, srv, current.ID, 2, "commit", data) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + captures := decodeChanges(t, w.Body.Bytes()).Captures + if len(captures) != 1 { + t.Fatalf("captures = %d, want 1 (%s)", len(captures), w.Body) + } + capture := captures[0] + if !capture.Truncated { + t.Error("truncated = false for a capture that dropped file entries") + } + if len(capture.Files) != 1 { + t.Fatalf("files = %d, want the single entry the producer capped the list to", len(capture.Files)) + } + if capture.Totals.Files != 250 || capture.Totals.Additions != 900 || capture.Totals.Deletions != 10 { + t.Errorf("totals = %+v, want the full 250/900/10 rather than a count of the 1 file carried", capture.Totals) + } +} + +// TestHandleTaskChangesRefusesACaptureItCannotNameSchema pins the schema +// marker's job: a payload whose shape this build does not know is not a +// capture it may render. Rendering it would show a diffstat nobody read, so +// the attempt reports that a capture was recorded and none was readable -- +// the panel's read-failure state -- rather than a capture of zeroes. +func TestHandleTaskChangesRefusesACaptureItCannotNameSchema(t *testing.T) { + tests := []struct { + name string + mutate func(map[string]any) + }{ + { + name: "no schema at all", + mutate: func(data map[string]any) { delete(data, "schema") }, + }, + { + name: "a schema this build does not know", + mutate: func(data map[string]any) { data["schema"] = "archie/task-changes@2" }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + data := captureData([]any{modifiedFile("internal/x.go", 12, 3)}, + map[string]any{"files": 1, "additions": 12, "deletions": 3}) + tt.mutate(data) + insertCapture(t, srv, current.ID, 2, "commit", data) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + body := decodeChanges(t, w.Body.Bytes()) + if !body.Found { + t.Error("found = false although a capture event was recorded for the attempt") + } + if len(body.Captures) != 0 { + t.Errorf("captures = %+v, want none: a payload this build cannot name must not be rendered as a capture", + body.Captures) + } + }) + } +} + +// TestHandleTaskChangesRefusesAPayloadWhoseKeySetDrifted pins the other half +// of the schema guard: the schema names the shape, the exact key set proves +// the shape arrived. A key renamed, dropped or added means the payload is not +// the one this reader knows, and reading it leniently is how a lost +// truncation marker becomes "not truncated" and a moved cap becomes "every +// file, none dropped". +func TestHandleTaskChangesRefusesAPayloadWhoseKeySetDrifted(t *testing.T) { + tests := []struct { + name string + mutate func(map[string]any) + }{ + { + name: "the truncation marker renamed", + mutate: func(data map[string]any) { + delete(data, "truncated") + data["truncated_files"] = true + }, + }, + { + name: "the file list dropped", + mutate: func(data map[string]any) { delete(data, "files") }, + }, + { + name: "a key this reader does not know", + mutate: func(data map[string]any) { data["schema_version"] = 1 }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + data := captureData([]any{modifiedFile("internal/x.go", 1, 0)}, + map[string]any{"files": task.MaxCapturedFiles + 1, "additions": 1, "deletions": 0}) + tt.mutate(data) + insertCapture(t, srv, current.ID, 2, "commit", data) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + body := decodeChanges(t, w.Body.Bytes()) + if !body.Found { + t.Error("found = false although a capture event was recorded for the attempt") + } + if len(body.Captures) != 0 { + t.Errorf("captures = %+v, want none: a payload whose keys drifted must not be read as zero values", + body.Captures) + } + }) + } +} + +// TestHandleTaskChangesLinksThePullRequestOfTheFinalCapture is the reader half +// of the requirement the commit-time captures cannot meet: their pr_number is +// necessarily 0, and the capture OpenPR takes once the number exists is what +// gives the panel a pull-request link. +func TestHandleTaskChangesLinksThePullRequestOfTheFinalCapture(t *testing.T) { + srv := newTestServer(t) + srv.ConfigSource = func(_ context.Context) (ConfigView, bool, error) { + return multiIdentityView(), true, nil + } + current := twoAttemptTask(t, srv) + + beforePR := captureData([]any{modifiedFile("internal/x.go", 1, 0)}, + map[string]any{"files": 1, "additions": 1, "deletions": 0}) + beforePR["captured_after"] = "commit-push" + insertCapture(t, srv, current.ID, 2, "commit-push", beforePR) + + withPR := captureData([]any{modifiedFile("internal/x.go", 1, 0)}, + map[string]any{"files": 1, "additions": 1, "deletions": 0}) + withPR["captured_after"] = "open-pr" + withPR["pr_number"] = 7 + insertCapture(t, srv, current.ID, 2, "open-pr", withPR) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + captures := decodeChanges(t, w.Body.Bytes()).Captures + if len(captures) != 2 { + t.Fatalf("captures = %d, want both the push and the open-pr capture (%s)", len(captures), w.Body) + } + if captures[0].PRNumber != 0 || captures[0].PRURL != "" { + t.Errorf("the push capture = pr %d url %q, want no PR: it was taken before one existed", + captures[0].PRNumber, captures[0].PRURL) + } + if captures[1].CapturedAfter != "open-pr" || captures[1].PRNumber != 7 { + t.Fatalf("the final capture = %q pr %d, want open-pr, 7", captures[1].CapturedAfter, captures[1].PRNumber) + } + if captures[1].PRURL != "https://gitea.example/acme/widget/pulls/7" { + t.Errorf("pr_url = %q, want the pull request the capture names", captures[1].PRURL) + } +} + +// TestHandleTaskChangesRefusesACaptureThatLostItsFileCap pins the cap from the +// reading side: `files` is bounded at task.MaxCapturedFiles by the producer, +// and a payload carrying more than that is one whose cap was lost. Rendering +// it would advertise the loss as a complete capture of every file. +func TestHandleTaskChangesRefusesACaptureThatLostItsFileCap(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + files := make([]any, 0, task.MaxCapturedFiles+1) + for i := range task.MaxCapturedFiles + 1 { + files = append(files, modifiedFile(fmt.Sprintf("file-%03d.go", i), 1, 0)) + } + insertCapture(t, srv, current.ID, 2, "commit", + captureData(files, map[string]any{"files": len(files), "additions": len(files), "deletions": 0})) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + body := decodeChanges(t, w.Body.Bytes()) + if !body.Found { + t.Error("found = false although a capture event was recorded for the attempt") + } + if len(body.Captures) != 0 { + t.Errorf("captures = %d entries, want none: a payload over the cap is one whose cap was lost", + len(body.Captures)) + } +} + +// TestHandleTaskChangesSkipsCapturesWithNoReadablePayload pins the degrade +// rule: a capture whose data is absent or malformed is skipped rather than +// failing the read, and the attempt still reports that a capture was recorded. +func TestHandleTaskChangesSkipsCapturesWithNoReadablePayload(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + + insertTaskEvent(t, srv, events.Event{ + Kind: events.KindChangesCaptured, TaskID: current.ID, Attempt: 2, Stage: "commit", + At: railBase, Data: map[string]any{"files": "not-an-array"}, + }) + insertTaskEvent(t, srv, events.Event{ + Kind: events.KindChangesCaptured, TaskID: current.ID, Attempt: 2, Stage: "commit", + At: railBase.Add(time.Second), + }) + insertCapture(t, srv, current.ID, 2, "commit", + captureData([]any{modifiedFile("internal/kept.go", 1, 0)}, + map[string]any{"files": 1, "additions": 1, "deletions": 0})) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + body := decodeChanges(t, w.Body.Bytes()) + if !body.Found { + t.Error("found = false although a capture event was recorded for the attempt") + } + if len(body.Captures) != 1 { + t.Fatalf("captures = %+v, want only the readable one", body.Captures) + } + if got := body.Captures[0].Files[0].Path; got != "internal/kept.go" { + t.Errorf("kept file = %q, want internal/kept.go", got) + } +} + +// TestHandleTaskChangesLinksTheCaptureRepositoryAndPullRequest reuses the task +// list's own forge projection: the page needs a repository link and, once a PR +// exists, a pull-request link, and it must get them from the same source the +// task list uses rather than a second one. +func TestHandleTaskChangesLinksTheCaptureRepositoryAndPullRequest(t *testing.T) { + srv := newTestServer(t) + srv.ConfigSource = func(_ context.Context) (ConfigView, bool, error) { + return multiIdentityView(), true, nil + } + current := twoAttemptTask(t, srv) + + for _, prNumber := range []int{0, 7} { + data := captureData([]any{modifiedFile("internal/x.go", 1, 0)}, + map[string]any{"files": 1, "additions": 1, "deletions": 0}) + data["pr_number"] = prNumber + insertCapture(t, srv, current.ID, 2, "commit", data) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/changes?attempt=2")) + if w.Code != http.StatusOK { + t.Fatalf("pr %d: status = %d, body %s", prNumber, w.Code, w.Body) + } + captures := decodeChanges(t, w.Body.Bytes()).Captures + capture := captures[len(captures)-1] + if capture.RepoURL != "https://gitea.example/acme/widget" { + t.Errorf("pr %d: repo_url = %q, want the task's gitea repository", prNumber, capture.RepoURL) + } + wantPR := "" + if prNumber > 0 { + wantPR = "https://gitea.example/acme/widget/pulls/7" + } + if capture.PRURL != wantPR { + t.Errorf("pr %d: pr_url = %q, want %q", prNumber, capture.PRURL, wantPR) + } + } +} diff --git a/internal/webui/api_tasks_debug.go b/internal/webui/api_tasks_debug.go new file mode 100644 index 000000000..30dc08b22 --- /dev/null +++ b/internal/webui/api_tasks_debug.go @@ -0,0 +1,45 @@ +package webui + +import ( + "net/http" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" + "github.com/samcharles93/archie-core/internal/events" +) + +// taskDebugView is GET /api/tasks/{id}/debug: the stored task record as it is, +// and every event recorded for the task. It is deliberately not a generic +// store-dump route -- the task list is capped at 100 rows, so a page that wanted +// to show an older task's raw provenance had no row to join against. Nothing +// here is projected, filtered or re-spelled: reading it is the point. +// +// Events are UNFILTERED. A debug view that silently hid the events of other +// attempts would be worse than useless; each event carries its own attempt, so +// the operator sees everything and can attribute it. Attempt reports only which +// attempt the page had selected. No log payload is included: the log tab already +// serves it, and embedding it would duplicate a large body for no new +// information. +type taskDebugView struct { + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Task task.Task `json:"task"` + Events []events.Event `json:"events"` +} + +// handleTaskDebug serves the task's raw record together with its whole event +// list, for whichever attempt the request names. +func (s *Server) handleTaskDebug(w http.ResponseWriter, r *http.Request) { + t, attempt, ok := s.taskAttemptTarget(w, r) + if !ok { + return + } + evs, err := s.Store.TaskEvents(r.Context(), t.ID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + if evs == nil { + evs = []events.Event{} + } + writeJSON(w, taskDebugView{TaskID: t.ID, Attempt: attempt, Task: *t, Events: evs}) +} diff --git a/internal/webui/api_tasks_debug_test.go b/internal/webui/api_tasks_debug_test.go new file mode 100644 index 000000000..cf448b4fa --- /dev/null +++ b/internal/webui/api_tasks_debug_test.go @@ -0,0 +1,98 @@ +package webui + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/domain/workflow" + "github.com/samcharles93/archie-core/internal/events" +) + +// TestHandleTaskDebugReturnsTheWholeRecordAndEveryEvent pins R7's read: the +// stored task record verbatim, and EVERY event of the task rather than only the +// selected attempt's -- each event carries its own attempt, so a filtered list +// would hide the very provenance the view exists to show. +func TestHandleTaskDebugReturnsTheWholeRecordAndEveryEvent(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + + insertTaskEvent(t, srv, events.Event{ + Kind: events.KindStageStart, TaskID: current.ID, Attempt: 1, Stage: "prepare", At: railBase, + }) + insertTaskEvent(t, srv, events.Event{ + Kind: events.KindAgentFinish, TaskID: current.ID, Attempt: 0, At: railBase.Add(time.Second), + Data: map[string]any{"status": "ok"}, + }) + insertTaskEvent(t, srv, events.Event{ + Kind: events.KindStageStart, TaskID: current.ID, Attempt: 2, Stage: "implement", + At: railBase.Add(2 * time.Second), + }) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/debug?attempt=1")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + raw := w.Body.String() + if strings.Contains(raw, `"entries"`) { + t.Errorf("body carries a log payload: %s", raw) + } + + var body struct { + TaskID int64 `json:"task_id"` + Attempt int `json:"attempt"` + Task workflow.Task `json:"task"` + Events []struct { + Kind string `json:"kind"` + Attempt int `json:"attempt"` + } `json:"events"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, w.Body) + } + if body.TaskID != current.ID || body.Attempt != 1 { + t.Errorf("envelope = task %d attempt %d, want task %d attempt 1 (the selected attempt)", + body.TaskID, body.Attempt, current.ID) + } + if body.Task.ID != current.ID || body.Task.Status != workflow.StatusRunning || body.Task.Attempt != 2 { + t.Errorf("task record = id %d status %q attempt %d, want the stored record (%d, running, 2)", + body.Task.ID, body.Task.Status, body.Task.Attempt, current.ID) + } + if len(body.Events) != 3 { + t.Fatalf("events = %d, want all 3 including the one recorded against a different attempt (%s)", + len(body.Events), w.Body) + } + wantAttempts := []int{1, 0, 2} + for i, want := range wantAttempts { + if body.Events[i].Attempt != want { + t.Errorf("event %d attempt = %d, want %d (order and attribution preserved)", i, body.Events[i].Attempt, want) + } + } + if !strings.Contains(raw, `"attempt":0`) { + t.Errorf("body = %s, want attempt carried on every event so an unattributed one stays distinguishable", raw) + } +} + +// TestHandleTaskDebugResolvesTheCurrentAttemptWithoutAParameter pins that the +// envelope reports the attempt the page selected, defaulting to the task's +// current attempt exactly as the log read does. +func TestHandleTaskDebugResolvesTheCurrentAttemptWithoutAParameter(t *testing.T) { + srv := newTestServer(t) + current := twoAttemptTask(t, srv) + + w := getTaskAPI(t, srv, taskRoute(current.ID, "/debug")) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + var body struct { + Attempt int `json:"attempt"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, w.Body) + } + if body.Attempt != current.Attempt { + t.Errorf("attempt = %d, want the task's current attempt %d", body.Attempt, current.Attempt) + } +} diff --git a/internal/webui/api_tasks_logs.go b/internal/webui/api_tasks_logs.go index 1e9c9a29d..260e73972 100644 --- a/internal/webui/api_tasks_logs.go +++ b/internal/webui/api_tasks_logs.go @@ -48,8 +48,12 @@ func (s *Server) handleTaskLogs(w http.ResponseWriter, r *http.Request) { page, err := reader.TaskLog(r.Context(), id, attempt, logging.Query{ Levels: splitCSV(q.Get("level")), Component: strings.TrimSpace(q.Get("component")), - Contains: strings.TrimSpace(q.Get("q")), - Limit: limit, + // Stage is a narrowing filter, not a scoping one: only entries a stage + // tagged carry the field, so the UI states that a stage filter matches + // the lines that record a stage and nothing else. + Stage: strings.TrimSpace(q.Get("stage")), + Contains: strings.TrimSpace(q.Get("q")), + Limit: limit, }) if err != nil { // A reader that exists but cannot read here is still a statement about @@ -134,32 +138,16 @@ func (s *Server) handleTaskLogDownload(w http.ResponseWriter, r *http.Request) { // the attempt to read: the "attempt" query parameter when the request names // one, otherwise the task's current Attempt. It answers the request itself and // reports false when either step fails. +// +// The resolution itself is taskAttemptTarget's, shared with the attempt rail, +// the changed-files read and the debug view, so every per-attempt read of one +// task selects the same attempt for the same request. func (s *Server) taskLogTarget(w http.ResponseWriter, r *http.Request) (id int64, attempt int, ok bool) { - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { - http.Error(w, "bad id", http.StatusBadRequest) + t, attempt, ok := s.taskAttemptTarget(w, r) + if !ok { return 0, 0, false } - task, err := s.Store.TaskByID(r.Context(), id) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return 0, 0, false - } - if task == nil { - http.Error(w, "task not found", http.StatusNotFound) - return 0, 0, false - } - - attempt = task.Attempt - if raw := strings.TrimSpace(r.URL.Query().Get("attempt")); raw != "" { - parsed, err := strconv.Atoi(raw) - if err != nil { - http.Error(w, "bad attempt", http.StatusBadRequest) - return 0, 0, false - } - attempt = parsed - } - return id, attempt, true + return t.ID, attempt, true } // taskLogLimit bounds a page the way handleLogs bounds the daemon-wide read: diff --git a/internal/webui/api_tasks_logs_test.go b/internal/webui/api_tasks_logs_test.go index a6ebf7879..a56469e03 100644 --- a/internal/webui/api_tasks_logs_test.go +++ b/internal/webui/api_tasks_logs_test.go @@ -96,6 +96,103 @@ func TestHandleTaskLogsHonoursExplicitAttempt(t *testing.T) { } } +// TestHandleTaskLogsFiltersByStageAndKeepsTheAttempt pins R5's read half: the +// stage parameter reaches the reader's query, narrows the attempt's entries to +// the lines that record that stage, and leaves both the attempt it resolved and +// the file's existence (found) untouched -- a filter that matches nothing is +// "nothing matching this filter", never "this deployment cannot read logs". +func TestHandleTaskLogsFiltersByStageAndKeepsTheAttempt(t *testing.T) { + srv := newTestServer(t) + ctx := t.Context() + baseDir := t.TempDir() + srv.TaskLogs = logging.NewTaskRegistry(baseDir, logging.NewFeed(10), logging.TaskSinkOptions{}) + + if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "task", "", "", ""); err != nil { + t.Fatal(err) + } + task, err := srv.Store.TaskByIssue(ctx, "acme", "widget", 1) + if err != nil { + t.Fatal(err) + } + + // Written to attempt 1's file: an earlier attempt the task's current + // Attempt field does not point at, so the attempt must be requested. + sink, err := logging.NewTaskSink(baseDir, task.ID, 1, logging.TaskSinkOptions{}) + if err != nil { + t.Fatal(err) + } + sink.Logger().Warn("committing the worktree", "stage", "commit") + sink.Logger().Warn("agent produced a diff", "component", "agent") + if err := sink.Close(); err != nil { + t.Fatal(err) + } + + tests := []struct { + name string + query map[string]string + wantCount int + wantFound bool + }{ + { + name: "no stage filter", + query: map[string]string{"attempt": "1"}, + wantCount: 2, + wantFound: true, + }, + { + name: "the stage this attempt recorded", + query: map[string]string{"attempt": "1", "stage": "commit"}, + wantCount: 1, + wantFound: true, + }, + { + name: "a stage no entry records", + query: map[string]string{"attempt": "1", "stage": "implement"}, + wantCount: 0, + wantFound: true, + }, + { + name: "a stage filter on an attempt with no log at all", + query: map[string]string{"attempt": "2", "stage": "commit"}, + wantCount: 0, + wantFound: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := getTaskLogs(t, srv, task.ID, tt.query) + if w.Code != http.StatusOK { + t.Fatalf("status = %d, body %s", w.Code, w.Body) + } + var body struct { + Entries []logging.Entry `json:"entries"` + Attempt int `json:"attempt"` + Found bool `json:"found"` + Disabled bool `json:"disabled"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode response: %v (%s)", err, w.Body) + } + wantAttempt := 1 + if tt.query["attempt"] == "2" { + wantAttempt = 2 + } + if body.Attempt != wantAttempt { + t.Errorf("attempt = %d, want the requested attempt %d", body.Attempt, wantAttempt) + } + if len(body.Entries) != tt.wantCount { + t.Errorf("entries = %d, want %d (%s)", len(body.Entries), tt.wantCount, w.Body) + } + if body.Found != tt.wantFound { + t.Errorf("found = %v, want %v: a filter that matches nothing is not a missing log", body.Found, tt.wantFound) + } + if body.Disabled { + t.Error("disabled = true for a process that has a task-log reader") + } + }) + } +} + func TestHandleTaskLogsBadID(t *testing.T) { srv := newTestServer(t) req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/not-a-number/logs", nil) diff --git a/internal/webui/server.go b/internal/webui/server.go index cd5cc2193..00f0f3606 100644 --- a/internal/webui/server.go +++ b/internal/webui/server.go @@ -243,6 +243,9 @@ func (s *Server) registerTaskRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/task-meta", s.handleTaskMeta) mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction) mux.HandleFunc("GET /api/tasks/{id}", s.handleTask) + mux.HandleFunc("GET /api/tasks/{id}/attempts", s.handleTaskAttempts) + mux.HandleFunc("GET /api/tasks/{id}/changes", s.handleTaskChanges) + mux.HandleFunc("GET /api/tasks/{id}/debug", s.handleTaskDebug) mux.HandleFunc("GET /api/tasks/{id}/logs", s.handleTaskLogs) mux.HandleFunc("GET /api/tasks/{id}/logs/download", s.handleTaskLogDownload) } diff --git a/internal/worktree/worktree.go b/internal/worktree/worktree.go index b511b2e9c..ea2fdde38 100644 --- a/internal/worktree/worktree.go +++ b/internal/worktree/worktree.go @@ -36,8 +36,11 @@ import ( "github.com/go-git/go-git/v6/plumbing" gitclient "github.com/go-git/go-git/v6/plumbing/client" "github.com/go-git/go-git/v6/plumbing/filemode" + fdiff "github.com/go-git/go-git/v6/plumbing/format/diff" "github.com/go-git/go-git/v6/plumbing/object" githttp "github.com/go-git/go-git/v6/plumbing/transport/http" + + "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) // preparedSentinel marks a worktree as fully cloned, branched and @@ -598,38 +601,49 @@ func remoteUsesHTTP(r *git.Repository) bool { // Diffing against the remote tip instead would attribute every commit // landed on base since the branch started to this task. func (m *Manager) patch(ctx context.Context, dir, base string) (*object.Patch, error) { + p, _, err := m.patchFromMergeBase(ctx, dir, base) + return p, err +} + +// patchFromMergeBase is patch plus the commit the diff was actually taken +// against. That commit is the merge base of base and HEAD, which is NOT base's +// tip once anyone has landed on the base branch since this branch diverged. +// A capture records it beside the file list it measured, so the two describe +// one change set: re-resolving origin/ on the side would name the new +// tip instead. +func (m *Manager) patchFromMergeBase(ctx context.Context, dir, base string) (*object.Patch, plumbing.Hash, error) { r, err := git.PlainOpen(dir) if err != nil { - return nil, fmt.Errorf("open worktree: %w", err) + return nil, plumbing.ZeroHash, fmt.Errorf("open worktree: %w", err) } baseHash, err := resolveBase(r, base) if err != nil { - return nil, err + return nil, plumbing.ZeroHash, err } head, err := r.Head() if err != nil { - return nil, fmt.Errorf("resolve HEAD: %w", err) + return nil, plumbing.ZeroHash, fmt.Errorf("resolve HEAD: %w", err) } baseCommit, err := r.CommitObject(baseHash) if err != nil { - return nil, fmt.Errorf("load base commit: %w", err) + return nil, plumbing.ZeroHash, fmt.Errorf("load base commit: %w", err) } headCommit, err := r.CommitObject(head.Hash()) if err != nil { - return nil, fmt.Errorf("load head commit: %w", err) + return nil, plumbing.ZeroHash, fmt.Errorf("load head commit: %w", err) } bases, err := baseCommit.MergeBase(headCommit) if err != nil { - return nil, fmt.Errorf("find merge base for %s...HEAD: %w", remoteBase(base), err) + return nil, plumbing.ZeroHash, fmt.Errorf("find merge base for %s...HEAD: %w", remoteBase(base), err) } if len(bases) == 0 { - return nil, fmt.Errorf("find merge base for %s...HEAD: no common ancestor", remoteBase(base)) + return nil, plumbing.ZeroHash, fmt.Errorf("find merge base for %s...HEAD: no common ancestor", remoteBase(base)) } p, err := bases[0].PatchContext(ctx, headCommit) if err != nil { - return nil, fmt.Errorf("diff %s...HEAD: %w", remoteBase(base), err) + return nil, plumbing.ZeroHash, fmt.Errorf("diff %s...HEAD: %w", remoteBase(base), err) } - return p, nil + return p, bases[0].Hash, nil } // ChangedLines reports lines added+deleted vs the base branch -- the @@ -687,6 +701,104 @@ func (m *Manager) ChangedFiles(ctx context.Context, dir, base string) ([]string, return files, nil } +// fileTypeMask is the file-type subset of a tree entry's mode: the bits that +// distinguish a regular file from a symlink or a gitlink. A mode change inside +// one type (the executable bit) is a modification, exactly as git reports it; +// a change across types is a typechange. +const fileTypeMask = 0o170000 + +// ChangedFileStats reports what HEAD changed against base, as the per-file +// status and line counts one attempt's capture records. It reuses patch's +// three-dot semantics: diffing against the remote tip instead would attribute +// every commit landed on base since the branch started to this task. +// +// ChangedLines, Diff and ChangedFiles stay the shape stages call; this is the +// same measurement with the detail a capture needs, so there is still exactly +// one diff path -- and it reports the base that path diffed against. +func (m *Manager) ChangedFileStats(ctx context.Context, dir, base string) (task.ChangeStats, error) { + // The diffed base is the merge base patchFromMergeBase diffed against, not + // base's tip: the recorded pair has to describe the file list beside it. + p, diffedBase, err := m.patchFromMergeBase(ctx, dir, base) + if err != nil { + return task.ChangeStats{}, err + } + r, err := git.PlainOpen(dir) + if err != nil { + return task.ChangeStats{}, fmt.Errorf("open worktree: %w", err) + } + head, err := r.Head() + if err != nil { + return task.ChangeStats{}, fmt.Errorf("resolve HEAD: %w", err) + } + + patches := p.FilePatches() + // Paths come from FilePatches and counts from Stats, joined by position, + // because Stats() carries one entry per patch that produced textual chunks + // and SKIPS the rest (binary files, and any change whose content is + // identical). Reading the two lists off the same index would shift every + // later file's counts onto the wrong path as soon as one binary file is in + // the change. Totals come from Stats so they agree with ChangedLines, which + // sums the same list. + stats := p.Stats() + next := 0 + files := make([]task.FileChange, 0, len(patches)) + totals := task.ChangeTotals{Files: len(patches)} + for _, fp := range patches { + change := fileChange(fp) + if change.Binary || next >= len(stats) { + files = append(files, change) + continue + } + change.Additions = stats[next].Addition + change.Deletions = stats[next].Deletion + totals.Additions += stats[next].Addition + totals.Deletions += stats[next].Deletion + next++ + files = append(files, change) + } + + return task.ChangeStats{ + BaseSHA: diffedBase.String(), + HeadSHA: head.Hash().String(), + Files: files, + Totals: totals, + }, nil +} + +// fileChange classifies one file patch: whether the file was added, deleted, +// renamed, retyped or modified, and whether it produced any textual hunks. +func fileChange(fp fdiff.FilePatch) task.FileChange { + from, to := fp.Files() + change := task.FileChange{ + // No textual hunks. This is what go-git can tell us, not a claim about + // the file on disk: a binary file reports it, and so does a rename whose + // content did not change. + Binary: len(fp.Chunks()) == 0, + } + // At least one side is always present: a change with both entries empty is + // rejected upstream (object.Change.Action), so there is no third state to + // report here. + switch { + case from == nil: + change.Path = to.Path() + change.Status = task.ChangeAdded + case to == nil: + change.Path = from.Path() + change.Status = task.ChangeDeleted + case from.Path() != to.Path(): + change.Path = to.Path() + change.OldPath = from.Path() + change.Status = task.ChangeRenamed + case from.Mode()&fileTypeMask != to.Mode()&fileTypeMask: + change.Path = to.Path() + change.Status = task.ChangeTypeChanged + default: + change.Path = to.Path() + change.Status = task.ChangeModified + } + return change +} + // Snapshot exports HEAD's tracked files into a fresh, empty destDir with no // .git directory: file contents only, no commit history, branch name, or // reflog. Used to build the adversarial reviewer's isolated workspace diff --git a/internal/worktree/worktree_test.go b/internal/worktree/worktree_test.go index 5c9835e76..94c48ebc6 100644 --- a/internal/worktree/worktree_test.go +++ b/internal/worktree/worktree_test.go @@ -15,6 +15,7 @@ import ( "github.com/go-git/go-git/v6/plumbing/object" "github.com/samcharles93/archie-core/internal/container" + "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) const testBase = "main" @@ -1127,3 +1128,334 @@ func TestTaskBriefIsNeverCommitted(t *testing.T) { t.Errorf("brief missing after commit: %v", err) } } + +func TestOperationsOnNonRepositoryDiffstat(t *testing.T) { + ctx := context.Background() + m := &Manager{WorkDir: t.TempDir()} + if _, err := m.ChangedFileStats(ctx, t.TempDir(), testBase); err == nil { + t.Error("ChangedFileStats() error = nil, want a failure") + } +} + +// diffstatSeed is one file written into the fixture's first commit. +type diffstatSeed struct { + path string + content string +} + +// newDiffstatRepo builds a repository whose only commit is reachable as both +// the branch tip and refs/remotes/origin/. That remote-tracking ref is +// what resolveBase prefers, so the three-dot base is the same commit whether +// or not the fixture ever had a remote -- and a diffstat fixture needs a base +// commit that already contains the paths a change modifies, renames or +// deletes. +func newDiffstatRepo(t *testing.T, seeds []diffstatSeed) (string, *git.Repository, plumbing.Hash) { + t.Helper() + dir := t.TempDir() + r, err := git.PlainInit(dir, false, git.WithDefaultBranch(plumbing.NewBranchReferenceName(testBase))) + if err != nil { + t.Fatalf("init fixture repo: %v", err) + } + for _, seed := range seeds { + writeSeedCommit(t, r, dir, seed.path, seed.content, "seed "+seed.path) + } + head, err := r.Head() + if err != nil { + t.Fatalf("resolve fixture HEAD: %v", err) + } + if err := r.Storer.SetReference(plumbing.NewHashReference( + plumbing.NewRemoteReferenceName(git.DefaultRemoteName, testBase), head.Hash(), + )); err != nil { + t.Fatalf("set remote-tracking base ref: %v", err) + } + return dir, r, head.Hash() +} + +// commitAll commits the fixture repo's working tree, failing the test on a +// commit error. +func commitAll(t *testing.T, r *git.Repository, dir, message string) { + t.Helper() + disableSigning(t, r) + wt, err := r.Worktree() + if err != nil { + t.Fatalf("worktree: %v", err) + } + if _, err := wt.Add("."); err != nil { + t.Fatalf("add all: %v", err) + } + sig := testSignature() + if _, err := wt.Commit(message, &git.CommitOptions{Author: sig, Committer: sig}); err != nil { + t.Fatalf("commit: %v", err) + } +} + +// TestChangedFileStatsReportsWhatOneAttemptChanged is the producer-side half +// of the changed-file capture: status and per-file line counts are read off +// the SAME three-dot patch the diff cap reads, where the merge base is +// resolved, so a capture can never disagree with the size gate about what +// changed. +func TestChangedFileStatsReportsWhatOneAttemptChanged(t *testing.T) { + binaryContent := []byte{0x00, 0x01, 0x02, 0xff, 0xfe} + + tests := []struct { + name string + seeds []diffstatSeed + mutate func(t *testing.T, dir string, r *git.Repository) + wantFiles []task.FileChange + wantTotal task.ChangeTotals + }{ + { + name: "added", + seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("one\ntwo\n"), 0o600); err != nil { + t.Fatal(err) + } + }, + wantFiles: []task.FileChange{ + {Path: "new.txt", Status: task.ChangeAdded, Additions: 2}, + }, + wantTotal: task.ChangeTotals{Files: 1, Additions: 2}, + }, + { + name: "modified", + seeds: []diffstatSeed{{path: "a.txt", content: "one\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("one\ntwo\n"), 0o600); err != nil { + t.Fatal(err) + } + }, + wantFiles: []task.FileChange{ + {Path: "a.txt", Status: task.ChangeModified, Additions: 1}, + }, + wantTotal: task.ChangeTotals{Files: 1, Additions: 1}, + }, + { + name: "deleted", + seeds: []diffstatSeed{{path: "a.txt", content: "one\ntwo\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + if err := os.Remove(filepath.Join(dir, "a.txt")); err != nil { + t.Fatal(err) + } + }, + wantFiles: []task.FileChange{ + {Path: "a.txt", Status: task.ChangeDeleted, Deletions: 2}, + }, + wantTotal: task.ChangeTotals{Files: 1, Deletions: 2}, + }, + { + name: "renamed", + seeds: []diffstatSeed{{path: "old.txt", content: "same content\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + if err := os.Remove(filepath.Join(dir, "old.txt")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("same content\n"), 0o600); err != nil { + t.Fatal(err) + } + }, + // go-git reports the rename with its old path preserved and no line + // changes, because the content is identical: the line counts describe + // the content diff, not the path change. + wantFiles: []task.FileChange{ + {Path: "new.txt", OldPath: "old.txt", Status: task.ChangeRenamed}, + }, + wantTotal: task.ChangeTotals{Files: 1}, + }, + { + name: "binary alongside a text file keeps both paths with their own counts", + seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + // The binary file sorts before the text file, and go-git's + // Patch.Stats skips it entirely (no textual chunks). A capture + // that read paths and counts off one shared index would hand the + // text file's counts to the binary file here. + if err := os.WriteFile(filepath.Join(dir, "aaa-image.bin"), binaryContent, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "zzz-text.txt"), []byte("one\ntwo\n"), 0o600); err != nil { + t.Fatal(err) + } + }, + wantFiles: []task.FileChange{ + {Path: "aaa-image.bin", Status: task.ChangeAdded, Binary: true}, + {Path: "zzz-text.txt", Status: task.ChangeAdded, Additions: 2}, + }, + wantTotal: task.ChangeTotals{Files: 2, Additions: 2}, + }, + { + name: "a regular file replaced by a symlink is a typechange", + seeds: []diffstatSeed{{path: "link.txt", content: "target\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + if err := os.Remove(filepath.Join(dir, "link.txt")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("target", filepath.Join(dir, "link.txt")); err != nil { + t.Fatal(err) + } + }, + // git reports this as a typechange: the entry changed from a regular + // file to a symlink. The line counts are the content diff (a symlink's + // blob holds the target path, without the trailing newline). + wantFiles: []task.FileChange{ + {Path: "link.txt", Status: task.ChangeTypeChanged, Additions: 1, Deletions: 1}, + }, + wantTotal: task.ChangeTotals{Files: 1, Additions: 1, Deletions: 1}, + }, + { + name: "a rename alongside a binary file keeps every count with its own path", + seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}, {path: "old.txt", content: "same content\n"}}, + mutate: func(t *testing.T, dir string, _ *git.Repository) { + t.Helper() + if err := os.Remove(filepath.Join(dir, "old.txt")); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "new.txt"), []byte("same content\n"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "aaa-image.bin"), binaryContent, 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "zzz-text.txt"), []byte("one\ntwo\n"), 0o600); err != nil { + t.Fatal(err) + } + }, + wantFiles: []task.FileChange{ + {Path: "aaa-image.bin", Status: task.ChangeAdded, Binary: true}, + {Path: "new.txt", OldPath: "old.txt", Status: task.ChangeRenamed}, + {Path: "zzz-text.txt", Status: task.ChangeAdded, Additions: 2}, + }, + wantTotal: task.ChangeTotals{Files: 3, Additions: 2}, + }, + { + name: "nothing changed", + seeds: []diffstatSeed{{path: "README.md", content: "seed\n"}}, + mutate: func(*testing.T, string, *git.Repository) {}, + // Empty, not nil: the persisted payload carries a list, and a null + // there would read as a missing measurement rather than a measured + // zero. + wantFiles: []task.FileChange{}, + wantTotal: task.ChangeTotals{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + dir, r, baseHash := newDiffstatRepo(t, tt.seeds) + tt.mutate(t, dir, r) + var head plumbing.Hash + if tt.name != "nothing changed" { + commitAll(t, r, dir, "change") + got, err := r.Head() + if err != nil { + t.Fatal(err) + } + head = got.Hash() + } else { + head = baseHash + } + + m := &Manager{WorkDir: t.TempDir()} + stats, err := m.ChangedFileStats(t.Context(), dir, testBase) + if err != nil { + t.Fatalf("ChangedFileStats() error = %v", err) + } + if stats.BaseSHA != baseHash.String() { + t.Errorf("BaseSHA = %q, want the resolved base %q", stats.BaseSHA, baseHash) + } + if stats.HeadSHA != head.String() { + t.Errorf("HeadSHA = %q, want HEAD %q", stats.HeadSHA, head) + } + if len(stats.Files) != len(tt.wantFiles) { + t.Fatalf("Files = %+v, want %d entries %+v", stats.Files, len(tt.wantFiles), tt.wantFiles) + } + for i, want := range tt.wantFiles { + if got := stats.Files[i]; got != want { + t.Errorf("Files[%d] = %+v, want %+v", i, got, want) + } + } + if stats.Totals != tt.wantTotal { + t.Errorf("Totals = %+v, want %+v", stats.Totals, tt.wantTotal) + } + }) + } +} + +// TestChangedFileStatsRecordsTheDiffedBaseNotTheAdvancedTip pins the identity +// of the recorded base to the commit the file list was actually diffed against +// -- the merge base -- and not to base's tip, which moves whenever anyone +// lands on the base branch mid-run. Naming the tip would pair a file list with +// a commit it was never compared to. +func TestChangedFileStatsRecordsTheDiffedBaseNotTheAdvancedTip(t *testing.T) { + ctx := context.Background() + host := newLocalRemote(t, "acme", "todo") + m := newManager(t, host) + + dir, _, err := m.Prepare(ctx, "acme", "todo", testBase, 8, "feat: mine", "", "feature") + if err != nil { + t.Fatalf("Prepare() error = %v", err) + } + r, err := git.PlainOpen(dir) + if err != nil { + t.Fatal(err) + } + diverged, err := r.ResolveRevision(plumbing.Revision(remoteBase(testBase))) + if err != nil { + t.Fatalf("resolve the base this branch diverged from: %v", err) + } + + if err := os.WriteFile(filepath.Join(dir, "mine.txt"), []byte("mine\n"), 0o600); err != nil { + t.Fatal(err) + } + if _, err := m.CommitAll(ctx, dir, "feat: mine"); err != nil { + t.Fatalf("CommitAll() error = %v", err) + } + + // Another author lands on the base branch and this clone fetches it, so + // origin/ now names a commit this branch never contained. + seed := filepath.Join(t.TempDir(), "other") + sr, err := git.PlainClone(seed, &git.CloneOptions{URL: filepath.Join(host, "acme", "todo.git")}) + if err != nil { + t.Fatalf("clone for second author: %v", err) + } + writeSeedCommit(t, sr, seed, "theirs.txt", "theirs\n", "chore: theirs") + ref := plumbing.NewBranchReferenceName(testBase) + if err := sr.Push(&git.PushOptions{ + RemoteName: git.DefaultRemoteName, + RefSpecs: []gitconfig.RefSpec{gitconfig.RefSpec(ref + ":" + ref)}, + }); err != nil { + t.Fatalf("second author push: %v", err) + } + if err := r.Fetch(&git.FetchOptions{RemoteName: git.DefaultRemoteName}); err != nil { + t.Fatalf("fetch: %v", err) + } + tip, err := r.ResolveRevision(plumbing.Revision(remoteBase(testBase))) + if err != nil { + t.Fatalf("resolve the advanced base tip: %v", err) + } + if tip == diverged { + t.Fatal("the base branch did not advance; this test would assert nothing") + } + + stats, err := m.ChangedFileStats(ctx, dir, testBase) + if err != nil { + t.Fatalf("ChangedFileStats() error = %v", err) + } + if stats.BaseSHA != diverged.String() { + t.Errorf("BaseSHA = %q, want the diffed merge base %q (the base tip is %q)", + stats.BaseSHA, diverged, tip) + } + // The same rule from the other side: a file list measured from the merge + // base cannot name a commit that landed on the base branch afterwards. + for _, f := range stats.Files { + if f.Path == "theirs.txt" { + t.Errorf("Files = %+v, includes another author's file: the diff is not merge-base relative", stats.Files) + } + } +} diff --git a/proto/state/v1/state.proto b/proto/state/v1/state.proto index 67dcdcb77..6f89a7855 100644 --- a/proto/state/v1/state.proto +++ b/proto/state/v1/state.proto @@ -162,6 +162,11 @@ message Event { int64 issue = 6; string workflow = 7; string stage = 8; + // attempt is the run this event belongs to. Zero means UNATTRIBUTED, not a + // first attempt: rows written before the field existed, and the deliberately + // task-agnostic producers, all carry zero. A reader must report those as + // unattributable rather than presenting them as one run. + int64 attempt = 11; string detail = 9; string data_json = 10; } @@ -412,6 +417,10 @@ message ReadTaskLogRequest { string contains = 6; google.protobuf.Timestamp since = 7; google.protobuf.Timestamp until = 8; + // stage filters on an entry's own "stage" field. Only entries a stage + // tagged carry one -- agent and tool output is logged without a stage, so a + // stage filter narrows the file rather than covering it. Empty means any. + string stage = 9; } // found=false is not an error: the task has no log file for that attempt. // That is a different condition from a process that cannot read logs at all diff --git a/ui/dist/assets/index.css b/ui/dist/assets/index.css index a60ad6077..53d7ee75c 100644 --- a/ui/dist/assets/index.css +++ b/ui/dist/assets/index.css @@ -1 +1 @@ -:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}.chat-drawer{inset:var(--sp-4);pointer-events:none;z-index:40;justify-content:flex-end;align-items:stretch;display:flex;position:fixed}.chat-drawer-panel{pointer-events:auto;z-index:1;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:min(430px,100%);height:100%;box-shadow:var(--shadow-md);opacity:0;transition:opacity var(--transition), transform var(--transition);grid-template-rows:auto minmax(0,1fr);display:grid;position:relative;overflow:hidden;transform:translate(1.2rem)}.chat-drawer:not(.is-open) .chat-drawer-panel{pointer-events:none}.chat-drawer.is-open .chat-drawer-panel{opacity:1;transform:none}.chat-drawer-head{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--border);display:flex}.chat-scrim{background:color-mix(in srgb, var(--bg) 40%, transparent);opacity:0;pointer-events:none;transition:opacity var(--transition);position:fixed;inset:0}.chat-drawer.is-open .chat-scrim{opacity:1;pointer-events:auto}body.chat-open{overflow:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top>div{display:flex}.dash-top>div>.card{flex:1}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:220px;font-size:var(--text-xs);white-space:normal}.task-action-error-refused{color:var(--warn)}.task-action-error-broken{color:var(--danger)}.task-action-error-session{color:var(--warn);align-items:center;gap:var(--sp-1);flex-wrap:wrap;display:inline-flex}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}.task-logs-section{margin-top:var(--sp-4)}.task-logs-section .task-decision-title{justify-content:space-between;align-items:center;display:flex}.task-log-list{max-height:40vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);margin-top:var(--sp-2);overflow-y:auto}.task-log-loading,.task-log-error{padding:var(--sp-3) 0;color:var(--fg-muted)}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.wf-form{gap:var(--sp-2);flex-direction:column;display:flex}.wf-form input,.wf-form select,.wf-form textarea{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2);width:100%}.wf-form textarea{resize:vertical}.wf-form input:focus,.wf-form select:focus,.wf-form textarea:focus{outline:2px solid var(--accent);outline-offset:-1px}.wf-form input::placeholder,.wf-form textarea::placeholder{color:var(--fg-subtle)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.curator-card{gap:var(--sp-2);flex-direction:column;display:flex}.curator-health-message{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.curator-meta{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.curator-actions{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.curator-action{border-top:1px solid var(--border);padding-top:var(--sp-2)}.curator-action-head{justify-content:space-between;gap:var(--sp-2);font-size:var(--text-sm);display:flex}.curator-action-type{color:var(--fg);font-weight:600}.curator-action-time{color:var(--fg-subtle);font-size:var(--text-xs)}.curator-action-detail{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.curator-action-reason{color:var(--fg-subtle);font-size:var(--text-xs);margin:var(--sp-1) 0 0}.cfg-page{max-width:70rem;margin:0 auto}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-5) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.kv-list{column-gap:var(--sp-4);grid-template-columns:max-content minmax(0,1fr) auto;row-gap:0;display:grid}.kv{grid-template-columns:subgrid;align-items:center;row-gap:var(--sp-1);padding:var(--sp-2) 0;border-radius:var(--radius-sm);grid-column:1/-1;display:grid}@supports not (grid-template-columns:subgrid){.kv-list{flex-direction:column;width:auto;display:flex}.kv{column-gap:var(--sp-4);grid-template-columns:minmax(8rem,16rem) minmax(0,1fr) auto}}.kv+.kv{border-top:1px solid var(--border)}.kv:hover{background:var(--surface-hover)}.kv-label{font-size:var(--text-sm);color:var(--fg-muted)}.kv-value{min-width:0;font-size:var(--text-sm);color:var(--fg);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.kv-value.is-empty{color:var(--fg-subtle)}.kv-actions{align-items:center;gap:var(--sp-2);justify-self:end;display:flex}.kv-note{font-size:var(--text-xs);color:var(--fg-subtle);grid-column:2/-1}.kv-note.is-error{color:var(--danger)}.kv.is-locked .kv-value{color:var(--fg-muted)}.kv-btn{font:inherit;font-size:var(--text-xs);color:var(--fg-subtle);border:1px solid var(--border);border-radius:var(--radius-sm);padding:2px var(--sp-2);cursor:pointer;background:0 0;flex:none;transition:color .12s,border-color .12s,background .12s}.kv:hover .kv-btn,.kv:focus-within .kv-btn{color:var(--fg-muted);border-color:var(--border-strong)}.kv-btn:hover{color:var(--fg);border-color:var(--accent);background:var(--accent-soft)}.kv-btn:focus-visible{outline:2px solid var(--accent);outline-offset:1px}.kv-flag{font-size:var(--text-xs);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-pill);padding:1px var(--sp-2);flex:none}.kv-input{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--bg,var(--surface));border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);width:100%;min-width:0}.kv-input:focus{outline:2px solid var(--accent);outline-offset:-1px}.kv-save,.kv-cancel{font:inherit;font-size:var(--text-xs);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);cursor:pointer;flex:none}.kv-save{background:var(--accent);border:1px solid var(--accent);color:var(--accent-fg);font-weight:500}.kv-save:disabled{opacity:.6;cursor:default}.kv-cancel{border:1px solid var(--border-strong);color:var(--fg-muted);background:0 0}.kv-cancel:hover{color:var(--fg)}.cfg-notice{border-left:3px solid var(--warn)}.cfg-notice p{font-size:var(--text-sm);color:var(--warn);margin:0}@media (width<=700px){.kv-list{flex-direction:column;width:auto;display:flex}.kv{column-gap:var(--sp-4);grid-template-columns:minmax(0,1fr) auto}.kv-label{grid-column:1}.kv-actions{grid-area:1/2}.kv-value,.kv-note{white-space:normal;overflow-wrap:anywhere;grid-column:1/-1}}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.capture-row{cursor:pointer}.capture-row:hover{background:var(--bg-raised)}.capture-row:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}.capture-detail-row td{padding:var(--sp-3) var(--sp-3) var(--sp-4);border-bottom:1px solid var(--border)}.capture-detail{gap:var(--sp-4);grid-template-columns:1fr 1fr;display:grid}.capture-detail-section{min-width:0}.capture-detail-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);margin-bottom:var(--sp-2)}.capture-payload{background:var(--bg-raised);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-3);font-family:var(--font-mono);font-size:var(--text-xs);white-space:pre-wrap;word-break:break-word;max-height:24rem;overflow:auto}.capture-empty{color:var(--fg-muted);font-size:var(--text-sm)}@media (width<=640px){.capture-detail{grid-template-columns:1fr}}.mapping-form,.mapping-fields,.mapping-payload{margin-bottom:var(--sp-4);padding:var(--sp-4)}.mapping-form-row{gap:var(--sp-1);margin-bottom:var(--sp-3);font-size:var(--text-sm);color:var(--fg-subtle);flex-direction:column;display:flex}.mapping-input,.mapping-select{padding:var(--sp-2);border:1px solid var(--border-strong);border-radius:var(--radius-sm);background:var(--bg-raised);color:var(--fg);font:inherit}.mapping-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);margin-bottom:var(--sp-2)}.mapping-fields-table .mapping-input{width:100%}.mapping-empty-fields{color:var(--fg-muted);font-size:var(--text-sm);padding:var(--sp-3) 0}.mapping-error{color:var(--danger,#e5484d);font-size:var(--text-sm);margin-bottom:var(--sp-3)}.mapping-tree-list{padding-left:var(--sp-4);font-family:var(--font-mono);font-size:var(--text-xs);margin:0;list-style:none}.mapping-tree-item{padding:2px 0}.mapping-tree-key,.mapping-tree-value{cursor:pointer;border-radius:var(--radius-sm);padding:0 4px}.mapping-tree-key:hover,.mapping-tree-value:hover{background:var(--bg-raised);outline:1px solid var(--accent)}.mapping-tree-value{color:var(--fg-subtle);margin-left:var(--sp-1)}.binding-form{margin-bottom:var(--sp-4);padding:var(--sp-4)}.binding-form-row{gap:var(--sp-1);margin-bottom:var(--sp-3);font-size:var(--text-sm);color:var(--fg-subtle);flex-direction:column;display:flex}.binding-input,.binding-select{padding:var(--sp-2);border:1px solid var(--border-strong);border-radius:var(--radius-sm);background:var(--bg-raised);color:var(--fg);font:inherit}.binding-error{color:var(--danger,#e5484d);font-size:var(--text-sm);margin-bottom:var(--sp-3)}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-drawer .chat-page{height:100%}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-media-img{border:1px solid var(--border);object-fit:contain;background:var(--surface);cursor:pointer;border-radius:.5rem;max-width:100%;max-height:24rem;margin:.4rem 0;display:block}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-tools{gap:.2rem;margin-bottom:.5rem;font-size:.78rem;display:grid}.chat-tools:empty{display:none}.chat-tool{color:var(--fg-muted);overflow-wrap:anywhere;align-items:baseline;gap:.4rem;display:flex}.chat-tool-name{color:var(--fg);font-weight:600}.chat-tool.failed .chat-tool-summary{color:var(--danger)}.chat-nav-chip{border:1px solid color-mix(in srgb, var(--accent) 45%, var(--border));background:var(--accent-soft);color:var(--accent);cursor:pointer;transition:background var(--transition), border-color var(--transition), color var(--transition);border-radius:999px;align-items:center;gap:.4rem;padding:.4rem .7rem;font-size:.82rem;font-weight:600;display:inline-flex}.chat-nav-chip:hover{border-color:var(--accent);background:color-mix(in srgb, var(--accent) 16%, var(--surface))}.chat-nav-chip:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.chat-nav-chip-icon{font-size:.8rem;line-height:1}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} +:root{--font-sans:ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;--font-mono:ui-monospace, "SF Mono", "JetBrains Mono", Menlo, Consolas, monospace;--text-xs:.6875rem;--text-sm:.8125rem;--text-base:.875rem;--text-lg:1.0625rem;--text-xl:1.375rem;--text-2xl:1.875rem;--text-3xl:2.5rem;--sp-1:.25rem;--sp-2:.5rem;--sp-3:.75rem;--sp-4:1rem;--sp-5:1.5rem;--sp-6:2rem;--sp-7:3rem;--radius-sm:6px;--radius-md:10px;--radius-lg:14px;--radius-xl:20px;--radius-pill:999px;--transition:.14s cubic-bezier(.4, 0, .2, 1)}[data-theme=dark]{--bg:#0d1014;--bg-raised:#141920;--surface:#171d25;--surface-hover:#1d242e;--border:#232b36;--border-strong:#303a48;--fg:#e8edf4;--fg-muted:#8b97a8;--fg-subtle:#5d6878;--accent:#4c8dff;--accent-fg:#fff;--accent-soft:#4c8dff24;--ok:#3fbf7f;--ok-soft:#3fbf7f24;--warn:#e8a33d;--warn-soft:#e8a33d24;--danger:#f0616d;--danger-soft:#f0616d24;--info:#4c8dff;--info-soft:#4c8dff24;--idle:#6b7688;--idle-soft:#6b768824;--accent-2:#7b5cff;--bg-blur:#1419208c;--surface-glass:#171d259e;--surface-glass-strong:#141920c7;--workspace:#11151b8c;--hairline:#ffffff0f;--wash-a:#4c8dff1a;--wash-b:#7b5cff1f;--wash-c:#3fbf7f0f;--shadow-workspace:0 24px 70px #00000080;--shadow-sm:0 1px 2px #0006;--shadow-md:0 8px 28px #0000006b}[data-theme=light]{--bg:#f6f8fb;--bg-raised:#fff;--surface:#fff;--surface-hover:#f1f4f9;--border:#e2e8f0;--border-strong:#cbd5e1;--fg:#16202e;--fg-muted:#5a6779;--fg-subtle:#8c99ab;--accent:#2563eb;--accent-fg:#fff;--accent-soft:#2563eb1a;--ok:#10935c;--ok-soft:#10935c1f;--warn:#b87514;--warn-soft:#b875141f;--danger:#d4344a;--danger-soft:#d4344a1f;--info:#2563eb;--info-soft:#2563eb1a;--idle:#64748b;--idle-soft:#64748b1f;--accent-2:#7c3aed;--bg-blur:#fff9;--surface-glass:#ffffffb8;--surface-glass-strong:#ffffffe0;--workspace:#ffffff8c;--hairline:#0f172a0f;--wash-a:#2563eb1a;--wash-b:#7c3aed1f;--wash-c:#10935c12;--shadow-workspace:0 24px 70px #0f172a24;--shadow-sm:0 1px 2px #0f172a0f;--shadow-md:0 8px 28px #0f172a1a}*,:before,:after{box-sizing:border-box}html,body{height:100%;margin:0}body{color:var(--fg);font-family:var(--font-sans);font-size:var(--text-base);-webkit-font-smoothing:antialiased;line-height:1.5}a{color:inherit;text-decoration:none}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.visually-hidden{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}body{background:radial-gradient(70rem 40rem at 8% -10%, var(--wash-a), transparent 62%), radial-gradient(56rem 34rem at 92% 4%, var(--wash-b), transparent 58%), radial-gradient(48rem 30rem at 50% 108%, var(--wash-c), transparent 60%), var(--bg);padding:var(--sp-4);background-attachment:fixed}.shell{min-height:calc(100vh - var(--sp-4) * 2);border-radius:var(--radius-xl);border:1px solid var(--hairline);background:var(--workspace);-webkit-backdrop-filter:blur(28px)saturate(120%);backdrop-filter:blur(28px)saturate(120%);box-shadow:var(--shadow-workspace);flex-direction:column;display:flex;overflow:hidden}.topbar{align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--hairline);background:var(--bg-blur);z-index:10;display:flex;position:sticky;top:0}.brand{align-items:center;gap:var(--sp-2);font-weight:600;font-size:var(--text-sm);letter-spacing:-.01em;flex:none;display:flex}.brand-mark{background:linear-gradient(135deg, var(--accent), var(--accent-2));color:#fff;width:26px;height:26px;font-size:var(--text-xs);border-radius:8px;place-items:center;font-weight:700;display:grid}.nav{border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);align-items:center;gap:2px;margin:0 auto;padding:3px;display:flex}.nav-item{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);color:var(--fg-muted);font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:background var(--transition), color var(--transition);display:inline-flex}.nav-item:hover{color:var(--fg);background:var(--surface-hover)}.nav-item[aria-current=page]{background:var(--accent);color:var(--accent-fg);font-weight:500}.nav-item .nav-label{display:inline}.topbar-end{align-items:center;gap:var(--sp-2);flex:none;display:flex}.topbar-search{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-pill);background:var(--surface-glass-strong);border:1px solid var(--hairline);color:var(--fg-subtle);display:flex}.topbar-search input{color:var(--fg);font:inherit;font-size:var(--text-sm);background:0 0;border:0;outline:none;width:8rem}.topbar-search input::placeholder{color:var(--fg-subtle)}.mobile-search-toggle{display:none}.icon-btn{border-radius:var(--radius-pill);border:1px solid var(--hairline);background:var(--surface-glass-strong);width:32px;height:32px;color:var(--fg-muted);cursor:pointer;transition:color var(--transition), background var(--transition);place-items:center;display:grid}.icon-btn:hover{color:var(--fg);background:var(--surface-hover)}.avatar{border-radius:var(--radius-pill);width:32px;height:32px;font-size:var(--text-xs);color:#fff;background:linear-gradient(135deg, var(--accent), var(--accent-2));cursor:pointer;flex:none;place-items:center;font-weight:600;display:grid}.ico{flex:none;display:block}.main{padding:var(--sp-6);flex:1;width:100%;overflow-x:hidden}.chat-drawer{inset:var(--sp-4);pointer-events:none;z-index:40;justify-content:flex-end;align-items:stretch;display:flex;position:fixed}.chat-drawer-panel{pointer-events:auto;z-index:1;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:min(430px,100%);height:100%;box-shadow:var(--shadow-md);opacity:0;transition:opacity var(--transition), transform var(--transition);grid-template-rows:auto minmax(0,1fr);display:grid;position:relative;overflow:hidden;transform:translate(1.2rem)}.chat-drawer:not(.is-open) .chat-drawer-panel{pointer-events:none}.chat-drawer.is-open .chat-drawer-panel{opacity:1;transform:none}.chat-drawer-head{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-3) var(--sp-4);border-bottom:1px solid var(--border);display:flex}.chat-scrim{background:color-mix(in srgb, var(--bg) 40%, transparent);opacity:0;pointer-events:none;transition:opacity var(--transition);position:fixed;inset:0}.chat-drawer.is-open .chat-scrim{opacity:1;pointer-events:auto}body.chat-open{overflow:hidden}@media (width<=1220px) and (width>=901px){.topbar{flex-wrap:wrap}.nav{border-radius:var(--radius-lg);flex-wrap:wrap;order:3;justify-content:center;width:100%;margin:0}}@media (width<=900px){body{padding:0}.shell{min-height:100vh;box-shadow:none;border:0;border-radius:0}.topbar{padding:var(--sp-3);gap:var(--sp-2);flex-wrap:wrap}.nav{border-radius:var(--radius-lg);scrollbar-width:none;flex-wrap:nowrap;order:3;justify-content:flex-start;width:100%;overflow-x:auto}.nav::-webkit-scrollbar{display:none}.nav-item .nav-label{display:inline}.topbar-search{background:0 0;border:0;padding:0;overflow:hidden}.topbar-search-icon{display:none}.mobile-search-toggle{display:grid}.topbar-search input{opacity:0;pointer-events:none;width:0;transition:width var(--transition), opacity var(--transition);padding:0}.topbar-search.is-open,.topbar-search:focus-within{padding-right:var(--sp-2);border:1px solid var(--hairline);background:var(--surface-glass-strong)}.topbar-search.is-open input,.topbar-search:focus-within input{opacity:1;pointer-events:auto;width:min(9rem,34vw)}.main{padding:var(--sp-4)}}.page-head{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-6);flex-wrap:wrap;display:flex}.page-title{font-size:var(--text-2xl);letter-spacing:-.02em;margin:0;font-weight:600}.page-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.page-actions{gap:var(--sp-2);align-items:center;display:flex}.btn{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-4);border-radius:var(--radius-pill);border:1px solid var(--border-strong);background:var(--surface);color:var(--fg);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:background var(--transition), border-color var(--transition);display:inline-flex}.btn:hover{background:var(--surface-hover)}.btn-primary{background:var(--accent);border-color:var(--accent);color:var(--accent-fg);font-weight:500}.btn-primary:hover{filter:brightness(1.08);background:var(--accent)}.btn-icon{padding:var(--sp-2);border-radius:var(--radius-sm)}.card{background:var(--surface-glass);-webkit-backdrop-filter:blur(14px);backdrop-filter:blur(14px);border:1px solid var(--hairline);border-radius:var(--radius-lg);padding:var(--sp-5);box-shadow:var(--shadow-sm);overflow-x:auto}.card-head{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.card-title{font-size:var(--text-base);margin:0;font-weight:600}.card-sub{font-size:var(--text-xs);color:var(--fg-muted);margin:var(--sp-1) 0 0}.grid{gap:var(--sp-4);display:grid}.grid>*{min-width:0}.grid-4{grid-template-columns:repeat(auto-fit,minmax(220px,1fr))}.grid-2{grid-template-columns:repeat(auto-fit,minmax(340px,1fr))}.pill{align-items:center;gap:var(--sp-1);padding:2px var(--sp-2);border-radius:var(--radius-pill);font-size:var(--text-xs);white-space:nowrap;font-weight:500;display:inline-flex}.pill:before{content:"";background:currentColor;border-radius:50%;width:5px;height:5px}.pill-ok{color:var(--ok);background:var(--ok-soft)}.pill-warn{color:var(--warn);background:var(--warn-soft)}.pill-danger{color:var(--danger);background:var(--danger-soft)}.pill-info{color:var(--info);background:var(--info-soft)}.pill-idle{color:var(--idle);background:var(--idle-soft)}.table{border-collapse:collapse;width:100%;font-size:var(--text-sm)}.table-scroll{-webkit-overflow-scrolling:touch;min-width:0;max-width:100%;overflow-x:auto}.table-scroll>.table{min-width:42rem}.table th{text-align:left;font-weight:500;font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);padding:0 var(--sp-3) var(--sp-3);border-bottom:1px solid var(--border)}.table td{padding:var(--sp-3);border-bottom:1px solid var(--border);color:var(--fg-muted)}.table tbody tr:last-child td{border-bottom:0}.table tbody tr:hover td{background:var(--surface-hover)}.table td.strong{color:var(--fg);font-weight:500}.mono{font-family:var(--font-mono);font-size:.95em}.empty{text-align:center;padding:var(--sp-7) var(--sp-4);color:var(--fg-muted)}.empty-title{color:var(--fg);margin-bottom:var(--sp-1);font-weight:500}.skeleton{background:linear-gradient(90deg, var(--surface) 25%, var(--surface-hover) 50%, var(--surface) 75%);border-radius:var(--radius-sm);background-size:200% 100%;animation:1.4s infinite shimmer}@keyframes shimmer{to{background-position:-200% 0}}@media (prefers-reduced-motion:reduce){*,:before,:after{transition-duration:.01ms!important;animation-duration:.01ms!important}}.nav-soon{font-size:var(--text-xs);color:var(--fg-subtle);background:var(--surface-hover);padding:1px var(--sp-2);border-radius:var(--radius-pill);margin-left:auto}.nav-item[aria-disabled]{opacity:.55;cursor:default}.nav-item[aria-disabled]:hover{color:var(--fg-muted);background:0 0}.stat-head{justify-content:space-between;align-items:center;gap:var(--sp-2);display:flex}.stat-label{font-size:var(--text-sm);color:var(--fg-muted)}.stat-trend{font-size:var(--text-xs);align-items:center;gap:3px;font-weight:500;display:inline-flex}.stat-trend.up{color:var(--ok)}.stat-trend.down{color:var(--danger)}.stat-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin:var(--sp-2) 0 0;font-weight:600}.stat-unit{font-size:var(--text-lg);color:var(--fg-muted);margin-left:var(--sp-1)}.stat-compare{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:var(--sp-1)}.spark{width:100%;height:34px;margin-top:var(--sp-3);display:block}.setup{margin-bottom:var(--sp-4)}.setup-pct{font-size:var(--text-lg);color:var(--accent);font-weight:600}.setup-complete-actions{align-items:center;gap:var(--sp-2);display:flex}.setup-dismiss{width:28px;height:28px;font-size:var(--text-lg);line-height:1}.setup-done .setup-pct{color:var(--ok)}.setup-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-bottom:var(--sp-4);overflow:hidden}.setup-bar-fill{background:var(--accent);border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.setup-list{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.setup-step{gap:var(--sp-3);align-items:flex-start;display:flex}.setup-check{border:1.5px solid var(--border-strong);width:18px;height:18px;font-size:var(--text-xs);color:var(--fg-subtle);border-radius:50%;flex:none;place-items:center;margin-top:1px;display:grid}.setup-step.done .setup-check{background:var(--ok-soft);color:var(--ok);border-color:#0000}.setup-step-title{font-size:var(--text-sm)}.setup-step.done .setup-step-title{color:var(--fg-muted);text-decoration:line-through}.setup-step-detail{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.hero{justify-content:space-between;align-items:flex-start;gap:var(--sp-5);margin-bottom:var(--sp-5);flex-wrap:wrap;display:flex}.hero-title{font-size:var(--text-3xl);letter-spacing:-.03em;margin:0;font-weight:600}.hero-sub{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-2) 0 0}.hero-actions{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.dash-top{gap:var(--sp-4);margin-bottom:var(--sp-4);grid-template-columns:minmax(0,1.6fr) minmax(0,1fr);display:grid}.dash-top>*,.dash-split>*{min-width:0}.dash-top>div{display:flex}.dash-top>div>.card{flex:1}.dash-top-standalone{grid-template-columns:minmax(0,1fr)}@media (width<=1080px){.dash-top{grid-template-columns:minmax(0,1fr)}}.gauge-wrap{place-items:center;display:grid;position:relative}.gauge{width:100%;max-width:200px;display:block}.gauge-value{transition:stroke-dashoffset .6s cubic-bezier(.4,0,.2,1)}.gauge-center{text-align:center;position:absolute;top:52%;transform:translateY(-50%)}.gauge-pct{font-size:var(--text-2xl);letter-spacing:-.03em;font-weight:600}.gauge-label{font-size:var(--text-xs);color:var(--fg-muted)}.pulse-list{margin:var(--sp-4) 0 0;gap:var(--sp-2);flex-direction:column;padding:0;list-style:none;display:flex}.pulse-item{justify-content:space-between;align-items:center;gap:var(--sp-3);font-size:var(--text-sm);padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);display:flex}.pulse-name{color:var(--fg-muted);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.segbar{border-radius:var(--radius-pill);background:var(--border);gap:2px;height:10px;display:flex;overflow:hidden}.segbar-part{height:100%;display:block}.segbar-ok{background:var(--ok)}.segbar-warn{background:var(--warn)}.segbar-danger{background:var(--danger)}.segbar-info{background:var(--info)}.segbar-idle{background:var(--idle)}.segbar-legend{gap:var(--sp-4);margin-top:var(--sp-3);flex-wrap:wrap;display:flex}.segbar-key{align-items:center;gap:var(--sp-2);font-size:var(--text-xs);color:var(--fg-muted);display:inline-flex}.segbar-dot{border-radius:50%;width:8px;height:8px}.forecast-value{font-size:var(--text-3xl);letter-spacing:-.03em;margin-bottom:var(--sp-1);font-weight:600}.forecast-note{font-size:var(--text-xs);color:var(--fg-subtle);margin-bottom:var(--sp-4)}.dash-split{gap:var(--sp-4);margin-top:var(--sp-4);grid-template-columns:minmax(0,1fr) minmax(0,1.5fr);display:grid}@media (width<=1080px){.dash-split{grid-template-columns:minmax(0,1fr)}}.stat-card{position:relative;overflow:hidden}.dash-section{margin-bottom:var(--sp-5)}.dash-section-head{align-items:baseline;gap:var(--sp-3);margin-bottom:var(--sp-3);padding-left:var(--sp-1);display:flex}.dash-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.08em;color:var(--fg-subtle);margin:0;font-weight:600}.dash-section-note{font-size:var(--text-xs);color:var(--fg-subtle)}.hero-actions-inner{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.btn-attention{border-color:var(--warn);color:var(--warn);background:var(--warn-soft);font-weight:500}.btn-attention:hover{background:var(--warn-soft);filter:brightness(1.1)}.task-summary{margin-bottom:var(--sp-5)}.task-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.task-search,.task-filter{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3)}.task-search{width:220px}.task-search:focus,.task-filter:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.task-row{cursor:pointer}.task-expand{width:1.5rem;height:1.5rem;margin-right:var(--sp-2);color:var(--fg-muted);border:1px solid var(--border);font:inherit;cursor:pointer;background:0 0;border-radius:50%;padding:0;line-height:1}.task-expand:hover,.task-expand:focus-visible{color:var(--fg);border-color:var(--accent)}.activity-row{cursor:pointer}.activity-row:hover td,.activity-row:focus td{background:var(--surface-hover)}.activity-row:focus{outline:2px solid var(--accent);outline-offset:-2px}.task-source-link{color:var(--accent);text-decoration:none}.task-source-link:hover{text-decoration:underline}.task-detail-link{color:inherit}.task-detail-link:hover,.task-detail-link:focus-visible{text-decoration:underline;-webkit-text-decoration-color:var(--accent);text-decoration-color:var(--accent)}.task-actions{gap:var(--sp-1);white-space:nowrap;flex-wrap:wrap;display:flex}.btn-small{padding:var(--sp-1) var(--sp-2);font-size:var(--text-xs)}.btn-quiet{color:var(--fg-muted)}.task-action-error{max-width:220px;font-size:var(--text-xs);white-space:normal}.task-action-error-refused{color:var(--warn)}.task-action-error-broken{color:var(--danger)}.task-action-error-session{color:var(--warn);align-items:center;gap:var(--sp-1);flex-wrap:wrap;display:inline-flex}.task-decision{margin-bottom:var(--sp-4);padding:var(--sp-3);border-left:3px solid var(--accent);background:var(--surface)}.task-detail-actions{justify-content:space-between;align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);padding-bottom:var(--sp-3);border-bottom:1px solid var(--hairline);display:flex}.task-decision-title{color:var(--fg);font-weight:600}.task-decision-plan{margin-top:var(--sp-2);color:var(--fg-muted);white-space:pre-wrap}.task-logs-section{margin-top:var(--sp-4)}.task-logs-section .task-decision-title{justify-content:space-between;align-items:center;display:flex}.task-log-list{max-height:40vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);margin-top:var(--sp-2);overflow-y:auto}.task-log-loading,.task-log-error{padding:var(--sp-3) 0;color:var(--fg-muted)}@media (width<=700px){.task-filters,.task-search{width:100%}.task-filter{flex:100%}.table-scroll:has(.task-row){overflow:visible}.table:has(.task-row){display:block}.table:has(.task-row) tbody{display:block}.table-scroll>.table:has(.task-row){width:100%;min-width:0}.table:has(.task-row) thead{display:none}.task-row{gap:var(--sp-2) var(--sp-4);margin-bottom:var(--sp-3);padding:var(--sp-3);border:1px solid var(--hairline);border-radius:var(--radius-lg);background:var(--surface-glass);grid-template-columns:1fr 1fr;display:grid}.task-row td{justify-content:space-between;align-items:center;gap:var(--sp-2);padding:var(--sp-1) 0;text-align:right;border:0;display:flex}.task-row td:before{content:attr(data-label);color:var(--fg-subtle);font-size:var(--text-xs);text-align:left;font-weight:500}.task-row td:nth-child(3),.task-row td:last-child{grid-column:1/-1}.task-row td:last-child{align-items:flex-start}.task-timeline-row,.task-timeline-row td{width:100%;display:block}.task-timeline-row td{margin:calc(var(--sp-2) * -1) 0 var(--sp-4);border-radius:0 0 var(--radius-lg) var(--radius-lg)}.task-detail-actions{flex-direction:column;align-items:flex-start}}@media (width<=480px){.task-row{grid-template-columns:1fr}.task-row td:nth-child(3),.task-row td:last-child{grid-column:auto}}.task-timeline-row td{background:var(--bg-raised);padding:var(--sp-4)}.task-timeline-loading{color:var(--fg-muted);font-size:var(--text-sm)}.task-timeline-error{align-items:flex-start;gap:var(--sp-2);flex-direction:column;display:flex}.task-timeline-error .task-timeline-title{color:var(--fg);font-weight:500}.task-timeline{gap:var(--sp-3);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.task-timeline-entry{gap:var(--sp-3);align-items:flex-start;display:flex}.task-timeline-dot{background:var(--accent);border-radius:50%;flex:none;width:8px;height:8px;margin-top:5px}.task-timeline-kind{font-size:var(--text-sm);color:var(--fg);font-weight:500}.task-timeline-detail{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.task-timeline-when{font-size:var(--text-xs);color:var(--fg-subtle);margin-top:2px}.run-meta{align-items:center;gap:var(--sp-4);margin:calc(var(--sp-2) * -1) 0 var(--sp-4);font-size:var(--text-sm);flex-wrap:wrap;display:flex}.run-meta-item{align-items:center;gap:var(--sp-2);display:inline-flex}.run-meta-label{color:var(--fg-muted);font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em}.run-meta-value{color:var(--fg)}.run-meta-muted{color:var(--fg-muted)}.run-meta-link{color:var(--accent)}.run-meta-link:hover{text-decoration:underline}.run-note{margin:0 0 var(--sp-4);padding:var(--sp-3) var(--sp-4);border-left:3px solid var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);color:var(--fg);font-size:var(--text-sm)}.run-restart{align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.run-restart-copy,.run-restart-unavailable{color:var(--fg-muted);font-size:var(--text-sm);flex:22rem;margin:0}.run-restart-error{font-size:var(--text-sm);flex:100%;margin:0}.run-restart-error-refused{color:var(--warn)}.run-restart-error-broken{color:var(--danger)}.run-restart-error-session-expired{color:var(--warn)}.run-attempts{gap:var(--sp-2);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.run-attempt{align-items:center;gap:var(--sp-2);padding:var(--sp-2) var(--sp-3);border:1px solid var(--border);border-radius:var(--radius-pill);background:var(--surface);color:var(--fg-muted);font:inherit;font-size:var(--text-sm);cursor:pointer;transition:border-color var(--transition), color var(--transition);display:inline-flex}.run-attempt:hover{border-color:var(--border-strong);color:var(--fg)}.run-attempt.is-selected{border-color:var(--accent);background:var(--accent-soft);color:var(--fg)}.run-attempt-id{font-weight:500}.run-attempt-meta{color:var(--fg-muted);font-size:var(--text-xs)}.run-card{padding-top:var(--sp-4)}.tab-bar{gap:var(--sp-1);border-bottom:1px solid var(--border);margin-bottom:var(--sp-4);scrollbar-width:thin;display:flex;overflow-x:auto}.tab{padding:var(--sp-2) var(--sp-3);border-radius:var(--radius-sm) var(--radius-sm) 0 0;color:var(--fg-muted);font:inherit;font-size:var(--text-sm);white-space:nowrap;cursor:pointer;transition:color var(--transition), background var(--transition);background:0 0;border:0;border-bottom:2px solid #0000;position:relative}.tab:hover{color:var(--fg);background:var(--surface-hover)}.tab.is-selected{color:var(--fg);border-bottom-color:var(--accent);font-weight:500}.run-panel{min-width:0;min-height:6rem}.run-panel:focus-visible{outline:2px solid var(--accent);outline-offset:4px}.run-loading{padding:var(--sp-5) 0;color:var(--fg-muted);font-size:var(--text-sm)}.run-error{align-items:flex-start;gap:var(--sp-2);padding:var(--sp-3) 0;flex-direction:column;display:flex}.run-error-title{color:var(--fg);font-weight:500}.run-error-detail{color:var(--fg-muted);font-size:var(--text-sm);max-width:60ch}.run-json{padding:var(--sp-3);background:var(--bg-raised);border:1px solid var(--border);border-radius:var(--radius-sm);max-height:60vh;font-family:var(--font-mono);font-size:var(--text-xs);white-space:pre-wrap;overflow-wrap:anywhere;margin:0;line-height:1.5;overflow:auto}.run-rail-head{align-items:center;gap:var(--sp-3);margin-bottom:var(--sp-4);flex-wrap:wrap;display:flex}.run-rail-attempt{font-weight:600}.run-rail-when{color:var(--fg-muted);font-size:var(--text-xs)}.run-stages{margin:0;padding:0;list-style:none}.run-stage{gap:var(--sp-2);padding-bottom:var(--sp-4);grid-template-columns:1.75rem 1fr;display:grid;position:relative}.run-stage:before{content:"";background:var(--border-strong);width:1px;position:absolute;top:1rem;bottom:0;left:.6875rem}.run-stage:last-child:before{display:none}.run-stage-node{z-index:1;border:2px solid var(--border-strong);background:var(--bg-raised);border-radius:50%;width:.875rem;height:.875rem;margin:.25rem 0 0 .25rem;position:relative}.run-stage[data-status=ok] .run-stage-node{border-color:var(--ok)}.run-stage[data-status=failed] .run-stage-node{border-color:var(--danger)}.run-stage[data-status=interrupted] .run-stage-node{border-color:var(--warn)}.run-stage[data-status=running] .run-stage-node{border-color:var(--info)}.run-stage-body{min-width:0}.run-stage-head{align-items:center;gap:var(--sp-2);flex-wrap:wrap;display:flex}.run-stage-name{color:var(--fg);overflow-wrap:anywhere;min-width:0;font-weight:500}.run-stage-duration{color:var(--fg-muted);font-size:var(--text-xs)}.run-stage-error{margin-top:var(--sp-2);padding:var(--sp-2) var(--sp-3);border-left:3px solid var(--danger);background:var(--danger-soft);border-radius:var(--radius-sm);color:var(--fg-muted);font-size:var(--text-sm);white-space:pre-wrap;overflow-wrap:anywhere}.run-agent-report{margin-top:var(--sp-2);color:var(--fg-muted);font-size:var(--text-xs)}.run-agent-report-label{color:var(--fg-muted)}.run-rail-legend,.run-rail-note{margin:var(--sp-3) 0 0;color:var(--fg-muted);font-size:var(--text-xs);max-width:70ch}.run-rail-legend strong{color:var(--fg-muted)}.run-capture+.run-capture{margin-top:var(--sp-5);padding-top:var(--sp-4);border-top:1px solid var(--border)}.run-capture-head{justify-content:space-between;align-items:baseline;gap:var(--sp-3);flex-wrap:wrap;display:flex}.run-capture-when{color:var(--fg);font-size:var(--text-sm);font-weight:500}.run-capture-at{color:var(--fg-muted);font-size:var(--text-xs)}.run-capture-meta{align-items:center;gap:var(--sp-3);margin:var(--sp-2) 0 var(--sp-3);color:var(--fg-muted);font-size:var(--text-xs);flex-wrap:wrap;display:flex}.run-capture-link{color:var(--accent)}.run-capture-link:hover{text-decoration:underline}.run-capture-branch,.run-capture-sha,.run-capture-totals{color:var(--fg-muted)}.run-changes-table td{padding:var(--sp-2) var(--sp-3);vertical-align:top}.run-changes-path{color:var(--fg);word-break:break-all}.run-changes-old{color:var(--fg-muted)}.run-changes-count{text-align:right;white-space:nowrap}.run-changes-hint,.run-changes-note,.run-changes-empty{color:var(--fg-muted);font-size:var(--text-xs)}.run-changes-hint{display:block}.run-changes-empty{padding:var(--sp-3) 0}.run-config-scope{margin:0 0 var(--sp-2);color:var(--fg-muted);font-size:var(--text-sm);max-width:75ch}.run-config-when{margin-bottom:var(--sp-3);color:var(--fg-muted);font-size:var(--text-xs)}.run-config-unknown{margin-bottom:var(--sp-2);color:var(--warn);font-size:var(--text-sm)}.task-log-filters{padding-bottom:var(--sp-3);border-bottom:1px solid var(--border)}.task-log-attempt{color:var(--fg);font-size:var(--text-sm);font-weight:500}.task-log-filter{align-items:center;gap:var(--sp-2);display:inline-flex}.task-log-filter-label{color:var(--fg-muted);font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em}.task-log-filter-note{color:var(--fg-muted);font-size:var(--text-xs);flex:100%;max-width:80ch;margin:0}.run-panel .task-log-list{border:1px solid var(--border);border-radius:var(--radius-sm);background:var(--bg-raised);max-height:62vh;padding:0 var(--sp-2)}.run-page .pill{color:var(--fg)}.run-page .pill-ok:before{background:var(--ok)}.run-page .pill-warn:before{background:var(--warn)}.run-page .pill-danger:before{background:var(--danger)}.run-page .pill-info:before{background:var(--info)}.run-page .pill-idle:before{background:var(--idle)}@media (width<=700px){.run-meta{margin-bottom:var(--sp-3)}.run-restart{align-items:flex-start}.run-attempts{padding-bottom:var(--sp-1);flex-wrap:nowrap;overflow-x:auto}.run-stage{padding-bottom:var(--sp-3);border-bottom:1px solid var(--border);grid-template-columns:1fr}.run-stage:before,.run-stage-node{display:none}.run-capture-head{align-items:flex-start;gap:var(--sp-1);flex-direction:column}}@media (width<=480px){.tab{padding:var(--sp-2)}.run-json{max-height:45vh}}@media (prefers-reduced-motion:reduce){.run-attempt,.tab{transition:none}}.skill-search{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);width:220px}.skill-search:focus{outline:2px solid var(--accent-soft);outline-offset:1px}.skill-card{flex-direction:column;display:flex}.skill-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0 0 var(--sp-3);flex:1}.skill-source{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-stage-card{margin-top:var(--sp-4)}.wf-rate{font-size:var(--text-sm);color:var(--fg);align-items:baseline;gap:var(--sp-2);display:flex}.wf-rate-sub{font-size:var(--text-xs);color:var(--fg-subtle)}.wf-bar{border-radius:var(--radius-pill);background:var(--border);height:5px;margin-top:var(--sp-2);width:140px;overflow:hidden}.wf-bar-fill{border-radius:var(--radius-pill);height:100%;transition:width var(--transition)}.wf-bar-ok{background:var(--ok)}.wf-bar-warn{background:var(--warn)}.wf-bar-danger{background:var(--danger)}.wf-bar-info{background:var(--info)}.wf-form{gap:var(--sp-2);flex-direction:column;display:flex}.wf-form input,.wf-form select,.wf-form textarea{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--surface);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-2);width:100%}.wf-form textarea{resize:vertical}.wf-form input:focus,.wf-form select:focus,.wf-form textarea:focus{outline:2px solid var(--accent);outline-offset:-1px}.wf-form input::placeholder,.wf-form textarea::placeholder{color:var(--fg-subtle)}.channel-card{gap:var(--sp-1);flex-direction:column;display:flex}.channel-desc{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.channel-detail{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.curator-card{gap:var(--sp-2);flex-direction:column;display:flex}.curator-health-message{color:var(--fg-muted);font-size:var(--text-sm);margin:0}.curator-meta{color:var(--fg-subtle);font-size:var(--text-xs);margin:0}.curator-actions{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.curator-action{border-top:1px solid var(--border);padding-top:var(--sp-2)}.curator-action-head{justify-content:space-between;gap:var(--sp-2);font-size:var(--text-sm);display:flex}.curator-action-type{color:var(--fg);font-weight:600}.curator-action-time{color:var(--fg-subtle);font-size:var(--text-xs)}.curator-action-detail{color:var(--fg-muted);font-size:var(--text-sm);margin:var(--sp-1) 0 0}.curator-action-reason{color:var(--fg-subtle);font-size:var(--text-xs);margin:var(--sp-1) 0 0}.cfg-page{max-width:70rem;margin:0 auto}.cfg-section{margin-bottom:var(--sp-4)}.cfg-subhead{font-size:var(--text-sm);color:var(--fg-muted);margin:var(--sp-5) 0 var(--sp-2);font-weight:600}.cfg-subhead:first-child{margin-top:0}.kv-list{column-gap:var(--sp-4);grid-template-columns:max-content minmax(0,1fr) auto;row-gap:0;display:grid}.kv{grid-template-columns:subgrid;align-items:center;row-gap:var(--sp-1);padding:var(--sp-2) 0;border-radius:var(--radius-sm);grid-column:1/-1;display:grid}@supports not (grid-template-columns:subgrid){.kv-list{flex-direction:column;width:auto;display:flex}.kv{column-gap:var(--sp-4);grid-template-columns:minmax(8rem,16rem) minmax(0,1fr) auto}}.kv+.kv{border-top:1px solid var(--border)}.kv:hover{background:var(--surface-hover)}.kv-label{font-size:var(--text-sm);color:var(--fg-muted)}.kv-value{min-width:0;font-size:var(--text-sm);color:var(--fg);text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.kv-value.is-empty{color:var(--fg-subtle)}.kv-actions{align-items:center;gap:var(--sp-2);justify-self:end;display:flex}.kv-note{font-size:var(--text-xs);color:var(--fg-subtle);grid-column:2/-1}.kv-note.is-error{color:var(--danger)}.kv.is-locked .kv-value{color:var(--fg-muted)}.kv-btn{font:inherit;font-size:var(--text-xs);color:var(--fg-subtle);border:1px solid var(--border);border-radius:var(--radius-sm);padding:2px var(--sp-2);cursor:pointer;background:0 0;flex:none;transition:color .12s,border-color .12s,background .12s}.kv:hover .kv-btn,.kv:focus-within .kv-btn{color:var(--fg-muted);border-color:var(--border-strong)}.kv-btn:hover{color:var(--fg);border-color:var(--accent);background:var(--accent-soft)}.kv-btn:focus-visible{outline:2px solid var(--accent);outline-offset:1px}.kv-flag{font-size:var(--text-xs);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-pill);padding:1px var(--sp-2);flex:none}.kv-input{font:inherit;font-size:var(--text-sm);color:var(--fg);background:var(--bg,var(--surface));border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);width:100%;min-width:0}.kv-input:focus{outline:2px solid var(--accent);outline-offset:-1px}.kv-save,.kv-cancel{font:inherit;font-size:var(--text-xs);border-radius:var(--radius-sm);padding:var(--sp-1) var(--sp-2);cursor:pointer;flex:none}.kv-save{background:var(--accent);border:1px solid var(--accent);color:var(--accent-fg);font-weight:500}.kv-save:disabled{opacity:.6;cursor:default}.kv-cancel{border:1px solid var(--border-strong);color:var(--fg-muted);background:0 0}.kv-cancel:hover{color:var(--fg)}.cfg-notice{border-left:3px solid var(--warn)}.cfg-notice p{font-size:var(--text-sm);color:var(--warn);margin:0}@media (width<=700px){.kv-list{flex-direction:column;width:auto;display:flex}.kv{column-gap:var(--sp-4);grid-template-columns:minmax(0,1fr) auto}.kv-label{grid-column:1}.kv-actions{grid-area:1/2}.kv-value,.kv-note{white-space:normal;overflow-wrap:anywhere;grid-column:1/-1}}.log-filters{gap:var(--sp-2);flex-wrap:wrap;align-items:center;display:flex}.log-status{gap:var(--sp-3);align-items:center;display:flex}.log-meta{font-size:var(--text-xs);color:var(--fg-subtle);font-family:var(--font-mono)}.log-select,.log-search{background:var(--bg-raised);border:1px solid var(--border-strong);color:var(--fg);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);font:inherit;font-size:var(--text-sm)}.log-search{min-width:220px}.log-select:focus,.log-search:focus{outline:2px solid var(--accent);outline-offset:-1px}.log-list{max-height:62vh;font-family:var(--font-mono);font-size:var(--text-xs);border-top:1px solid var(--border);overflow-y:auto}.log-loading{padding:var(--sp-5);color:var(--fg-muted);text-align:center}.log-row{gap:var(--sp-3);padding:var(--sp-2) var(--sp-1);border-bottom:1px solid var(--border);grid-template-columns:62px 52px 1fr;align-items:baseline;display:grid}.log-row:hover{background:var(--surface-hover)}.log-time{color:var(--fg-subtle)}.log-level{letter-spacing:.04em;font-size:10px;font-weight:600}.log-danger .log-level{color:var(--danger)}.log-warn .log-level{color:var(--warn)}.log-info .log-level{color:var(--info)}.log-idle .log-level{color:var(--idle)}.log-danger .log-msg{color:var(--fg)}.log-body{gap:var(--sp-2);flex-wrap:wrap;align-items:baseline;min-width:0;display:flex}.log-msg{color:var(--fg);word-break:break-word}.log-field{color:var(--fg-muted);background:var(--bg-raised);border-radius:var(--radius-sm);padding:0 var(--sp-2);white-space:nowrap;text-overflow:ellipsis;max-width:100%;overflow:hidden}.log-field-key{color:var(--fg-subtle)}.log-field-key:after{content:"=";opacity:.6}@media (width<=860px){.log-row{grid-template-columns:56px 1fr}.log-level{display:none}.log-search{flex:1;min-width:0}}.capture-row{cursor:pointer}.capture-row:hover{background:var(--bg-raised)}.capture-row:focus-visible{outline:2px solid var(--accent);outline-offset:-2px}.capture-detail-row td{padding:var(--sp-3) var(--sp-3) var(--sp-4);border-bottom:1px solid var(--border)}.capture-detail{gap:var(--sp-4);grid-template-columns:1fr 1fr;display:grid}.capture-detail-section{min-width:0}.capture-detail-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);margin-bottom:var(--sp-2)}.capture-payload{background:var(--bg-raised);border:1px solid var(--border-strong);border-radius:var(--radius-sm);padding:var(--sp-3);font-family:var(--font-mono);font-size:var(--text-xs);white-space:pre-wrap;word-break:break-word;max-height:24rem;overflow:auto}.capture-empty{color:var(--fg-muted);font-size:var(--text-sm)}@media (width<=640px){.capture-detail{grid-template-columns:1fr}}.mapping-form,.mapping-fields,.mapping-payload{margin-bottom:var(--sp-4);padding:var(--sp-4)}.mapping-form-row{gap:var(--sp-1);margin-bottom:var(--sp-3);font-size:var(--text-sm);color:var(--fg-subtle);flex-direction:column;display:flex}.mapping-input,.mapping-select{padding:var(--sp-2);border:1px solid var(--border-strong);border-radius:var(--radius-sm);background:var(--bg-raised);color:var(--fg);font:inherit}.mapping-section-title{font-size:var(--text-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-subtle);margin-bottom:var(--sp-2)}.mapping-fields-table .mapping-input{width:100%}.mapping-empty-fields{color:var(--fg-muted);font-size:var(--text-sm);padding:var(--sp-3) 0}.mapping-error{color:var(--danger,#e5484d);font-size:var(--text-sm);margin-bottom:var(--sp-3)}.mapping-tree-list{padding-left:var(--sp-4);font-family:var(--font-mono);font-size:var(--text-xs);margin:0;list-style:none}.mapping-tree-item{padding:2px 0}.mapping-tree-key,.mapping-tree-value{cursor:pointer;border-radius:var(--radius-sm);padding:0 4px}.mapping-tree-key:hover,.mapping-tree-value:hover{background:var(--bg-raised);outline:1px solid var(--accent)}.mapping-tree-value{color:var(--fg-subtle);margin-left:var(--sp-1)}.binding-form{margin-bottom:var(--sp-4);padding:var(--sp-4)}.binding-form-row{gap:var(--sp-1);margin-bottom:var(--sp-3);font-size:var(--text-sm);color:var(--fg-subtle);flex-direction:column;display:flex}.binding-input,.binding-select{padding:var(--sp-2);border:1px solid var(--border-strong);border-radius:var(--radius-sm);background:var(--bg-raised);color:var(--fg);font:inherit}.binding-error{color:var(--danger,#e5484d);font-size:var(--text-sm);margin-bottom:var(--sp-3)}.mem-loading{padding:var(--sp-5);text-align:center;color:var(--fg-muted)}.mem-warning{font-size:var(--text-sm);color:var(--warn);background:var(--warn-soft);border-radius:var(--radius-sm);padding:var(--sp-2) var(--sp-3);margin:0 0 var(--sp-3)}.mem-tools{gap:var(--sp-2);flex-direction:column;margin:0;padding:0;list-style:none;display:flex}.mem-tool{padding:var(--sp-3);border-radius:var(--radius-sm);background:var(--bg-raised);border:1px solid var(--hairline)}.mem-tool-name{font-size:var(--text-sm);color:var(--fg);font-weight:500}.mem-tool-desc{font-size:var(--text-xs);color:var(--fg-muted);margin-top:2px}.chat-page{flex-direction:column;height:calc(100vh - 5rem);display:flex;overflow:hidden}.chat-drawer .chat-page{height:100%}.chat-page-content{flex-direction:column;flex:auto;min-height:0;display:flex;overflow:hidden}.chat-topbar{flex:none;justify-content:space-between;align-items:center;gap:1rem;margin-bottom:1rem;display:flex}.chat-kicker,.chat-workspace-label{color:var(--fg-muted);letter-spacing:.12em;font-size:.68rem;font-weight:700}.chat-topbar-actions{align-items:center;gap:.55rem;display:flex}.chat-topbar-actions .chat-select{min-width:0;max-width:14rem}.chat-update-panel{border:1px solid var(--border);color:var(--fg-muted);border-radius:.75rem;flex:none;justify-content:space-between;align-items:center;gap:1rem;margin:0 0 .75rem;padding:.7rem .9rem;font-size:.8rem;display:flex}.chat-update-panel>div:first-child{gap:.2rem;display:grid}.chat-update-panel strong{color:var(--fg)}.chat-update-actions{flex-shrink:0;gap:.45rem;display:flex}.chat-dangerous-panel{border:1px solid color-mix(in srgb, var(--danger) 45%, var(--border));border-radius:.75rem;flex:none;margin:0 0 .75rem;padding:.8rem .9rem}.chat-dangerous-head,.chat-dangerous-controls,.chat-dangerous-pending{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-dangerous-head{margin-bottom:.7rem}.chat-dangerous-controls{flex-wrap:wrap;align-items:stretch}.chat-dangerous-controls>div{flex:18rem;gap:.45rem;display:flex}.chat-dangerous-input{background:var(--surface-hover);min-width:0;color:var(--fg);border:1px solid var(--border-strong);font:inherit;border-radius:.5rem;flex:1;padding:.5rem .65rem}.chat-dangerous-pending-list{gap:.45rem;margin-top:.75rem;display:grid}.chat-dangerous-pending{border-top:1px solid var(--border);color:var(--fg-muted);padding-top:.55rem;font-size:.8rem}.chat-layout{flex:auto;grid-template-columns:242px minmax(0,1fr);gap:.75rem;min-height:0;display:grid;overflow:hidden}.chat-sidebar,.chat-workspace{background:var(--surface);border:1px solid var(--border);border-radius:1rem}.chat-sidebar{padding:.8rem;overflow-y:auto}.chat-sidebar-head,.chat-toolbar,.chat-compose-actions{justify-content:space-between;align-items:center;gap:.6rem;display:flex}.chat-session-list{gap:.35rem;margin-top:1rem;display:grid}.chat-session{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.65rem;gap:.25rem;padding:.7rem;display:grid}.chat-session:hover,.chat-session.active{background:var(--surface-hover);color:var(--fg);border-color:var(--border-strong)}.chat-session span{font-size:.72rem}.chat-workspace{grid-template-rows:auto minmax(0,1fr) auto;min-width:0;display:grid;overflow:hidden}.chat-workspace-head{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;padding:.85rem 1.1rem;display:flex}.chat-session-tools{color:var(--fg-muted);margin-left:.6rem;font-size:.78rem;position:relative}.chat-session-tools summary{cursor:pointer}.chat-session-tool-list{z-index:2;background:var(--surface);border:1px solid var(--border-strong);border-radius:.65rem;flex-wrap:wrap;gap:.35rem;width:min(22rem,72vw);padding:.55rem;display:flex;position:absolute;top:calc(100% + .45rem);right:0;box-shadow:0 .7rem 2rem #0000004d}.chat-select{background:var(--surface-hover);color:var(--fg);border:1px solid var(--border-strong);border-radius:.5rem;padding:.5rem .65rem}.chat-transcript{align-content:start;gap:1rem;padding:1.25rem;display:grid;overflow:auto}.chat-empty-state{text-align:center;place-self:center;width:min(100%,40rem);padding:3rem 1rem}.chat-empty-mark{border:1px solid var(--border-strong);width:2.6rem;height:2.6rem;color:var(--accent);border-radius:.8rem;place-items:center;margin:0 auto 1rem;font-weight:700;display:grid}.chat-empty-state h2{letter-spacing:-.04em;margin:0;font-size:clamp(1.5rem,3vw,2.25rem)}.chat-empty-state p{color:var(--fg-muted);margin:.6rem 0 1.4rem}.chat-prompt-grid{flex-wrap:wrap;justify-content:center;gap:.5rem;display:flex}.chat-prompt{border:1px solid var(--border);background:var(--surface-hover);color:var(--fg-muted);cursor:pointer;border-radius:999px;padding:.55rem .75rem}.chat-prompt:hover{color:var(--fg);border-color:var(--border-strong)}.chat-bubble-row{display:flex}.chat-bubble-row.user{justify-content:flex-end}.chat-bubble{background:var(--surface-hover);border-radius:.85rem;max-width:min(78ch,86%);padding:.8rem 1rem;line-height:1.5}.chat-bubble-row.user .chat-bubble{background:color-mix(in srgb, var(--accent) 18%, var(--surface))}.chat-bubble-meta{color:var(--fg-muted);margin-bottom:.3rem;font-size:.7rem}.chat-bubble-text{white-space:pre-wrap;overflow-wrap:anywhere}.chat-bubble-text p{margin:0 0 .7rem}.chat-bubble-text p:last-child{margin-bottom:0}.chat-bubble-text h1,.chat-bubble-text h2,.chat-bubble-text h3{letter-spacing:-.02em;margin:.2rem 0 .6rem;line-height:1.2}.chat-bubble-text h1{font-size:1.25rem}.chat-bubble-text h2{font-size:1.1rem}.chat-bubble-text h3{font-size:1rem}.chat-bubble-text ul,.chat-bubble-text ol{margin:.25rem 0 .75rem;padding-left:1.35rem}.chat-bubble-text blockquote{border-left:3px solid var(--accent);color:var(--fg-muted);margin:.5rem 0;padding:.35rem .75rem}.chat-bubble-text code{background:color-mix(in srgb, var(--fg) 10%, transparent);border-radius:.3rem;padding:.1rem .3rem;font-size:.9em}.chat-bubble-text pre{border:1px solid var(--border);background:color-mix(in srgb, var(--surface) 75%, #000);border-radius:.5rem;margin:.6rem 0;padding:.75rem;overflow:auto}.chat-bubble-text pre code{background:0 0;padding:0}.chat-bubble-text a{color:var(--accent)}.chat-media-img{border:1px solid var(--border);object-fit:contain;background:var(--surface);cursor:pointer;border-radius:.5rem;max-width:100%;max-height:24rem;margin:.4rem 0;display:block}.chat-bubble-text table{border-collapse:collapse;width:100%;margin:.7rem 0;font-size:.92em}.chat-bubble-text th,.chat-bubble-text td{text-align:left;border:1px solid var(--border);padding:.45rem .6rem}.chat-bubble-text th{color:var(--fg);background:color-mix(in srgb, var(--surface) 70%, transparent);font-weight:700}.chat-tools{gap:.2rem;margin-bottom:.5rem;font-size:.78rem;display:grid}.chat-tools:empty{display:none}.chat-tool{color:var(--fg-muted);overflow-wrap:anywhere;align-items:baseline;gap:.4rem;display:flex}.chat-tool-name{color:var(--fg);font-weight:600}.chat-tool.failed .chat-tool-summary{color:var(--danger)}.chat-nav-chip{border:1px solid color-mix(in srgb, var(--accent) 45%, var(--border));background:var(--accent-soft);color:var(--accent);cursor:pointer;transition:background var(--transition), border-color var(--transition), color var(--transition);border-radius:999px;align-items:center;gap:.4rem;padding:.4rem .7rem;font-size:.82rem;font-weight:600;display:inline-flex}.chat-nav-chip:hover{border-color:var(--accent);background:color-mix(in srgb, var(--accent) 16%, var(--surface))}.chat-nav-chip:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.chat-nav-chip-icon{font-size:.8rem;line-height:1}.chat-compose{border-top:1px solid var(--border);padding:.85rem 1rem 1rem}.chat-composer-shell{background:var(--surface-hover);border:1px solid var(--border-strong);border-radius:.9rem;padding:.7rem .8rem .55rem;position:relative}.chat-composer{resize:vertical;box-sizing:border-box;width:100%;min-height:3.3rem;color:var(--fg);font:inherit;background:0 0;border:0;padding:.25rem 0}.chat-composer:focus{outline:0}.chat-command-menu{z-index:3;background:var(--surface);border:1px solid var(--border-strong);border-radius:.7rem;gap:.15rem;max-height:18rem;padding:.35rem;display:grid;position:absolute;bottom:calc(100% - .25rem);left:.8rem;right:.8rem;overflow:auto;box-shadow:0 .7rem 2rem #0000004d}.chat-command-menu[hidden]{display:none}.chat-command-option{text-align:left;color:var(--fg-muted);cursor:pointer;background:0 0;border:1px solid #0000;border-radius:.45rem;grid-template-columns:minmax(8rem,14rem) 1fr;align-items:center;gap:.65rem;padding:.5rem .6rem;display:grid}.chat-command-option:hover,.chat-command-option[aria-selected=true]{color:var(--fg);background:var(--surface-hover);border-color:var(--border)}.chat-command-option code{color:var(--fg)}.chat-compose-actions{margin-top:.55rem}.chat-hint,.chat-empty{color:var(--fg-muted);font-size:.78rem}.chat-command-help{color:var(--fg-muted);margin-right:auto;font-size:.78rem}.chat-command-help summary{cursor:pointer}.chat-command-list{min-width:min(34rem,70vw);max-width:40rem;padding-top:.4rem;line-height:1.45}.chat-command-item{grid-template-columns:minmax(10rem,16rem) 1fr;gap:.7rem;padding:.3rem 0;display:grid}.chat-command-item code{color:var(--fg)}@media (width<=760px){.chat-topbar,.chat-topbar-actions{flex-direction:column;align-items:flex-start}.chat-layout{grid-template-columns:1fr}.chat-sidebar{max-height:14rem;overflow:auto}}@media (width<=520px){.chat-update-panel{flex-direction:column;align-items:flex-start}} diff --git a/ui/dist/assets/index.js b/ui/dist/assets/index.js index 1db2451f9..c5e4ca6e4 100644 --- a/ui/dist/assets/index.js +++ b/ui/dist/assets/index.js @@ -1,16 +1,16 @@ -(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)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;tt&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=ee(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function M(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function N(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||M(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||M(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function P(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(F):e.constructor===void 0?v({},e):null}function I(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;de.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}var se=15e3;function ce(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 le(e){try{let t=(await e.text()).trim();if(t)return t.split(` -`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var ue=class extends Error{constructor(e,t){super(e),this.status=t}};function de(e){let t=e instanceof ue?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function fe(e,t){let n=await fetch(e,t);if(!n.ok)throw new ue(await le(n),n.status);return n}async function z(e,{method:t=`GET`,body:n,timeoutMs:r=se,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await fe(e,o);return i?s.json():void 0}var B={summary:()=>z(`/api/summary`),tasks:()=>z(`/api/tasks`),taskMeta:()=>z(`/api/task-meta`),task:e=>z(`/api/tasks/${e}`),taskAction:(e,t)=>z(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>z(`/api/setup`),capabilities:()=>z(`/api/capabilities`),workflows:()=>z(`/api/workflows`),workRequest:e=>z(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>z(`/api/skills`),channels:()=>z(`/api/channels`),curators:()=>z(`/api/curators`),channelReload:e=>z(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>z(`/api/config`),version:()=>z(`/api/version`),configUpdate:e=>z(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>z(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>z(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>z(`/api/logs`+ce(e)),taskLogs:(e,t)=>z(`/api/tasks/${e}/logs`+ce(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>z(`/api/captures`+ce({limit:e})),mappings:()=>z(`/api/mappings`),mappingCreate:e=>z(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>z(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>z(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>z(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>z(`/api/bindings`),bindingCreate:e=>z(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>z(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>z(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>z(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>z(`/api/memory`),chatSessions:()=>z(`/api/chat/sessions`),chatMessages:e=>z(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>z(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>z(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>z(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:oe(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>z(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>z(`/api/chat/update`),chatUpdateDefer:e=>z(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>z(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>z(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>z(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>z(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>fe(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function V(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 pe(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 me(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var he=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],ge=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],_e=[...he],ve=[...ge],ye=new Map(_e.map(e=>[e.id,e])),be=new Map(ve.map(e=>[e.id,e]));function xe(e){return ye.get(e)?.label||e||`Unknown`}function Se(e){return ye.get(e)?.kind||`idle`}function Ce(){return _e.map(e=>e.id)}function H(){return new Set(_e.filter(e=>e.needs_you).map(e=>e.id))}function we(e){return be.get(e)||null}function U(e,t,...n){let[r,...i]=e.split(`.`),a=document.createElement(r||`div`);i.length&&(a.className=i.join(` `)),t!==void 0&&(typeof t!=`object`||t instanceof Node)&&(n.unshift(t),t=null);for(let[e,n]of Object.entries(t||{}))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?a.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?a.className=[a.className,n].filter(Boolean).join(` `):e===`html`?a.innerHTML=n:a.setAttribute(e,n===!0?``:String(n)));return Te(a,n),a}function Te(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 Ee(e,...t){return e.replaceChildren(),Te(e,t),e}function De(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 Oe(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}var ke={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,curators:``,captures:``,mappings:``,bindings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,close:``,help:``};function W(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=ke[e]||ke.dashboard,r}var Ae,G,je,Me,Ne=0,Pe=[],K=t,Fe=K.__b,Ie=K.__r,Le=K.diffed,Re=K.__c,ze=K.unmount,Be=K.__;function Ve(e,t){K.__h&&K.__h(G,e,Ne||t),Ne=0;var n=G.__H||(G.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function q(e){return Ne=1,He(Xe,e)}function He(e,t,n){var r=Ve(Ae++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Xe(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=G,!G.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};G.__f=!0;var a=G.shouldComponentUpdate,o=G.componentWillUpdate;G.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},G.shouldComponentUpdate=i}return r.__N||r.__}function J(e,t){var n=Ve(Ae++,3);!K.__s&&Ye(n.__H,t)&&(n.__=e,n.u=t,G.__H.__h.push(n))}function Y(e){return Ne=5,Ue(function(){return{current:e}},[])}function Ue(e,t){var n=Ve(Ae++,7);return Ye(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function We(){for(var e;e=Pe.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(qe),t.__h.some(Je),t.__h=[]}catch(n){t.__h=[],K.__e(n,e.__v)}}}K.__b=function(e){G=null,Fe&&Fe(e)},K.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Be&&Be(e,t)},K.__r=function(e){Ie&&Ie(e),Ae=0;var t=(G=e.__c).__H;t&&(je===G?(t.__h=[],G.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(qe),t.__h.some(Je),t.__h=[],Ae=0)),je=G},K.diffed=function(e){Le&&Le(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Pe.push(t)!==1&&Me===K.requestAnimationFrame||((Me=K.requestAnimationFrame)||Ke)(We)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),je=G=null},K.__c=function(e,t){t.some(function(e){try{e.__h.some(qe),e.__h=e.__h.filter(function(e){return!e.__||Je(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],K.__e(n,e.__v)}}),Re&&Re(e,t)},K.unmount=function(e){ze&&ze(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{qe(e)}catch(e){t=e}}),n.__H=void 0,t&&K.__e(t,n.__v))};var Ge=typeof requestAnimationFrame==`function`;function Ke(e){var t,n=function(){clearTimeout(r),Ge&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Ge&&(t=requestAnimationFrame(n))}function qe(e){var t=G,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),G=t}function Je(e){var t=G;e.__c=e.__(),G=t}function Ye(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Xe(e,t){return typeof t==`function`?t(e):t}function Ze({label:e,value:t,unit:n,trend:r,compare:i,series:a=[],goodDirection:o=`up`}){let s=r==null?null:r>=0?`up`:`down`,c=s==null?null:s===o;return U(`div.card.stat`,U(`div.stat-head`,U(`span.stat-label`,e),s&&U(`span.stat-trend.${c?`up`:`down`}`,W(s===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(r).toFixed(1)}%`)),U(`div.stat-value`,t,n&&U(`span.stat-unit`,n)),i&&U(`div.stat-compare`,i),a.length>1&&Qe(a,c===!1?`var(--danger)`:`var(--ok)`))}function Qe(e,t=`var(--ok)`,{width:n=220,height:r=34}={}){let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=e.length>1?n/(e.length-1):n,c=e.map((e,t)=>`${(t*s).toFixed(1)},${(r-(e-a)/o*r).toFixed(1)}`).join(` `),l=U(`svg.spark`,{viewBox:`0 0 ${n} ${r}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return l.innerHTML=``,l}function $e({value:e,label:t,size:n=168}){let r=Math.max(0,Math.min(100,Number(e)||0)),i=r>=90?`var(--ok)`:r>=70?`var(--warn)`:`var(--danger)`,a=n/2,o=n/2,s=2*Math.PI*62*(240/360),c=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${a+62*Math.cos(n)} ${o+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${a+62*Math.cos(r)} ${o+62*Math.sin(r)}`].join(` `)},l=U(`svg.gauge`,{viewBox:`0 0 ${n} ${n*.78}`,role:`img`,"aria-label":`${t}: ${r}%`});return l.innerHTML=` +(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)}})();var e,t,n,r,i,a,o,s,c,l,u,d,f,p,m={},h=[],g=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,_=Array.isArray;function v(e,t){for(var n in t)e[n]=t[n];return e}function y(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function b(t,n,r){var i,a,o,s={};for(o in n)o==`key`?i=n[o]:o==`ref`?a=n[o]:s[o]=n[o];if(arguments.length>2&&(s.children=arguments.length>3?e.call(arguments,2):r),typeof t==`function`&&t.defaultProps!=null)for(o in t.defaultProps)s[o]===void 0&&(s[o]=t.defaultProps[o]);return x(t,s,i,a,null)}function x(e,r,i,a,o){var s={type:e,props:r,key:i,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:o??++n,__i:-1,__u:0};return o==null&&t.vnode!=null&&t.vnode(s),s}function S(e){return e.children}function C(e,t){this.props=e,this.context=t}function w(e,t){if(t==null)return e.__?w(e.__,e.__i+1):null;for(var n;tt&&r.sort(o),e=r.shift(),t=r.length,T(e)}finally{r.length=O.__r=0}}function k(e,t,n,r,i,a,o,s,c,l,u){var d,f,p,g,_,v,y=r&&r.__k||h,b=t.length;for(c=A(n,t,y,c,b),d=0;d0?o=e.__k[a]=x(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[a]=o,c=a+f,o.__=e,o.__b=e.__b+1,s=null,(l=o.__i=M(o,n,c,d))!=-1&&(d--,(s=n[l])&&(s.__u|=2)),s==null||s.__v==null?(l==-1&&(i>u?f--:ic?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a+!!u){for(i=n-1,a=n+1;i>=0||a=0?i--:a++])!=null&&!(2&l.__u)&&s==l.key&&c==l.type)return o}return-1}function N(e,t,n){t[0]==`-`?e.setProperty(t,n??``):e[t]=n==null?``:typeof n!=`number`||g.test(t)?n:n+`px`}function P(e,t,n,r,i){var a,o;n:if(t==`style`)if(typeof n==`string`)e.style.cssText=n;else{if(typeof r==`string`&&(e.style.cssText=r=``),r)for(t in r)n&&t in n||N(e.style,t,``);if(n)for(t in n)r&&n[t]==r[t]||N(e.style,t,n[t])}else if(t[0]==`o`&&t[1]==`n`)a=t!=(t=t.replace(u,`$1`)),o=t.toLowerCase(),t=o in e||t==`onFocusOut`||t==`onFocusIn`?o.slice(2):t.slice(2),e.l||={},e.l[t+a]=n,n?r?n[l]=r[l]:(n[l]=d,e.addEventListener(t,a?p:f,a)):e.removeEventListener(t,a?p:f,a);else{if(i==`http://www.w3.org/2000/svg`)t=t.replace(/xlink(H|:h)/,`h`).replace(/sName$/,`s`);else if(t!=`width`&&t!=`height`&&t!=`href`&&t!=`list`&&t!=`form`&&t!=`tabIndex`&&t!=`download`&&t!=`rowSpan`&&t!=`colSpan`&&t!=`role`&&t!=`popover`&&t in e)try{e[t]=n??``;break n}catch{}typeof n==`function`||(n==null||!1===n&&t[4]!=`-`?e.removeAttribute(t):e.setAttribute(t,t==`popover`&&n==1?``:n))}}function F(e){return function(n){if(this.l){var r=this.l[n.type+e];if(n[c]==null)n[c]=d++;else if(n[c]0?e:_(e)?e.map(L):e.constructor===void 0?v({},e):null}function R(n,r,i,a,o,s,c,l,u){var d,f,p,h,g,v,b,x=i.props||m,S=r.props,C=r.type;if(C==`svg`?o=`http://www.w3.org/2000/svg`:C==`math`?o=`http://www.w3.org/1998/Math/MathML`:o||=`http://www.w3.org/1999/xhtml`,s!=null){for(d=0;de.toString(16).padStart(2,`0`));return`${n.slice(0,4).join(``)}-${n.slice(4,6).join(``)}-${n.slice(6,8).join(``)}-${n.slice(8,10).join(``)}-${n.slice(10).join(``)}`}var ae=15e3;function V(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 oe(e){try{let t=(await e.text()).trim();if(t)return t.split(` +`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var se=class extends Error{constructor(e,t){super(e),this.status=t}};function ce(e){let t=e instanceof se?e.status:void 0,n=e?.message||`Action failed`;return t===401?{kind:`session-expired`,message:n}:t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function le(e,t){let n=await fetch(e,t);if(!n.ok)throw new se(await oe(n),n.status);return n}async function H(e,{method:t=`GET`,body:n,timeoutMs:r=ae,parse:i=!0}={}){let a={Accept:`application/json`},o={method:t,headers:a,signal:AbortSignal.timeout(r)};t!==`GET`&&(a[`Content-Type`]=`application/json`,a[`X-Archie-CSRF`]=`1`),n!==void 0&&(o.body=JSON.stringify(n));let s=await le(e,o);return i?s.json():void 0}var U={summary:()=>H(`/api/summary`),tasks:()=>H(`/api/tasks`),taskMeta:()=>H(`/api/task-meta`),task:e=>H(`/api/tasks/${e}`),taskAttempts:e=>H(`/api/tasks/${e}/attempts`),taskChanges:(e,t)=>H(`/api/tasks/${e}/changes`+V(t)),taskDebug:(e,t)=>H(`/api/tasks/${e}/debug`+V(t)),taskAction:(e,t)=>H(`/api/tasks/${e}/action`,{method:`POST`,body:{action:t}}),setup:()=>H(`/api/setup`),capabilities:()=>H(`/api/capabilities`),workflows:()=>H(`/api/workflows`),workRequest:e=>H(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>H(`/api/skills`),channels:()=>H(`/api/channels`),curators:()=>H(`/api/curators`),channelReload:e=>H(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>H(`/api/config`),version:()=>H(`/api/version`),configUpdate:e=>H(`/api/config`,{method:`PATCH`,body:{updates:e}}),configRepoUpdate:(e,t,n,r)=>H(`/api/config/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{method:`PATCH`,body:{field:n,value:r}}),configReset:e=>H(`/api/config/reset`,{method:`POST`,body:{key:e}}),logs:e=>H(`/api/logs`+V(e)),taskLogs:(e,t)=>H(`/api/tasks/${e}/logs`+V(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>H(`/api/captures`+V({limit:e})),mappings:()=>H(`/api/mappings`),mappingCreate:e=>H(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>H(`/api/mappings/${e}`,{method:`PATCH`,body:t}),mappingDelete:e=>H(`/api/mappings/${e}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>H(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>H(`/api/bindings`),bindingCreate:e=>H(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>H(`/api/bindings/${e}`,{method:`PATCH`,body:t}),bindingDelete:e=>H(`/api/bindings/${e}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>H(`/api/bindings/${e}/approve`,{method:`POST`}),memory:()=>H(`/api/memory`),chatSessions:()=>H(`/api/chat/sessions`),chatMessages:e=>H(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>H(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>H(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>H(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:ie(),text:t,page:location.hash.slice(1)||`/`}}),chatPersona:(e,t)=>H(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatUpdate:()=>H(`/api/chat/update`),chatUpdateDefer:e=>H(`/api/chat/update/defer`,{method:`POST`,body:{snapshot:e}}),chatUpdateInstall:e=>H(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:12e4}),chatDangerous:()=>H(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>H(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>H(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,{signal:t}={})=>le(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t})};function ue(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 de(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 fe(e,t){return e?t.filter(t=>t.section&&e[t.section]===!1).map(e=>e.path):[]}var pe=[{id:`queued`,label:`Queued`,kind:`idle`},{id:`running`,label:`Working`,kind:`info`},{id:`waiting_human`,label:`Waiting for you`,kind:`warn`,needs_you:!0},{id:`pr_open`,label:`In review`,kind:`ok`},{id:`merged`,label:`Merged`,kind:`ok`},{id:`parked`,label:`Parked`,kind:`warn`,needs_you:!0},{id:`dead`,label:`Stopped (too many retries)`,kind:`danger`},{id:`rejected`,label:`Rejected`,kind:`danger`},{id:`closed_wont_do`,label:`Won't do`,kind:`idle`}],me=[{id:`cancel`,label:`Cancel`,kind:`quiet`,confirm:`Cancel "{title}"? This closes the forge issue.`},{id:`stop`,label:`Stop`,kind:`primary`,confirm:`Stop "{title}"? Recoverable work will remain parked.`},{id:`approve`,label:`Approve`,kind:`primary`},{id:`reject`,label:`Reject`,kind:`quiet`,confirm:`Reject "{title}"? This closes the forge issue.`},{id:`retry`,label:`Retry`,kind:`primary`},{id:`abandon`,label:`Abandon`,kind:`quiet`,confirm:`Abandon "{title}"? This closes the forge issue.`},{id:`archive`,label:`Archive`,kind:`quiet`,confirm:`Archive the local record for "{title}"?`},{id:`open_pr`,label:`Open PR`,kind:`link`},{id:`open_issue`,label:`Open issue`,kind:`link`}],he=[...pe],ge=[...me],_e=new Map(he.map(e=>[e.id,e])),ve=new Map(ge.map(e=>[e.id,e]));function ye(e){return _e.get(e)?.label||e||`Unknown`}function be(e){return _e.get(e)?.kind||`idle`}function xe(){return he.map(e=>e.id)}function Se(){return new Set(he.filter(e=>e.needs_you).map(e=>e.id))}function Ce(e){return ve.get(e)||null}function W(e,t,...n){let[r,...i]=e.split(`.`),a=document.createElement(r||`div`);i.length&&(a.className=i.join(` `)),t!==void 0&&(typeof t!=`object`||t instanceof Node)&&(n.unshift(t),t=null);for(let[e,n]of Object.entries(t||{}))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?a.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?a.className=[a.className,n].filter(Boolean).join(` `):e===`html`?a.innerHTML=n:a.setAttribute(e,n===!0?``:String(n)));return we(a,n),a}function we(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 Te(e,...t){return e.replaceChildren(),we(e,t),e}function Ee(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 De(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}var Oe={dashboard:``,chat:``,tasks:``,logs:``,skills:``,workflows:``,memory:``,channels:``,curators:``,captures:``,mappings:``,bindings:``,settings:``,search:``,moon:``,sun:``,refresh:``,bell:``,trendUp:``,trendDown:``,check:``,close:``,help:``};function G(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=Oe[e]||Oe.dashboard,r}var ke,K,Ae,je,Me=0,Ne=[],q=t,Pe=q.__b,Fe=q.__r,Ie=q.diffed,Le=q.__c,Re=q.unmount,ze=q.__;function Be(e,t){q.__h&&q.__h(K,e,Me||t),Me=0;var n=K.__H||(K.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function J(e){return Me=1,Ve(Ye,e)}function Ve(e,t,n){var r=Be(ke++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Ye(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=K,!K.__f)){var i=function(e,t,n){if(!r.__c.__H)return!0;var i=!1,o=r.__c.props!==e;if(r.__c.__H.__.some(function(e){if(e.__N){i=!0;var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),a){var s=a.call(this,e,t,n);return i?s||o:s}return!i||o};K.__f=!0;var a=K.shouldComponentUpdate,o=K.componentWillUpdate;K.componentWillUpdate=function(e,t,n){if(this.__e){var r=a;a=void 0,i(e,t,n),a=r}o&&o.call(this,e,t,n)},K.shouldComponentUpdate=i}return r.__N||r.__}function Y(e,t){var n=Be(ke++,3);!q.__s&&Je(n.__H,t)&&(n.__=e,n.u=t,K.__H.__h.push(n))}function X(e){return Me=5,He(function(){return{current:e}},[])}function He(e,t){var n=Be(ke++,7);return Je(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}function Ue(){for(var e;e=Ne.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(Ke),t.__h.some(qe),t.__h=[]}catch(n){t.__h=[],q.__e(n,e.__v)}}}q.__b=function(e){K=null,Pe&&Pe(e)},q.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),ze&&ze(e,t)},q.__r=function(e){Fe&&Fe(e),ke=0;var t=(K=e.__c).__H;t&&(Ae===K?(t.__h=[],K.__h=[],t.__.some(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.some(Ke),t.__h.some(qe),t.__h=[],ke=0)),Ae=K},q.diffed=function(e){Ie&&Ie(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(Ne.push(t)!==1&&je===q.requestAnimationFrame||((je=q.requestAnimationFrame)||Ge)(Ue)),t.__H.__.some(function(e){e.u&&=(e.__H=e.u,void 0)})),Ae=K=null},q.__c=function(e,t){t.some(function(e){try{e.__h.some(Ke),e.__h=e.__h.filter(function(e){return!e.__||qe(e)})}catch(n){t.some(function(e){e.__h&&=[]}),t=[],q.__e(n,e.__v)}}),Le&&Le(e,t)},q.unmount=function(e){Re&&Re(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some(function(e){try{Ke(e)}catch(e){t=e}}),n.__H=void 0,t&&q.__e(t,n.__v))};var We=typeof requestAnimationFrame==`function`;function Ge(e){var t,n=function(){clearTimeout(r),We&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);We&&(t=requestAnimationFrame(n))}function Ke(e){var t=K,n=e.__c;typeof n==`function`&&(e.__c=void 0,n()),K=t}function qe(e){var t=K;e.__c=e.__(),K=t}function Je(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Ye(e,t){return typeof t==`function`?t(e):t}function Xe({label:e,value:t,unit:n,trend:r,compare:i,series:a=[],goodDirection:o=`up`}){let s=r==null?null:r>=0?`up`:`down`,c=s==null?null:s===o;return W(`div.card.stat`,W(`div.stat-head`,W(`span.stat-label`,e),s&&W(`span.stat-trend.${c?`up`:`down`}`,G(s===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(r).toFixed(1)}%`)),W(`div.stat-value`,t,n&&W(`span.stat-unit`,n)),i&&W(`div.stat-compare`,i),a.length>1&&Ze(a,c===!1?`var(--danger)`:`var(--ok)`))}function Ze(e,t=`var(--ok)`,{width:n=220,height:r=34}={}){let i=Math.max(...e,1),a=Math.min(...e,0),o=i-a||1,s=e.length>1?n/(e.length-1):n,c=e.map((e,t)=>`${(t*s).toFixed(1)},${(r-(e-a)/o*r).toFixed(1)}`).join(` `),l=W(`svg.spark`,{viewBox:`0 0 ${n} ${r}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return l.innerHTML=``,l}function Qe({value:e,label:t,size:n=168}){let r=Math.max(0,Math.min(100,Number(e)||0)),i=r>=90?`var(--ok)`:r>=70?`var(--warn)`:`var(--danger)`,a=n/2,o=n/2,s=2*Math.PI*62*(240/360),c=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${a+62*Math.cos(n)} ${o+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${a+62*Math.cos(r)} ${o+62*Math.sin(r)}`].join(` `)},l=W(`svg.gauge`,{viewBox:`0 0 ${n} ${n*.78}`,role:`img`,"aria-label":`${t}: ${r}%`});return l.innerHTML=` `,U(`div.gauge-wrap`,l,U(`div.gauge-center`,U(`div.gauge-pct`,`${Math.round(r)}%`),U(`div.gauge-label`,t)))}function et(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return U(`div`,U(`div.segbar`,...e.filter(e=>e.value>0).map(e=>U(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),U(`div.segbar-legend`,...e.map(e=>U(`span.segbar-key`,U(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var tt=0;Array.isArray;function X(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--tt,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function Z({text:e,kind:t=`idle`}){return X(`span`,{className:`pill pill-${t}`,children:e})}var nt=`archie.setup-complete.dismissed.v1`;function rt(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?.(nt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function it(e=globalThis.localStorage){e?.setItem?.(nt,`1`)}var at=new Set([`waiting_human`,`parked`]);function ot(e=[]){let t=e.filter(e=>at.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 st({node:e}){let t=Y();return J(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function ct(e){return X(st,{node:Ze(e)})}function lt(e){return X(st,{node:$e(e)})}function ut({segments:e}){return X(st,{node:et(e)})}function dt({name:e,opts:t}){return X(st,{node:W(e,t)})}function ft({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pt(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 mt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function ht(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 gt(){let[e,t]=q([]),[n,r]=q(`connecting`),[i,a]=q(`idle`),[o,s]=q(new Map),[c,l]=q(null),[u,d]=q(null),[f,p]=q(null),[m,h]=q(null),[g,_]=q(null),[,v]=q(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([B.summary(),B.setup().catch(()=>null),B.workflows().catch(()=>null),B.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};J(()=>(y(),V(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{it(),v(e=>!e)},x=u?.operator?`${mt()}, ${u.operator}`:mt(),C=null;if(g)C=X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=ot(m),t=e.attention.count,n=e.running.count;C=X(S,{children:[t>0&&X(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[X(dt,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&X(`a`,{className:`btn`,href:e.running.href,children:[X(dt,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),X(`a`,{className:`btn`,href:`#/logs`,children:[X(dt,{name:`logs`,opts:{size:15}}),` Logs`]}),X(`button`,{className:`btn btn-primary`,onClick:y,children:[X(dt,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=X(`div`,{className:`card`,children:X(ft,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=X(S,{children:[X(ct,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),X(ct,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(ct,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),X(ct,{label:`Tokens used`,value:Oe(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:ht(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=rt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=X(`div`,{className:`card setup`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Finish setting up`}),X(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),X(`span`,{className:`setup-pct`,children:[t,`%`]})]}),X(`div`,{className:`setup-bar`,children:X(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),X(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>X(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[X(`span`,{className:`setup-check`,children:e.done?X(dt,{name:`check`,opts:{size:12}}):``}),X(`div`,{children:[X(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&X(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=X(`div`,{className:`card setup setup-done`,children:X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Setup complete`}),X(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),X(`div`,{className:`setup-complete-actions`,children:[X(`span`,{className:`setup-pct`,children:X(dt,{name:`check`,opts:{size:16}})}),X(`button`,{className:`icon-btn setup-dismiss`,type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onClick:b,children:`×`})]})]})})}let O=null;if(c){let e=f?.workflows||[],t=e.reduce((e,t)=>e+(t.runs||0),0),n=e.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),r=e.reduce((e,t)=>e+(t.parked||0),0);if(!t)O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Gate pulse`})}),X(ft,{title:`No completed runs yet`,detail:`Once Archie finishes a task, its gate pass rate appears here.`})]});else{let i=n/t*100;O=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Gate pulse`}),X(`p`,{className:`card-sub`,children:`Work that passed its quality gates`})]})}),X(lt,{value:i,label:`pass rate`}),X(`ul`,{className:`pulse-list`,children:[e.slice(0,3).map((e,t)=>X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:e.workflow||`workflow`}),X(Z,{text:`${e.merged||0}/${e.runs||0}`,kind:(e.merged||0)===(e.runs||0)?`ok`:(e.parked||0)>0?`warn`:`info`})]},t)),r>0&&X(`li`,{className:`pulse-item`,children:[X(`span`,{className:`pulse-name`,children:`Parked, awaiting you`}),X(Z,{text:String(r),kind:`warn`})]})]})]})}}let k=null;if(c){let e=c?.tokens_by_day||[],t=e.reduce((e,t)=>e+(t.tokens||0),0);if(!e.length)k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`h2`,{className:`card-title`,children:`Token outlook`})}),X(ft,{title:`Nothing spent yet`,detail:`Usage appears here once Archie runs its first task.`})]});else{let n=t/e.length,r=Math.round(n*30),i=e.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);k=X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Token outlook`}),X(`p`,{className:`card-sub`,children:`Next 30 days at the current rate`})]})}),X(`div`,{className:`forecast-value`,children:Oe(r)}),X(`div`,{className:`forecast-note`,children:[`Based on `,Oe(Math.round(n)),` per day over `,e.length,` days`]}),X(ut,{segments:[{label:`Last 7 days (${Oe(i)})`,value:i,kind:`info`},{label:`Earlier (${Oe(t-i)})`,value:Math.max(t-i,0),kind:`idle`}]})]})}}return X(S,{children:[X(`div`,{className:`hero`,children:[X(`div`,{children:[X(`h1`,{className:`hero-title`,children:x}),X(`p`,{className:`hero-sub`,children:`Your agent's control room — what it is working on, what needs you, and what it is spending.`})]}),X(`div`,{className:`hero-actions`,children:X(`div`,{className:`hero-actions-inner`,children:C})})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Health`})}),X(`div`,{className:`dash-top ${D?`dash-top-standalone`:``}`,children:[X(`div`,{children:T}),X(`div`,{children:O})]})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:[X(`h2`,{className:`dash-section-title`,children:`Throughput`}),X(`span`,{className:`dash-section-note`,children:`Across all repositories`})]}),X(`div`,{className:`grid grid-4`,children:w})]}),X(`div`,{className:`dash-section`,children:[X(`div`,{className:`dash-section-head`,children:X(`h2`,{className:`dash-section-title`,children:`Right now`})}),X(`div`,{className:`dash-split`,children:[X(`div`,{children:k}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`Live activity`}),X(`p`,{className:`card-sub`,children:`Last 50, newest first`})]}),X(Z,{text:n,kind:i})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Event`}),X(`th`,{children:`Task`}),X(`th`,{children:`Detail`}),X(`th`,{children:`When`})]})}),X(`tbody`,{children:e.length?e.map((e,t)=>{let n=pt(e,o),r=n>0,i=()=>{r&&(location.hash=`#/tasks?task=${encodeURIComponent(n)}`)};return X(`tr`,{className:r?`activity-row`:``,role:r?`link`:void 0,tabIndex:r?`0`:void 0,title:r?`Open task details`:void 0,onClick:r?i:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[X(`td`,{className:`strong`,children:X(`span`,{children:e.kind||e.type||`event`})}),X(`td`,{className:`mono`,children:r?`#${n}`:`—`}),X(`td`,{children:e.detail||e.message||``}),X(`td`,{children:De(e.at||Date.now())})]},t)}):X(`tr`,{children:X(`td`,{colSpan:`4`,children:X(ft,{title:`Waiting for activity`,detail:`Events appear here as Archie works.`})})})})]})})]})]})]})]})}function _t(){return X(gt,{})}function vt(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 yt=H(),bt=new Set([`needs_you`,...Ce()]);function xt(e){let t=e?.get?.(`status`)||``;return bt.has(t)?t:``}function St(e,t){return t?t===`needs_you`?yt.has(e.status):e.status===t:!0}function Ct(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function wt(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function Tt(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function Et(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=wt(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,t.error].filter(Boolean).join(` — `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[t.previous_stage&&`after ${t.previous_stage}`,t.previous_reason].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=Tt(t.iterations),i=Tt(t.tokens),a=Number(t.cached_tokens)||0,o=Tt((Number(t.prompt_tokens)||0)-a),s=Tt(t.completion_tokens),c=Tt(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}return{title:Ct(e.kind||e.type),detail:e.detail||``}}function Dt(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ot(e){let t=e.fields||{};return U(`div.log-row.log-${Dt(e.level)}`,U(`span.log-time.mono`,At(e.time)),U(`span.log-level`,(e.level||`info`).toUpperCase()),U(`span.log-body`,U(`span.log-msg`,e.message||e.msg||``),...Object.entries(t).map(([e,t])=>U(`span.log-field`,U(`span.log-field-key`,e),String(kt(t))))))}function kt(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function At(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jt({entry:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(Ot(e))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Mt(e,t){return`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`)}function Nt({state:e,onRetry:t,taskId:n}){if(e===void 0)return X(`div`,{className:`task-log-loading`,children:`Loading attempt log…`});if(e===null)return X(`div`,{className:`task-log-error`,children:[X(`div`,{className:`task-timeline-detail`,children:`Could not load this attempt's log.`}),X(`button`,{className:`btn`,onClick:t,children:`Retry`})]});if(e.found===!1&&!e.disabled)return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No log recorded for this attempt`}),X(`div`,{children:`This attempt produced no output, or it has not started writing yet.`})]});if(e.disabled)return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`No persisted log for this attempt`}),X(`div`,{children:`This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.`})]});let r=e.entries||[],i=n==null?null:Mt(n,e.attempt),a=i?X(`a`,{className:`btn btn-small task-log-download`,href:i,download:!0,children:`Download log`}):null;return r.length?X(S,{children:[X(`div`,{className:`log-list task-log-list`,children:r.map((e,t)=>X(jt,{entry:e},t))}),a]}):X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:`Nothing recorded`}),X(`div`,{children:`This attempt's log file has no entries matching the current filter.`}),a]})}function Pt(e){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(Ze(e))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Ft({kind:e,message:t}){return e===`session-expired`?X(`span`,{className:`task-action-error task-action-error-session`,children:[`Your session has expired.`,` `,X(`button`,{className:`button btn btn-small`,type:`button`,onClick:()=>window.location.reload(),children:`Reload to sign in`})]}):e===`refused`?X(`span`,{className:`task-action-error task-action-error-refused`,children:[t,` — you can't do that.`]}):X(`span`,{className:`task-action-error task-action-error-broken`,children:[t,` — try again, or check the daemon.`]})}function It({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Lt({query:e}){let[t,n]=q(null),[r,i]=q(null),[a,o]=q(()=>xt(e)),[s,c]=q(``),l=Number(e.get(`task`)),u=Number.isFinite(l)&&l>0?l:null,[d,f]=q(u),[p,m]=q(u!==null),[h,g]=q(new Map),[_,v]=q(new Map),[y,b]=q(new Set),[x,C]=q(new Map),[w,T]=q(new Set),E=async()=>{try{i(null);let e=await B.tasks();n(e),d&&e.some(e=>String(e.id)===String(d))&&(h.has(d)||D(d))}catch(e){i(String(e.message||e)),n(null)}};J(()=>{E()},[]);let D=async e=>{try{let t=await B.task(e);g(n=>new Map(n).set(e,t||[]))}catch{g(t=>new Map(t).set(e,null))}},O=async e=>{v(t=>{let n=new Map(t);return n.delete(e),n});try{let t=await B.taskLogs(e,{limit:500});v(n=>new Map(n).set(e,t))}catch{v(t=>new Map(t).set(e,null))}},k=async(e,t)=>{C(t=>{let n=new Map(t);return n.delete(e),n}),T(t=>new Set(t).add(e));try{await B.taskAction(e,t),T(t=>{let n=new Set(t);return n.delete(e),n}),t===`archive`&&f(null),await E()}catch(t){T(t=>{let n=new Set(t);return n.delete(e),n}),C(n=>new Map(n).set(e,de(t)))}};J(()=>{p&&d&&t&&(m(!1),requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${d}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`center`,behavior:`smooth`}))}))},[p,d,t]);let A=(e,t)=>{t&&t.stopPropagation();let n=d!==e;f(n?e:null),n&&D(e)},j=e=>{b(t=>{let n=new Set(t);return n.has(e)?n.delete(e):(n.add(e),_.has(e)||O(e)),n})},ee=()=>{if(!t)return null;let e=t.length,n={};for(let e of t)n[e.status]=(n[e.status]||0)+1;let r=n.running||0,i=(n.waiting_human||0)+(n.parked||0),a=(n.merged||0)+(n.pr_open||0);return X(`div`,{className:`grid grid-4 task-summary`,children:[X(Pt,{label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),X(Pt,{label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),X(Pt,{label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),X(Pt,{label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`})]})},M=e=>{let t=x.get(e.id),n=t?Ft(t):null,r=w.has(e.id),i=e=>e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``,a=(e.actions||[]).map(t=>{let n=we(t);if(!n)return null;let a=e.title||`this task`,o=n.confirm?n.confirm.replaceAll(`{title}`,a):void 0,s=[`button`,`btn`,`btn-small`,i(n.kind)].filter(Boolean).join(` `);if(n.kind===`link`){if(t===`open_pr`)return N(e,`pull_request`,e.pr_number,n.label);if(t===`open_issue`)return N(e,`issue`,e.issue_number,n.label)}return X(`button`,{className:s,type:`button`,disabled:r,onClick:n=>{n.stopPropagation(),!(o&&!window.confirm(o))&&k(e.id,t)},children:n.label},t)}).filter(Boolean);return!a.length&&!n?`—`:X(`div`,{className:`task-actions`,children:[n,a]})},N=(e,t,n,r)=>{let i=t===`issue`?e.issue_url:e.pr_url;return!i||!n||t===`issue`&&e.source===`chat`?X(`button`,{className:`btn btn-small`,type:`button`,disabled:!0,title:`${r} is unavailable`,children:r}):X(`a`,{className:`btn btn-small`,href:i,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:r})},P=e=>{let t=e.repo_url;return t?X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open ${e.owner}/${e.repo} on the forge`,onClick:e=>e.stopPropagation(),children:[e.owner,`/`,e.repo]}):null},te=e=>{let t=e.issue_url;return e.source===`chat`||!t||!e.issue_number?null:X(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open issue #${e.issue_number} on the forge`,onClick:e=>e.stopPropagation(),children:[`#`,e.issue_number]})},ne=e=>{let t=h.get(e.id),n=y.has(e.id);return X(`tr`,{className:`task-timeline-row`,id:`task-timeline-${e.id}`,children:X(`td`,{colSpan:8,children:[X(`div`,{className:`task-detail-actions`,children:[X(`div`,{className:`task-decision-title`,children:`Available actions`}),M(e)]}),e.status===`waiting_human`&&e.plan&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Decision required`}),X(`div`,{className:`task-decision-plan`,children:e.plan})]}),e.status===`parked`&&e.park_reason&&X(`div`,{className:`task-decision`,children:[X(`div`,{className:`task-decision-title`,children:`Park reason`}),X(`div`,{className:`task-decision-plan`,children:e.park_reason})]}),t===void 0?X(`div`,{className:`task-timeline-loading`,children:`Loading timeline…`}):t===null?X(`div`,{className:`task-timeline-error`,children:[X(`div`,{className:`task-timeline-title`,children:`Could not load timeline`}),X(`div`,{className:`task-timeline-detail`,children:`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`}),X(`button`,{className:`btn`,onClick:()=>D(e.id),children:`Retry`})]}):t.length?X(`ul`,{className:`task-timeline`,children:t.map((e,t)=>{let n=Et(e);return X(`li`,{className:`task-timeline-entry`,children:[X(`span`,{className:`task-timeline-dot`}),X(`div`,{children:[X(`div`,{className:`task-timeline-kind`,children:n.title}),n.detail&&X(`div`,{className:`task-timeline-detail`,children:n.detail}),X(`div`,{className:`task-timeline-when`,children:De(e.at)})]})]},t)})}):X(It,{title:`No events yet`,detail:`This task has not recorded any transitions.`}),X(`div`,{className:`task-logs-section`,children:[X(`div`,{className:`task-decision-title`,children:[`Attempt log`,X(`button`,{className:`btn btn-small`,onClick:()=>j(e.id),style:{marginLeft:`10px`},children:n?`Hide`:`Show`})]}),n&&X(Nt,{state:_.get(e.id),taskId:e.id,onRetry:()=>O(e.id)})]})]})})};return X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Tasks`}),X(`p`,{className:`page-sub`,children:`Every issue archied has picked up, and where it stands.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:E,children:`Refresh`})})]}),r?X(`div`,{className:`grid grid-4 task-summary`,children:X(`div`,{className:`card`,children:X(It,{title:`Cannot reach archied`,detail:r})})}):ee(),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:`All tasks`}),X(`p`,{className:`card-sub`,children:`Click a row for its timeline`})]}),X(`div`,{className:`task-filters`,children:[X(`input`,{className:`task-search`,type:`search`,placeholder:`Search by title or repo…`,value:s,onInput:e=>c(e.target.value.trim().toLowerCase())}),X(`select`,{className:`task-filter`,value:a,onChange:e=>o(e.target.value),children:[X(`option`,{value:``,children:`All statuses`}),X(`option`,{value:`needs_you`,children:`Needs you`}),Ce().map(e=>X(`option`,{value:e,children:xe(e)},e))]})]})]}),X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(e=>X(`th`,{children:e},e))})}),X(`tbody`,{children:(()=>{if(r)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(It,{title:`Cannot reach archied`,detail:r})})});if(!t)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(`div`,{className:`task-timeline-loading`,children:`Loading tasks...`})})});if(!t.length)return X(`tr`,{children:X(`td`,{colSpan:8,children:X(It,{title:`No tasks yet`,detail:`Tasks appear here once archied picks up an issue to work.`})})});let e=t.filter(e=>St(e,a)?!s||`${e.title} ${e.repo}`.toLowerCase().includes(s):!1);return e.length?e.map(e=>{let t=d===e.id,n=`task-timeline-${e.id}`;return X(S,{children:[X(`tr`,{className:`task-row`,id:`task-row-${e.id}`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),A(e.id,t))},onClick:t=>A(e.id,t),...vt(e,t),children:[X(`td`,{className:`mono`,"data-label":`Repository`,children:[X(`button`,{className:`task-expand`,type:`button`,"aria-expanded":String(t),"aria-controls":n,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${e.title||`untitled task`}`,onClick:t=>A(e.id,t),children:t?`−`:`+`}),P(e)??`${e.owner}/${e.repo}`]}),X(`td`,{className:`mono`,"data-label":`Issue`,children:te(e)??`#${e.issue_number}`}),X(`td`,{className:`strong`,"data-label":`Title`,children:e.title||`(untitled)`}),X(`td`,{"data-label":`Status`,children:X(Z,{text:xe(e.status),kind:Se(e.status)})}),X(`td`,{"data-label":`Workflow`,children:e.workflow||`—`}),X(`td`,{"data-label":`Stage`,children:e.stage||`—`}),X(`td`,{"data-label":`Last activity`,title:e.created_at?`Created ${De(e.created_at)}`:``,children:De(e.updated_at)}),X(`td`,{"data-label":`Actions`,children:M(e)})]}),t&&ne(e)]},e.id)}):X(`tr`,{children:X(`td`,{colSpan:8,children:X(It,{title:`No matching tasks`,detail:`Try a different search or status filter.`})})})})()})]})})]})]})}function Rt(e){return X(Lt,{query:e})}function zt({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Bt(e){return X(Vt,{query:e})}function Vt(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q(null),o=async()=>{try{let e=await B.skills();t(e?.skills||[]),a(null)}catch(e){t([]),a(String(e.message||e))}};J(()=>{o()},[]);let s=(e,t)=>!t||`${e.name} ${e.description}`.toLowerCase().includes(t),c=Ue(()=>e.filter(e=>s(e,n)),[e,n]);return X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Skills`}),X(`p`,{class:`page-sub`,children:`What Archie can do, in plain language.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:o,children:`Refresh`})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:[X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Catalogue`}),X(`p`,{class:`card-sub`,children:`Project, shared, and user-global skills`})]}),X(`input`,{class:`skill-search`,type:`search`,placeholder:`Search skills…`,onInput:e=>r(e.target.value.trim().toLowerCase())})]}),X(`div`,{class:`grid grid-2`,children:i?X(zt,{title:`Cannot reach archied`,detail:i}):e.length?c.length?c.map(e=>X(`div`,{class:`card skill-card`,children:[X(`div`,{class:`card-head`,children:[X(`h3`,{class:`card-title`,children:e.name||`Untitled skill`}),e.workflow&&X(Z,{text:e.workflow,kind:`info`})]}),X(`p`,{class:`skill-desc`,children:e.description||`No description provided.`}),X(`div`,{class:`skill-source`,children:e.source||`Unknown source`})]},e.name)):X(zt,{title:`No skills match`,detail:`Nothing found for "${n}".`}):X(zt,{title:`No skills discovered yet`,detail:`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`})})]})]})}var Ht={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function Ut(e){return Ht[e]?Ht[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function Wt(e,t){return t?Math.round(e/t*100):0}function Gt(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 Kt({title:e,detail:t}){return X(`div`,{class:`empty`,children:[X(`div`,{class:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function qt({fraction:e,kind:t=`ok`}){let n=Math.min(100,Math.max(0,e));return X(`div`,{class:`wf-bar`,children:X(`div`,{class:`wf-bar-fill wf-bar-${t}`,style:{width:`${n}%`}})})}function Jt(e){return X(Yt,{query:e})}function Yt(){let[e,t]=q([]),[n,r]=q([]),[i,a]=q([]),[o,s]=q(null),c=async()=>{try{let e=await B.workflows();t(e?.definitions||[]),r(e?.workflows||[]),a(e?.stages||[]),s(null)}catch(e){s(String(e.message||e))}};return J(()=>{c()},[]),X(`div`,{children:[X(`div`,{class:`page-head`,children:[X(`div`,{children:[X(`h1`,{class:`page-title`,children:`Workflows`}),X(`p`,{class:`page-sub`,children:`Run outcomes and spend per workflow, and where stages get stuck.`})]}),X(`div`,{class:`page-actions`,children:X(`button`,{class:`btn`,onClick:c,children:`Refresh`})})]}),X(Xt,{definitions:e}),o?X(`div`,{class:`card`,children:X(Kt,{title:`Cannot reach archied`,detail:o})}):X(S,{children:[X(Zt,{workflows:n,definitions:e}),X(Qt,{stages:i})]})]})}function Xt({definitions:e}){if(!e.length)return null;let t=e.filter(e=>e.enabled)[0]?.id||``,[n,r]=q(``),[i,a]=q(``),[o,s]=q(t),[c,l]=q(``),[u,d]=q(``),[f,p]=q(!1),[m,h]=q(``);return J(()=>{!o&&t&&s(t)},[t,o]),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Start work`}),X(`p`,{class:`card-sub`,children:`This enters Archie’s normal admitted task queue.`})]})}),X(`form`,{class:`wf-form`,onSubmit:async e=>{e.preventDefault(),p(!0),h(``);try{let e=await B.workRequest({identity:n,repository:i,workflow:o,title:c,instructions:u});h(`Queued task #${e.task_id}.`),r(``),a(``),s(t),l(``),d(``)}catch(e){h(String(e.message||e))}finally{p(!1)}},children:[X(`input`,{placeholder:`Identity`,required:!0,value:n,onInput:e=>r(e.target.value)}),X(`input`,{placeholder:`owner/repository`,required:!0,value:i,onInput:e=>a(e.target.value)}),X(`select`,{required:!0,value:o,onInput:e=>s(e.target.value),children:e.filter(e=>e.enabled).map(e=>X(`option`,{value:e.id,children:Ut(e.name||e.id)},e.id))}),X(`input`,{placeholder:`Short task title`,required:!0,value:c,onInput:e=>l(e.target.value)}),X(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3,value:u,onInput:e=>d(e.target.value)}),X(`button`,{class:`btn`,type:`submit`,disabled:f,children:`Start work`}),m&&X(`p`,{class:`card-sub`,children:m})]})]})}function Zt({workflows:e,definitions:t}){let n=new Map(e.map(e=>[e.workflow,e])),r=t.map(e=>({...e,...n.get(e.id)||{workflow:e.id,runs:0,merged:0}}));return r.length?X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Per workflow`}),X(`p`,{class:`card-sub`,children:`Success rate is merged tasks over all runs`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Origin`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Success rate`}),X(`th`,{children:`Avg tokens`}),X(`th`,{children:`Avg steps`})]})}),X(`tbody`,{children:r.map(e=>{let t=Wt(e.merged,e.runs);return X(`tr`,{children:[X(`td`,{class:`strong`,children:Ut(e.workflow)}),X(`td`,{class:`mono`,children:e.origin||`registry`}),X(`td`,{children:`${e.runs} run${e.runs===1?``:`s`}`}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[t,`%`,X(`span`,{class:`wf-rate-sub`,children:[e.merged,` of `,e.runs,` merged`]})]}),X(qt,{fraction:t,kind:t>=50?`ok`:`warn`})]}),X(`td`,{class:`mono`,children:e.avg_tokens?e.avg_tokens.toLocaleString():`—`}),X(`td`,{class:`mono`,children:e.avg_steps?e.avg_steps.toFixed(1):`—`})]},e.workflow)})})]})})]}):X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per workflow`})})}),X(Kt,{title:`No workflow runs yet`,detail:`Stats appear here once a task has run through a workflow.`})]})}function Qt({stages:e}){if(!e.length)return X(`div`,{class:`card wf-stage-card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:X(`h2`,{class:`card-title`,children:`Per stage`})})}),X(Kt,{title:`No stage data yet`,detail:`Stage timing and failures appear here once workflows have run.`})]});let t=Math.max(...e.map(e=>e.avg_ms||0),1),n=[...e].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),r=[...e].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);return X(`div`,{class:`grid grid-2 wf-stage-card`,children:[X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Slowest stages`}),X(`p`,{class:`card-sub`,children:`Average duration, this workflow's stages`})]})}),X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Runs`}),X(`th`,{children:`Avg duration`})]})}),X(`tbody`,{children:n.map((e,n)=>X(`tr`,{children:[X(`td`,{children:Ut(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:e.runs}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:Gt(e.avg_ms)}),X(qt,{fraction:Wt(e.avg_ms,t),kind:`info`})]})]},n))})]})})]}),X(`div`,{class:`card`,children:[X(`div`,{class:`card-head`,children:X(`div`,{children:[X(`h2`,{class:`card-title`,children:`Most failures`}),X(`p`,{class:`card-sub`,children:`Stages that error out, over their runs`})]})}),r.length?X(`div`,{class:`table-scroll`,children:X(`table`,{class:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Workflow`}),X(`th`,{children:`Stage`}),X(`th`,{children:`Failures`})]})}),X(`tbody`,{children:r.map((e,t)=>X(`tr`,{children:[X(`td`,{children:Ut(e.workflow)}),X(`td`,{class:`strong`,children:e.stage}),X(`td`,{children:[X(`div`,{class:`wf-rate`,children:[e.errors,` of `,e.runs]}),X(qt,{fraction:Wt(e.errors,e.runs),kind:`danger`})]})]},t))})]})}):X(Kt,{title:`No failures recorded`,detail:`Every stage has completed cleanly so far.`})]})]})}function $t({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function en(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function tn(){let[e,t]=q([]),[n,r]=q(null),i=async()=>{try{let e=await B.channels();t(e?.channels||[]),r(null)}catch(e){r(String(e.message||e))}};return J(()=>{i()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Channels`}),X(`p`,{className:`page-sub`,children:`The conversational front-ends Archie can be reached through.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:i,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:n?X($t,{title:`Cannot reach archied`,detail:n}):e.length===0?X($t,{title:`No channels configured`,detail:`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`}):e.map(e=>X(`div`,{className:`card channel-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Z,{text:e.state||(e.configured?`configured`:`stopped`),kind:en(e.state,e.configured)})]}),X(`p`,{className:`channel-desc`,children:e.description}),X(`p`,{className:`channel-detail`,children:e.detail}),e.reload_supported?X(`button`,{className:`btn`,onClick:async t=>{t.currentTarget.disabled=!0;try{await B.channelReload(e.id||e.name.toLowerCase()),await i()}catch{}finally{t.currentTarget&&(t.currentTarget.disabled=!1)}},children:`Reload`}):X(`p`,{className:`channel-detail`,children:`Reload requires a daemon restart for this adapter.`})]},e.id||e.name))})]})}function nn(e){return X(tn,{query:e})}function rn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function an(e){return X(on,{query:e})}function on({query:e}){let[t,n]=q([]),[r,i]=q(null),a=async()=>{try{let e=await B.curators();n(e?.curators||[]),i(null)}catch(e){i(String(e.message||e))}};return J(()=>{a()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Curators`}),X(`p`,{className:`page-sub`,children:`Background agents that maintain memory and skills: what ran, and why.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:a,children:`Refresh`})})]}),X(`div`,{className:`grid grid-2`,children:r?X(rn,{title:`Cannot reach archied`,detail:r}):t.length?t.map(e=>X(cn,{curator:e},e.name)):X(rn,{title:`No curators registered`,detail:`Curators are background agent loops that maintain memory and skills. None are registered on this daemon.`})})]})}function sn(e){switch(e){case`healthy`:return`ok`;case`degraded`:return`warn`;case`unhealthy`:return`danger`;default:return`idle`}}function cn({curator:e}){let t=e.recent_actions||[];return X(`div`,{className:`card curator-card`,children:[X(`div`,{className:`card-head`,children:[X(`h3`,{className:`card-title`,children:e.name}),X(Z,{text:e.health?.status||`unknown`,kind:sn(e.health?.status)})]}),e.health?.message&&X(`p`,{className:`curator-health-message`,children:e.health.message}),X(`p`,{className:`curator-meta`,children:e.last_run_at?`Last ran ${De(e.last_run_at)} · ${e.last_run_actions} action${e.last_run_actions===1?``:`s`}`:`Has not run yet`}),t.length?X(`ul`,{className:`curator-actions`,children:t.map((e,t)=>X(`li`,{className:`curator-action`,children:[X(`div`,{className:`curator-action-head`,children:[X(`span`,{className:`curator-action-type`,children:e.type||`action`}),X(`span`,{className:`curator-action-time`,children:De(e.at)})]}),e.detail&&X(`p`,{className:`curator-action-detail`,children:e.detail}),e.reason&&X(`p`,{className:`curator-action-reason`,children:[`Why: `,e.reason]})]},t))}):X(`p`,{className:`curator-meta`,children:`No recorded activity yet.`})]})}function ln(e){return e==null||e===``?`—`:String(e)}function un({label:e,value:t,opts:n}){let r=ln(t),[i,a]=q(!1),[o,s]=q(``),[c,l]=q(null),[u,d]=q(!1),[f,p]=q(!1),m=n?.key;if(!m)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n?.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let h=n.locked?.[m];if(h)return X(`div`,{className:`kv is-locked`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`span`,{className:`kv-note`,children:h})]});if(n.editable===!1)return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let g=n.overridden?.includes(m),_=()=>{s(String(n.raw??``)),l(null),a(!0)},v=async()=>{p(!0),l(null);try{await B.configReset(m),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{p(!1)}},y=async()=>{let e=dn(n.type,o);if(e.error){l(e.error);return}d(!0),l(null);try{await(n.save||(e=>B.configUpdate({[m]:e})))(e.value),a(!1),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{d(!1)}};if(i){let t=Y(null);J(()=>{t.current&&t.current.focus()},[]);let r=e=>{e.key===`Enter`&&(e.preventDefault(),y()),e.key===`Escape`&&a(!1)},i;return i=n.type===`bool`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:[X(`option`,{value:`true`,children:`true`}),X(`option`,{value:`false`,children:`false`})]}):n.type===`enum`?X(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:(n.options||[]).map(e=>X(`option`,{value:e,children:e},e))}):X(`input`,{className:`kv-input`,type:`text`,value:o,onInput:e=>s(e.target.value),onKeyDown:r,ref:t}),X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),i,X(`div`,{className:`kv-actions`,children:[X(`button`,{className:`kv-save`,type:`button`,onClick:y,disabled:u,children:`Save`}),X(`button`,{className:`kv-cancel`,type:`button`,onClick:()=>a(!1),disabled:u,children:`Cancel`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,title:n.hint,children:e}),X(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),X(`div`,{className:`kv-actions`,children:[g&&X(`span`,{className:`kv-flag`,title:`Set from the dashboard; this shadows the value in the config file`,children:`overridden`}),X(`button`,{className:`kv-btn`,type:`button`,title:`Edit ${e}`,onClick:_,children:`Edit`}),g&&X(`button`,{className:`kv-btn`,type:`button`,title:`Discard the dashboard value and fall back to the config file`,onClick:v,disabled:f,children:`Reset`})]}),c&&X(`span`,{className:`kv-note is-error`,children:c})]})}function dn(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 fn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function pn({sub:e,title:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:t||`Update status`}),X(`p`,{className:`card-sub`,children:e})]})}),n]})}var mn={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},hn={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function gn({components:e}){return!e||!e.length?X(pn,{sub:`How each component is deployed, and whether what's running matches what's installed.`,children:X(fn,{title:`No components reported`,detail:`The configured update-check command returned nothing.`})}):X(pn,{sub:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Component`}),X(`th`,{children:`Install type`}),X(`th`,{children:`Running`}),X(`th`,{children:`Latest available`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:e.map(e=>X(`tr`,{title:[`Installed claim: ${e.installed_claim||`unknown`}`,`Running: ${e.running_version||`not observed`}`,e.reference?`Reference: ${e.reference}`:null].filter(Boolean).join(` -`),children:[X(`td`,{className:`strong`,children:e.label||e.id}),X(`td`,{className:`mono`,children:e.install_type||`—`}),X(`td`,{className:`mono`,children:e.running_version||`—`}),X(`td`,{className:`mono`,children:e.latest_available||`—`}),X(`td`,{children:X(Z,{text:mn[e.status]||e.status,kind:hn[e.status]||`idle`})})]},e.id||e.label))})]})})})}function Q({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function $({title:e,sub:t,children:n}){return X(`div`,{className:`card cfg-section`,children:[X(`div`,{className:`card-head`,children:X(`div`,{children:[X(`h2`,{className:`card-title`,children:e}),X(`p`,{className:`card-sub`,children:t})]})}),n]})}function _n({origins:e}){return e?.length?X($,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:X(`div`,{className:`kv-list`,children:e.map((e,t)=>X(un,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):X($,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:X(Q,{title:`Source provenance is unavailable.`})})}function vn(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function yn({data:e,error:t}){if(t)return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:X(Q,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return X($,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?X(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??xe(e.id),n=e.kind??Se(e.id);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(Z,{text:t,kind:n})})]},e.id)})}):X(Q,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),X(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?X(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=vn(e.kind);return X(`div`,{className:`kv`,children:[X(`span`,{className:`kv-label`,children:e.id}),X(`span`,{className:`kv-value`,children:X(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):X(Q,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function bn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(!1),[o,s]=q(null),[c,l]=q(!!e[t]);return r?X(`td`,{children:[X(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await B.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{children:c?`yes`:`no`})}function xn({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=q(String(e[t]??0)),[o,s]=q(null),[c,l]=q(!1);return r?X(`td`,{children:[X(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await B.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&X(`span`,{className:`kv-note is-error`,children:o})]}):X(`td`,{className:`mono`,children:i})}function Sn({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return X($,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:X(Q,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return X($,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Repository`}),X(`th`,{children:`Base branch`}),X(`th`,{children:`Ecosystem`}),X(`th`,{children:`Quality gate`}),X(`th`,{children:`Protected paths`}),X(`th`,{children:`Concurrent`}),X(`th`,{children:`Max retries`}),X(`th`,{children:`Self-review`})]})}),X(`tbody`,{children:e.map((e,i)=>X(`tr`,{children:[X(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),X(`td`,{className:`mono`,children:e.base}),X(`td`,{children:e.ecosystem||`go`}),X(`td`,{className:`mono`,children:r(e.gate)}),X(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),X(bn,{r:e,field:`allow_concurrent`,onSaved:t,editable:n}),X(xn,{r:e,field:`max_retries`,onSaved:t,editable:n}),X(bn,{r:e,field:`review_enabled`,onSaved:t,editable:n})]},i))})]})})})}function Cn(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function wn({models:e,providers:t}){let n=Object.entries(e||{}),r=Object.entries(t||{});return X($,{title:`Models & providers`,sub:`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,children:[X(`h3`,{className:`cfg-subhead`,children:`Model roles`}),n.length?X(`div`,{className:`kv-list`,children:n.map(([e,t])=>X(un,{label:Cn(e),value:t},e))}):X(Q,{title:`No model roles configured`,detail:`Assign a model to at least one role (e.g. "builder") in [models].`}),X(`h3`,{className:`cfg-subhead`,children:`Providers`}),r.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[X(`th`,{children:`Provider`}),X(`th`,{children:`Class`}),X(`th`,{children:`Base URL`}),X(`th`,{children:`API key env var`}),X(`th`,{children:`Status`})]})}),X(`tbody`,{children:r.map(([e,t])=>X(`tr`,{children:[X(`td`,{className:`strong`,children:e}),X(`td`,{children:t.class}),X(`td`,{className:`mono`,children:t.base_url||`default`}),X(`td`,{className:`mono`,children:t.api_key_env||`—`}),X(`td`,{children:t.configured?X(Z,{text:`configured`,kind:`ok`}):X(Z,{text:`missing credentials`,kind:`warn`})})]},e))})]})}):X(Q,{title:`No providers configured`,detail:`Add a [providers.] entry so a model role above has something to run on.`})]})}function Tn(){let[e,t]=q(null),[n,r]=q(null),[i,a]=q(null),[o,s]=q(null),[c,l]=q(!1),[u,d]=q(null),[f,p]=q(null),m=()=>{h(),g(),_()},h=async()=>{try{let e=await B.config();t(e),r(null)}catch(e){r(String(e.message||e))}},g=async()=>{try{let e=await B.version();a(e?.components||[]),s(null),l(!1)}catch(e){e?.status===501?l(!0):s(String(e.message||e))}},_=async()=>{try{let e=await B.taskMeta();d(e),p(null)}catch(e){p(String(e.message||e))}};return J(()=>{m()},[]),X(`div`,{className:`cfg-page`,children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Configuration`}),X(`p`,{className:`page-sub`,children:`What archied is actually running with right now.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:m,children:`Refresh`})})]}),X(`div`,{children:!c&&(o?X(`div`,{className:`card`,children:X(Q,{title:`Update status unavailable`,detail:o})}):i?X(gn,{components:i}):null)}),X(`div`,{children:X(yn,{data:u,error:f})}),X(`div`,{children:n?X(`div`,{className:`card`,children:X(Q,{title:`Cannot reach archied`,detail:n})}):!e||Object.keys(e).length===0?X(`div`,{className:`card`,children:X(Q,{title:`No configuration loaded`,detail:`archied is running without a config file wired into the dashboard, so there is nothing to show.`})}):X(S,{children:[e.reload?.overlay_unavailable&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The runtime config overlay is not in effect: `,e.reload.overlay_unavailable]})}),e.reload?.last_error&&X(`div`,{className:`card cfg-notice`,children:X(`p`,{children:[`The last config reload failed; the running config is unchanged: `,e.reload.last_error]})}),(e.schema||[]).map((t,n)=>{let r=t.fields.filter(e=>e.type!==`structured`);return r.length?X($,{title:t.label,sub:t.description,children:X(`div`,{className:`kv-list`,children:r.map(t=>X(un,{label:t.label,value:t.value,opts:{key:t.key,type:t.type,options:t.options,raw:t.value,hint:t.description,editable:t.editable&&e.editable!==!1,locked:e.locked||{},overridden:e.overridden||[],onSaved:h}},t.key))})},n):null}),X(Sn,{repos:e.repositories,onSaved:h,editable:e.editable!==!1}),X(wn,{models:e.models,providers:e.providers}),X(_n,{origins:e.provenance})]})})]})}function En(e){return X(Tn,{query:e})}function Dn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function On(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function kn(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function An(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jn({entry:e}){let t=e.fields||{};return X(`div`,{className:`log-row log-${On(e.level)}`,children:[X(`span`,{className:`log-time mono`,children:An(e.time)}),X(`span`,{className:`log-level`,children:(e.level||`info`).toUpperCase()}),X(`span`,{className:`log-body`,children:[X(`span`,{className:`log-msg`,children:e.message||e.msg||``}),Object.entries(t).map(([e,t])=>X(`span`,{className:`log-field`,children:[X(`span`,{className:`log-field-key`,children:e}),String(kn(t))]},e))]})]})}var Mn=[{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 Nn(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Pn(){let[e,t]=q({level:``,component:``,q:``}),[n,r]=q(!1),[i,a]=q([]),[o,s]=q([]),c=Y(new Map),[l,u]=q(0),[d,f]=q(!1),[p,m]=q(`connecting`),[h,g]=q(`Refreshing…`),_=Y(null),v=Y(null),y=async()=>{g(`Refreshing…`);try{let t=await B.logs({level:e.level,component:e.component,q:e.q,limit:500});a(e=>{let n=t.components||[];return e.length===n.length&&e.every((e,t)=>e===n[t])?e:n}),f(!!t.disabled);let n=t.disabled?`Durable history unavailable; live daemon logs continue.`:t.truncated?`showing the most recent matches from ${t.file}`:t.file||``;g(n),s(t.entries||[])}catch{g(`Cannot read logs`)}};J(()=>{y()},[e]),J(()=>{let e=pe(e=>{if(b.current)return;let t=e;S.current(t)&&(c.current.set(Nn(t),t),t.fields?.component&&a(e=>e.includes(t.fields.component)?e:[...e,t.fields.component]),u(e=>e+1))},e=>{m(e)});return()=>e()},[]);let b=Y(n);b.current=n;let x=t=>{if(e.level&&!e.level.split(`,`).includes((t.level||``).toUpperCase())||e.component&&t.fields?.component!==e.component)return!1;if(e.q){let n=e.q.toLowerCase();if(!`${t.message||t.msg||``} ${JSON.stringify(t.fields||{})}`.toLowerCase().includes(n))return!1}return!0},S=Y(x);S.current=x;let C=Ue(()=>{let e=new Map;for(let t of o)e.set(Nn(t),t);for(let[t,n]of c.current)e.set(t,n);return[...e.values()].filter(x).slice(-1e3)},[o,l,e]);return J(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[C]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Logs`}),X(`p`,{className:`page-sub`,children:`What Archie has been doing, newest last.`})]}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn ${n?`btn-primary`:``}`,onClick:()=>r(!n),children:n?`Resume`:`Pause`}),X(`button`,{className:`btn`,onClick:y,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{className:`log-filters`,children:[X(`select`,{className:`log-select`,value:e.level,onChange:e=>t(t=>({...t,level:e.target.value})),children:Mn.map(e=>X(`option`,{value:e.value,children:e.label},e.value))}),X(`select`,{className:`log-select`,value:e.component,onChange:e=>t(t=>({...t,component:e.target.value})),children:[X(`option`,{value:``,children:`All components`}),i.map(e=>X(`option`,{value:e,children:e},e))]}),X(`input`,{className:`log-search`,type:`search`,placeholder:`Search messages and fields…`,onInput:e=>{let n=e.target.value;v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{t(e=>({...e,q:n}))},250)}})]}),X(`div`,{className:`log-status`,children:[X(`span`,{className:`log-meta`,children:h}),X(Z,{text:p,kind:p===`live`?`ok`:`warn`})]})]}),X(`div`,{className:`log-list`,ref:_,children:h===`Cannot read logs`?X(Dn,{title:`Cannot read logs`}):C.length?C.map(e=>X(jn,{entry:e},Nn(e))):X(Dn,{title:d?`Durable history unavailable`:`Nothing matches`,detail:d?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`})})]})]})}function Fn(e){return X(Pn,{query:e})}function In({capture:e,expanded:t,onToggle:n}){return X(S,{children:[X(`tr`,{className:`capture-row`,tabIndex:`0`,"aria-expanded":String(t),onClick:n,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n(e))},children:[X(`td`,{className:`mono`,children:e.source||`(unknown)`}),X(`td`,{title:e.received_at||``,children:De(e.received_at)}),X(`td`,{children:X(Z,{text:`Unbound`,kind:`idle`})}),X(`td`,{className:`mono`,children:e.content_type||`—`}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,children:t?`Hide`:`View`})})]}),t&&X(Ln,{capture:e})]})}function Ln({capture:e}){return X(`tr`,{className:`capture-detail-row`,children:X(`td`,{colSpan:`5`,children:X(`div`,{className:`capture-detail`,children:[X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Payload`}),X(Rn,{raw:e.body})]}),X(`div`,{className:`capture-detail-section`,children:[X(`div`,{className:`capture-detail-title`,children:`Headers`}),X(Rn,{raw:e.headers})]})]})})})}function Rn({raw:e}){return e?X(`pre`,{className:`capture-payload`,children:zn(e)}):X(`div`,{className:`capture-empty`,children:`(empty)`})}function zn(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function Bn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Vn(e){return X(Hn,{query:e})}function Hn({query:e}){let[t,n]=q([]),[r,i]=q(null),[a,o]=q(null),[s,c]=q(!0),[l,u]=q({text:`connecting`,kind:`idle`}),d=async()=>{try{let e=await B.captures(100);c(e.enabled!==!1),n(e.captures||[]),o(null)}catch(e){o(String(e.message||e))}};return J(()=>{d();let e=V(e=>{e.kind===`capture`&&d()},e=>{u({text:e,kind:e===`live`?`ok`:`warn`})});return()=>e()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Event inspector`}),X(`p`,{className:`page-sub`,children:`Real inbound payloads archie has captured, most recent first.`})]}),X(`div`,{className:`page-actions`,children:[X(Z,{text:l.text,kind:l.kind}),X(`button`,{className:`btn`,onClick:d,children:`Refresh`})]})]}),X(`div`,{className:`card`,children:a?X(Bn,{title:`Cannot reach archied`,detail:a}):s?t.length?X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Source`,`Received`,`Binding`,`Content type`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(In,{capture:e,expanded:r===e.id,onToggle:()=>i(r===e.id?null:e.id)},e.id))})]})}):X(Bn,{title:`No captures yet`,detail:`Point a webhook at /webhooks/capture/ and it will show up here.`}):X(Bn,{title:`Capture is not configured`,detail:`This deployment has no capture storage wired up.`})})]})}var Un=[`string`,`number`,`bool`,`object`,`array`,`any`];function Wn(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 Gn(e,t){return e?`${e}.${t}`:t}function Kn(e,t){return`${e}[${t}]`}function qn({value:e,path:t=``,name:n=``,onPick:r}){return typeof e==`object`&&e?X(`ul`,{className:`mapping-tree-list`,children:(Array.isArray(e)?e.map((e,n)=>[String(n),e,Kn(t,n)]):Object.entries(e).map(([e,n])=>[e,n,Gn(t,e)])).map(([e,t,n])=>X(`li`,{className:`mapping-tree-item`,children:[X(`span`,{className:`mapping-tree-key`,onClick:i=>{i.stopPropagation(),r&&r({path:n,type:Wn(t),name:e})},children:e}),X(qn,{value:t,path:n,name:e,onPick:r})]},n))}):X(`span`,{className:`mapping-tree-value`,onClick:i=>{i.stopPropagation(),r&&r({path:t,type:Wn(e),name:n})},children:JSON.stringify(e)})}function Jn({fields:e,preview:t,onRemove:n,onNameChange:r,onTypeChange:i,onRequiredChange:a}){if(!e.length)return X(`div`,{className:`mapping-empty-fields`,children:`Click a value in the payload to bind a field.`});let o=new Map((t?.failures||[]).map(e=>[e.field_name,e]));return X(`table`,{className:`table mapping-fields-table`,children:[X(`thead`,{children:X(`tr`,{children:[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:e.map((e,s)=>X(`tr`,{children:[X(`td`,{children:X(`input`,{className:`mapping-input`,value:e.name,onInput:e=>r?.(s,e.target.value)})}),X(`td`,{className:`mono`,children:e.path}),X(`td`,{children:X(`select`,{className:`mapping-select`,value:e.type,onChange:e=>i?.(s,e.target.value),children:Un.map(e=>X(`option`,{value:e,children:e},e))})}),X(`td`,{children:X(`input`,{type:`checkbox`,checked:e.required,onChange:e=>a?.(s,e.target.checked)})}),X(`td`,{children:X(Yn,{field:e,preview:t,failureByField:o})}),X(`td`,{children:X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(s),children:`Remove`})})]},s))})]})}function Yn({field:e,preview:t,failureByField:n}){if(!t)return X(Z,{text:`not previewed`,kind:`idle`});let r=n.get(e.name);return r?X(Z,{text:r.reason,kind:`danger`}):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?X(Z,{text:JSON.stringify(t.values[e.name]),kind:`ok`}):X(Z,{text:`skipped (optional)`,kind:`idle`})}function Xn({mapping:e,onEdit:t,onDelete:n}){return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.source_hint||`—`}),X(`td`,{children:String(e.fields?.length??0)}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(e),children:`Delete`})]})]})}function Zn({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function Qn(e){return X($n,{query:e})}function $n({query:e}){let[t,n]=q([]),[r,i]=q([]),[a,o]=q(null),[s,c]=q(null),l=async()=>{try{let[e,t]=await Promise.all([B.mappings(),B.captures(100)]);n(e.mappings||[]),i(t.captures||[]),o(null)}catch(e){o(String(e.message||e))}};J(()=>{l()},[]);let u=()=>{c({id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},d=e=>{c({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})},f=async e=>{if(window.confirm(`Delete mapping "${e.name}"?`))try{await B.mappingDelete(e.id),await l()}catch(e){o(String(e.message||e))}},p=e=>{let t=r.find(t=>String(t.id)===String(e));c(e=>{let n={...e,captureId:t?t.id:null,preview:null};if(!t)n.payload=null,n.payloadError=null;else try{n.payload=JSON.parse(t.body),n.payloadError=null}catch{n.payload=null,n.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}return n})},m=({path:e,type:t,name:n})=>{c(r=>{let i=new Set(r.fields.map(e=>e.name)),a=n||`field`,o=1;for(;i.has(a);)a=`${n||`field`}_${++o}`;let s=[...r.fields,{name:a,path:e,type:t,required:!0}];return{...r,fields:s,preview:null}})},h=e=>{c(t=>{let n=t.fields.slice();return n.splice(e,1),{...t,fields:n,preview:null}})},g=(e,t)=>{c(n=>{let r=n.fields.slice();return r[e]={...r[e],...t},{...n,fields:r,preview:null}})};return s?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:s.id?`Edit mapping`:`New mapping`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>{c(null)},children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:async()=>{let e={name:s.name,source_hint:s.sourceHint,fields:s.fields};try{s.id?await B.mappingUpdate(s.id,e):await B.mappingCreate(e),c(null),await l()}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Save`})]})]}),s.actionError&&X(`div`,{className:`mapping-error`,children:s.actionError}),X(`div`,{className:`card mapping-form`,children:[X(`label`,{className:`mapping-form-row`,children:[`Name`,X(`input`,{className:`mapping-input`,value:s.name,onInput:e=>c(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Source hint (organisational only)`,X(`input`,{className:`mapping-input`,value:s.sourceHint,onInput:e=>c(t=>({...t,sourceHint:e.target.value}))})]}),X(`label`,{className:`mapping-form-row`,children:[`Preview against captured event`,X(`select`,{className:`mapping-select`,value:s.captureId||``,onChange:e=>p(e.target.value),children:[X(`option`,{value:``,children:`— pick a captured event —`}),r.map(e=>X(`option`,{value:e.id,children:[e.source||`(unknown)`,` — `,e.received_at||``]},e.id))]})]})]}),X(`div`,{className:`card mapping-fields`,children:[X(`div`,{className:`mapping-section-title`,children:`Bound fields`}),X(Jn,{fields:s.fields,preview:s.preview,onRemove:h,onNameChange:(e,t)=>g(e,{name:t}),onTypeChange:(e,t)=>g(e,{type:t}),onRequiredChange:(e,t)=>g(e,{required:t})}),X(`button`,{className:`btn`,type:`button`,onClick:async()=>{if(!s.captureId){c(e=>({...e,actionError:`Pick a captured event to preview against.`}));return}try{let e=await B.mappingPreview(s.captureId,s.fields);c(t=>({...t,preview:e,actionError:null}))}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Preview`})]}),X(`div`,{className:`card mapping-payload`,children:[X(`div`,{className:`mapping-section-title`,children:`Payload — click a value to bind it`}),s.payloadError?X(`div`,{className:`mapping-error`,children:s.payloadError}):s.payload===null?X(`div`,{className:`mapping-empty-fields`,children:`Pick a captured event above to see its payload.`}):X(qn,{value:s.payload,onPick:m})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Field mappings`}),X(`p`,{className:`page-sub`,children:`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:u,children:`New mapping`})})]}),a?X(Zn,{title:`Cannot reach archied`,detail:a}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source hint`,`Fields`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(Xn,{mapping:e,onEdit:()=>d(e),onDelete:()=>f(e)},e.id))})]})})}):X(Zn,{title:`No mappings yet`,detail:`Create one from a captured event to reuse fields in a future playbook binding.`})]})}var er={draft:`draft`,pending_approval:`pending approval`,armed:`armed`},tr={draft:`idle`,pending_approval:`warn`,armed:`ok`};function nr({status:e}){return X(Z,{text:er[e]||e,kind:tr[e]||`idle`})}function rr({binding:e,onEdit:t,onApprove:n,onDelete:r}){let i=e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`;return X(`tr`,{children:[X(`td`,{children:e.name}),X(`td`,{className:`mono`,children:e.matcher?.source||`—`}),X(`td`,{children:e.workflow}),X(`td`,{className:`mono`,children:i}),X(`td`,{children:X(nr,{status:e.status})}),X(`td`,{children:[X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),e.status===`pending_approval`&&X(`button`,{className:`btn btn-small btn-primary`,type:`button`,onClick:()=>n?.(e),children:`Approve`}),X(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>r?.(e),children:`Delete`})]})]})}function ir({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function ar(e){return X(sr,{query:e})}function or(){return{id:null,name:``,source:``,mappingId:``,workflow:``,owner:``,repo:``,secret:``,actionError:null}}function sr({query:e}){let[t,n]=q([]),[r,i]=q([]),[a,o]=q([]),[s,c]=q(null),[l,u]=q(null),d=async()=>{try{let[e,t,r]=await Promise.all([B.bindings(),B.mappings(),B.workflows()]);n(e.bindings||[]),i(t.mappings||[]),o((r.definitions||[]).filter(e=>e.enabled)),c(null)}catch(e){c(String(e.message||e))}};J(()=>{d()},[]);let f=()=>{u(or())},p=e=>{u({id:e.id,name:e.name,source:e.matcher?.source||``,mappingId:e.mapping_id?String(e.mapping_id):``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,secret:``,actionError:null})},m=()=>u(null),h=async()=>{let e={name:l.name,matcher:{source:l.source},mapping_id:Number(l.mappingId)||0,workflow:l.workflow,owner:l.owner,repo:l.repo,secret:l.secret};try{l.id?await B.bindingUpdate(l.id,e):await B.bindingCreate(e),u(null),await d()}catch(e){u(t=>({...t,actionError:String(e.message||e)}))}},g=async e=>{try{await B.bindingApprove(e.id),await d()}catch(e){c(String(e.message||e))}},_=async e=>{if(window.confirm(`Delete binding "${e.name}"?`))try{await B.bindingDelete(e.id),await d()}catch(e){c(String(e.message||e))}};return l?X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:X(`h1`,{className:`page-title`,children:l.id?`Edit binding`:`New binding`})}),X(`div`,{className:`page-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:m,children:`Cancel`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:h,children:`Save`})]})]}),l.actionError&&X(`div`,{className:`binding-error`,children:l.actionError}),X(`div`,{className:`card binding-form`,children:[X(`label`,{className:`binding-form-row`,children:[`Name`,X(`input`,{className:`binding-input`,value:l.name,onInput:e=>u(t=>({...t,name:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Source (the path segment senders POST to, e.g. "sentry")`,X(`input`,{className:`binding-input`,value:l.source,onInput:e=>u(t=>({...t,source:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Field mapping`,X(`select`,{className:`binding-select`,value:l.mappingId,onChange:e=>u(t=>({...t,mappingId:e.target.value})),children:[X(`option`,{value:``,children:`— pick a saved mapping —`}),r.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Workflow`,X(`select`,{className:`binding-select`,value:l.workflow,onChange:e=>u(t=>({...t,workflow:e.target.value})),children:[X(`option`,{value:``,children:`— pick a workflow —`}),a.map(e=>X(`option`,{value:e.id,children:e.name},e.id))]})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- owner (optional; leave both blank for the single-configured-repo default)`,X(`input`,{className:`binding-input`,value:l.owner,onInput:e=>u(t=>({...t,owner:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Repo pin -- repo`,X(`input`,{className:`binding-input`,value:l.repo,onInput:e=>u(t=>({...t,repo:e.target.value}))})]}),X(`label`,{className:`binding-form-row`,children:[`Shared secret (`,l.id?`leave blank to keep the current secret`:`senders sign with this via HMAC-SHA256`,`)`,X(`input`,{className:`binding-input`,type:`password`,value:l.secret,onInput:e=>u(t=>({...t,secret:e.target.value}))})]})]})]}):X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Playbook bindings`}),X(`p`,{className:`page-sub`,children:`Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn btn-primary`,type:`button`,onClick:f,children:`New binding`})})]}),s?X(ir,{title:`Cannot reach archied`,detail:s}):t.length?X(`div`,{className:`card`,children:X(`div`,{className:`table-scroll`,children:X(`table`,{className:`table`,children:[X(`thead`,{children:X(`tr`,{children:[`Name`,`Source`,`Workflow`,`Repo pin`,`Status`,``].map((e,t)=>X(`th`,{children:e},t))})}),X(`tbody`,{children:t.map(e=>X(rr,{binding:e,onEdit:()=>p(e),onApprove:()=>g(e),onDelete:()=>_(e)},e.id))})]})})}):X(ir,{title:`No bindings yet`,detail:`Create one from a saved field mapping to turn a captured webhook into a workflow.`})]})}function cr({title:e,detail:t}){return X(`div`,{className:`empty`,children:[X(`div`,{className:`empty-title`,children:e}),t&&X(`div`,{children:t})]})}function lr(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}function ur({provider:e}){let t=e.tools||[];return X(`div`,{className:`card`,children:[X(`div`,{className:`card-head`,children:[X(`div`,{children:[X(`h2`,{className:`card-title`,children:e.name||`provider`}),X(`p`,{className:`card-sub`,children:lr(e.role)})]}),e.available?X(Z,{text:`ready`,kind:`ok`}):X(Z,{text:`unavailable`,kind:`danger`})]}),!e.available&&X(`p`,{className:`mem-warning`,children:`Configured but not usable right now — a required binary or connection may be missing.`}),t.length?X(`ul`,{className:`mem-tools`,children:t.map((e,t)=>X(`li`,{className:`mem-tool`,children:[X(`div`,{className:`mem-tool-name mono`,children:e.name}),e.description&&X(`div`,{className:`mem-tool-desc`,children:e.description})]},t))}):X(`p`,{className:`mem-warning`,children:`This provider exposes no tools, so the agent cannot use it.`})]})}function dr(){let[e,t]=q(null),[n,r]=q(!0),[i,a]=q(null),[o,s]=q(!0),c=async()=>{s(!0),a(null);try{let e=await B.memory();r(!!e.enabled),t(e.providers||[])}catch(e){a(String(e.message||e))}finally{s(!1)}};return J(()=>{c()},[]),X(`div`,{children:[X(`div`,{className:`page-head`,children:[X(`div`,{children:[X(`h1`,{className:`page-title`,children:`Memory`}),X(`p`,{className:`page-sub`,children:`What Archie can recall between conversations, and the tools it uses to do it.`})]}),X(`div`,{className:`page-actions`,children:X(`button`,{className:`btn`,onClick:c,children:`Refresh`})})]}),X(`div`,{children:o?X(`div`,{className:`card`,children:X(`div`,{className:`mem-loading`,children:`Loading…`})}):i?X(`div`,{className:`card`,children:X(cr,{title:`Cannot read memory providers`,detail:i})}):!n||!e.length?X(`div`,{className:`card`,children:X(cr,{title:`Memory is not configured`,detail:`Without a provider, Archie starts every conversation with no recollection of earlier ones.`})}):X(`div`,{className:`grid grid-2`,children:e.map((e,t)=>X(ur,{provider:e},t))})})]})}function fr(e){return X(dr,{query:e})}function pr(e){let t=document.createDocumentFragment(),n=/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g,r=0;for(let i of e.matchAll(n)){i.index>r&&t.append(document.createTextNode(e.slice(r,i.index)));let n=i[0];if(n.startsWith(`![`)){let e=n.match(/^!\[([^\]]*)\]\((.+)\)$/);e&&t.append(U(`img.chat-media-img`,{src:e[2],alt:e[1]||`Image`,loading:`lazy`}))}else if(n.startsWith(`~~`))t.append(U(`del`,n.slice(2,-2)));else if(n.startsWith(`**`)||n.startsWith(`__`))t.append(U(`strong`,n.slice(2,-2)));else if(n.startsWith("`"))t.append(U(`code`,n.slice(1,-1)));else if(n.startsWith(`[`)){let e=n.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);t.append(U(`a`,{href:e[2],target:`_blank`,rel:`noreferrer`},e[1]))}else t.append(U(`em`,n.slice(1,-1)));r=i.index+n.length}return r{r.length&&(t.append(U(`p`,pr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;eU(`td`,pr(e)))));t.append(U(`table`,U(`thead`,U(`tr`,...l.map(e=>U(`th`,pr(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(U(`h${d[1].length}`,pr(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=U(e)),i.append(U(`li`,pr((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(U(`blockquote`,pr(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(U(`pre`,U(`code`,a.join(` -`)))),t}function hr(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 gr(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var _r=`archie.web.chat.channel`;function vr(){let e=localStorage.getItem(_r);return e||(e=oe(),localStorage.setItem(_r,e)),e}function yr(e){return{text:e,sourceID:oe()}}function br(e){return{...e}}function xr(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?br(e.turn):yr(r),isRetry:n}}function Sr(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function Cr(e){return e?.status===501?null:`Could not check for updates.`}function wr(){return location.hash.slice(1)||`/`}function Tr({text:e}){let t=Y(null);return J(()=>{t.current&&t.current.replaceChildren(mr(e||``))},[e]),X(`div`,{ref:t,style:{display:`contents`}})}function Er(){let[e,t]=q([]),[n,r]=q(``),[i,a]=q([]),[o,s]=q(``),[c,l]=q(`Ready`),[u,d]=q(!1),[f,p]=q({}),[m,h]=q(``),[g,_]=q(``),[v,y]=q(``),[b,x]=q([]),[C,w]=q([]),[T,E]=q(0),[D,O]=q(!1),[k,A]=q(null),[j,ee]=q(null),[M,N]=q(null),[P,te]=q(``),[ne,re]=q(``),[F,I]=q(null),L=Y(null),R=Y(null),ie=Y(null),ae=Y(null),oe=Y(null),se=Y(u);se.current=u,J(()=>{L.current&&(L.current.scrollTop=L.current.scrollHeight)},[i,F]),J(()=>{V().catch(e=>{l(e.message||`Chat unavailable`)}),ce();let e=()=>{ie.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),ie.current?.abort()}},[]);async function ce(){try{let e=await B.chatUpdate();ee(e?.snapshot||null),A(e)}catch(e){let t=Cr(e);A(t?{error:t}:null)}}async function le(){if(j)try{await B.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function ue(){if(j)try{l(`Installing…`);let e=await B.chatUpdateInstall(j);ee(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function de(){try{let e=await B.chatDangerous();N(e)}catch(e){N({error:e.message||`Dangerous actions unavailable`})}}async function fe(e,t){if(t)try{await B.chatDangerousRequest(e,t),l(`Approval requested`),await de()}catch(e){l(e.message||`Could not request action`)}}async function z(e,t){try{await B.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await de()}catch(e){l(e.message||`Approval failed`)}}async function V(){let e=await B.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await de(),!n&&r[0]&&await pe(r[0].session_id,e,r)}async function pe(e,t,n){let i=t||f;r(e),a([]),I(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await B.chatMessage(vr(),`/resume ${e}`);let[t,n]=await Promise.all([B.chatMessages(e),B.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function me(e){if(n)try{l(`Working…`);let t=await B.chatMessage(vr(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await V(),(t.session_id||n)&&await pe(t.session_id||n),ae.current&&(ae.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function he(e,t){let n=window.prompt(t);n?.trim()&&me(`${e} ${n.trim()}`)}function ge(e){let t=e.target.value;h(t),!(!n||!t)&&B.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function _e(e){let t=e.target.value;if(_(t),t)try{let e=await B.chatMessage(vr(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await V()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ve(e){let t=e.target.value;if(y(t),t)try{let e=await B.chatMessage(vr(),`/model ${t}`);l(e.reply||`Model updated`),await V()}catch(e){l(`Model update failed: ${e.message||e}`)}}function ye(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),H({textOverride:`/restart`}))}function be(){s(`/new`),H({textOverride:`/new`})}function xe(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function Se(e){let t=C[e];if(!t||!R.current)return;let n=R.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function Ce(e){if(D&&C.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&C.some(e=>e.command===o.trim())){e.preventDefault(),O(!1),H();return}if(e.key===`ArrowDown`){e.preventDefault(),E(e=>(e+1)%C.length);return}if(e.key===`ArrowUp`){e.preventDefault(),E(e=>(e+C.length-1)%C.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),Se(T);return}if(e.key===`Escape`){e.preventDefault(),O(!1);return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),H())}async function H(e=null){let t=e?.textOverride,{text:n,turn:i,isRetry:c}=xr(e,t===void 0?o:t);if(!n||se.current)return;O(!1),d(!0),l(c?`Retrying…`:`Thinking…`),c||(a(e=>[...e,{from:`web`,text:n}]),s(``));let u=[];I({text:``,tools:[],isError:!1,turn:i,isRetry:c});let f=``,p=!1,m=!1,h=null;try{let e=new AbortController;ie.current=e,h=setTimeout(()=>{m=!0,e.abort()},12e4);let t=(await B.chatStream({channel_id:vr(),source_id:i.sourceID,text:i.text,page:wr()},{signal:e.signal})).body.getReader(),n=new TextDecoder,o=``;for(;;){let{value:e,done:i}=await t.read();o+=n.decode(e||new Uint8Array,{stream:!i});let a=o.split(` + class="gauge-value"/>`,W(`div.gauge-wrap`,l,W(`div.gauge-center`,W(`div.gauge-pct`,`${Math.round(r)}%`),W(`div.gauge-label`,t)))}function $e(e){let t=e.reduce((e,t)=>e+(t.value||0),0)||1;return W(`div`,W(`div.segbar`,...e.filter(e=>e.value>0).map(e=>W(`span`,{class:`segbar-part segbar-${e.kind||`idle`}`,style:`width:${(e.value/t*100).toFixed(1)}%`,title:`${e.label}: ${e.value}`}))),W(`div.segbar-legend`,...e.map(e=>W(`span.segbar-key`,W(`span`,{class:`segbar-dot segbar-${e.kind||`idle`}`}),e.label))))}var et=0;Array.isArray;function Z(e,n,r,i,a,o){n||={};var s,c,l=n;if(`ref`in l)for(c in l={},n)c==`ref`?s=n[c]:l[c]=n[c];var u={type:e,props:l,key:r,ref:s,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--et,__i:-1,__u:0,__source:a,__self:o};if(typeof e==`function`&&(s=e.defaultProps))for(c in s)l[c]===void 0&&(l[c]=s[c]);return t.vnode&&t.vnode(u),u}function Q({text:e,kind:t=`idle`}){return Z(`span`,{className:`pill pill-${t}`,children:e})}var tt=`archie.setup-complete.dismissed.v1`;function nt(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?.(tt),{kind:`incomplete`,remaining:n}):t?.getItem?.(`archie.setup-complete.dismissed.v1`)===`1`?{kind:`dismissed`,remaining:[]}:{kind:`complete`,remaining:[]}}function rt(e=globalThis.localStorage){e?.setItem?.(tt,`1`)}var it=new Set([`waiting_human`,`parked`]);function at(e=[]){let t=e.filter(e=>it.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 ot({node:e}){let t=X();return Y(()=>{t.current&&e&&t.current.replaceChildren(e)},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function st(e){return Z(ot,{node:Xe(e)})}function ct(e){return Z(ot,{node:Qe(e)})}function lt({segments:e}){return Z(ot,{node:$e(e)})}function ut({name:e,opts:t}){return Z(ot,{node:G(e,t)})}function dt({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function ft(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 pt(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function mt(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 ht(){let[e,t]=J([]),[n,r]=J(`connecting`),[i,a]=J(`idle`),[o,s]=J(new Map),[c,l]=J(null),[u,d]=J(null),[f,p]=J(null),[m,h]=J(null),[g,_]=J(null),[,v]=J(!1),y=async()=>{_(null);try{let[e,t,n,r]=await Promise.all([U.summary(),U.setup().catch(()=>null),U.workflows().catch(()=>null),U.tasks().catch(()=>[])]),i=new Map;for(let e of r)e.owner&&e.repo&&e.issue_number&&i.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);s(i),l(e),d(t),p(n),h(r)}catch(e){_(String(e.message||e))}};Y(()=>(y(),ue(e=>{t(t=>{let n=[e,...t];return n.splice(50),n})},e=>{r(e),a(e===`live`?`ok`:`warn`)})),[]);let b=()=>{rt(),v(e=>!e)},x=u?.operator?`${pt()}, ${u.operator}`:pt(),C=null;if(g)C=Z(`button`,{className:`btn btn-primary`,onClick:y,children:[Z(ut,{name:`refresh`,opts:{size:15}}),` Retry`]});else if(m!==null){let e=at(m),t=e.attention.count,n=e.running.count;C=Z(S,{children:[t>0&&Z(`a`,{className:`btn btn-attention`,href:e.attention.href,children:[Z(ut,{name:`tasks`,opts:{size:15}}),` `,t,` need`,t===1?`s`:``,` you`]}),n>0&&Z(`a`,{className:`btn`,href:e.running.href,children:[Z(ut,{name:`workflows`,opts:{size:15}}),` `,n,` running`]}),Z(`a`,{className:`btn`,href:`#/logs`,children:[Z(ut,{name:`logs`,opts:{size:15}}),` Logs`]}),Z(`button`,{className:`btn btn-primary`,onClick:y,children:[Z(ut,{name:`refresh`,opts:{size:15}}),` Refresh`]})]})}let w=null;if(g)w=Z(`div`,{className:`card`,children:Z(dt,{title:`Cannot reach archied`,detail:g})});else if(c){let e=c?.statuses||{},t=(e.merged||0)+(e.pr_open||0),n=(e.parked||0)+(e.waiting_human||0),r=Object.values(e).reduce((e,t)=>e+t,0),i=c?.tokens_by_day||[];w=Z(S,{children:[Z(st,{label:`Working now`,value:e.running||0,compare:`${e.queued||0} waiting to start`,series:i.map(e=>e.tokens||0)}),Z(st,{label:`Needs you`,value:n,compare:n?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),Z(st,{label:`Delivered`,value:t,compare:r?`${Math.round(t/r*100)}% of all tasks`:`No tasks yet`}),Z(st,{label:`Tokens used`,value:De(i.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${i.length||0} days`,trend:mt(i.map(e=>e.tokens||0)),goodDirection:`down`,series:i.map(e=>e.tokens||0)})]})}let T=null,E=nt(u),D=E.kind===`omit`||E.kind===`dismissed`;if(!D){let e=E.remaining;if(e.length){let t=Math.round((u.steps.length-e.length)/u.steps.length*100);T=Z(`div`,{className:`card setup`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Finish setting up`}),Z(`p`,{className:`card-sub`,children:`Archie needs these before it can work on its own.`})]}),Z(`span`,{className:`setup-pct`,children:[t,`%`]})]}),Z(`div`,{className:`setup-bar`,children:Z(`div`,{className:`setup-bar-fill`,style:{width:`${t}%`}})}),Z(`ul`,{className:`setup-list`,children:u.steps.map((e,t)=>Z(`li`,{className:`setup-step ${e.done?`done`:``}`,children:[Z(`span`,{className:`setup-check`,children:e.done?Z(ut,{name:`check`,opts:{size:12}}):``}),Z(`div`,{children:[Z(`div`,{className:`setup-step-title`,children:e.title}),e.detail&&Z(`div`,{className:`setup-step-detail`,children:e.detail})]})]},t))})]})}else T=Z(`div`,{className:`card setup setup-done`,children:Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Setup complete`}),Z(`p`,{className:`card-sub`,children:`Archie is configured and ready to work.`})]}),Z(`div`,{className:`setup-complete-actions`,children:[Z(`span`,{className:`setup-pct`,children:Z(ut,{name:`check`,opts:{size:16}})}),Z(`button`,{className:`icon-btn setup-dismiss`,type:`button`,title:`Dismiss setup complete`,"aria-label":`Dismiss setup complete`,onClick:b,children:`×`})]})]})})}let O=null;if(c){let e=f?.workflows||[],t=e.reduce((e,t)=>e+(t.runs||0),0),n=e.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),r=e.reduce((e,t)=>e+(t.parked||0),0);if(!t)O=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`h2`,{className:`card-title`,children:`Gate pulse`})}),Z(dt,{title:`No completed runs yet`,detail:`Once Archie finishes a task, its gate pass rate appears here.`})]});else{let i=n/t*100;O=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Gate pulse`}),Z(`p`,{className:`card-sub`,children:`Work that passed its quality gates`})]})}),Z(ct,{value:i,label:`pass rate`}),Z(`ul`,{className:`pulse-list`,children:[e.slice(0,3).map((e,t)=>Z(`li`,{className:`pulse-item`,children:[Z(`span`,{className:`pulse-name`,children:e.workflow||`workflow`}),Z(Q,{text:`${e.merged||0}/${e.runs||0}`,kind:(e.merged||0)===(e.runs||0)?`ok`:(e.parked||0)>0?`warn`:`info`})]},t)),r>0&&Z(`li`,{className:`pulse-item`,children:[Z(`span`,{className:`pulse-name`,children:`Parked, awaiting you`}),Z(Q,{text:String(r),kind:`warn`})]})]})]})}}let k=null;if(c){let e=c?.tokens_by_day||[],t=e.reduce((e,t)=>e+(t.tokens||0),0);if(!e.length)k=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`h2`,{className:`card-title`,children:`Token outlook`})}),Z(dt,{title:`Nothing spent yet`,detail:`Usage appears here once Archie runs its first task.`})]});else{let n=t/e.length,r=Math.round(n*30),i=e.slice(-7).reduce((e,t)=>e+(t.tokens||0),0);k=Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Token outlook`}),Z(`p`,{className:`card-sub`,children:`Next 30 days at the current rate`})]})}),Z(`div`,{className:`forecast-value`,children:De(r)}),Z(`div`,{className:`forecast-note`,children:[`Based on `,De(Math.round(n)),` per day over `,e.length,` days`]}),Z(lt,{segments:[{label:`Last 7 days (${De(i)})`,value:i,kind:`info`},{label:`Earlier (${De(t-i)})`,value:Math.max(t-i,0),kind:`idle`}]})]})}}return Z(S,{children:[Z(`div`,{className:`hero`,children:[Z(`div`,{children:[Z(`h1`,{className:`hero-title`,children:x}),Z(`p`,{className:`hero-sub`,children:`Your agent's control room — what it is working on, what needs you, and what it is spending.`})]}),Z(`div`,{className:`hero-actions`,children:Z(`div`,{className:`hero-actions-inner`,children:C})})]}),Z(`div`,{className:`dash-section`,children:[Z(`div`,{className:`dash-section-head`,children:Z(`h2`,{className:`dash-section-title`,children:`Health`})}),Z(`div`,{className:`dash-top ${D?`dash-top-standalone`:``}`,children:[Z(`div`,{children:T}),Z(`div`,{children:O})]})]}),Z(`div`,{className:`dash-section`,children:[Z(`div`,{className:`dash-section-head`,children:[Z(`h2`,{className:`dash-section-title`,children:`Throughput`}),Z(`span`,{className:`dash-section-note`,children:`Across all repositories`})]}),Z(`div`,{className:`grid grid-4`,children:w})]}),Z(`div`,{className:`dash-section`,children:[Z(`div`,{className:`dash-section-head`,children:Z(`h2`,{className:`dash-section-title`,children:`Right now`})}),Z(`div`,{className:`dash-split`,children:[Z(`div`,{children:k}),Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`Live activity`}),Z(`p`,{className:`card-sub`,children:`Last 50, newest first`})]}),Z(Q,{text:n,kind:i})]}),Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Event`}),Z(`th`,{children:`Task`}),Z(`th`,{children:`Detail`}),Z(`th`,{children:`When`})]})}),Z(`tbody`,{children:e.length?e.map((e,t)=>{let n=ft(e,o),r=n>0,i=()=>{r&&(location.hash=`#/tasks?task=${encodeURIComponent(n)}`)};return Z(`tr`,{className:r?`activity-row`:``,role:r?`link`:void 0,tabIndex:r?`0`:void 0,title:r?`Open task details`:void 0,onClick:r?i:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[Z(`td`,{className:`strong`,children:Z(`span`,{children:e.kind||e.type||`event`})}),Z(`td`,{className:`mono`,children:r?`#${n}`:`—`}),Z(`td`,{children:e.detail||e.message||``}),Z(`td`,{children:Ee(e.at||Date.now())})]},t)}):Z(`tr`,{children:Z(`td`,{colSpan:`4`,children:Z(dt,{title:`Waiting for activity`,detail:`Events appear here as Archie works.`})})})})]})})]})]})]})]})}function gt(){return Z(ht,{})}function _t(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 vt=Se(),yt=new Set([`needs_you`,...xe()]);function bt(e){let t=e?.get?.(`status`)||``;return yt.has(t)?t:``}function xt(e,t){return t?t===`needs_you`?vt.has(e.status):e.status===t:!0}function St(e){return String(e||`event`).replaceAll(`_`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function Ct(e){let t=Number(e);if(!Number.isFinite(t)||t<0)return``;if(t<1e3)return`${Math.round(t)} ms`;let n=t/1e3;if(n<60)return`${n.toFixed(+(n<10))} s`;let r=Math.round(n),i=Math.floor(r/60),a=r%60;if(i<60)return a===0?`${i} min`:`${i} min ${a} s`;let o=Math.floor(i/60),s=i-o*60;return s===0?`${o} h`:`${o} h ${s} min`}function wt(e){let t=Number(e);return!Number.isFinite(t)||t<=0?``:t.toLocaleString(`en-US`)}function Tt(e={}){let t=e.data||{},n=e.stage||`unknown stage`,r=e.workflow?`${e.workflow} workflow`:``;if(e.kind===`stage_start`)return{title:`Started stage: ${n}`,detail:r};if(e.kind===`stage_finish`){let e=Ct(t.duration_ms),i=[r,e&&`ran for ${e}`].filter(Boolean).join(` · `);return{title:t.interrupted?`Stage interrupted: ${n}`:t.error?`Stage failed: ${n}`:`Finished stage: ${n}`,detail:[i,t.error].filter(Boolean).join(` — `)}}if(e.kind===`task_retried`){let n=Number(t.retry_count);return{title:Number.isFinite(n)&&n>0?`Retry ${n}`:`Retry requested`,detail:[t.previous_stage&&`after ${t.previous_stage}`,t.previous_reason].filter(Boolean).join(`: `)||e.detail||``}}if(e.kind===`agent_finish`){let r=wt(t.iterations),i=wt(t.tokens),a=Number(t.cached_tokens)||0,o=wt((Number(t.prompt_tokens)||0)-a),s=wt(t.completion_tokens),c=wt(t.cached_tokens),l=[r&&`${r} iterations`,i&&`${i} tokens`,o&&`${o} fresh prompt`,s&&`${s} completion`,c&&`${c} cached`,t.model].filter(Boolean);return{title:`Agent ${t.status||`finished`}: ${n}`,detail:l.join(` · `)||e.detail||``}}if(e.kind===`config_captured`)return{title:`Configuration captured`,detail:`The effective task-runtime configuration for this run.`};if(e.kind===`changes_captured`){let e=Number(t.totals?.files);return{title:`Change capture recorded`,detail:[Number.isFinite(e)&&e>0?`${e} file${e===1?``:`s`} changed`:``,t.captured_after?`captured after ${t.captured_after}`:``].filter(Boolean).join(` · `)}}return{title:St(e.kind||e.type),detail:e.detail||``}}var Et=[{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 Dt(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function Ot(e){let t=e.fields||{};return W(`div.log-row.log-${Dt(e.level)}`,W(`span.log-time.mono`,At(e.time)),W(`span.log-level`,(e.level||`info`).toUpperCase()),W(`span.log-body`,W(`span.log-msg`,e.message||e.msg||``),...Object.entries(t).map(([e,t])=>W(`span.log-field`,W(`span.log-field-key`,e),String(kt(t))))))}function kt(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function At(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function jt({entry:e}){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(Ot(e))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function Mt(e,t){return`/api/tasks/${e}/logs/download`+(t==null?``:`?attempt=${t}`)}var Nt={level:``,stage:``};function Pt(e,t,n=Nt){let r=n||Nt;return[e,Number(t)||0,r.level||``,r.stage||``].join(`|`)}function Ft({filters:e,onFilterChange:t,stages:n,attempt:r}){let i=n=>t?.({...e,...n}),a=Number(r)||0;return Z(`div`,{className:`log-filters task-log-filters`,children:[Z(`span`,{className:`task-log-attempt`,children:a>0?`Attempt ${a}`:`Current attempt`}),t?Z(S,{children:[Z(`label`,{className:`task-log-filter`,children:[Z(`span`,{className:`task-log-filter-label`,children:`Level`}),Z(`select`,{className:`task-filter`,value:e.level,"aria-label":`Filter log entries by level`,onChange:e=>i({level:e.target.value}),children:Et.map(e=>Z(`option`,{value:e.value,children:e.label},e.value))})]}),Z(`label`,{className:`task-log-filter`,children:[Z(`span`,{className:`task-log-filter-label`,children:`Stage`}),Z(`select`,{className:`task-filter`,value:e.stage,"aria-label":`Filter log entries by stage`,onChange:e=>i({stage:e.target.value}),children:[Z(`option`,{value:``,children:`All stages`}),(n||[]).map(e=>Z(`option`,{value:e,children:e},e))]})]}),e.stage?Z(`p`,{className:`task-log-filter-note`,children:`A stage filter matches only log lines that record a stage. Agent and tool output carries none, so it is not shown while this filter is set.`}):null,!e.stage&&!(n||[]).length?Z(`p`,{className:`task-log-filter-note`,children:`This attempt recorded no stage names, so the stage filter has nothing to match.`}):null]}):null]})}function It({text:e}){return Z(`p`,{className:`visually-hidden`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:e})}function Lt({state:e,onRetry:t,taskId:n,attempt:r,filters:i=Nt,onFilterChange:a,stages:o=[]}){let s=Number(r)||Number(e?.attempt)||0,c,l;if(e===void 0)c=`Loading this attempt's log`,l=Z(`div`,{className:`task-log-loading`,children:`Loading attempt log…`});else if(e===null)c=`This attempt's log could not be loaded`,l=Z(`div`,{className:`task-log-error`,children:[Z(`div`,{className:`task-timeline-detail`,children:`Could not load this attempt's log.`}),Z(`button`,{className:`btn`,onClick:t,children:`Retry`})]});else if(e.found===!1&&!e.disabled)c=`No log recorded for this attempt`,l=Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`No log recorded for this attempt`}),Z(`div`,{children:`This attempt produced no output, or it has not started writing yet.`})]});else if(e.disabled)c=`This dashboard cannot read task logs`,l=Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`No persisted log for this attempt`}),Z(`div`,{children:`This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.`})]});else{let t=e.entries||[],r=n==null?null:Mt(n,s||null),i=r?Z(`a`,{className:`btn btn-small task-log-download`,href:r,download:!0,children:`Download log`}):null;t.length?(c=`${t.length} log entr${t.length===1?`y`:`ies`} shown`,l=Z(S,{children:[Z(`div`,{className:`log-list task-log-list`,children:t.map((e,t)=>Z(jt,{entry:e},t))}),i]})):(c=`This attempt's log has no entries matching the current filter`,l=Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`Nothing recorded`}),Z(`div`,{children:`This attempt's log file has no entries matching the current filter.`}),i]}))}return Z(S,{children:[Z(Ft,{filters:i,onFilterChange:a,stages:o,attempt:s}),Z(It,{text:c}),l]})}function Rt(){return typeof window<`u`&&window.matchMedia?.(`(prefers-reduced-motion: reduce)`)?.matches===!0}function zt(){return Rt()?`auto`:`smooth`}function Bt(e){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(Xe(e))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function Vt({kind:e,message:t}){return e===`session-expired`?Z(`span`,{className:`task-action-error task-action-error-session`,children:[`Your session has expired.`,` `,Z(`button`,{className:`button btn btn-small`,type:`button`,onClick:()=>window.location.reload(),children:`Reload to sign in`})]}):e===`refused`?Z(`span`,{className:`task-action-error task-action-error-refused`,children:[t,` — you can't do that.`]}):Z(`span`,{className:`task-action-error task-action-error-broken`,children:[t,` — try again, or check the daemon.`]})}function Ht({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Ut({taskId:e,attempt:t,state:n,onLoad:r,onRetry:i}){let a=X(r);return a.current=r,Y(()=>{n===void 0&&a.current()},[n]),Z(Lt,{state:n,taskId:e,attempt:t,onRetry:i})}function Wt({query:e}){let[t,n]=J(null),[r,i]=J(null),[a,o]=J(()=>bt(e)),[s,c]=J(``),l=Number(e.get(`task`)),u=Number.isFinite(l)&&l>0?l:null,[d,f]=J(u),[p,m]=J(u!==null),[h,g]=J(new Map),[_,v]=J(new Map),y=X(new Set),[b,x]=J(new Set),[C,w]=J(new Map),[T,E]=J(new Set),D=async()=>{try{i(null);let e=await U.tasks();return n(e),d&&e.some(e=>String(e.id)===String(d))&&(h.has(d)||O(d)),e}catch(e){return i(String(e.message||e)),n(null),null}};Y(()=>{D()},[]);let O=async e=>{try{let t=await U.task(e);g(n=>new Map(n).set(e,t||[]))}catch{g(t=>new Map(t).set(e,null))}},k=async(e,t,{force:n=!1}={})=>{let r=Pt(e,t);if(!(y.current.has(r)&&!n)){y.current.add(r),n&&v(e=>{let t=new Map(e);return t.delete(r),t});try{let n=await U.taskLogs(e,{attempt:t||void 0,limit:500});v(e=>new Map(e).set(r,n))}catch{v(e=>new Map(e).set(r,null))}}},A=e=>{g(t=>{let n=new Map(t);return n.delete(e),n})},j=async(e,t)=>{w(t=>{let n=new Map(t);return n.delete(e),n}),E(t=>new Set(t).add(e));try{await U.taskAction(e,t),E(t=>{let n=new Set(t);return n.delete(e),n}),t===`archive`&&f(null),A(e);let n=await D();Array.isArray(n)&&n.find(t=>String(t.id)===String(e))&&d===e&&O(e)}catch(t){E(t=>{let n=new Set(t);return n.delete(e),n}),w(n=>new Map(n).set(e,ce(t)))}};Y(()=>{p&&d&&t&&(m(!1),requestAnimationFrame(()=>{let e=document.getElementById(`task-row-${d}`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView?.({block:`center`,behavior:zt()}))}))},[p,d,t]);let M=(e,t)=>{t&&t.stopPropagation();let n=d!==e;f(n?e:null),n&&O(e)},N=e=>{x(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},P=()=>{if(!t)return null;let e=t.length,n={};for(let e of t)n[e.status]=(n[e.status]||0)+1;let r=n.running||0,i=(n.waiting_human||0)+(n.parked||0),a=(n.merged||0)+(n.pr_open||0);return Z(`div`,{className:`grid grid-4 task-summary`,children:[Z(Bt,{label:`Total tasks`,value:e,compare:e?`Everything archied has ever picked up`:`No tasks yet`}),Z(Bt,{label:`Working now`,value:r,compare:e?`${r} of ${e} in progress`:`Nothing running`}),Z(Bt,{label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),Z(Bt,{label:`Delivered`,value:a,compare:e?`${Math.round(a/e*100)}% of all tasks`:`No tasks yet`})]})},F=e=>{let t=C.get(e.id),n=t?Vt(t):null,r=T.has(e.id),i=e=>e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``,a=(e.actions||[]).map(t=>{let n=Ce(t);if(!n)return null;let a=e.title||`this task`,o=n.confirm?n.confirm.replaceAll(`{title}`,a):void 0,s=[`button`,`btn`,`btn-small`,i(n.kind)].filter(Boolean).join(` `);if(n.kind===`link`){if(t===`open_pr`)return I(e,`pull_request`,e.pr_number,n.label);if(t===`open_issue`)return I(e,`issue`,e.issue_number,n.label)}return Z(`button`,{className:s,type:`button`,disabled:r,onClick:n=>{n.stopPropagation(),!(o&&!window.confirm(o))&&j(e.id,t)},children:n.label},t)}).filter(Boolean);return!a.length&&!n?`—`:Z(`div`,{className:`task-actions`,children:[n,a]})},I=(e,t,n,r)=>{let i=t===`issue`?e.issue_url:e.pr_url;return!i||!n||t===`issue`&&e.source===`chat`?Z(`button`,{className:`btn btn-small`,type:`button`,disabled:!0,title:`${r} is unavailable`,children:r}):Z(`a`,{className:`btn btn-small`,href:i,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:r})},ee=e=>{let t=e.repo_url;return t?Z(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open ${e.owner}/${e.repo} on the forge`,onClick:e=>e.stopPropagation(),children:[e.owner,`/`,e.repo]}):null},te=e=>{let t=e.issue_url;return e.source===`chat`||!t||!e.issue_number?null:Z(`a`,{className:`task-source-link`,href:t,target:`_blank`,rel:`noreferrer`,title:`Open issue #${e.issue_number} on the forge`,onClick:e=>e.stopPropagation(),children:[`#`,e.issue_number]})},L=e=>{let t=Pt(e.id,e.attempt),n=h.get(e.id),r=b.has(e.id);return Z(`tr`,{className:`task-timeline-row`,id:`task-timeline-${e.id}`,children:Z(`td`,{colSpan:8,children:[Z(`div`,{className:`task-detail-actions`,children:[Z(`div`,{className:`task-decision-title`,children:`Available actions`}),F(e)]}),e.status===`waiting_human`&&e.plan&&Z(`div`,{className:`task-decision`,children:[Z(`div`,{className:`task-decision-title`,children:`Decision required`}),Z(`div`,{className:`task-decision-plan`,children:e.plan})]}),e.status===`parked`&&e.park_reason&&Z(`div`,{className:`task-decision`,children:[Z(`div`,{className:`task-decision-title`,children:`Park reason`}),Z(`div`,{className:`task-decision-plan`,children:e.park_reason})]}),n===void 0?Z(`div`,{className:`task-timeline-loading`,children:`Loading timeline…`}):n===null?Z(`div`,{className:`task-timeline-error`,children:[Z(`div`,{className:`task-timeline-title`,children:`Could not load timeline`}),Z(`div`,{className:`task-timeline-detail`,children:`archied did not answer for this task's events. It may be restarting — retry, or check the daemon.`}),Z(`button`,{className:`btn`,onClick:()=>O(e.id),children:`Retry`})]}):n.length?Z(`ul`,{className:`task-timeline`,children:n.map((e,t)=>{let n=Tt(e);return Z(`li`,{className:`task-timeline-entry`,children:[Z(`span`,{className:`task-timeline-dot`}),Z(`div`,{children:[Z(`div`,{className:`task-timeline-kind`,children:n.title}),n.detail&&Z(`div`,{className:`task-timeline-detail`,children:n.detail}),Z(`div`,{className:`task-timeline-when`,children:Ee(e.at)})]})]},t)})}):Z(Ht,{title:`No events yet`,detail:`This task has not recorded any transitions.`}),Z(`div`,{className:`task-logs-section`,children:[Z(`div`,{className:`task-decision-title`,children:[`Attempt log`,Z(`button`,{className:`btn btn-small`,onClick:()=>N(e.id),style:{marginLeft:`10px`},children:r?`Hide`:`Show`})]}),r&&Z(Ut,{taskId:e.id,attempt:e.attempt,state:_.has(t)?_.get(t):void 0,onLoad:()=>k(e.id,e.attempt),onRetry:()=>k(e.id,e.attempt,{force:!0})})]})]})})};return Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Tasks`}),Z(`p`,{className:`page-sub`,children:`Every issue archied has picked up, and where it stands.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:D,children:`Refresh`})})]}),r?Z(`div`,{className:`grid grid-4 task-summary`,children:Z(`div`,{className:`card`,children:Z(Ht,{title:`Cannot reach archied`,detail:r})})}):P(),Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:`All tasks`}),Z(`p`,{className:`card-sub`,children:`Click a row for its timeline`})]}),Z(`div`,{className:`task-filters`,children:[Z(`input`,{className:`task-search`,type:`search`,placeholder:`Search by title or repo…`,value:s,onInput:e=>c(e.target.value.trim().toLowerCase())}),Z(`select`,{className:`task-filter`,value:a,onChange:e=>o(e.target.value),children:[Z(`option`,{value:``,children:`All statuses`}),Z(`option`,{value:`needs_you`,children:`Needs you`}),xe().map(e=>Z(`option`,{value:e,children:ye(e)},e))]})]})]}),Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Repo`,`Issue`,`Title`,`Status`,`Workflow`,`Stage`,`Last activity`,`Action`].map(e=>Z(`th`,{children:e},e))})}),Z(`tbody`,{children:(()=>{if(r)return Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(Ht,{title:`Cannot reach archied`,detail:r})})});if(!t)return Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(`div`,{className:`task-timeline-loading`,children:`Loading tasks...`})})});if(!t.length)return Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(Ht,{title:`No tasks yet`,detail:`Tasks appear here once archied picks up an issue to work.`})})});let e=t.filter(e=>xt(e,a)?!s||`${e.title} ${e.repo}`.toLowerCase().includes(s):!1);return e.length?e.map(e=>{let t=d===e.id,n=`task-timeline-${e.id}`;return Z(S,{children:[Z(`tr`,{className:`task-row`,id:`task-row-${e.id}`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),M(e.id,t))},onClick:t=>M(e.id,t),..._t(e,t),children:[Z(`td`,{className:`mono`,"data-label":`Repository`,children:[Z(`button`,{className:`task-expand`,type:`button`,"aria-expanded":String(t),"aria-controls":n,"aria-label":`${t?`Collapse`:`Expand`} timeline for ${e.title||`untitled task`}`,onClick:t=>M(e.id,t),children:t?`−`:`+`}),ee(e)??`${e.owner}/${e.repo}`]}),Z(`td`,{className:`mono`,"data-label":`Issue`,children:te(e)??`#${e.issue_number}`}),Z(`td`,{className:`strong`,"data-label":`Title`,children:Z(`a`,{className:`task-detail-link`,href:`#/tasks/${e.id}`,title:`Open the run detail for this task`,onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:e.title||`(untitled)`})}),Z(`td`,{"data-label":`Status`,children:Z(Q,{text:ye(e.status),kind:be(e.status)})}),Z(`td`,{"data-label":`Workflow`,children:e.workflow||`—`}),Z(`td`,{"data-label":`Stage`,children:e.stage||`—`}),Z(`td`,{"data-label":`Last activity`,title:e.created_at?`Created ${Ee(e.created_at)}`:``,children:Ee(e.updated_at)}),Z(`td`,{"data-label":`Actions`,children:F(e)})]}),t&&L(e)]},e.id)}):Z(`tr`,{children:Z(`td`,{colSpan:8,children:Z(Ht,{title:`No matching tasks`,detail:`Try a different search or status filter.`})})})})()})]})})]})]})}function Gt(e){return Z(Wt,{query:e})}function Kt(e,t){return`${e}-tab-${t}`}function qt(e,t){return`${e}-panel-${t}`}function Jt({tabs:e,active:t,onSelect:n,prefix:r=`run`,label:i=`Run detail views`}){let a=X([]),o=t=>{let r=e[t];r&&(n?.(r.id),a.current[t]?.focus?.())};return Z(`div`,{className:`tab-bar`,role:`tablist`,"aria-label":i,onKeyDown:n=>{let r=e.findIndex(e=>e.id===t);if(r<0)return;let i;if(n.key===`ArrowRight`)i=(r+1)%e.length;else if(n.key===`ArrowLeft`)i=(r-1+e.length)%e.length;else if(n.key===`Home`)i=0;else if(n.key===`End`)i=e.length-1;else return;n.preventDefault(),o(i)},children:e.map((e,i)=>{let o=e.id===t;return Z(`button`,{ref:e=>{a.current[i]=e},id:Kt(r,e.id),className:`tab${o?` is-selected`:``}`,type:`button`,role:`tab`,"aria-selected":o,"aria-controls":qt(r,e.id),tabIndex:o?0:-1,onClick:()=>n?.(e.id),children:e.label},e.id)})})}var Yt={ok:{label:`ok`,kind:`ok`},failed:{label:`failed`,kind:`danger`},interrupted:{label:`interrupted`,kind:`warn`},running:{label:`running`,kind:`info`},unknown:{label:`unknown`,kind:`idle`}};function Xt(e){return Yt[e]||{label:e||`unknown`,kind:`idle`}}function Zt(e,t,n){return(e||[]).filter(e=>e&&e.kind===`agent_finish`&&Number(e.attempt)===Number(t)&&(e.stage||``)===(n||``)).map(e=>Tt(e))}function Qt(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`start time not recorded`:`started ${t.toISOString().replace(`T`,` `).slice(0,16)} UTC`}function $t({stage:e,attemptNumber:t,events:n}){let r=Xt(e.status),i=Ct(e.duration_ms),a=Zt(n,t,e.name);return Z(`li`,{className:`run-stage`,"data-status":e.status||`unknown`,children:[Z(`span`,{className:`run-stage-node`,"aria-hidden":`true`}),Z(`div`,{className:`run-stage-body`,children:[Z(`div`,{className:`run-stage-head`,children:[Z(`span`,{className:`run-stage-name mono`,children:e.name||`(unnamed stage)`}),Z(Q,{text:r.label,kind:r.kind}),Z(`span`,{className:`run-stage-duration`,children:i?`ran for ${i}`:`duration not recorded`})]}),e.error?Z(`div`,{className:`run-stage-error`,children:e.error}):null,a.map((e,t)=>Z(`div`,{className:`run-agent-report`,children:[Z(`span`,{className:`run-agent-report-label`,children:`Agent's own report, not verified by archie: `}),[e.title,e.detail].filter(Boolean).join(` · `)]},t))]})]})}function en({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function tn({count:e}){let t=Number(e)||0;return t?Z(`p`,{className:`run-rail-note`,children:[t,` event`,t===1?``:`s`,` on this task predate attempt attribution and cannot be assigned to a run.`]}):null}function nn({state:e,attemptNumber:t,events:n,onRetry:r}){if(e===void 0)return Z(`div`,{className:`run-loading`,children:`Loading this task's attempts…`});if(e===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this task's attempts`}),Z(`div`,{className:`run-error-detail`,children:`archied did not answer for this task's run history. It may be restarting — retry, or check the daemon.`}),r?Z(`button`,{className:`btn`,type:`button`,onClick:r,children:`Retry`}):null]});let i=e?.attempts||[];if(!i.length)return Z(S,{children:[Z(en,{title:`No attempts recorded`,detail:`This task has no recorded run. An attempt is written when a stage event is emitted, and none exist here.`}),Z(tn,{count:e?.unattributed_events})]});let a=i.find(e=>Number(e.attempt)===Number(t));if(!a)return Z(S,{children:[Z(en,{title:`Attempt ${t} is not recorded for this task`,detail:`This task recorded attempt ${i.map(e=>e.attempt).join(`, `)}.`}),Z(tn,{count:e?.unattributed_events})]});let o=a.stages||[],s=Xt(a.status);return Z(`div`,{className:`run-rail`,children:[Z(`div`,{className:`run-rail-head`,children:[Z(`span`,{className:`run-rail-attempt`,children:[`Attempt `,a.attempt]}),Z(Q,{text:s.label,kind:s.kind}),Z(`span`,{className:`run-rail-when`,children:Qt(a.started_at)})]}),o.length?Z(`ol`,{className:`run-stages`,"aria-label":`Stages recorded in attempt ${a.attempt}`,children:o.map((e,t)=>Z($t,{stage:e,attemptNumber:a.attempt,events:n},`${e.seq??t}:${e.name}`))}):Z(en,{title:`No stages recorded for this attempt`,detail:`The attempt exists, but nothing recorded a stage for it.`}),Z(`p`,{className:`run-rail-legend`,children:[Z(`strong`,{children:`ok`}),` means the stage returned without error. Archie records no exit code and does not verify that the work was correct, so this is a progress status, not a check result.`]}),Z(tn,{count:e?.unattributed_events})]})}var rn={added:`Added`,modified:`Modified`,deleted:`Deleted`,renamed:`Renamed`,typechange:`Type changed`};function an(e){return rn[e]||e||`unknown`}function on(e,t){let n=e?.repo_url||t?.repo_url||``,r=t&&String(t.pr_number??``)!==``&&String(t.pr_number)===String(e?.pr_number??``);return{repo:n,pr:e?.pr_url||r&&t.pr_url||``}}function sn(e={}){let t=Number(e.files)||0,n=[`${t} file${t===1?``:`s`}`];return e.additions&&n.push(`+${e.additions}`),e.deletions&&n.push(`−${e.deletions}`),n.join(` · `)}function cn({capture:e}){let t=e.files||[],n=Number(e.totals?.files)||t.length;return t.length?Z(S,{children:[Z(`table`,{className:`table run-changes-table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Path`}),Z(`th`,{children:`Change`}),Z(`th`,{className:`run-changes-count`,children:`Added`}),Z(`th`,{className:`run-changes-count`,children:`Deleted`})]})}),Z(`tbody`,{children:t.map((e,t)=>Z(`tr`,{children:[Z(`td`,{className:`mono run-changes-path`,children:[e.old_path?Z(`span`,{className:`run-changes-old`,children:[e.old_path,` → `]}):null,e.path]}),Z(`td`,{children:[an(e.status),e.binary?Z(`span`,{className:`run-changes-hint`,children:`no textual hunks`}):null]}),Z(`td`,{className:`run-changes-count mono`,children:e.additions?`+${e.additions}`:`—`}),Z(`td`,{className:`run-changes-count mono`,children:e.deletions?`−${e.deletions}`:`—`})]},`${e.path}:${t}`))})]}),e.truncated?Z(`p`,{className:`run-changes-note`,children:[`Showing the first `,t.length,` of `,n,` files. The totals above cover every file in this capture.`]}):null]}):Z(`div`,{className:`run-changes-empty`,children:[`This capture recorded no file entries`,n?`, though its totals cover ${n} file${n===1?``:`s`}`:``,`.`]})}function ln({capture:e,task:t}){let n=on(e,t),r=e.pr_number;return Z(`section`,{className:`run-capture`,children:[Z(`div`,{className:`run-capture-head`,children:[Z(`span`,{className:`run-capture-when`,children:[e.captured_after?`Captured after ${e.captured_after}`:`Captured`,e.stage?` in stage ${e.stage}`:``]}),Z(`span`,{className:`run-capture-at`,children:e.captured_at?Ee(e.captured_at):``})]}),Z(`div`,{className:`run-capture-meta`,children:[Z(`span`,{className:`mono`,children:n.repo?Z(`a`,{className:`run-capture-link`,href:n.repo,target:`_blank`,rel:`noreferrer`,children:[e.owner,`/`,e.repo]}):`${e.owner||``}/${e.repo||``}`}),e.branch?Z(`span`,{className:`mono run-capture-branch`,children:[e.branch,e.base?` → ${e.base}`:``]}):null,e.head_sha?Z(`span`,{className:`mono run-capture-sha`,children:String(e.head_sha).slice(0,8)}):null,r?n.pr?Z(`a`,{className:`run-capture-link`,href:n.pr,target:`_blank`,rel:`noreferrer`,children:[`PR #`,r]}):Z(`span`,{className:`mono`,children:[`PR #`,r]}):null,Z(`span`,{className:`run-capture-totals`,children:sn(e.totals)})]}),Z(cn,{capture:e})]})}function un({state:e,task:t,onRetry:n}){if(e===void 0)return Z(`div`,{className:`run-loading`,children:`Loading changed files…`});if(e===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this attempt's changed files`}),Z(`div`,{className:`run-error-detail`,children:`archied did not answer for this attempt. It may be restarting — retry, or check the daemon.`}),n?Z(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]});let r=e.captures||[];return e.found===!0&&!r.length?Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`A change capture was recorded but could not be read`}),Z(`div`,{children:`This attempt has a change capture event, but this dashboard could not decode its payload. That is a read failure, not a statement about what the attempt changed.`})]}):!e.found||!r.length?Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`No change capture was recorded for this attempt`}),Z(`div`,{children:`Archie records what an attempt changed when it commits or pushes that work. Nothing was recorded here — the attempt may predate capture, or it produced no commit. This is not the same as "no files changed".`})]}):Z(`div`,{className:`run-changes`,children:r.map((e,n)=>Z(ln,{capture:e,task:t},`${e.captured_at||``}:${n}`))})}function dn(e,t){return(e||[]).find(e=>e&&e.kind===`config_captured`&&Number(e.attempt)===Number(t))||null}function fn({events:e,attempt:t,onRetry:n}){if(e===void 0)return Z(`div`,{className:`run-loading`,children:`Loading this task's events…`});if(e===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this task's events`}),Z(`div`,{className:`run-error-detail`,children:`The configuration is recorded as an event on the task, so it cannot be shown while the event stream is unreadable. archied did not answer — retry, or check the daemon.`}),n?Z(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]});let r=dn(e,t);if(!r)return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:`Not captured for this run`}),Z(`div`,{children:[`Archie records the effective configuration when it dispatches an attempt. Attempt `,t,` `,`has no such record — it predates the record, or the capture did not run. Nothing here says the run used the defaults.`]})]});let i=r.data||{},a=i.schema||``,o=i.document;return Z(`div`,{className:`run-config`,children:[Z(`p`,{className:`run-config-scope`,children:[`This is attempt `,r.attempt,`'s effective task-runtime configuration: a non-secret subset covering bot identity, models, limits, budgets, dispatch, diff cap, notifications, forge host and tool policy. It is not the dashboard configuration view — providers, repositories, identities, credentials and lock state are not part of it.`]}),Z(`div`,{className:`run-config-when`,children:[`Captured `,r.at||`at an unrecorded time`,r.stage?` in stage ${r.stage}`:``]}),a===`archie/task-config@1`?Z(`pre`,{className:`run-json`,children:JSON.stringify(o??{},null,2)}):Z(S,{children:[Z(`div`,{className:`run-config-unknown`,children:[`Recorded in an unknown schema`,a?` (${a})`:``,`. The raw payload is shown verbatim; nothing here reinterprets it.`]}),Z(`pre`,{className:`run-json`,children:JSON.stringify(i,null,2)})]})]})}function pn({state:e,attempt:t,onRetry:n}){return e===void 0?Z(`div`,{className:`run-loading`,children:`Loading the stored record…`}):e===null?Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load the stored record`}),Z(`div`,{className:`run-error-detail`,children:`archied did not answer for this task's debug view. It may be restarting — retry, or check the daemon.`}),n?Z(`button`,{className:`btn`,type:`button`,onClick:n,children:`Retry`}):null]}):Z(`div`,{className:`run-debug`,children:[Z(`p`,{className:`run-debug-note`,children:[`The stored task record and its events, verbatim. Events are unfiltered on purpose: this is every event the task has, and each one carries the attempt it belongs to. Attempt `,t,` `,`is the one selected above.`]}),Z(`pre`,{className:`run-json`,children:JSON.stringify(e,null,2)})]})}var mn=[{id:`stages`,label:`Stages`},{id:`log`,label:`Log`},{id:`changes`,label:`Changed files`},{id:`config`,label:`Configuration`},{id:`debug`,label:`Debug`}],hn=`run`,gn=new Set(mn.map(e=>e.id));function _n(e){let t=String(e??``).trim();if(!/^\d+$/.test(t))return null;let n=Number(t);return Number.isSafeInteger(n)&&n>0?n:null}function vn(e){let t=e?.get?.(`tab`)||``;return gn.has(t)?t:mn[0].id}function yn(e){let t=e?.get?.(`attempt`);if(t==null||t===``)return null;let n=Number(t);return Number.isInteger(n)&&n>0?n:null}function bn(e,t,n){let r=new URLSearchParams;return r.set(`tab`,t||mn[0].id),n&&r.set(`attempt`,String(n)),`#/tasks/${e}?${r.toString()}`}function xn(e,t,n){try{window.history.replaceState(null,``,`${location.pathname}${location.search}${bn(e,t,n)}`)}catch{}}function Sn(e,t){return`${e}|${Number(t)||0}`}function Cn({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function wn({id:e}){return Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Task not found`}),Z(`p`,{className:`page-sub`,children:[`No task with id `,e,` in this deployment.`]})]}),Z(`div`,{className:`page-actions`,children:Z(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`})})]}),Z(`div`,{className:`card`,children:Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:[`Nothing is recorded for task `,e]}),Z(`div`,{children:`archied answered that this task does not exist, so there is no run history to show.`})]})})]})}function Tn({raw:e}){return Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Not a task id`}),Z(`p`,{className:`page-sub`,children:`The run view addresses one task by its id: #/tasks/42`})]}),Z(`div`,{className:`page-actions`,children:Z(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`})})]}),Z(`div`,{className:`card`,children:Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:[`“`,e,`” is not a task id`]}),Z(`div`,{children:`A task id is a positive whole number. Nothing was requested.`})]})})]})}function En({attempts:e,selected:t,onSelect:n}){let r=e?.attempts||[];return r.length?Z(`div`,{className:`run-attempts`,role:`group`,"aria-label":`Attempts of this task`,children:r.map(e=>{let r=Xt(e.status),i=Number(e.attempt)===Number(t);return Z(`button`,{type:`button`,className:`run-attempt${i?` is-selected`:``}`,"aria-pressed":i,onClick:()=>n(e.attempt),children:[Z(`span`,{className:`run-attempt-id`,children:[`Attempt `,e.attempt]}),Z(Q,{text:r.label,kind:r.kind}),Z(`span`,{className:`run-attempt-meta`,children:[(e.stages||[]).length,` stage`,(e.stages||[]).length===1?``:`s`]})]},e.attempt)})}):null}function Dn({id:e,query:t}){let[n,r]=J(()=>vn(t)),[i,a]=J(()=>yn(t)),[o,s]=J(void 0),[c,l]=J(void 0),[u,d]=J(!1),[f,p]=J(void 0),[m,h]=J(Nt),[g,_]=J(new Map),[v,y]=J(new Map),[b,x]=J(new Map),[S,C]=J(!1),[w,T]=J(null),[E,D]=J(0),O=X(new Set),k=Array.isArray(o)&&o.find(t=>String(t.id)===String(e))||null,A=Number(c?.current_attempt)>0?Number(c.current_attempt):null,j=i??A,M=(c?.attempts||[]).find(e=>Number(e.attempt)===Number(j)),N=[...new Set((M?.stages||[]).map(e=>e.name).filter(Boolean))],P=(e,t,n,{force:r=!1}={})=>{O.current.has(e)&&!r||(O.current.add(e),n(t=>new Map(t).set(e,void 0)),t().then(t=>n(n=>new Map(n).set(e,t))).catch(()=>n(t=>new Map(t).set(e,null))))},F=()=>{s(void 0),U.tasks().then(e=>s(e)).catch(()=>s(null))},I=()=>{l(void 0),d(!1),U.taskAttempts(e).then(e=>l(e)).catch(e=>{e?.status===404&&d(!0),l(null)})},ee=()=>{p(void 0),U.task(e).then(e=>p(e||[])).catch(()=>p(null))},te=(t,n)=>P(Pt(e,t,m),()=>U.taskLogs(e,{attempt:t||void 0,level:m.level,stage:m.stage,limit:500}),_,n),L=(t,n)=>P(Sn(e,t),()=>U.taskChanges(e,{attempt:t}),y,n),R=(t,n)=>P(Sn(e,t),()=>U.taskDebug(e,{attempt:t}),x,n),ne=()=>{O.current=new Set,_(new Map),y(new Map),x(new Map),F(),I(),ee(),D(e=>e+1)};Y(()=>{F(),I(),ee()},[]),Y(()=>{j!=null&&(n===`log`?te(j):n===`changes`?L(j):n===`debug`&&R(j))},[n,j,m,E]),Y(()=>{xn(e,n,j)},[e,n,j]);let z=async()=>{let t=k?.title||`task ${e}`;if(window.confirm(`Start a new run for "${t}"? This is a new attempt, and the previous attempt's commits are discarded.`)){T(null),C(!0);try{await U.taskAction(e,`retry`),O.current=new Set,_(new Map),y(new Map),x(new Map),a(null),F(),I(),ee(),D(e=>e+1)}catch(e){T(ce(e))}finally{C(!1)}}};if(u)return Z(wn,{id:e});let B=j==null?null:Pt(e,j,m),re=Sn(e,j),ie=Sn(e,j),ae=()=>{if(n===`stages`)return Z(nn,{state:c,attemptNumber:j,events:f,onRetry:I});if(c===void 0)return Z(`div`,{className:`run-loading`,children:`Loading this task's attempts…`});if(c===null)return Z(`div`,{className:`run-error`,children:[Z(`div`,{className:`run-error-title`,children:`Could not load this task's attempts`}),Z(`div`,{className:`run-error-detail`,children:`This panel reads one attempt, and the task's run history could not be read.`}),Z(`button`,{className:`btn`,type:`button`,onClick:I,children:`Retry`})]});if(j==null)return Z(Cn,{title:`No attempt recorded`,detail:`This task has no recorded run, so there is nothing to read for an attempt.`});switch(n){case`log`:return Z(Lt,{state:B&&g.has(B)?g.get(B):void 0,attempt:j,stages:N,filters:m,onFilterChange:h,taskId:e,onRetry:()=>te(j,{force:!0})});case`changes`:return Z(un,{state:v.has(re)?v.get(re):void 0,task:k,onRetry:()=>L(j,{force:!0})});case`config`:return Z(fn,{events:f,attempt:j,onRetry:ee});case`debug`:return Z(pn,{state:b.has(ie)?b.get(ie):void 0,attempt:j,onRetry:()=>R(j,{force:!0})});default:return Z(nn,{state:c,attemptNumber:j,events:f,onRetry:I})}},V=Ce(`retry`),oe=!!(V&&(k?.actions||[]).includes(`retry`));return Z(`div`,{className:`run-page`,children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:k?.title||`Task #${e}`}),Z(`p`,{className:`page-sub`,children:[`One run of task `,e,k?.workflow?` · ${k.workflow} workflow`:``,k?.repo?` · ${k.owner}/${k.repo}`:``]})]}),Z(`div`,{className:`page-actions`,children:[Z(`a`,{className:`btn`,href:`#/tasks`,children:`Back to tasks`}),Z(`button`,{className:`btn`,type:`button`,onClick:ne,children:`Refresh`})]})]}),Z(`div`,{className:`run-meta`,children:[Z(`span`,{className:`run-meta-item`,children:[Z(`span`,{className:`run-meta-label`,children:`Task status`}),o===void 0?Z(`span`,{className:`run-meta-muted`,children:`loading…`}):k?Z(Q,{text:ye(k.status),kind:be(k.status)}):Z(`span`,{className:`run-meta-muted`,children:`not read`})]}),Z(`span`,{className:`run-meta-item`,children:[Z(`span`,{className:`run-meta-label`,children:`Attempt`}),Z(`span`,{className:`run-meta-value`,children:c===null?`run history unreadable`:c===void 0?`loading…`:j==null?`none recorded`:`attempt ${j} of ${A??j}`})]}),k?.repo_url?Z(`a`,{className:`run-meta-link`,href:k.repo_url,target:`_blank`,rel:`noreferrer`,children:[k.owner,`/`,k.repo]}):null,k?.issue_url&&k.issue_number?Z(`a`,{className:`run-meta-link`,href:k.issue_url,target:`_blank`,rel:`noreferrer`,children:[`Issue #`,k.issue_number]}):null,k?.pr_url&&k.pr_number?Z(`a`,{className:`run-meta-link`,href:k.pr_url,target:`_blank`,rel:`noreferrer`,children:[`PR #`,k.pr_number]}):null]}),o===null?Z(`p`,{className:`run-note`,children:`The task list could not be read, so this page cannot show the task's current status or its operator controls. The run history below comes from the task's own endpoints.`}):null,Array.isArray(o)&&!k?Z(`p`,{className:`run-note`,children:[`Task `,e,` is not among the tasks this dashboard lists (the list covers the 100 most recently updated). Its recorded attempts are shown below; the Debug tab holds the stored record verbatim.`]}):null,Z(`section`,{className:`run-restart`,"aria-label":`Start a new run`,children:[Z(`button`,{className:`btn ${V?.kind===`primary`?`btn-primary`:``}`,type:`button`,disabled:!oe||S,title:`Retry this task as a new run`,onClick:z,children:S?`Starting…`:`Start a new run`}),Z(`p`,{className:`run-restart-copy`,children:`Starts a new attempt for this task: a fresh worktree reset onto the base branch. The previous attempt's commits are discarded — they are not carried into the new run.`}),!oe&&o!==void 0?Z(`p`,{className:`run-restart-unavailable`,children:k?`A new run can only start from a parked task. This task is ${ye(k.status)}.`:`This task's operator controls could not be read, so a new run cannot be started from here.`}):null,w?Z(`p`,{className:`run-restart-error run-restart-error-${w.kind}`,children:w.kind===`session-expired`?`Your session has expired. Reload to sign in.`:w.kind===`refused`?`${w.message} — this run cannot be restarted from here.`:`${w.message} — try again, or check the daemon.`}):null]}),Z(En,{attempts:c,selected:j,onSelect:e=>a(e)}),Z(`div`,{className:`card run-card`,children:[Z(Jt,{tabs:mn,active:n,onSelect:r,prefix:hn}),Z(`div`,{className:`run-panel`,role:`tabpanel`,id:qt(hn,n),"aria-labelledby":Kt(hn,n),tabIndex:0,children:ae()})]})]})}function On(e,t){let n=t?.id,r=_n(n);return r===null?Z(Tn,{raw:n??``}):Z(Dn,{id:r,query:e},r)}function kn({title:e,detail:t}){return Z(`div`,{class:`empty`,children:[Z(`div`,{class:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function An(e){return Z(jn,{query:e})}function jn(){let[e,t]=J([]),[n,r]=J(``),[i,a]=J(null),o=async()=>{try{let e=await U.skills();t(e?.skills||[]),a(null)}catch(e){t([]),a(String(e.message||e))}};Y(()=>{o()},[]);let s=(e,t)=>!t||`${e.name} ${e.description}`.toLowerCase().includes(t),c=He(()=>e.filter(e=>s(e,n)),[e,n]);return Z(`div`,{children:[Z(`div`,{class:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{class:`page-title`,children:`Skills`}),Z(`p`,{class:`page-sub`,children:`What Archie can do, in plain language.`})]}),Z(`div`,{class:`page-actions`,children:Z(`button`,{class:`btn`,onClick:o,children:`Refresh`})})]}),Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Catalogue`}),Z(`p`,{class:`card-sub`,children:`Project, shared, and user-global skills`})]}),Z(`input`,{class:`skill-search`,type:`search`,placeholder:`Search skills…`,onInput:e=>r(e.target.value.trim().toLowerCase())})]}),Z(`div`,{class:`grid grid-2`,children:i?Z(kn,{title:`Cannot reach archied`,detail:i}):e.length?c.length?c.map(e=>Z(`div`,{class:`card skill-card`,children:[Z(`div`,{class:`card-head`,children:[Z(`h3`,{class:`card-title`,children:e.name||`Untitled skill`}),e.workflow&&Z(Q,{text:e.workflow,kind:`info`})]}),Z(`p`,{class:`skill-desc`,children:e.description||`No description provided.`}),Z(`div`,{class:`skill-source`,children:e.source||`Unknown source`})]},e.name)):Z(kn,{title:`No skills match`,detail:`Nothing found for "${n}".`}):Z(kn,{title:`No skills discovered yet`,detail:`Skills live as SKILL.md files under project, shared, or user-global .agents/skills// directories. Add one and refresh to make it available.`})})]})]})}var Mn={bootstrap:`Bootstrap`,implement:`Implement`,tdd:`TDD`,feasibility:`Feasibility check`};function Nn(e){return Mn[e]?Mn[e]:e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown`}function Pn(e,t){return t?Math.round(e/t*100):0}function Fn(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 In({title:e,detail:t}){return Z(`div`,{class:`empty`,children:[Z(`div`,{class:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Ln({fraction:e,kind:t=`ok`}){let n=Math.min(100,Math.max(0,e));return Z(`div`,{class:`wf-bar`,children:Z(`div`,{class:`wf-bar-fill wf-bar-${t}`,style:{width:`${n}%`}})})}function Rn(e){return Z(zn,{query:e})}function zn(){let[e,t]=J([]),[n,r]=J([]),[i,a]=J([]),[o,s]=J(null),c=async()=>{try{let e=await U.workflows();t(e?.definitions||[]),r(e?.workflows||[]),a(e?.stages||[]),s(null)}catch(e){s(String(e.message||e))}};return Y(()=>{c()},[]),Z(`div`,{children:[Z(`div`,{class:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{class:`page-title`,children:`Workflows`}),Z(`p`,{class:`page-sub`,children:`Run outcomes and spend per workflow, and where stages get stuck.`})]}),Z(`div`,{class:`page-actions`,children:Z(`button`,{class:`btn`,onClick:c,children:`Refresh`})})]}),Z(Bn,{definitions:e}),o?Z(`div`,{class:`card`,children:Z(In,{title:`Cannot reach archied`,detail:o})}):Z(S,{children:[Z(Vn,{workflows:n,definitions:e}),Z(Hn,{stages:i})]})]})}function Bn({definitions:e}){if(!e.length)return null;let t=e.filter(e=>e.enabled)[0]?.id||``,[n,r]=J(``),[i,a]=J(``),[o,s]=J(t),[c,l]=J(``),[u,d]=J(``),[f,p]=J(!1),[m,h]=J(``);return Y(()=>{!o&&t&&s(t)},[t,o]),Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Start work`}),Z(`p`,{class:`card-sub`,children:`This enters Archie’s normal admitted task queue.`})]})}),Z(`form`,{class:`wf-form`,onSubmit:async e=>{e.preventDefault(),p(!0),h(``);try{let e=await U.workRequest({identity:n,repository:i,workflow:o,title:c,instructions:u});h(`Queued task #${e.task_id}.`),r(``),a(``),s(t),l(``),d(``)}catch(e){h(String(e.message||e))}finally{p(!1)}},children:[Z(`input`,{placeholder:`Identity`,required:!0,value:n,onInput:e=>r(e.target.value)}),Z(`input`,{placeholder:`owner/repository`,required:!0,value:i,onInput:e=>a(e.target.value)}),Z(`select`,{required:!0,value:o,onInput:e=>s(e.target.value),children:e.filter(e=>e.enabled).map(e=>Z(`option`,{value:e.id,children:Nn(e.name||e.id)},e.id))}),Z(`input`,{placeholder:`Short task title`,required:!0,value:c,onInput:e=>l(e.target.value)}),Z(`textarea`,{placeholder:`Instructions for the work`,required:!0,rows:3,value:u,onInput:e=>d(e.target.value)}),Z(`button`,{class:`btn`,type:`submit`,disabled:f,children:`Start work`}),m&&Z(`p`,{class:`card-sub`,children:m})]})]})}function Vn({workflows:e,definitions:t}){let n=new Map(e.map(e=>[e.workflow,e])),r=t.map(e=>({...e,...n.get(e.id)||{workflow:e.id,runs:0,merged:0}}));return r.length?Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Per workflow`}),Z(`p`,{class:`card-sub`,children:`Success rate is merged tasks over all runs`})]})}),Z(`div`,{class:`table-scroll`,children:Z(`table`,{class:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Workflow`}),Z(`th`,{children:`Origin`}),Z(`th`,{children:`Runs`}),Z(`th`,{children:`Success rate`}),Z(`th`,{children:`Avg tokens`}),Z(`th`,{children:`Avg steps`})]})}),Z(`tbody`,{children:r.map(e=>{let t=Pn(e.merged,e.runs);return Z(`tr`,{children:[Z(`td`,{class:`strong`,children:Nn(e.workflow)}),Z(`td`,{class:`mono`,children:e.origin||`registry`}),Z(`td`,{children:`${e.runs} run${e.runs===1?``:`s`}`}),Z(`td`,{children:[Z(`div`,{class:`wf-rate`,children:[t,`%`,Z(`span`,{class:`wf-rate-sub`,children:[e.merged,` of `,e.runs,` merged`]})]}),Z(Ln,{fraction:t,kind:t>=50?`ok`:`warn`})]}),Z(`td`,{class:`mono`,children:e.avg_tokens?e.avg_tokens.toLocaleString():`—`}),Z(`td`,{class:`mono`,children:e.avg_steps?e.avg_steps.toFixed(1):`—`})]},e.workflow)})})]})})]}):Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:Z(`h2`,{class:`card-title`,children:`Per workflow`})})}),Z(In,{title:`No workflow runs yet`,detail:`Stats appear here once a task has run through a workflow.`})]})}function Hn({stages:e}){if(!e.length)return Z(`div`,{class:`card wf-stage-card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:Z(`h2`,{class:`card-title`,children:`Per stage`})})}),Z(In,{title:`No stage data yet`,detail:`Stage timing and failures appear here once workflows have run.`})]});let t=Math.max(...e.map(e=>e.avg_ms||0),1),n=[...e].sort((e,t)=>(t.avg_ms||0)-(e.avg_ms||0)),r=[...e].filter(e=>e.errors>0).sort((e,t)=>t.errors-e.errors);return Z(`div`,{class:`grid grid-2 wf-stage-card`,children:[Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Slowest stages`}),Z(`p`,{class:`card-sub`,children:`Average duration, this workflow's stages`})]})}),Z(`div`,{class:`table-scroll`,children:Z(`table`,{class:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Workflow`}),Z(`th`,{children:`Stage`}),Z(`th`,{children:`Runs`}),Z(`th`,{children:`Avg duration`})]})}),Z(`tbody`,{children:n.map((e,n)=>Z(`tr`,{children:[Z(`td`,{children:Nn(e.workflow)}),Z(`td`,{class:`strong`,children:e.stage}),Z(`td`,{children:e.runs}),Z(`td`,{children:[Z(`div`,{class:`wf-rate`,children:Fn(e.avg_ms)}),Z(Ln,{fraction:Pn(e.avg_ms,t),kind:`info`})]})]},n))})]})})]}),Z(`div`,{class:`card`,children:[Z(`div`,{class:`card-head`,children:Z(`div`,{children:[Z(`h2`,{class:`card-title`,children:`Most failures`}),Z(`p`,{class:`card-sub`,children:`Stages that error out, over their runs`})]})}),r.length?Z(`div`,{class:`table-scroll`,children:Z(`table`,{class:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Workflow`}),Z(`th`,{children:`Stage`}),Z(`th`,{children:`Failures`})]})}),Z(`tbody`,{children:r.map((e,t)=>Z(`tr`,{children:[Z(`td`,{children:Nn(e.workflow)}),Z(`td`,{class:`strong`,children:e.stage}),Z(`td`,{children:[Z(`div`,{class:`wf-rate`,children:[e.errors,` of `,e.runs]}),Z(Ln,{fraction:Pn(e.errors,e.runs),kind:`danger`})]})]},t))})]})}):Z(In,{title:`No failures recorded`,detail:`Every stage has completed cleanly so far.`})]})]})}function Un({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Wn(e,t){return e===`running`?`ok`:e===`failed`||e===`degraded`?`warn`:`idle`}function Gn(){let[e,t]=J([]),[n,r]=J(null),i=async()=>{try{let e=await U.channels();t(e?.channels||[]),r(null)}catch(e){r(String(e.message||e))}};return Y(()=>{i()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Channels`}),Z(`p`,{className:`page-sub`,children:`The conversational front-ends Archie can be reached through.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:i,children:`Refresh`})})]}),Z(`div`,{className:`grid grid-2`,children:n?Z(Un,{title:`Cannot reach archied`,detail:n}):e.length===0?Z(Un,{title:`No channels configured`,detail:`Configure [chat.telegram] or [chat.webhook_addr] in config.toml to talk to Archie outside the dashboard.`}):e.map(e=>Z(`div`,{className:`card channel-card`,children:[Z(`div`,{className:`card-head`,children:[Z(`h3`,{className:`card-title`,children:e.name}),Z(Q,{text:e.state||(e.configured?`configured`:`stopped`),kind:Wn(e.state,e.configured)})]}),Z(`p`,{className:`channel-desc`,children:e.description}),Z(`p`,{className:`channel-detail`,children:e.detail}),e.reload_supported?Z(`button`,{className:`btn`,onClick:async t=>{t.currentTarget.disabled=!0;try{await U.channelReload(e.id||e.name.toLowerCase()),await i()}catch{}finally{t.currentTarget&&(t.currentTarget.disabled=!1)}},children:`Reload`}):Z(`p`,{className:`channel-detail`,children:`Reload requires a daemon restart for this adapter.`})]},e.id||e.name))})]})}function Kn(e){return Z(Gn,{query:e})}function qn({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Jn(e){return Z(Yn,{query:e})}function Yn({query:e}){let[t,n]=J([]),[r,i]=J(null),a=async()=>{try{let e=await U.curators();n(e?.curators||[]),i(null)}catch(e){i(String(e.message||e))}};return Y(()=>{a()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Curators`}),Z(`p`,{className:`page-sub`,children:`Background agents that maintain memory and skills: what ran, and why.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:a,children:`Refresh`})})]}),Z(`div`,{className:`grid grid-2`,children:r?Z(qn,{title:`Cannot reach archied`,detail:r}):t.length?t.map(e=>Z(Zn,{curator:e},e.name)):Z(qn,{title:`No curators registered`,detail:`Curators are background agent loops that maintain memory and skills. None are registered on this daemon.`})})]})}function Xn(e){switch(e){case`healthy`:return`ok`;case`degraded`:return`warn`;case`unhealthy`:return`danger`;default:return`idle`}}function Zn({curator:e}){let t=e.recent_actions||[];return Z(`div`,{className:`card curator-card`,children:[Z(`div`,{className:`card-head`,children:[Z(`h3`,{className:`card-title`,children:e.name}),Z(Q,{text:e.health?.status||`unknown`,kind:Xn(e.health?.status)})]}),e.health?.message&&Z(`p`,{className:`curator-health-message`,children:e.health.message}),Z(`p`,{className:`curator-meta`,children:e.last_run_at?`Last ran ${Ee(e.last_run_at)} · ${e.last_run_actions} action${e.last_run_actions===1?``:`s`}`:`Has not run yet`}),t.length?Z(`ul`,{className:`curator-actions`,children:t.map((e,t)=>Z(`li`,{className:`curator-action`,children:[Z(`div`,{className:`curator-action-head`,children:[Z(`span`,{className:`curator-action-type`,children:e.type||`action`}),Z(`span`,{className:`curator-action-time`,children:Ee(e.at)})]}),e.detail&&Z(`p`,{className:`curator-action-detail`,children:e.detail}),e.reason&&Z(`p`,{className:`curator-action-reason`,children:[`Why: `,e.reason]})]},t))}):Z(`p`,{className:`curator-meta`,children:`No recorded activity yet.`})]})}function Qn(e){return e==null||e===``?`—`:String(e)}function $n({label:e,value:t,opts:n}){let r=Qn(t),[i,a]=J(!1),[o,s]=J(``),[c,l]=J(null),[u,d]=J(!1),[f,p]=J(!1),m=n?.key;if(!m)return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n?.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let h=n.locked?.[m];if(h)return Z(`div`,{className:`kv is-locked`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),Z(`span`,{className:`kv-note`,children:h})]});if(n.editable===!1)return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r})]});let g=n.overridden?.includes(m),_=()=>{s(String(n.raw??``)),l(null),a(!0)},v=async()=>{p(!0),l(null);try{await U.configReset(m),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{p(!1)}},y=async()=>{let e=er(n.type,o);if(e.error){l(e.error);return}d(!0),l(null);try{await(n.save||(e=>U.configUpdate({[m]:e})))(e.value),a(!1),n.onSaved?.()}catch(e){l(String(e.message||e))}finally{d(!1)}};if(i){let t=X(null);Y(()=>{t.current&&t.current.focus()},[]);let r=e=>{e.key===`Enter`&&(e.preventDefault(),y()),e.key===`Escape`&&a(!1)},i;return i=n.type===`bool`?Z(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:[Z(`option`,{value:`true`,children:`true`}),Z(`option`,{value:`false`,children:`false`})]}):n.type===`enum`?Z(`select`,{className:`kv-input`,value:o,onChange:e=>s(e.target.value),onKeyDown:r,ref:t,children:(n.options||[]).map(e=>Z(`option`,{value:e,children:e},e))}):Z(`input`,{className:`kv-input`,type:`text`,value:o,onInput:e=>s(e.target.value),onKeyDown:r,ref:t}),Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),i,Z(`div`,{className:`kv-actions`,children:[Z(`button`,{className:`kv-save`,type:`button`,onClick:y,disabled:u,children:`Save`}),Z(`button`,{className:`kv-cancel`,type:`button`,onClick:()=>a(!1),disabled:u,children:`Cancel`})]}),c&&Z(`span`,{className:`kv-note is-error`,children:c})]})}return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,title:n.hint,children:e}),Z(`span`,{className:`kv-value mono ${r===`—`?`is-empty`:``}`,title:r,children:r}),Z(`div`,{className:`kv-actions`,children:[g&&Z(`span`,{className:`kv-flag`,title:`Set from the dashboard; this shadows the value in the config file`,children:`overridden`}),Z(`button`,{className:`kv-btn`,type:`button`,title:`Edit ${e}`,onClick:_,children:`Edit`}),g&&Z(`button`,{className:`kv-btn`,type:`button`,title:`Discard the dashboard value and fall back to the config file`,onClick:v,disabled:f,children:`Reset`})]}),c&&Z(`span`,{className:`kv-note is-error`,children:c})]})}function er(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 tr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function nr({sub:e,title:t,children:n}){return Z(`div`,{className:`card cfg-section`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:t||`Update status`}),Z(`p`,{className:`card-sub`,children:e})]})}),n]})}var rr={ok:`OK`,update_available:`Update available`,drift:`Drift`,unknown:`Unknown`},ir={ok:`ok`,update_available:`info`,drift:`danger`,unknown:`idle`};function ar({components:e}){return!e||!e.length?Z(nr,{sub:`How each component is deployed, and whether what's running matches what's installed.`,children:Z(tr,{title:`No components reported`,detail:`The configured update-check command returned nothing.`})}):Z(nr,{sub:`How each component is deployed, and whether what's running matches what's installed. Hover a row for the exact versions compared.`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Component`}),Z(`th`,{children:`Install type`}),Z(`th`,{children:`Running`}),Z(`th`,{children:`Latest available`}),Z(`th`,{children:`Status`})]})}),Z(`tbody`,{children:e.map(e=>Z(`tr`,{title:[`Installed claim: ${e.installed_claim||`unknown`}`,`Running: ${e.running_version||`not observed`}`,e.reference?`Reference: ${e.reference}`:null].filter(Boolean).join(` +`),children:[Z(`td`,{className:`strong`,children:e.label||e.id}),Z(`td`,{className:`mono`,children:e.install_type||`—`}),Z(`td`,{className:`mono`,children:e.running_version||`—`}),Z(`td`,{className:`mono`,children:e.latest_available||`—`}),Z(`td`,{children:Z(Q,{text:rr[e.status]||e.status,kind:ir[e.status]||`idle`})})]},e.id||e.label))})]})})})}function $({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function or({title:e,sub:t,children:n}){return Z(`div`,{className:`card cfg-section`,children:[Z(`div`,{className:`card-head`,children:Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:e}),Z(`p`,{className:`card-sub`,children:t})]})}),n]})}function sr({origins:e}){return e?.length?Z(or,{title:`Configuration sources`,sub:`Applied from top to bottom; later entries take precedence over earlier ones.`,children:Z(`div`,{className:`kv-list`,children:e.map((e,t)=>Z($n,{label:`${e.layer} ${e.role}${e.feature?` (${e.feature})`:``}`,value:e.path},t))})}):Z(or,{title:`Configuration sources`,sub:`The files that supplied the running configuration.`,children:Z($,{title:`Source provenance is unavailable.`})})}function cr(e){return e===`quiet`?`btn-quiet`:e===`danger`?`btn-danger`:``}function lr({data:e,error:t}){if(t)return Z(or,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships.`,children:Z($,{title:`Lifecycle unavailable`,detail:t})});let n=e?.statuses||[],r=e?.actions||[];return Z(or,{title:`Work lifecycle`,sub:`The task statuses and operator actions archied ships. Add one on the backend and it appears here without a frontend change.`,children:[Z(`h3`,{className:`cfg-subhead`,children:`Statuses`}),n.length?Z(`div`,{className:`kv-list`,children:n.map(e=>{let t=e.label??ye(e.id),n=e.kind??be(e.id);return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,children:e.id}),Z(`span`,{className:`kv-value`,children:Z(Q,{text:t,kind:n})})]},e.id)})}):Z($,{title:`No statuses reported`,detail:`The server did not return any lifecycle statuses.`}),Z(`h3`,{className:`cfg-subhead`,children:`Actions`}),r.length?Z(`div`,{className:`kv-list`,children:r.map(e=>{let t=e.label??e.id,n=cr(e.kind);return Z(`div`,{className:`kv`,children:[Z(`span`,{className:`kv-label`,children:e.id}),Z(`span`,{className:`kv-value`,children:Z(`button`,{className:`btn btn-small ${n}`,type:`button`,disabled:!0,children:t})})]},e.id)})}):Z($,{title:`No actions reported`,detail:`The server did not return any operator actions.`})]})}function ur({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=J(!1),[o,s]=J(null),[c,l]=J(!!e[t]);return r?Z(`td`,{children:[Z(`input`,{className:`repo-field-checkbox`,type:`checkbox`,checked:c,onChange:async r=>{let i=r.target.checked;l(i),a(!0),s(null);try{await U.configRepoUpdate(e.owner,e.name,t,i),n?.()}catch(e){l(!i),s(String(e.message||e))}finally{a(!1)}},disabled:i}),o&&Z(`span`,{className:`kv-note is-error`,children:o})]}):Z(`td`,{children:c?`yes`:`no`})}function dr({r:e,field:t,onSaved:n,editable:r=!0}){let[i,a]=J(String(e[t]??0)),[o,s]=J(null),[c,l]=J(!1);return r?Z(`td`,{children:[Z(`input`,{className:`kv-input`,type:`text`,value:i,onChange:e=>a(e.target.value),onBlur:async()=>{let r=parseInt(i,10);if(Number.isNaN(r)){s(`Enter a whole number`);return}l(!0),s(null);try{await U.configRepoUpdate(e.owner,e.name,t,r),n?.()}catch(e){s(String(e.message||e))}finally{l(!1)}},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),e.target.blur())},disabled:c}),o&&Z(`span`,{className:`kv-note is-error`,children:o})]}):Z(`td`,{className:`mono`,children:i})}function fr({repos:e,onSaved:t,editable:n=!0}){if(!e?.length)return Z(or,{title:`Repositories`,sub:`The repositories Archie polls for work.`,children:Z($,{title:`No repositories configured`,detail:`Add a [[repos]] entry in config.toml so Archie has somewhere to work.`})});let r=e=>e?.length?e.map(e=>e.join(` `)).join(` → `):`—`;return Z(or,{title:`Repositories`,sub:`Each repository Archie polls, and the quality gate a change must pass before it opens a pull request. Concurrent tasks, retries, and self-review are per-repository overrides -- PATCH /api/config/repos/{owner}/{name}, not the file config.toml directly.`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Repository`}),Z(`th`,{children:`Base branch`}),Z(`th`,{children:`Ecosystem`}),Z(`th`,{children:`Quality gate`}),Z(`th`,{children:`Protected paths`}),Z(`th`,{children:`Concurrent`}),Z(`th`,{children:`Max retries`}),Z(`th`,{children:`Self-review`})]})}),Z(`tbody`,{children:e.map((e,i)=>Z(`tr`,{children:[Z(`td`,{className:`strong`,children:[e.owner,`/`,e.name]}),Z(`td`,{className:`mono`,children:e.base}),Z(`td`,{children:e.ecosystem||`go`}),Z(`td`,{className:`mono`,children:r(e.gate)}),Z(`td`,{className:`mono`,children:e.protect?.length?e.protect.join(`, `):`—`}),Z(ur,{r:e,field:`allow_concurrent`,onSaved:t,editable:n}),Z(dr,{r:e,field:`max_retries`,onSaved:t,editable:n}),Z(ur,{r:e,field:`review_enabled`,onSaved:t,editable:n})]},i))})]})})})}function pr(e){return e?e.charAt(0).toUpperCase()+e.slice(1).replace(/_/g,` `):`Unknown role`}function mr({models:e,providers:t}){let n=Object.entries(e||{}),r=Object.entries(t||{});return Z(or,{title:`Models & providers`,sub:`Which model handles each stage of work, and which LLM providers are wired up. Only the environment variable NAME is shown, never its value.`,children:[Z(`h3`,{className:`cfg-subhead`,children:`Model roles`}),n.length?Z(`div`,{className:`kv-list`,children:n.map(([e,t])=>Z($n,{label:pr(e),value:t},e))}):Z($,{title:`No model roles configured`,detail:`Assign a model to at least one role (e.g. "builder") in [models].`}),Z(`h3`,{className:`cfg-subhead`,children:`Providers`}),r.length?Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[Z(`th`,{children:`Provider`}),Z(`th`,{children:`Class`}),Z(`th`,{children:`Base URL`}),Z(`th`,{children:`API key env var`}),Z(`th`,{children:`Status`})]})}),Z(`tbody`,{children:r.map(([e,t])=>Z(`tr`,{children:[Z(`td`,{className:`strong`,children:e}),Z(`td`,{children:t.class}),Z(`td`,{className:`mono`,children:t.base_url||`default`}),Z(`td`,{className:`mono`,children:t.api_key_env||`—`}),Z(`td`,{children:t.configured?Z(Q,{text:`configured`,kind:`ok`}):Z(Q,{text:`missing credentials`,kind:`warn`})})]},e))})]})}):Z($,{title:`No providers configured`,detail:`Add a [providers.] entry so a model role above has something to run on.`})]})}function hr(){let[e,t]=J(null),[n,r]=J(null),[i,a]=J(null),[o,s]=J(null),[c,l]=J(!1),[u,d]=J(null),[f,p]=J(null),m=()=>{h(),g(),_()},h=async()=>{try{let e=await U.config();t(e),r(null)}catch(e){r(String(e.message||e))}},g=async()=>{try{let e=await U.version();a(e?.components||[]),s(null),l(!1)}catch(e){e?.status===501?l(!0):s(String(e.message||e))}},_=async()=>{try{let e=await U.taskMeta();d(e),p(null)}catch(e){p(String(e.message||e))}};return Y(()=>{m()},[]),Z(`div`,{className:`cfg-page`,children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Configuration`}),Z(`p`,{className:`page-sub`,children:`What archied is actually running with right now.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:m,children:`Refresh`})})]}),Z(`div`,{children:!c&&(o?Z(`div`,{className:`card`,children:Z($,{title:`Update status unavailable`,detail:o})}):i?Z(ar,{components:i}):null)}),Z(`div`,{children:Z(lr,{data:u,error:f})}),Z(`div`,{children:n?Z(`div`,{className:`card`,children:Z($,{title:`Cannot reach archied`,detail:n})}):!e||Object.keys(e).length===0?Z(`div`,{className:`card`,children:Z($,{title:`No configuration loaded`,detail:`archied is running without a config file wired into the dashboard, so there is nothing to show.`})}):Z(S,{children:[e.reload?.overlay_unavailable&&Z(`div`,{className:`card cfg-notice`,children:Z(`p`,{children:[`The runtime config overlay is not in effect: `,e.reload.overlay_unavailable]})}),e.reload?.last_error&&Z(`div`,{className:`card cfg-notice`,children:Z(`p`,{children:[`The last config reload failed; the running config is unchanged: `,e.reload.last_error]})}),(e.schema||[]).map((t,n)=>{let r=t.fields.filter(e=>e.type!==`structured`);return r.length?Z(or,{title:t.label,sub:t.description,children:Z(`div`,{className:`kv-list`,children:r.map(t=>Z($n,{label:t.label,value:t.value,opts:{key:t.key,type:t.type,options:t.options,raw:t.value,hint:t.description,editable:t.editable&&e.editable!==!1,locked:e.locked||{},overridden:e.overridden||[],onSaved:h}},t.key))})},n):null}),Z(fr,{repos:e.repositories,onSaved:h,editable:e.editable!==!1}),Z(mr,{models:e.models,providers:e.providers}),Z(sr,{origins:e.provenance})]})})]})}function gr(e){return Z(hr,{query:e})}function _r({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function vr(e){switch((e||``).toUpperCase()){case`ERROR`:return`danger`;case`WARN`:return`warn`;case`DEBUG`:return`idle`;default:return`info`}}function yr(e){return e==null?``:typeof e==`object`?JSON.stringify(e):e}function br(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?`--:--:--`:t.toTimeString().slice(0,8)}function xr({entry:e}){let t=e.fields||{};return Z(`div`,{className:`log-row log-${vr(e.level)}`,children:[Z(`span`,{className:`log-time mono`,children:br(e.time)}),Z(`span`,{className:`log-level`,children:(e.level||`info`).toUpperCase()}),Z(`span`,{className:`log-body`,children:[Z(`span`,{className:`log-msg`,children:e.message||e.msg||``}),Object.entries(t).map(([e,t])=>Z(`span`,{className:`log-field`,children:[Z(`span`,{className:`log-field-key`,children:e}),String(yr(t))]},e))]})]})}function Sr(e){return`${e.time||``}|${e.level||``}|${e.message||e.msg||``}|${JSON.stringify(e.fields||{})}`}function Cr(){let[e,t]=J({level:``,component:``,q:``}),[n,r]=J(!1),[i,a]=J([]),[o,s]=J([]),c=X(new Map),[l,u]=J(0),[d,f]=J(!1),[p,m]=J(`connecting`),[h,g]=J(`Refreshing…`),_=X(null),v=X(null),y=async()=>{g(`Refreshing…`);try{let t=await U.logs({level:e.level,component:e.component,q:e.q,limit:500});a(e=>{let n=t.components||[];return e.length===n.length&&e.every((e,t)=>e===n[t])?e:n}),f(!!t.disabled);let n=t.disabled?`Durable history unavailable; live daemon logs continue.`:t.truncated?`showing the most recent matches from ${t.file}`:t.file||``;g(n),s(t.entries||[])}catch{g(`Cannot read logs`)}};Y(()=>{y()},[e]),Y(()=>{let e=de(e=>{if(b.current)return;let t=e;S.current(t)&&(c.current.set(Sr(t),t),t.fields?.component&&a(e=>e.includes(t.fields.component)?e:[...e,t.fields.component]),u(e=>e+1))},e=>{m(e)});return()=>e()},[]);let b=X(n);b.current=n;let x=t=>{if(e.level&&!e.level.split(`,`).includes((t.level||``).toUpperCase())||e.component&&t.fields?.component!==e.component)return!1;if(e.q){let n=e.q.toLowerCase();if(!`${t.message||t.msg||``} ${JSON.stringify(t.fields||{})}`.toLowerCase().includes(n))return!1}return!0},S=X(x);S.current=x;let C=He(()=>{let e=new Map;for(let t of o)e.set(Sr(t),t);for(let[t,n]of c.current)e.set(t,n);return[...e.values()].filter(x).slice(-1e3)},[o,l,e]);return Y(()=>{_.current&&(_.current.scrollTop=_.current.scrollHeight)},[C]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Logs`}),Z(`p`,{className:`page-sub`,children:`What Archie has been doing, newest last.`})]}),Z(`div`,{className:`page-actions`,children:[Z(`button`,{className:`btn ${n?`btn-primary`:``}`,onClick:()=>r(!n),children:n?`Resume`:`Pause`}),Z(`button`,{className:`btn`,onClick:y,children:`Refresh`})]})]}),Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{className:`log-filters`,children:[Z(`select`,{className:`log-select`,value:e.level,onChange:e=>t(t=>({...t,level:e.target.value})),children:Et.map(e=>Z(`option`,{value:e.value,children:e.label},e.value))}),Z(`select`,{className:`log-select`,value:e.component,onChange:e=>t(t=>({...t,component:e.target.value})),children:[Z(`option`,{value:``,children:`All components`}),i.map(e=>Z(`option`,{value:e,children:e},e))]}),Z(`input`,{className:`log-search`,type:`search`,placeholder:`Search messages and fields…`,onInput:e=>{let n=e.target.value;v.current&&clearTimeout(v.current),v.current=setTimeout(()=>{t(e=>({...e,q:n}))},250)}})]}),Z(`div`,{className:`log-status`,children:[Z(`span`,{className:`log-meta`,children:h}),Z(Q,{text:p,kind:p===`live`?`ok`:`warn`})]})]}),Z(`div`,{className:`log-list`,ref:_,children:h===`Cannot read logs`?Z(_r,{title:`Cannot read logs`}):C.length?C.map(e=>Z(xr,{entry:e},Sr(e))):Z(_r,{title:d?`Durable history unavailable`:`Nothing matches`,detail:d?`Live daemon logs will appear here while this page is open.`:`Try a wider level or clear the search.`})})]})]})}function wr(e){return Z(Cr,{query:e})}function Tr({capture:e,expanded:t,onToggle:n}){return Z(S,{children:[Z(`tr`,{className:`capture-row`,tabIndex:`0`,"aria-expanded":String(t),onClick:n,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),n(e))},children:[Z(`td`,{className:`mono`,children:e.source||`(unknown)`}),Z(`td`,{title:e.received_at||``,children:Ee(e.received_at)}),Z(`td`,{children:Z(Q,{text:`Unbound`,kind:`idle`})}),Z(`td`,{className:`mono`,children:e.content_type||`—`}),Z(`td`,{children:Z(`button`,{className:`btn btn-small`,type:`button`,children:t?`Hide`:`View`})})]}),t&&Z(Er,{capture:e})]})}function Er({capture:e}){return Z(`tr`,{className:`capture-detail-row`,children:Z(`td`,{colSpan:`5`,children:Z(`div`,{className:`capture-detail`,children:[Z(`div`,{className:`capture-detail-section`,children:[Z(`div`,{className:`capture-detail-title`,children:`Payload`}),Z(Dr,{raw:e.body})]}),Z(`div`,{className:`capture-detail-section`,children:[Z(`div`,{className:`capture-detail-title`,children:`Headers`}),Z(Dr,{raw:e.headers})]})]})})})}function Dr({raw:e}){return e?Z(`pre`,{className:`capture-payload`,children:Or(e)}):Z(`div`,{className:`capture-empty`,children:`(empty)`})}function Or(e){try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}}function kr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Ar(e){return Z(jr,{query:e})}function jr({query:e}){let[t,n]=J([]),[r,i]=J(null),[a,o]=J(null),[s,c]=J(!0),[l,u]=J({text:`connecting`,kind:`idle`}),d=async()=>{try{let e=await U.captures(100);c(e.enabled!==!1),n(e.captures||[]),o(null)}catch(e){o(String(e.message||e))}};return Y(()=>{d();let e=ue(e=>{e.kind===`capture`&&d()},e=>{u({text:e,kind:e===`live`?`ok`:`warn`})});return()=>e()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Event inspector`}),Z(`p`,{className:`page-sub`,children:`Real inbound payloads archie has captured, most recent first.`})]}),Z(`div`,{className:`page-actions`,children:[Z(Q,{text:l.text,kind:l.kind}),Z(`button`,{className:`btn`,onClick:d,children:`Refresh`})]})]}),Z(`div`,{className:`card`,children:a?Z(kr,{title:`Cannot reach archied`,detail:a}):s?t.length?Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Source`,`Received`,`Binding`,`Content type`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:t.map(e=>Z(Tr,{capture:e,expanded:r===e.id,onToggle:()=>i(r===e.id?null:e.id)},e.id))})]})}):Z(kr,{title:`No captures yet`,detail:`Point a webhook at /webhooks/capture/ and it will show up here.`}):Z(kr,{title:`Capture is not configured`,detail:`This deployment has no capture storage wired up.`})})]})}var Mr=[`string`,`number`,`bool`,`object`,`array`,`any`];function Nr(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 Pr(e,t){return e?`${e}.${t}`:t}function Fr(e,t){return`${e}[${t}]`}function Ir({value:e,path:t=``,name:n=``,onPick:r}){return typeof e==`object`&&e?Z(`ul`,{className:`mapping-tree-list`,children:(Array.isArray(e)?e.map((e,n)=>[String(n),e,Fr(t,n)]):Object.entries(e).map(([e,n])=>[e,n,Pr(t,e)])).map(([e,t,n])=>Z(`li`,{className:`mapping-tree-item`,children:[Z(`span`,{className:`mapping-tree-key`,onClick:i=>{i.stopPropagation(),r&&r({path:n,type:Nr(t),name:e})},children:e}),Z(Ir,{value:t,path:n,name:e,onPick:r})]},n))}):Z(`span`,{className:`mapping-tree-value`,onClick:i=>{i.stopPropagation(),r&&r({path:t,type:Nr(e),name:n})},children:JSON.stringify(e)})}function Lr({fields:e,preview:t,onRemove:n,onNameChange:r,onTypeChange:i,onRequiredChange:a}){if(!e.length)return Z(`div`,{className:`mapping-empty-fields`,children:`Click a value in the payload to bind a field.`});let o=new Map((t?.failures||[]).map(e=>[e.field_name,e]));return Z(`table`,{className:`table mapping-fields-table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Field name`,`Path`,`Type`,`Required`,`Preview`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:e.map((e,s)=>Z(`tr`,{children:[Z(`td`,{children:Z(`input`,{className:`mapping-input`,value:e.name,onInput:e=>r?.(s,e.target.value)})}),Z(`td`,{className:`mono`,children:e.path}),Z(`td`,{children:Z(`select`,{className:`mapping-select`,value:e.type,onChange:e=>i?.(s,e.target.value),children:Mr.map(e=>Z(`option`,{value:e,children:e},e))})}),Z(`td`,{children:Z(`input`,{type:`checkbox`,checked:e.required,onChange:e=>a?.(s,e.target.checked)})}),Z(`td`,{children:Z(Rr,{field:e,preview:t,failureByField:o})}),Z(`td`,{children:Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(s),children:`Remove`})})]},s))})]})}function Rr({field:e,preview:t,failureByField:n}){if(!t)return Z(Q,{text:`not previewed`,kind:`idle`});let r=n.get(e.name);return r?Z(Q,{text:r.reason,kind:`danger`}):Object.prototype.hasOwnProperty.call(t.values||{},e.name)?Z(Q,{text:JSON.stringify(t.values[e.name]),kind:`ok`}):Z(Q,{text:`skipped (optional)`,kind:`idle`})}function zr({mapping:e,onEdit:t,onDelete:n}){return Z(`tr`,{children:[Z(`td`,{children:e.name}),Z(`td`,{className:`mono`,children:e.source_hint||`—`}),Z(`td`,{children:String(e.fields?.length??0)}),Z(`td`,{children:[Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>n?.(e),children:`Delete`})]})]})}function Br({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Vr(e){return Z(Hr,{query:e})}function Hr({query:e}){let[t,n]=J([]),[r,i]=J([]),[a,o]=J(null),[s,c]=J(null),l=async()=>{try{let[e,t]=await Promise.all([U.mappings(),U.captures(100)]);n(e.mappings||[]),i(t.captures||[]),o(null)}catch(e){o(String(e.message||e))}};Y(()=>{l()},[]);let u=()=>{c({id:null,name:``,sourceHint:``,fields:[],captureId:null,payload:null,payloadError:null,preview:null,actionError:null})},d=e=>{c({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})},f=async e=>{if(window.confirm(`Delete mapping "${e.name}"?`))try{await U.mappingDelete(e.id),await l()}catch(e){o(String(e.message||e))}},p=e=>{let t=r.find(t=>String(t.id)===String(e));c(e=>{let n={...e,captureId:t?t.id:null,preview:null};if(!t)n.payload=null,n.payloadError=null;else try{n.payload=JSON.parse(t.body),n.payloadError=null}catch{n.payload=null,n.payloadError=`This capture's body is not valid JSON, so its fields cannot be mapped by path.`}return n})},m=({path:e,type:t,name:n})=>{c(r=>{let i=new Set(r.fields.map(e=>e.name)),a=n||`field`,o=1;for(;i.has(a);)a=`${n||`field`}_${++o}`;let s=[...r.fields,{name:a,path:e,type:t,required:!0}];return{...r,fields:s,preview:null}})},h=e=>{c(t=>{let n=t.fields.slice();return n.splice(e,1),{...t,fields:n,preview:null}})},g=(e,t)=>{c(n=>{let r=n.fields.slice();return r[e]={...r[e],...t},{...n,fields:r,preview:null}})};return s?Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:Z(`h1`,{className:`page-title`,children:s.id?`Edit mapping`:`New mapping`})}),Z(`div`,{className:`page-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:()=>{c(null)},children:`Cancel`}),Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:async()=>{let e={name:s.name,source_hint:s.sourceHint,fields:s.fields};try{s.id?await U.mappingUpdate(s.id,e):await U.mappingCreate(e),c(null),await l()}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Save`})]})]}),s.actionError&&Z(`div`,{className:`mapping-error`,children:s.actionError}),Z(`div`,{className:`card mapping-form`,children:[Z(`label`,{className:`mapping-form-row`,children:[`Name`,Z(`input`,{className:`mapping-input`,value:s.name,onInput:e=>c(t=>({...t,name:e.target.value}))})]}),Z(`label`,{className:`mapping-form-row`,children:[`Source hint (organisational only)`,Z(`input`,{className:`mapping-input`,value:s.sourceHint,onInput:e=>c(t=>({...t,sourceHint:e.target.value}))})]}),Z(`label`,{className:`mapping-form-row`,children:[`Preview against captured event`,Z(`select`,{className:`mapping-select`,value:s.captureId||``,onChange:e=>p(e.target.value),children:[Z(`option`,{value:``,children:`— pick a captured event —`}),r.map(e=>Z(`option`,{value:e.id,children:[e.source||`(unknown)`,` — `,e.received_at||``]},e.id))]})]})]}),Z(`div`,{className:`card mapping-fields`,children:[Z(`div`,{className:`mapping-section-title`,children:`Bound fields`}),Z(Lr,{fields:s.fields,preview:s.preview,onRemove:h,onNameChange:(e,t)=>g(e,{name:t}),onTypeChange:(e,t)=>g(e,{type:t}),onRequiredChange:(e,t)=>g(e,{required:t})}),Z(`button`,{className:`btn`,type:`button`,onClick:async()=>{if(!s.captureId){c(e=>({...e,actionError:`Pick a captured event to preview against.`}));return}try{let e=await U.mappingPreview(s.captureId,s.fields);c(t=>({...t,preview:e,actionError:null}))}catch(e){c(t=>({...t,actionError:String(e.message||e)}))}},children:`Preview`})]}),Z(`div`,{className:`card mapping-payload`,children:[Z(`div`,{className:`mapping-section-title`,children:`Payload — click a value to bind it`}),s.payloadError?Z(`div`,{className:`mapping-error`,children:s.payloadError}):s.payload===null?Z(`div`,{className:`mapping-empty-fields`,children:`Pick a captured event above to see its payload.`}):Z(Ir,{value:s.payload,onPick:m})]})]}):Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Field mappings`}),Z(`p`,{className:`page-sub`,children:`Bind named fields to JSON paths from a real captured event, ready for a playbook binding.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:u,children:`New mapping`})})]}),a?Z(Br,{title:`Cannot reach archied`,detail:a}):t.length?Z(`div`,{className:`card`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Name`,`Source hint`,`Fields`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:t.map(e=>Z(zr,{mapping:e,onEdit:()=>d(e),onDelete:()=>f(e)},e.id))})]})})}):Z(Br,{title:`No mappings yet`,detail:`Create one from a captured event to reuse fields in a future playbook binding.`})]})}var Ur={draft:`draft`,pending_approval:`pending approval`,armed:`armed`},Wr={draft:`idle`,pending_approval:`warn`,armed:`ok`};function Gr({status:e}){return Z(Q,{text:Ur[e]||e,kind:Wr[e]||`idle`})}function Kr({binding:e,onEdit:t,onApprove:n,onDelete:r}){let i=e.owner&&e.repo?`${e.owner}/${e.repo}`:`—`;return Z(`tr`,{children:[Z(`td`,{children:e.name}),Z(`td`,{className:`mono`,children:e.matcher?.source||`—`}),Z(`td`,{children:e.workflow}),Z(`td`,{className:`mono`,children:i}),Z(`td`,{children:Z(Gr,{status:e.status})}),Z(`td`,{children:[Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>t?.(e),children:`Edit`}),e.status===`pending_approval`&&Z(`button`,{className:`btn btn-small btn-primary`,type:`button`,onClick:()=>n?.(e),children:`Approve`}),Z(`button`,{className:`btn btn-small`,type:`button`,onClick:()=>r?.(e),children:`Delete`})]})]})}function qr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Jr(e){return Z(Xr,{query:e})}function Yr(){return{id:null,name:``,source:``,mappingId:``,workflow:``,owner:``,repo:``,secret:``,actionError:null}}function Xr({query:e}){let[t,n]=J([]),[r,i]=J([]),[a,o]=J([]),[s,c]=J(null),[l,u]=J(null),d=async()=>{try{let[e,t,r]=await Promise.all([U.bindings(),U.mappings(),U.workflows()]);n(e.bindings||[]),i(t.mappings||[]),o((r.definitions||[]).filter(e=>e.enabled)),c(null)}catch(e){c(String(e.message||e))}};Y(()=>{d()},[]);let f=()=>{u(Yr())},p=e=>{u({id:e.id,name:e.name,source:e.matcher?.source||``,mappingId:e.mapping_id?String(e.mapping_id):``,workflow:e.workflow||``,owner:e.owner||``,repo:e.repo||``,secret:``,actionError:null})},m=()=>u(null),h=async()=>{let e={name:l.name,matcher:{source:l.source},mapping_id:Number(l.mappingId)||0,workflow:l.workflow,owner:l.owner,repo:l.repo,secret:l.secret};try{l.id?await U.bindingUpdate(l.id,e):await U.bindingCreate(e),u(null),await d()}catch(e){u(t=>({...t,actionError:String(e.message||e)}))}},g=async e=>{try{await U.bindingApprove(e.id),await d()}catch(e){c(String(e.message||e))}},_=async e=>{if(window.confirm(`Delete binding "${e.name}"?`))try{await U.bindingDelete(e.id),await d()}catch(e){c(String(e.message||e))}};return l?Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:Z(`h1`,{className:`page-title`,children:l.id?`Edit binding`:`New binding`})}),Z(`div`,{className:`page-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:m,children:`Cancel`}),Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:h,children:`Save`})]})]}),l.actionError&&Z(`div`,{className:`binding-error`,children:l.actionError}),Z(`div`,{className:`card binding-form`,children:[Z(`label`,{className:`binding-form-row`,children:[`Name`,Z(`input`,{className:`binding-input`,value:l.name,onInput:e=>u(t=>({...t,name:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Source (the path segment senders POST to, e.g. "sentry")`,Z(`input`,{className:`binding-input`,value:l.source,onInput:e=>u(t=>({...t,source:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Field mapping`,Z(`select`,{className:`binding-select`,value:l.mappingId,onChange:e=>u(t=>({...t,mappingId:e.target.value})),children:[Z(`option`,{value:``,children:`— pick a saved mapping —`}),r.map(e=>Z(`option`,{value:e.id,children:e.name},e.id))]})]}),Z(`label`,{className:`binding-form-row`,children:[`Workflow`,Z(`select`,{className:`binding-select`,value:l.workflow,onChange:e=>u(t=>({...t,workflow:e.target.value})),children:[Z(`option`,{value:``,children:`— pick a workflow —`}),a.map(e=>Z(`option`,{value:e.id,children:e.name},e.id))]})]}),Z(`label`,{className:`binding-form-row`,children:[`Repo pin -- owner (optional; leave both blank for the single-configured-repo default)`,Z(`input`,{className:`binding-input`,value:l.owner,onInput:e=>u(t=>({...t,owner:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Repo pin -- repo`,Z(`input`,{className:`binding-input`,value:l.repo,onInput:e=>u(t=>({...t,repo:e.target.value}))})]}),Z(`label`,{className:`binding-form-row`,children:[`Shared secret (`,l.id?`leave blank to keep the current secret`:`senders sign with this via HMAC-SHA256`,`)`,Z(`input`,{className:`binding-input`,type:`password`,value:l.secret,onInput:e=>u(t=>({...t,secret:e.target.value}))})]})]})]}):Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Playbook bindings`}),Z(`p`,{className:`page-sub`,children:`Tie a matcher, a field mapping, and a workflow together. New and edited bindings need explicit approval before they can fire.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:f,children:`New binding`})})]}),s?Z(qr,{title:`Cannot reach archied`,detail:s}):t.length?Z(`div`,{className:`card`,children:Z(`div`,{className:`table-scroll`,children:Z(`table`,{className:`table`,children:[Z(`thead`,{children:Z(`tr`,{children:[`Name`,`Source`,`Workflow`,`Repo pin`,`Status`,``].map((e,t)=>Z(`th`,{children:e},t))})}),Z(`tbody`,{children:t.map(e=>Z(Kr,{binding:e,onEdit:()=>p(e),onApprove:()=>g(e),onDelete:()=>_(e)},e.id))})]})})}):Z(qr,{title:`No bindings yet`,detail:`Create one from a saved field mapping to turn a captured webhook into a workflow.`})]})}function Zr({title:e,detail:t}){return Z(`div`,{className:`empty`,children:[Z(`div`,{className:`empty-title`,children:e}),t&&Z(`div`,{children:t})]})}function Qr(e){return e===`external`?`Added by you — an external store Archie was given`:`Built in — always available to Archie`}function $r({provider:e}){let t=e.tools||[];return Z(`div`,{className:`card`,children:[Z(`div`,{className:`card-head`,children:[Z(`div`,{children:[Z(`h2`,{className:`card-title`,children:e.name||`provider`}),Z(`p`,{className:`card-sub`,children:Qr(e.role)})]}),e.available?Z(Q,{text:`ready`,kind:`ok`}):Z(Q,{text:`unavailable`,kind:`danger`})]}),!e.available&&Z(`p`,{className:`mem-warning`,children:`Configured but not usable right now — a required binary or connection may be missing.`}),t.length?Z(`ul`,{className:`mem-tools`,children:t.map((e,t)=>Z(`li`,{className:`mem-tool`,children:[Z(`div`,{className:`mem-tool-name mono`,children:e.name}),e.description&&Z(`div`,{className:`mem-tool-desc`,children:e.description})]},t))}):Z(`p`,{className:`mem-warning`,children:`This provider exposes no tools, so the agent cannot use it.`})]})}function ei(){let[e,t]=J(null),[n,r]=J(!0),[i,a]=J(null),[o,s]=J(!0),c=async()=>{s(!0),a(null);try{let e=await U.memory();r(!!e.enabled),t(e.providers||[])}catch(e){a(String(e.message||e))}finally{s(!1)}};return Y(()=>{c()},[]),Z(`div`,{children:[Z(`div`,{className:`page-head`,children:[Z(`div`,{children:[Z(`h1`,{className:`page-title`,children:`Memory`}),Z(`p`,{className:`page-sub`,children:`What Archie can recall between conversations, and the tools it uses to do it.`})]}),Z(`div`,{className:`page-actions`,children:Z(`button`,{className:`btn`,onClick:c,children:`Refresh`})})]}),Z(`div`,{children:o?Z(`div`,{className:`card`,children:Z(`div`,{className:`mem-loading`,children:`Loading…`})}):i?Z(`div`,{className:`card`,children:Z(Zr,{title:`Cannot read memory providers`,detail:i})}):!n||!e.length?Z(`div`,{className:`card`,children:Z(Zr,{title:`Memory is not configured`,detail:`Without a provider, Archie starts every conversation with no recollection of earlier ones.`})}):Z(`div`,{className:`grid grid-2`,children:e.map((e,t)=>Z($r,{provider:e},t))})})]})}function ti(e){return Z(ei,{query:e})}function ni(e){let t=document.createDocumentFragment(),n=/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g,r=0;for(let i of e.matchAll(n)){i.index>r&&t.append(document.createTextNode(e.slice(r,i.index)));let n=i[0];if(n.startsWith(`![`)){let e=n.match(/^!\[([^\]]*)\]\((.+)\)$/);e&&t.append(W(`img.chat-media-img`,{src:e[2],alt:e[1]||`Image`,loading:`lazy`}))}else if(n.startsWith(`~~`))t.append(W(`del`,n.slice(2,-2)));else if(n.startsWith(`**`)||n.startsWith(`__`))t.append(W(`strong`,n.slice(2,-2)));else if(n.startsWith("`"))t.append(W(`code`,n.slice(1,-1)));else if(n.startsWith(`[`)){let e=n.match(/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/);t.append(W(`a`,{href:e[2],target:`_blank`,rel:`noreferrer`},e[1]))}else t.append(W(`em`,n.slice(1,-1)));r=i.index+n.length}return r{r.length&&(t.append(W(`p`,ni(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;eW(`td`,ni(e)))));t.append(W(`table`,W(`thead`,W(`tr`,...l.map(e=>W(`th`,ni(e))))),i));continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.append(W(`h${d[1].length}`,ni(d[2])));continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tagName.toLowerCase()!==e)&&(s(),i=W(e)),i.append(W(`li`,ni((f||p)[1])));continue}if(c.startsWith(`>`)){o(),s(),t.append(W(`blockquote`,ni(c.replace(/^>\s?/,``))));continue}r.push(c)}return o(),s(),a&&t.append(W(`pre`,W(`code`,a.join(` +`)))),t}function ii(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 ai(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oi=`archie.web.chat.channel`;function si(){let e=localStorage.getItem(oi);return e||(e=ie(),localStorage.setItem(oi,e)),e}function ci(e){return{text:e,sourceID:ie()}}function li(e){return{...e}}function ui(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?li(e.turn):ci(r),isRetry:n}}function di(e){return e.title||e.branch_name||`Conversation ${e.session_id.slice(0,8)}`}function fi(e){return e?.status===501?null:`Could not check for updates.`}function pi(){return location.hash.slice(1)||`/`}function mi({text:e}){let t=X(null);return Y(()=>{t.current&&t.current.replaceChildren(ri(e||``))},[e]),Z(`div`,{ref:t,style:{display:`contents`}})}function hi(){let[e,t]=J([]),[n,r]=J(``),[i,a]=J([]),[o,s]=J(``),[c,l]=J(`Ready`),[u,d]=J(!1),[f,p]=J({}),[m,h]=J(``),[g,_]=J(``),[v,y]=J(``),[b,x]=J([]),[C,w]=J([]),[T,E]=J(0),[D,O]=J(!1),[k,A]=J(null),[j,M]=J(null),[N,P]=J(null),[F,I]=J(``),[ee,te]=J(``),[L,R]=J(null),ne=X(null),z=X(null),B=X(null),re=X(null),ie=X(null),ae=X(u);ae.current=u,Y(()=>{ne.current&&(ne.current.scrollTop=ne.current.scrollHeight)},[i,L]),Y(()=>{ue().catch(e=>{l(e.message||`Chat unavailable`)}),V();let e=()=>{B.current?.abort()};return window.addEventListener(`archie:teardown`,e),()=>{window.removeEventListener(`archie:teardown`,e),B.current?.abort()}},[]);async function V(){try{let e=await U.chatUpdate();M(e?.snapshot||null),A(e)}catch(e){let t=fi(e);A(t?{error:t}:null)}}async function oe(){if(j)try{await U.chatUpdateDefer(j),A({snapshot:{deferred:!0},available:[]}),l(`Update deferred`)}catch(e){l(e.message||`Could not defer update`)}}async function se(){if(j)try{l(`Installing…`);let e=await U.chatUpdateInstall(j);M(null),A({snapshot:{},available:[]}),l(e?.result?.restart_requested?`Update installed; restart queued`:`Update complete`)}catch(e){l(e.message||`Update install failed`)}}async function ce(){try{let e=await U.chatDangerous();P(e)}catch(e){P({error:e.message||`Dangerous actions unavailable`})}}async function le(e,t){if(t)try{await U.chatDangerousRequest(e,t),l(`Approval requested`),await ce()}catch(e){l(e.message||`Could not request action`)}}async function H(e,t){try{await U.chatDangerousDecision(e,t),l(t===`deny`?`Action denied`:`Action approved`),await ce()}catch(e){l(e.message||`Approval failed`)}}async function ue(){let e=await U.chatSessions(),r=e.sessions||[];t(r),p(e),h(e.active_persona||``);let i=e.providers||[],a=e.active_provider||i[0]||``;_(a),y(e.active_model||``);let o=(e.commands||[]).map(e=>typeof e==`string`?{command:e,usage:e,description:``}:e);x(o),e.dangerous_available&&await ce(),!n&&r[0]&&await de(r[0].session_id,e,r)}async function de(e,t,n){let i=t||f;r(e),a([]),R(null);let o=i.active_personas?.[e]||i.active_persona||``;h(o);try{await U.chatMessage(si(),`/resume ${e}`);let[t,n]=await Promise.all([U.chatMessages(e),U.chatTurns(e)]),r=new Map;for(let e of n||[]){let t=e.assistant_message_id||e.AssistantMessageID;t&&r.set(t,e)}let i=(t||[]).map(e=>{let t=e.message_id||e.MessageID,n=r.get(t);return n?{...e,tool_calls:n.tool_calls||n.ToolCalls||[]}:e});a(i)}catch(e){l(e.message||`Could not load session messages`)}}async function fe(e){if(n)try{l(`Working…`);let t=await U.chatMessage(si(),e);t.session_id&&r(t.session_id),l(t.reply||`Session updated`),await ue(),(t.session_id||n)&&await de(t.session_id||n),re.current&&(re.current.open=!1)}catch(e){l(e.message||`Session action failed`)}}function pe(e,t){let n=window.prompt(t);n?.trim()&&fe(`${e} ${n.trim()}`)}function me(e){let t=e.target.value;h(t),!(!n||!t)&&U.chatPersona(n,t).then(()=>{p(e=>({...e,active_personas:{...e.active_personas||{},[n]:t}})),l(`Personality: ${t}`)}).catch(e=>{l(e.message||`Failed to set personality`)})}async function he(e){let t=e.target.value;if(_(t),t)try{let e=await U.chatMessage(si(),`/model --provider ${t}`);l(e.reply||`Provider updated`),await ue()}catch(e){l(`Provider update failed: ${e.message||e}`)}}async function ge(e){let t=e.target.value;if(y(t),t)try{let e=await U.chatMessage(si(),`/model ${t}`);l(e.reply||`Model updated`),await ue()}catch(e){l(`Model update failed: ${e.message||e}`)}}function _e(){window.confirm(`Reload the Telegram chat adapter?`)&&(s(`/restart`),Se({textOverride:`/restart`}))}function ve(){s(`/new`),Se({textOverride:`/new`})}function ye(e){let t=e.target.value;s(t);let n=t.slice(0,e.target.selectionStart).match(/(?:^|\s)\/([^\s]*)$/);if(n){let e=n[1].toLowerCase(),t=b.filter(t=>`${t.command} ${t.description}`.toLowerCase().includes(e)).slice(0,8);if(t.length){w(t),E(0),O(!0);return}}O(!1),w([])}function be(e){let t=C[e];if(!t||!z.current)return;let n=z.current,r=n.value.slice(0,n.selectionStart),i=n.value.slice(n.selectionStart),a=r.search(/(?:^|\s)\/[^\s]*$/),o=a<0?r.length:a+ +(r[a]===` `),c=`${r.slice(0,o)}${t.command} ${i}`;s(c),O(!1);let l=o+t.command.length+1;setTimeout(()=>{n.focus(),n.setSelectionRange(l,l)},0)}function xe(e){if(D&&C.length){if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&C.some(e=>e.command===o.trim())){e.preventDefault(),O(!1),Se();return}if(e.key===`ArrowDown`){e.preventDefault(),E(e=>(e+1)%C.length);return}if(e.key===`ArrowUp`){e.preventDefault(),E(e=>(e+C.length-1)%C.length);return}if(e.key===`Enter`&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey){e.preventDefault(),be(T);return}if(e.key===`Escape`){e.preventDefault(),O(!1);return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),Se())}async function Se(e=null){let t=e?.textOverride,{text:n,turn:i,isRetry:c}=ui(e,t===void 0?o:t);if(!n||ae.current)return;O(!1),d(!0),l(c?`Retrying…`:`Thinking…`),c||(a(e=>[...e,{from:`web`,text:n}]),s(``));let u=[];R({text:``,tools:[],isError:!1,turn:i,isRetry:c});let f=``,p=!1,m=!1,h=null;try{let e=new AbortController;B.current=e,h=setTimeout(()=>{m=!0,e.abort()},12e4);let t=(await U.chatStream({channel_id:si(),source_id:i.sourceID,text:i.text,page:pi()},{signal:e.signal})).body.getReader(),n=new TextDecoder,o=``;for(;;){let{value:e,done:i}=await t.read();o+=n.decode(e||new Uint8Array,{stream:!i});let a=o.split(` `);o=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&&r(n.session_id),n.type===`delta`&&(f+=n.text,I(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],I(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),I(null),l(`Ready`),await V()}catch(e){if(e.name===`AbortError`&&!m)I({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;I({text:t,tools:u,isError:!0,turn:br(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),ie.current=null,d(!1),R.current&&R.current.focus()}}function we(){l(`Stopping…`),n&&B.chatCancel(n).catch(()=>{}),ie.current?.abort()}let U=f.models_by_provider||{},Te=g&&U[g]?U[g]:f.models||[];return X(`div`,{className:`chat-page-content`,children:[X(`header`,{className:`chat-topbar`,children:[X(`div`,{children:[X(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),X(`h1`,{className:`page-title`,children:`Chat`})]}),X(`div`,{className:`chat-topbar-actions`,children:[X(`span`,{className:`chat-status`,children:c}),f.restart_available&&X(`button`,{className:`btn`,type:`button`,onClick:ye,children:`Reload Telegram`}),X(`button`,{className:`btn`,type:`button`,onClick:ce,children:`Check updates`}),X(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:ge,children:[X(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>X(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&X(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:_e,children:[X(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>X(`option`,{value:e,children:e},e))]}),X(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ve,children:[X(`option`,{value:``,children:`Model`}),Te.map(e=>X(`option`,{value:e,children:e},e))]})]})]}),k&&X(`div`,{className:`chat-update-panel`,children:k.error?X(`span`,{children:k.error}):k.available?.length?X(S,{children:[X(`div`,{children:[X(`strong`,{children:`Update available`}),X(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:le,children:`Defer`}),k.can_install&&X(`button`,{className:`btn btn-primary`,type:`button`,onClick:ue,children:`Install update`})]})]}):X(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&M&&X(`div`,{className:`chat-dangerous-panel`,children:[X(`div`,{className:`chat-dangerous-head`,children:[X(`strong`,{children:`Dangerous actions`}),X(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),X(`div`,{className:`chat-dangerous-controls`,children:[X(`div`,{children:[X(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:P,onChange:e=>te(e.target.value),children:[X(`option`,{value:``,children:`Select checkpoint`}),(M.checkpoints||[]).map(e=>X(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`rollback`,P),children:`Request rollback`})]}),X(`div`,{children:[X(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ne,onInput:e=>re(e.target.value)}),X(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`stop`,ne),children:`Request stop`})]})]}),X(`div`,{className:`chat-dangerous-pending-list`,children:(M.pending||[]).length?M.pending.map(e=>X(`div`,{className:`chat-dangerous-pending`,children:[X(`span`,{children:e.description}),X(`div`,{className:`chat-update-actions`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`approve`),children:`Approve`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`permanent`),children:`Approve for 24h`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>z(e.id,`deny`),children:`Deny`})]})]},e.id)):X(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),X(`div`,{className:`chat-layout`,children:[X(`aside`,{className:`chat-sidebar`,children:[X(`div`,{className:`chat-sidebar-head`,children:[X(`strong`,{children:`Conversations`}),X(`button`,{className:`btn btn-primary`,type:`button`,onClick:be,children:`+ New chat`})]}),X(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>X(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>pe(e.session_id),children:[X(`strong`,{children:Sr(e)}),X(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):X(`div`,{className:`chat-empty`,children:`Your conversations will appear here.`})})]}),X(`section`,{className:`chat-workspace`,children:[X(`div`,{className:`chat-workspace-head`,children:[X(`span`,{className:`chat-workspace-label`,children:`PERSONAL ASSISTANT`}),X(`details`,{className:`chat-command-help`,children:[X(`summary`,{children:[`Available commands (`,b.length,`)`]}),X(`div`,{className:`chat-command-list`,children:b.length?b.map(e=>X(`div`,{className:`chat-command-item`,children:[X(`code`,{children:e.usage||e.command}),X(`span`,{children:e.description||``})]},e.command)):X(`span`,{children:`Send a message to begin.`})})]}),X(`details`,{className:`chat-session-tools`,ref:ae,hidden:!n,children:[X(`summary`,{children:`Session actions`}),X(`div`,{className:`chat-session-tool-list`,children:[X(`button`,{className:`btn`,type:`button`,onClick:()=>me(`/retry`),children:`Retry`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>me(`/undo`),children:`Undo`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/title`,`Session title`),children:`Rename`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>he(`/branch`,`Branch name (optional)`),children:`Branch`}),X(`button`,{className:`btn`,type:`button`,onClick:()=>me(`/compress --preview`),children:`Preview compression`})]})]})]}),X(`div`,{className:`chat-transcript`,ref:L,children:!i.length&&!F?X(`div`,{className:`chat-empty-state`,children:[X(`span`,{className:`chat-empty-mark`,children:`A`}),X(`h2`,{children:`What are we working on?`}),X(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),X(`div`,{className:`chat-prompt-grid`,children:[X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Summarise active tasks`),R.current?.focus()},children:`Summarise active tasks`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Show running agents`),R.current?.focus()},children:`Show running agents`}),X(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Check system status`),R.current?.focus()},children:`Check system status`})]})]}):X(S,{children:[i.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return X(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:i?`Archie`:`You`}),i?X(S,{children:[a.length>0&&X(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err||`done`;return X(`div`,{className:`chat-tool ${e.err||e.Err||e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(Tr,{text:r})]}):X(`div`,{className:`chat-bubble-text`,children:r})]})},t)}),F&&X(`div`,{className:`chat-bubble-row assistant`,children:X(`div`,{className:`chat-bubble`,children:[X(`div`,{className:`chat-bubble-meta`,children:`Archie`}),F.tools?.length>0&&X(`div`,{className:`chat-tools`,children:F.tools.map((e,t)=>{if(e.path)return X(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[X(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),X(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.tool||`tool`,r=e.parameters||``,i=e.summary||e.text||(e.failed?`failed`:`running…`);return X(`div`,{className:`chat-tool ${e.failed?`failed`:``}`,children:[X(`span`,{className:`chat-tool-icon`,children:`🔧`}),X(`span`,{className:`chat-tool-name`,children:n}),r&&X(`code`,{className:`chat-tool-parameters`,children:r}),X(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),X(Tr,{text:F.text||`…`}),F.isError&&X(`button`,{className:`btn chat-retry`,type:`button`,onClick:()=>H({turn:F.turn}),children:`Retry`})]})})]})}),X(`div`,{className:`chat-compose`,children:X(`div`,{className:`chat-composer-shell`,children:[X(`textarea`,{ref:R,className:`chat-composer`,rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`,disabled:u,value:o,onInput:xe,onKeyDown:Ce}),D&&C.length>0&&X(`div`,{className:`chat-command-menu`,ref:oe,role:`listbox`,"aria-label":`Commands`,children:C.map((e,t)=>X(`button`,{type:`button`,role:`option`,"aria-selected":String(t===T),className:`chat-command-option`,onMouseDown:e=>e.preventDefault(),onClick:()=>Se(t),children:[X(`code`,{children:e.command}),X(`span`,{children:e.description||e.usage||``})]},e.command))}),X(`div`,{className:`chat-compose-actions`,children:[X(`span`,{className:`chat-hint`,children:`Enter to send · Shift+Enter for a new line`}),X(`button`,{className:`btn`,type:`button`,disabled:!u,onClick:we,children:`Stop`}),X(`button`,{className:`btn btn-primary`,type:`button`,disabled:u||!o.trim(),onClick:()=>H(),children:`Send`})]})]})})]})]})]})}function Dr(){let e=document.createElement(`div`);return e.className=`chat-page`,ae(X(Er,{}),e),e}var Or=[{path:`/`,label:`Dashboard`,icon:`dashboard`,view:_t},{path:`/chat`,label:`Chat`,icon:`chat`,view:Dr,section:`chat`},{path:`/tasks`,label:`Tasks`,icon:`tasks`,view:Rt},{path:`/logs`,label:`Logs`,icon:`logs`,view:Fn,section:`logs`},{path:`/captures`,label:`Event inspector`,icon:`captures`,view:Vn,section:`captures`},{path:`/mappings`,label:`Field mappings`,icon:`mappings`,view:Qn,section:`mappings`},{path:`/bindings`,label:`Playbook bindings`,icon:`bindings`,view:ar,section:`bindings`},{path:`/skills`,label:`Skills`,icon:`skills`,view:Bt,section:`skills`},{path:`/workflows`,label:`Workflows`,icon:`workflows`,view:Jt,section:`workflows`},{path:`/memory`,label:`Memory`,icon:`memory`,view:fr,section:`memory`},{path:`/curators`,label:`Curators`,icon:`curators`,view:an,section:`curators`},{path:`/channels`,label:`Channels`,icon:`channels`,view:nn,section:`channels`},{path:`/settings`,label:`Configuration`,icon:`settings`,view:En,section:`settings`}],kr=`archie.theme`;function Ar(e){document.documentElement.dataset.theme=e,localStorage.setItem(kr,e)}function jr(){return localStorage.getItem(kr)||`dark`}function Mr(e,t){let n=new Map,r=U(`nav.nav`,...[null].flatMap(()=>[...Or.map(t=>{let r=U(`a.nav-item`,{href:`#${t.path}`,onclick:n=>{t.soon?n.preventDefault():e(t.path)},"aria-disabled":t.soon||void 0,title:t.soon?`Coming soon`:void 0},W(t.icon),U(`span.nav-label`,t.label),t.soon&&U(`span.nav-soon`,`soon`));return n.set(t.path,r),r})])),i=U(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Ar(jr()===`dark`?`light`:`dark`),Ee(i,W(jr()===`dark`?`moon`:`sun`))}});Ee(i,W(jr()===`dark`?`moon`:`sun`));let a,o=()=>{a?.classList.remove(`is-open`),s.setAttribute(`aria-expanded`,`false`)},s=U(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{a.classList.add(`is-open`),s.setAttribute(`aria-expanded`,`true`),c.focus()}},W(`search`,{size:15})),c=U(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:t=>{if(t.key===`Escape`){t.preventDefault(),o(),t.target.blur();return}if(t.key!==`Enter`)return;let n=t.target.value.trim().toLowerCase(),r=Or.find(e=>!e.soon&&e.label.toLowerCase().startsWith(n));r&&(e(r.path),t.target.value=``,t.target.blur(),o())}});return a=U(`div.topbar-search`,U(`span.topbar-search-icon`,{"aria-hidden":`true`},W(`search`,{size:15})),s,c),{node:U(`header.topbar`,U(`div.brand`,U(`span.brand-mark`,`A`),`Archie`),r,U(`div.topbar-end`,a,U(`button.icon-btn.icon-btn-chat`,{"aria-label":`Open chat`,title:`Chat with Archie`,"aria-expanded":`false`,onclick:()=>t?.()},W(`chat`)),U(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},W(`help`)),i,U(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,r]of n)t===e?r.setAttribute(`aria-current`,`page`):r.removeAttribute(`aria-current`)},hide(e){for(let t of e)n.get(t)?.remove()}}}function Nr(){Ar(jr());let e=U(`main.main`),t=U(`aside.chat-drawer`,{"aria-label":`Chat with Archie`}),n=U(`button.icon-btn.chat-drawer-close`,{"aria-label":`Close chat`,title:`Close chat`,onclick:()=>o(!1)},W(`close`)),r=U(`div.chat-drawer-head`,U(`strong`,`Archie`),n);t.append(U(`div.chat-drawer-panel`,r,Dr()),U(`div.chat-scrim`,{onclick:()=>o(!1)}));let i=Mr(s,()=>o());B.capabilities().then(e=>i.hide(me(e?.sections,Or))).catch(()=>{});let a=U(`div.shell`,i.node,e,t);Ee(document.getElementById(`app`),a);function o(e){let n=e===void 0?!t.classList.contains(`is-open`):e;t.classList.toggle(`is-open`,n),document.body.classList.toggle(`chat-open`,n);let r=a.querySelector(`.icon-btn-chat`);r&&r.setAttribute(`aria-expanded`,String(n))}window.__archieToggleChat=o;function s(e){location.hash===`#`+e?c(e):location.hash=e}function c(t){e.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[n,r=``]=t.split(`?`,2),a=Or.find(e=>e.path===n)||Or[0];if(i.highlight(a.path),a.path===`/chat`){Ee(e),o(!0);return}let s=a.view?a.view(new URLSearchParams(r)):Pr(a);s instanceof Node?Ee(e,s):ae(s,e),o(!1)}window.addEventListener(`hashchange`,()=>c(location.hash.slice(1)||`/`)),window.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Escape`&&t.classList.contains(`is-open`)&&o(!1)}),c(location.hash.slice(1)||`/`)}function Pr(e){return U(`div`,U(`div.page-head`,U(`div`,U(`h1.page-title`,e.label))),U(`div.card`,U(`div.empty`,U(`div.empty-title`,`${e.label} is not built yet`),U(`div`,`This section is next up. Nothing is broken.`))))}Nr(); \ 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&&r(n.session_id),n.type===`delta`&&(f+=n.text,R(e=>e?{...e,text:f}:null)),n.type===`tool`&&(u=[...u,n],R(e=>e?{...e,tools:u}:null)),n.type===`navigate`&&(u=[...u,n],R(e=>e?{...e,tools:u}:null)),n.type===`done`&&(p=!0,f||=n.text),n.type===`error`)throw Error(n.text)}if(i)break}if(!p)throw Error(`chat stream ended before completion`);a(e=>[...e,{from:`assistant`,text:f,tool_calls:u}]),R(null),l(`Ready`),await ue()}catch(e){if(e.name===`AbortError`&&!m)R({text:`Turn stopped.`,tools:u,isError:!1,turn:i,isRetry:c}),l(`Stopped`);else{let t=`Unable to complete that turn: ${e.message||e}`;R({text:t,tools:u,isError:!0,turn:li(i),isRetry:c}),l(`Error — retry available`)}}finally{clearTimeout(h),B.current=null,d(!1),z.current&&z.current.focus()}}function Ce(){l(`Stopping…`),n&&U.chatCancel(n).catch(()=>{}),B.current?.abort()}let W=f.models_by_provider||{},we=g&&W[g]?W[g]:f.models||[];return Z(`div`,{className:`chat-page-content`,children:[Z(`header`,{className:`chat-topbar`,children:[Z(`div`,{children:[Z(`span`,{className:`chat-kicker`,children:`ARCHIE WORKSPACE`}),Z(`h1`,{className:`page-title`,children:`Chat`})]}),Z(`div`,{className:`chat-topbar-actions`,children:[Z(`span`,{className:`chat-status`,children:c}),f.restart_available&&Z(`button`,{className:`btn`,type:`button`,onClick:_e,children:`Reload Telegram`}),Z(`button`,{className:`btn`,type:`button`,onClick:V,children:`Check updates`}),Z(`select`,{className:`chat-select`,"aria-label":`Personality`,value:m,onChange:me,children:[Z(`option`,{value:``,children:`Personality`}),(f.personas||[]).map(e=>Z(`option`,{value:e,children:e},e))]}),(f.providers||[]).length>0&&Z(`select`,{className:`chat-select`,"aria-label":`Provider`,value:g,onChange:he,children:[Z(`option`,{value:``,children:`Provider`}),(f.providers||[]).map(e=>Z(`option`,{value:e,children:e},e))]}),Z(`select`,{className:`chat-select`,"aria-label":`Model`,value:v,onChange:ge,children:[Z(`option`,{value:``,children:`Model`}),we.map(e=>Z(`option`,{value:e,children:e},e))]})]})]}),k&&Z(`div`,{className:`chat-update-panel`,children:k.error?Z(`span`,{children:k.error}):k.available?.length?Z(S,{children:[Z(`div`,{children:[Z(`strong`,{children:`Update available`}),Z(`span`,{children:k.available.map(e=>`${e.Label||e.label}: ${e.Available||e.available}`).join(` · `)})]}),Z(`div`,{className:`chat-update-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:oe,children:`Defer`}),k.can_install&&Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:se,children:`Install update`})]})]}):Z(`span`,{children:k.snapshot?.deferred?`Update deferred.`:`Archie is up to date.`})}),f.dangerous_available&&N&&Z(`div`,{className:`chat-dangerous-panel`,children:[Z(`div`,{className:`chat-dangerous-head`,children:[Z(`strong`,{children:`Dangerous actions`}),Z(`span`,{className:`chat-hint`,children:`Every action requires approval.`})]}),Z(`div`,{className:`chat-dangerous-controls`,children:[Z(`div`,{children:[Z(`select`,{className:`chat-select`,"aria-label":`Checkpoint`,value:F,onChange:e=>I(e.target.value),children:[Z(`option`,{value:``,children:`Select checkpoint`}),(N.checkpoints||[]).map(e=>Z(`option`,{value:e.Number??e.number,children:[e.Number??e.number,` — `,e.Label??e.label??`checkpoint`]},e.Number??e.number))]}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>le(`rollback`,F),children:`Request rollback`})]}),Z(`div`,{children:[Z(`input`,{className:`chat-dangerous-input`,placeholder:`Process name or id`,"aria-label":`Process name or id`,value:ee,onInput:e=>te(e.target.value)}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>le(`stop`,ee),children:`Request stop`})]})]}),Z(`div`,{className:`chat-dangerous-pending-list`,children:(N.pending||[]).length?N.pending.map(e=>Z(`div`,{className:`chat-dangerous-pending`,children:[Z(`span`,{children:e.description}),Z(`div`,{className:`chat-update-actions`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:()=>H(e.id,`approve`),children:`Approve`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>H(e.id,`permanent`),children:`Approve for 24h`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>H(e.id,`deny`),children:`Deny`})]})]},e.id)):Z(`span`,{className:`chat-hint`,children:`No pending dangerous actions.`})})]}),Z(`div`,{className:`chat-layout`,children:[Z(`aside`,{className:`chat-sidebar`,children:[Z(`div`,{className:`chat-sidebar-head`,children:[Z(`strong`,{children:`Conversations`}),Z(`button`,{className:`btn btn-primary`,type:`button`,onClick:ve,children:`+ New chat`})]}),Z(`div`,{className:`chat-session-list`,children:e.length?e.map(e=>Z(`button`,{className:`chat-session ${n===e.session_id?`active`:``}`,type:`button`,onClick:()=>de(e.session_id),children:[Z(`strong`,{children:di(e)}),Z(`span`,{children:new Date(e.last_active_at).toLocaleString()})]},e.session_id)):Z(`div`,{className:`chat-empty`,children:`Your conversations will appear here.`})})]}),Z(`section`,{className:`chat-workspace`,children:[Z(`div`,{className:`chat-workspace-head`,children:[Z(`span`,{className:`chat-workspace-label`,children:`PERSONAL ASSISTANT`}),Z(`details`,{className:`chat-command-help`,children:[Z(`summary`,{children:[`Available commands (`,b.length,`)`]}),Z(`div`,{className:`chat-command-list`,children:b.length?b.map(e=>Z(`div`,{className:`chat-command-item`,children:[Z(`code`,{children:e.usage||e.command}),Z(`span`,{children:e.description||``})]},e.command)):Z(`span`,{children:`Send a message to begin.`})})]}),Z(`details`,{className:`chat-session-tools`,ref:re,hidden:!n,children:[Z(`summary`,{children:`Session actions`}),Z(`div`,{className:`chat-session-tool-list`,children:[Z(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/retry`),children:`Retry`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/undo`),children:`Undo`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`/title`,`Session title`),children:`Rename`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>pe(`/branch`,`Branch name (optional)`),children:`Branch`}),Z(`button`,{className:`btn`,type:`button`,onClick:()=>fe(`/compress --preview`),children:`Preview compression`})]})]})]}),Z(`div`,{className:`chat-transcript`,ref:ne,children:!i.length&&!L?Z(`div`,{className:`chat-empty-state`,children:[Z(`span`,{className:`chat-empty-mark`,children:`A`}),Z(`h2`,{children:`What are we working on?`}),Z(`p`,{children:`Ask Archie anything, or start with one of these prompts.`}),Z(`div`,{className:`chat-prompt-grid`,children:[Z(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Summarise active tasks`),z.current?.focus()},children:`Summarise active tasks`}),Z(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Show running agents`),z.current?.focus()},children:`Show running agents`}),Z(`button`,{className:`chat-prompt`,type:`button`,onClick:()=>{s(`Check system status`),z.current?.focus()},children:`Check system status`})]})]}):Z(S,{children:[i.map((e,t)=>{let n=e.from??e.From??``,r=e.text??e.Text??``,i=n!==`web`,a=e.tool_calls||e.ToolCalls||[];return Z(`div`,{className:`chat-bubble-row ${i?`assistant`:`user`}`,children:Z(`div`,{className:`chat-bubble`,children:[Z(`div`,{className:`chat-bubble-meta`,children:i?`Archie`:`You`}),i?Z(S,{children:[a.length>0&&Z(`div`,{className:`chat-tools`,children:a.map((e,t)=>{if(e.path)return Z(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[Z(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),Z(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.Name||e.tool||`tool`,r=e.parameters||e.Parameters||``,i=e.summary||e.Summary||e.text||e.err||e.Err||`done`;return Z(`div`,{className:`chat-tool ${e.err||e.Err||e.failed?`failed`:``}`,children:[Z(`span`,{className:`chat-tool-icon`,children:`🔧`}),Z(`span`,{className:`chat-tool-name`,children:n}),r&&Z(`code`,{className:`chat-tool-parameters`,children:r}),Z(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),Z(mi,{text:r})]}):Z(`div`,{className:`chat-bubble-text`,children:r})]})},t)}),L&&Z(`div`,{className:`chat-bubble-row assistant`,children:Z(`div`,{className:`chat-bubble`,children:[Z(`div`,{className:`chat-bubble-meta`,children:`Archie`}),L.tools?.length>0&&Z(`div`,{className:`chat-tools`,children:L.tools.map((e,t)=>{if(e.path)return Z(`a`,{className:`chat-nav-chip`,href:`#${e.path}`,title:`Go to ${e.label||e.path}`,children:[Z(`span`,{className:`chat-nav-chip-icon`,"aria-hidden":`true`,children:`↗`}),Z(`span`,{className:`chat-nav-chip-label`,children:e.label||e.path})]},t);let n=e.name||e.tool||`tool`,r=e.parameters||``,i=e.summary||e.text||(e.failed?`failed`:`running…`);return Z(`div`,{className:`chat-tool ${e.failed?`failed`:``}`,children:[Z(`span`,{className:`chat-tool-icon`,children:`🔧`}),Z(`span`,{className:`chat-tool-name`,children:n}),r&&Z(`code`,{className:`chat-tool-parameters`,children:r}),Z(`span`,{className:`chat-tool-summary`,children:i})]},t)})}),Z(mi,{text:L.text||`…`}),L.isError&&Z(`button`,{className:`btn chat-retry`,type:`button`,onClick:()=>Se({turn:L.turn}),children:`Retry`})]})})]})}),Z(`div`,{className:`chat-compose`,children:Z(`div`,{className:`chat-composer-shell`,children:[Z(`textarea`,{ref:z,className:`chat-composer`,rows:3,placeholder:`Message Archie… (commands like /status and /new work here)`,"aria-label":`Message Archie`,disabled:u,value:o,onInput:ye,onKeyDown:xe}),D&&C.length>0&&Z(`div`,{className:`chat-command-menu`,ref:ie,role:`listbox`,"aria-label":`Commands`,children:C.map((e,t)=>Z(`button`,{type:`button`,role:`option`,"aria-selected":String(t===T),className:`chat-command-option`,onMouseDown:e=>e.preventDefault(),onClick:()=>be(t),children:[Z(`code`,{children:e.command}),Z(`span`,{children:e.description||e.usage||``})]},e.command))}),Z(`div`,{className:`chat-compose-actions`,children:[Z(`span`,{className:`chat-hint`,children:`Enter to send · Shift+Enter for a new line`}),Z(`button`,{className:`btn`,type:`button`,disabled:!u,onClick:Ce,children:`Stop`}),Z(`button`,{className:`btn btn-primary`,type:`button`,disabled:u||!o.trim(),onClick:()=>Se(),children:`Send`})]})]})})]})]})]})}function gi(){let e=document.createElement(`div`);return e.className=`chat-page`,re(Z(hi,{}),e),e}function _i(e,t){let n=yi(t);for(let t of e){let e=bi(t.path,n);if(e)return{route:t,params:e}}return null}function vi(e){return e?.navPath||e?.path||`/`}function yi(e){let t=String(e??`/`).split(`?`,1)[0].split(`#`,1)[0];return t?t.length>1&&t.endsWith(`/`)?t.slice(0,-1):t:`/`}function bi(e,t){let n=String(e).split(`/`),r=String(t).split(`/`);if(n.length!==r.length)return null;let i={};for(let e=0;e[...xi.filter(e=>e.nav!==!1).map(t=>{let r=W(`a.nav-item`,{href:`#${t.path}`,onclick:n=>{t.soon?n.preventDefault():e(t.path)},"aria-disabled":t.soon||void 0,title:t.soon?`Coming soon`:void 0},G(t.icon),W(`span.nav-label`,t.label),t.soon&&W(`span.nav-soon`,`soon`));return n.set(t.path,r),r})])),i=W(`button.icon-btn`,{title:`Toggle light and dark`,"aria-label":`Toggle light and dark`,onclick:()=>{Ci(wi()===`dark`?`light`:`dark`),Te(i,G(wi()===`dark`?`moon`:`sun`))}});Te(i,G(wi()===`dark`?`moon`:`sun`));let a,o=()=>{a?.classList.remove(`is-open`),s.setAttribute(`aria-expanded`,`false`)},s=W(`button.icon-btn.mobile-search-toggle`,{type:`button`,"aria-label":`Open Jump to navigation`,"aria-expanded":`false`,onclick:()=>{a.classList.add(`is-open`),s.setAttribute(`aria-expanded`,`true`),c.focus()}},G(`search`,{size:15})),c=W(`input`,{type:`search`,placeholder:`Jump to…`,"aria-label":`Jump to a section`,onkeydown:t=>{if(t.key===`Escape`){t.preventDefault(),o(),t.target.blur();return}if(t.key!==`Enter`)return;let n=t.target.value.trim().toLowerCase(),r=xi.find(e=>e.nav!==!1&&!e.soon&&e.label.toLowerCase().startsWith(n));r&&(e(r.path),t.target.value=``,t.target.blur(),o())}});return a=W(`div.topbar-search`,W(`span.topbar-search-icon`,{"aria-hidden":`true`},G(`search`,{size:15})),s,c),{node:W(`header.topbar`,W(`div.brand`,W(`span.brand-mark`,`A`),`Archie`),r,W(`div.topbar-end`,a,W(`button.icon-btn.icon-btn-chat`,{"aria-label":`Open chat`,title:`Chat with Archie`,"aria-expanded":`false`,onclick:()=>t?.()},G(`chat`)),W(`button.icon-btn`,{title:`Documentation`,"aria-label":`Documentation`},G(`help`)),i,W(`div.avatar`,{title:`Signed in locally`},`A`))),highlight(e){for(let[t,r]of n)t===e?r.setAttribute(`aria-current`,`page`):r.removeAttribute(`aria-current`)},hide(e){for(let t of e)n.get(t)?.remove()}}}function Ei(){Ci(wi());let e=W(`main.main`),t=W(`aside.chat-drawer`,{"aria-label":`Chat with Archie`}),n=W(`button.icon-btn.chat-drawer-close`,{"aria-label":`Close chat`,title:`Close chat`,onclick:()=>o(!1)},G(`close`)),r=W(`div.chat-drawer-head`,W(`strong`,`Archie`),n);t.append(W(`div.chat-drawer-panel`,r,gi()),W(`div.chat-scrim`,{onclick:()=>o(!1)}));let i=Ti(s,()=>o());U.capabilities().then(e=>i.hide(fe(e?.sections,xi))).catch(()=>{});let a=W(`div.shell`,i.node,e,t);Te(document.getElementById(`app`),a);function o(e){let n=e===void 0?!t.classList.contains(`is-open`):e;t.classList.toggle(`is-open`,n),document.body.classList.toggle(`chat-open`,n);let r=a.querySelector(`.icon-btn-chat`);r&&r.setAttribute(`aria-expanded`,String(n))}window.__archieToggleChat=o;function s(e){location.hash===`#`+e?c(e):location.hash=e}function c(t){e.firstElementChild?.dispatchEvent(new CustomEvent(`archie:teardown`));let[n,r=``]=t.split(`?`,2),a=_i(xi,n),s=a?.route||xi[0];if(i.highlight(vi(s)),s.path===`/chat`){Te(e),o(!0);return}let c=s.view?s.view(new URLSearchParams(r),a?.params||{}):Di(s);c instanceof Node?Te(e,c):re(c,e),o(!1)}window.addEventListener(`hashchange`,()=>c(location.hash.slice(1)||`/`)),window.addEventListener(`keydown`,e=>{e.defaultPrevented||e.key===`Escape`&&t.classList.contains(`is-open`)&&o(!1)}),c(location.hash.slice(1)||`/`)}function Di(e){return W(`div`,W(`div.page-head`,W(`div`,W(`h1.page-title`,e.label))),W(`div.card`,W(`div.empty`,W(`div.empty-title`,`${e.label} is not built yet`),W(`div`,`This section is next up. Nothing is broken.`))))}Ei(); \ No newline at end of file diff --git a/ui/src/base/api.jsx b/ui/src/base/api.jsx index e98fd9065..7404780ca 100644 --- a/ui/src/base/api.jsx +++ b/ui/src/base/api.jsx @@ -95,6 +95,9 @@ export const api = { tasks: () => request("/api/tasks"), taskMeta: () => request("/api/task-meta"), task: (id) => request(`/api/tasks/${id}`), + taskAttempts: (id) => request(`/api/tasks/${id}/attempts`), + taskChanges: (id, params) => request(`/api/tasks/${id}/changes` + qs(params)), + taskDebug: (id, params) => request(`/api/tasks/${id}/debug` + qs(params)), taskAction: (id, action) => request(`/api/tasks/${id}/action`, { method: "POST", body: { action } }), setup: () => request("/api/setup"), capabilities: () => request("/api/capabilities"), diff --git a/ui/src/base/log-row.jsx b/ui/src/base/log-row.jsx index 9b5c8b634..68feb2df9 100644 --- a/ui/src/base/log-row.jsx +++ b/ui/src/base/log-row.jsx @@ -9,6 +9,18 @@ import { el } from "./dom.jsx"; * second distinct consumer". */ +// The level filter vocabulary. Server-side level filtering takes a CSV of +// levels (`splitCSV` in internal/webui/api_tasks_logs.go), so the combined +// options are a wire concern too, not a display choice. It lives here because +// both the daemon log page and a task attempt's log pane filter by level. +export const LOG_LEVELS = [ + { 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" }, +]; + export function levelKind(level) { switch ((level || "").toUpperCase()) { case "ERROR": diff --git a/ui/src/css/base.css b/ui/src/css/base.css index 9ab5215b1..6613c8227 100644 --- a/ui/src/css/base.css +++ b/ui/src/css/base.css @@ -30,3 +30,27 @@ a { color: inherit; text-decoration: none; } + +/* The focus floor. A component may style its own focus state; this guarantees + that nothing is ever focused and invisible for a keyboard user. `:focus-visible` + rather than `:focus` so a mouse click does not draw a ring around what was + clicked. */ +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* Accessible-only text: present to assistive technology, out of the visual + layout. Used for live-region status lines, which announce a change without + drawing a second, visible copy of the pane's own copy. */ +.visually-hidden { + position: absolute; + width: 1px; + height: 1px; + margin: -1px; + padding: 0; + border: 0; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} diff --git a/ui/src/logs/logs.jsx b/ui/src/logs/logs.jsx index a32a9d419..7eefa7950 100644 --- a/ui/src/logs/logs.jsx +++ b/ui/src/logs/logs.jsx @@ -2,6 +2,7 @@ import { h } from "preact"; import { useState, useEffect, useRef, useMemo } from "preact/hooks"; import "./logs.css"; import { api, subscribeLogs } from "../base/api.jsx"; +import { LOG_LEVELS } from "../base/log-row.jsx"; import { Pill } from "../base/pill.jsx"; function Empty({ title, detail }) { @@ -52,13 +53,6 @@ function LogRow({ entry }) { ); } -const LEVELS = [ - { 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 entryKey(entry) { return `${entry.time || ""}|${entry.level || ""}|${entry.message || entry.msg || ""}|${JSON.stringify(entry.fields || {})}`; @@ -191,7 +185,7 @@ function LogsApp() { value={filters.level} onChange={(e) => setFilters(f => ({ ...f, level: e.target.value }))} > - {LEVELS.map(l => )} + {LOG_LEVELS.map(l => )} change({ level: e.target.value })} + > + {LOG_LEVELS.map((level) => ( + + ))} + + + + {/* A stage filter is a narrowing, not a clean sweep: only lines a + stage tagged carry a stage, and agent/tool output never does. + Saying so beside the control is what keeps a sparse result from + reading as a broken pane. */} + {filters.stage ? ( +

+ A stage filter matches only log lines that record a stage. Agent and tool output + carries none, so it is not shown while this filter is set. +

+ ) : null} + {!filters.stage && !(stages || []).length ? ( +

+ This attempt recorded no stage names, so the stage filter has nothing to match. +

+ ) : null} + + ) : null} + + ); +} + +// The pane's state, announced once. It is a live region for STATE, not for the +// log's lines: putting aria-live on the list itself would read every entry +// aloud on every load, which for a 500-entry pane is unusable. `aria-atomic` +// makes the whole sentence re-announce rather than a fragment of it. +function LogStatus({ text }) { + return ( +

+ {text} +

+ ); +} + +export function TaskLogPanel({ + state, + onRetry, + taskId, + attempt, + filters = EMPTY_LOG_FILTERS, + onFilterChange, + stages = [], +}) { + const resolvedAttempt = Number(attempt) || Number(state?.attempt) || 0; + + // One live-region sentence per read outcome, so the pane announces WHICH case + // it is in. The two unavailable cases stay distinct in the announcement the + // same way they stay distinct on screen. + let status; + let body; if (state === undefined) { - return
Loading attempt log…
; - } - if (state === null) { - return ( + status = "Loading this attempt's log"; + body =
Loading attempt log…
; + } else if (state === null) { + status = "This attempt's log could not be loaded"; + body = (
Could not load this attempt's log.
- +
); - } - - // A reader exists in this process but the attempt has no log file. That is a - // fact about the attempt, and saying "logging was not enabled" here (which - // this panel used to do) told the operator to go and change a setting that - // was already correct. - if (state.found === false && !state.disabled) { - return ( + } else if (state.found === false && !state.disabled) { + // A reader exists in this process but the attempt has no log file. That is + // a fact about the attempt, and saying "logging was not enabled" here (which + // this panel used to do) told the operator to go and change a setting that + // was already correct. + status = "No log recorded for this attempt"; + body = (
No log recorded for this attempt
This attempt produced no output, or it has not started writing yet.
); - } - - // This process cannot read task logs at all. That IS about the deployment, - // and it is the only case where the panel may say so. - if (state.disabled) { - return ( + } else if (state.disabled) { + // This process cannot read task logs at all. That IS about the deployment, + // and it is the only case where the panel may say so. + status = "This dashboard cannot read task logs"; + body = (
No persisted log for this attempt
This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.
); + } else { + const entries = state.entries || []; + const download = taskId != null ? taskLogDownloadURL(taskId, resolvedAttempt || null) : null; + const footer = download ? ( + + Download log + + ) : null; + if (!entries.length) { + status = "This attempt's log has no entries matching the current filter"; + body = ( +
+
Nothing recorded
+
This attempt's log file has no entries matching the current filter.
+ {footer} +
+ ); + } else { + status = `${entries.length} log entr${entries.length === 1 ? "y" : "ies"} shown`; + body = ( + <> +
+ {entries.map((entry, i) => ( + + ))} +
+ {footer} + + ); + } } - const entries = state.entries || []; - const download = taskId != null ? taskLogDownloadURL(taskId, state.attempt) : null; - const footer = download ? ( - Download log - ) : null; - - if (!entries.length) { - return ( -
-
Nothing recorded
-
This attempt's log file has no entries matching the current filter.
- {footer} -
- ); - } return ( <> -
- {entries.map((entry, i) => ( - - ))} -
- {footer} + + + {body} ); } diff --git a/ui/src/tasks/tasks.css b/ui/src/tasks/tasks.css index a88292b69..3b31e2586 100644 --- a/ui/src/tasks/tasks.css +++ b/ui/src/tasks/tasks.css @@ -79,6 +79,19 @@ text-decoration: underline; } +/* The title cell links to the task's run detail page. It inherits the title's + colour so the row still reads as a list, and underlines on hover so the link + is discoverable. */ +.task-detail-link { + color: inherit; +} + +.task-detail-link:hover, +.task-detail-link:focus-visible { + text-decoration: underline; + text-decoration-color: var(--accent); +} + .task-actions { display: flex; gap: var(--sp-1); diff --git a/ui/src/tasks/tasks.jsx b/ui/src/tasks/tasks.jsx index dcc172fec..b5a990516 100644 --- a/ui/src/tasks/tasks.jsx +++ b/ui/src/tasks/tasks.jsx @@ -8,9 +8,22 @@ import { statTile as renderStatTile } from "../base/statTile.jsx"; import { taskRowA11y } from "./task-row.jsx"; import { initialTaskFilter, taskMatchesStatus } from "./task-filters.jsx"; import { describeTimelineEvent } from "./timeline-event.jsx"; -import { TaskLogPanel } from "./task-logs.jsx"; +import { TaskLogPanel, logCacheKey } from "./task-logs.jsx"; import { actionFor, statusIds, statusKind, statusLabel } from "../base/task-meta.jsx"; +// The shell's global reduced-motion rule switches CSS transitions and +// animations, NOT the JS smooth scroll this page performs when it reveals a +// deep-linked row. The decision therefore has to be made here, in JavaScript, +// and is exported so it can be tested directly (jsdom implements neither +// matchMedia nor scrollIntoView). +export function prefersReducedMotion() { + return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true; +} + +export function revealBehavior() { + return prefersReducedMotion() ? "auto" : "smooth"; +} + function StatTileNode(props) { const ref = useRef(null); useEffect(() => { @@ -50,6 +63,20 @@ function Empty({ title, detail }) { ); } +// The open log pane loads its own attempt's log whenever it is showing an +// attempt it has no cached entry for: a retry moves the pane to a new attempt, +// a forced reload drops its own entry, and a row can be reopened long after the +// click that first opened it. Loading only from that click is what would leave +// the pane sitting on "Loading…" with nothing fetching it. +function TaskLogSection({ taskId, attempt, state, onLoad, onRetry }) { + const load = useRef(onLoad); + load.current = onLoad; + useEffect(() => { + if (state === undefined) load.current(); + }, [state]); + return ; +} + function TasksApp({ query }) { const [tasks, setTasks] = useState(null); const [error, setError] = useState(null); @@ -63,6 +90,7 @@ function TasksApp({ query }) { const [eventCache, setEventCache] = useState(new Map()); const [logCache, setLogCache] = useState(new Map()); + const logRequests = useRef(new Set()); const [logsExpanded, setLogsExpanded] = useState(new Set()); const [actionErrors, setActionErrors] = useState(new Map()); const [actionsInFlight, setActionsInFlight] = useState(new Set()); @@ -77,9 +105,11 @@ function TasksApp({ query }) { loadTimeline(expandedId); } } + return res; } catch (err) { setError(String(err.message || err)); setTasks(null); + return null; } }; @@ -97,18 +127,40 @@ function TasksApp({ query }) { } }; - const loadTaskLogs = async (id) => { - setLogCache(prev => { + const loadTaskLogs = async (id, attempt, { force = false } = {}) => { + // The cache entry is identified by the task AND the attempt: a task alone + // cannot tell two runs apart, so a retry used to leave the previous + // attempt's log on screen under the new run. One request per key, unless a + // control explicitly asks for the read again. + const key = logCacheKey(id, attempt); + if (logRequests.current.has(key) && !force) return; + logRequests.current.add(key); + if (force) { + setLogCache(prev => { + const next = new Map(prev); + next.delete(key); + return next; + }); + } + try { + const res = await api.taskLogs(id, { attempt: attempt || undefined, limit: 500 }); + setLogCache(prev => new Map(prev).set(key, res)); + } catch { + setLogCache(prev => new Map(prev).set(key, null)); + } + }; + + // An operator action can change a task's timeline -- a retry begins a new + // attempt -- so the events cached for that task are dropped rather than served + // against the new state. The log cache needs no invalidation here: its key + // already carries the attempt, so the new run is a different entry and can + // never be answered by the ended attempt's log. + const invalidateTaskCaches = (id) => { + setEventCache(prev => { const next = new Map(prev); next.delete(id); return next; }); - try { - const res = await api.taskLogs(id, { limit: 500 }); - setLogCache(prev => new Map(prev).set(id, res)); - } catch { - setLogCache(prev => new Map(prev).set(id, null)); - } }; const performAction = async (id, action) => { @@ -127,7 +179,14 @@ function TasksApp({ query }) { return next; }); if (action === "archive") setExpandedId(null); - await load(); + invalidateTaskCaches(id); + const res = await load(); + // A row that is still open reloads against the attempt the task now has; + // otherwise it would sit on "Loading…" with its cache entry gone. + const updated = Array.isArray(res) ? res.find(t => String(t.id) === String(id)) : null; + if (updated && expandedId === id) { + loadTimeline(id); + } } catch (err) { setActionsInFlight(prev => { const next = new Set(prev); @@ -146,7 +205,9 @@ function TasksApp({ query }) { const row = document.getElementById(`task-row-${expandedId}`); if (row) { row.focus({ preventScroll: true }); - row.scrollIntoView({ block: "center", behavior: "smooth" }); + // Optional call: focusing a deep-linked row is a nicety, and not every + // environment implements scrollIntoView on an element. + row.scrollIntoView?.({ block: "center", behavior: revealBehavior() }); } }); } @@ -164,12 +225,8 @@ function TasksApp({ query }) { const toggleLogs = (id) => { setLogsExpanded(prev => { const next = new Set(prev); - if (next.has(id)) { - next.delete(id); - } else { - next.add(id); - if (!logCache.has(id)) loadTaskLogs(id); - } + if (next.has(id)) next.delete(id); + else next.add(id); return next; }); }; @@ -302,6 +359,7 @@ function TasksApp({ query }) { }; const renderTimelineRow = (t) => { + const logKey = logCacheKey(t.id, t.attempt); const cached = eventCache.get(t.id); const logsExpandedForTask = logsExpanded.has(t.id); @@ -359,7 +417,13 @@ function TasksApp({ query }) { {logsExpandedForTask && ( - loadTaskLogs(t.id)} /> + loadTaskLogs(t.id, t.attempt)} + onRetry={() => loadTaskLogs(t.id, t.attempt, { force: true })} + /> )} @@ -448,7 +512,15 @@ function TasksApp({ query }) { {issueLink(t) ?? `#${t.issue_number}`} - {t.title || "(untitled)"} + e.stopPropagation()} + onKeyDown={(e) => e.stopPropagation()} + > + {t.title || "(untitled)"} + diff --git a/ui/src/tasks/timeline-event.jsx b/ui/src/tasks/timeline-event.jsx index 635675be5..9818c693b 100644 --- a/ui/src/tasks/timeline-event.jsx +++ b/ui/src/tasks/timeline-event.jsx @@ -4,7 +4,9 @@ function words(value) { .replace(/\b\w/g, (letter) => letter.toUpperCase()); } -function duration(milliseconds) { +// Exported so the stage rail renders a duration exactly the way the timeline +// does; a second formatter would eventually disagree with this one. +export function duration(milliseconds) { const ms = Number(milliseconds); if (!Number.isFinite(ms) || ms < 0) return ""; if (ms < 1000) return `${Math.round(ms)} ms`; @@ -79,5 +81,21 @@ export function describeTimelineEvent(ev = {}) { }; } + // Condition (d): the two provenance kinds render as one human line. The + // captured payload is rendered by its own panel, never dumped into the + // timeline, so these cases name what was recorded and nothing more. + if (ev.kind === "config_captured") { + return { + title: "Configuration captured", + detail: "The effective task-runtime configuration for this run.", + }; + } + if (ev.kind === "changes_captured") { + const fileCount = Number(data.totals?.files); + const files = Number.isFinite(fileCount) && fileCount > 0 ? `${fileCount} file${fileCount === 1 ? "" : "s"} changed` : ""; + const after = data.captured_after ? `captured after ${data.captured_after}` : ""; + return { title: "Change capture recorded", detail: [files, after].filter(Boolean).join(" · ") }; + } + return { title: words(ev.kind || ev.type), detail: ev.detail || "" }; } diff --git a/ui/test/api-client.test.js b/ui/test/api-client.test.js index 63adfed89..70759389a 100644 --- a/ui/test/api-client.test.js +++ b/ui/test/api-client.test.js @@ -44,6 +44,9 @@ const READS = [ ["tasks", []], ["taskMeta", []], ["task", [1]], + ["taskAttempts", [1]], + ["taskChanges", [1, { attempt: 2 }]], + ["taskDebug", [1, { attempt: 2 }]], ["setup", []], ["capabilities", []], ["workflows", []], @@ -191,6 +194,28 @@ test("a 415 keeps the server's explanation and reads as refused", async () => { ); }); +// The run detail page's reads. `qs` drops empty values, so an attempt the page +// has not resolved yet must not be sent as an empty string: the server treats an +// absent attempt as "the task's current attempt", and `attempt=` would be a +// different, malformed request. +test("the run detail reads build their URLs with absent filters absent", async () => { + stubFetch(okResponse); + await api.taskAttempts(42); + await api.taskChanges(42, { attempt: 2 }); + await api.taskDebug(42, { attempt: 0 }); + await api.taskChanges(42, {}); + + assert.deepEqual( + calls.map((call) => call.path), + [ + "/api/tasks/42/attempts", + "/api/tasks/42/changes?attempt=2", + "/api/tasks/42/debug?attempt=0", + "/api/tasks/42/changes", + ], + ); +}); + test("every api method is classified by this suite", () => { const classified = new Set([ ...MUTATIONS.map(([name]) => name), diff --git a/ui/test/attempt-config.test.js b/ui/test/attempt-config.test.js new file mode 100644 index 000000000..e6bbe314e --- /dev/null +++ b/ui/test/attempt-config.test.js @@ -0,0 +1,111 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { render, cleanup } from "@testing-library/preact"; +import { AttemptConfig, CONFIG_SCHEMA, selectConfigEvent } from "../src/tasks/attempt-config.jsx"; + +const EVENTS = [ + { + kind: "config_captured", + attempt: 1, + at: "2026-09-18T07:00:00.100Z", + stage: "", + data: { schema: CONFIG_SCHEMA, document: { BotUser: "archie-attempt-one", Models: { main: "openai/gpt" } } }, + }, + { + kind: "config_captured", + attempt: 2, + at: "2026-09-18T07:05:00.100Z", + stage: "", + data: { schema: CONFIG_SCHEMA, document: { BotUser: "archie-attempt-two", Models: { main: "openai/gpt" } } }, + }, +]; + +function mount(props) { + const { container, unmount } = render(); + return { root: container, unmount }; +} + +// Selecting by kind alone would show the newest attempt's configuration on +// every attempt -- the merge-attempts bug the attempt column exists to prevent. +test("the configuration is selected by kind and attempt together", () => { + const { root, unmount } = mount({ events: EVENTS, attempt: 1 }); + assert.match(root.textContent, /archie-attempt-one/); + assert.doesNotMatch(root.textContent, /archie-attempt-two/); + assert.match(root.textContent, /attempt 1's effective task-runtime configuration/); + unmount(); +}); + +test("an attempt with no config event of its own says so, never another attempt's", () => { + const { root, unmount } = mount({ events: EVENTS, attempt: 3 }); + assert.equal(root.querySelector(".empty-title").textContent, "Not captured for this run"); + assert.doesNotMatch(root.textContent, /archie-attempt-one|archie-attempt-two/); + assert.match(root.textContent, /Nothing here says the run used the defaults/); + unmount(); +}); + +test("the document is passed through verbatim, pretty-printed", () => { + const { root, unmount } = mount({ events: EVENTS, attempt: 2 }); + const json = root.querySelector(".run-json").textContent; + assert.match(json, /"BotUser": "archie-attempt-two"/); + assert.match(json, /"Models"/); + unmount(); +}); + +// The page must not imply this document is the whole configuration: it is the +// non-secret task-runtime subset. +test("the panel states the scope of what was captured", () => { + const { root, unmount } = mount({ events: EVENTS, attempt: 1 }); + assert.match(root.textContent, /non-secret subset/); + assert.match(root.textContent, /not the dashboard configuration view/); + assert.match(root.textContent, /providers, repositories, identities, credentials and lock state/); + unmount(); +}); + +test("an unrecognised schema is named and its payload is still shown", () => { + const events = [ + { kind: "config_captured", attempt: 2, at: "2026-09-18T07:05:00.100Z", data: { schema: "archie/task-config@9", document: { future: true } } }, + ]; + const { root, unmount } = mount({ events, attempt: 2 }); + assert.match(root.textContent, /unknown schema \(archie\/task-config@9\)/); + assert.match(root.querySelector(".run-json").textContent, /"future": true/); + unmount(); +}); + +test("a config event with no data at all renders the raw payload rather than guessing", () => { + const events = [{ kind: "config_captured", attempt: 2, at: "2026-09-18T07:05:00.100Z" }]; + const { root, unmount } = mount({ events, attempt: 2 }); + assert.match(root.textContent, /unknown schema/); + assert.ok(root.querySelector(".run-json")); + unmount(); +}); + +test("loading and failure states are distinct, and the failure offers a retry", () => { + const loading = mount({ events: undefined, attempt: 1 }); + assert.match(loading.root.textContent, /Loading this task's events/); + loading.unmount(); + + const failed = mount({ events: null, attempt: 1, onRetry: () => {} }); + assert.match(failed.root.textContent, /Could not load this task's events/); + assert.equal(failed.root.querySelector("button").textContent, "Retry"); + failed.unmount(); +}); + +test("selectConfigEvent ignores other kinds and other attempts", () => { + const events = [ + { kind: "stage_finish", attempt: 2, data: {} }, + ...EVENTS, + ]; + assert.equal(selectConfigEvent(events, 2).attempt, 2); + assert.equal(selectConfigEvent(events, 3), null); + assert.equal(selectConfigEvent(undefined, 1), null); +}); + +// CONFIG_SCHEMA mirrors events.ConfigCapturedSchema (internal/events/events.go), +// which the Go suite pins by the same literal. Pinning both sides is what makes +// a one-sided rename a failing test rather than every attempt rendering as +// "unknown schema". +test("the config schema is the one the producer stamps", () => { + assert.equal(CONFIG_SCHEMA, "archie/task-config@1"); +}); + +test.after(() => cleanup()); diff --git a/ui/test/changed-files.test.js b/ui/test/changed-files.test.js new file mode 100644 index 000000000..d799d29a1 --- /dev/null +++ b/ui/test/changed-files.test.js @@ -0,0 +1,169 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { render, cleanup } from "@testing-library/preact"; +import { ChangedFiles, fileStatusLabel } from "../src/tasks/changed-files.jsx"; + +const CAPTURE = { + captured_at: "2026-09-18T07:03:00.000Z", + captured_after: "commit", + stage: "commit", + owner: "o", + repo: "r", + base: "main", + branch: "feat/42-x", + head_sha: "abcdef1234567890", + base_sha: "0987654321fedcba", + pr_number: 7, + totals: { files: 3, additions: 40, deletions: 5 }, + truncated: false, + files: [ + { path: "internal/x.go", old_path: "", status: "modified", additions: 12, deletions: 3, binary: false }, + { path: "bin/app", old_path: "", status: "added", additions: 0, deletions: 0, binary: true }, + { path: "internal/new.go", old_path: "internal/old.go", status: "renamed", additions: 1, deletions: 1, binary: false }, + ], +}; + +const TASK = { + id: 42, + repo_url: "https://forge.example.internal/o/r", + pr_number: 7, + pr_url: "https://forge.example.internal/o/r/pull/7", +}; + +function mount(props) { + const { container, unmount } = render(); + return { root: container, unmount }; +} + +function rowFor(root, path) { + return [...root.querySelectorAll(".run-changes-table tbody tr")].find((row) => + row.querySelector(".run-changes-path")?.textContent.includes(path), + ); +} + +// F5: nothing predating the capture has one, and the forge cannot supply one, so +// an empty view must not read as "this run changed nothing". +test("no capture recorded is not reported as no files changed", () => { + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: false, captures: [] } }); + assert.equal(root.querySelector(".empty-title").textContent, "No change capture was recorded for this attempt"); + assert.match(root.textContent, /not the same as "no files changed"/); + assert.doesNotMatch(root.textContent, /Nothing changed/); + unmount(); +}); + +test("a capture renders its per-file counts and statuses", () => { + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [CAPTURE] }, task: TASK }); + const modified = rowFor(root, "internal/x.go"); + assert.match(modified.textContent, /Modified/); + assert.doesNotMatch(modified.textContent, /modified/, "the raw status code must not be shown as a word"); + assert.match(modified.textContent, /\+12/); + assert.equal(root.querySelector(".run-capture-totals").textContent, "3 files · +40 · −5"); + unmount(); +}); + +// found:true with no readable capture is a READ failure, not "nothing was +// captured": the server reports found from the capture event's existence, so +// conflating the two tells the operator no capture was recorded when one +// demonstrably was. +test("a capture that was recorded but could not be read is not reported as missing", () => { + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [] } }); + assert.match(root.textContent, /could not be read/i); + assert.doesNotMatch(root.textContent, /No change capture was recorded/); + unmount(); +}); + +test("a renamed file shows the path it came from", () => { + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [CAPTURE] } }); + const renamed = rowFor(root, "internal/new.go"); + assert.match(renamed.textContent, /Renamed/); + assert.match(renamed.textContent, /internal\/old\.go → internal\/new\.go/); + unmount(); +}); + +// A zero-hunk file is "no textual hunks", which is what the capture actually +// recorded -- not a claim about the file's type on disk. +test("a file with no textual hunks is described that way, not as a binary", () => { + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [CAPTURE] } }); + const binary = rowFor(root, "bin/app"); + assert.match(binary.textContent, /no textual hunks/); + assert.match(binary.textContent, /Added/); + assert.doesNotMatch(binary.textContent, /binary/i); + unmount(); +}); + +test("a truncated capture says so while still reporting complete totals", () => { + const truncated = { ...CAPTURE, truncated: true, totals: { files: 210, additions: 900, deletions: 40 } }; + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [truncated] } }); + assert.match(root.textContent, /Showing the first 3 of 210 files/); + assert.match(root.textContent, /210 files · \+900 · −40/); + unmount(); +}); + +test("the capture links to the repository and the pull request", () => { + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [CAPTURE] }, task: TASK }); + const hrefs = [...root.querySelectorAll("a")].map((a) => a.getAttribute("href")); + assert.ok(hrefs.includes("https://forge.example.internal/o/r")); + assert.ok(hrefs.includes("https://forge.example.internal/o/r/pull/7")); + assert.match(root.textContent, /feat\/42-x → main/); + assert.match(root.textContent, /abcdef12/); + unmount(); +}); + +// A link is only rendered when there is a URL behind it: a capture with no forge +// coordinates shows its owner/repo and PR number as text rather than a dead link. +test("a capture with no forge URL shows plain text instead of a dead link", () => { + const bare = { ...CAPTURE, pr_number: 9 }; + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [bare] } }); + assert.match(root.textContent, /PR #9/); + assert.equal(root.querySelectorAll("a").length, 0); + unmount(); +}); + +test("multiple captures in one attempt all render, oldest first", () => { + const second = { + ...CAPTURE, + captured_at: "2026-09-18T07:06:00.000Z", + captured_after: "commit-push", + stage: "push", + }; + const { root, unmount } = mount({ state: { task_id: 42, attempt: 2, found: true, captures: [CAPTURE, second] } }); + const heads = [...root.querySelectorAll(".run-capture-when")].map((n) => n.textContent); + assert.deepEqual(heads, ["Captured after commit in stage commit", "Captured after commit-push in stage push"]); + unmount(); +}); + +test("loading and failure states are distinct, and the failure offers a retry", () => { + const loading = mount({ state: undefined }); + assert.match(loading.root.textContent, /Loading changed files/); + loading.unmount(); + + const failed = mount({ state: null, onRetry: () => {} }); + assert.match(failed.root.textContent, /Could not load this attempt's changed files/); + assert.equal(failed.root.querySelector("button").textContent, "Retry"); + failed.unmount(); +}); + +test("the status vocabulary is words, and an unknown status is passed through", () => { + assert.equal(fileStatusLabel("added"), "Added"); + assert.equal(fileStatusLabel("typechange"), "Type changed"); + assert.equal(fileStatusLabel("submodule"), "submodule"); +}); + +// The five statuses are the producer's own vocabulary +// (internal/domain/workflow/task/changes.go), pinned by literal in the Go suite. +// This pins the dashboard half to the same five strings: without it, a rename on +// one side renders raw status codes beside words and both suites stay green. +test("the status vocabulary matches the strings the producer persists", () => { + const persisted = { + added: "Added", + modified: "Modified", + deleted: "Deleted", + renamed: "Renamed", + typechange: "Type changed", + }; + for (const [status, label] of Object.entries(persisted)) { + assert.equal(fileStatusLabel(status), label, `${status} must be a known status, not passed through`); + } +}); + +test.after(() => cleanup()); diff --git a/ui/test/main-routing.test.js b/ui/test/main-routing.test.js new file mode 100644 index 000000000..78768f74d --- /dev/null +++ b/ui/test/main-routing.test.js @@ -0,0 +1,112 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { waitFor } from "@testing-library/preact"; + +// The router as the browser actually uses it: main.jsx is imported once (it +// starts on import), and every step below navigates by changing the hash and +// waiting for the app to follow. This is the only place the wiring between the +// route table, the matcher and the navigation highlight is exercised -- the +// matcher's own unit tests cannot see whether `show` hands the nav the section +// path or the detail path. +// +// archied is absent on purpose: every request fails, which is itself a state +// these pages must render honestly rather than blankly. +globalThis.fetch = async () => { + throw new Error("no daemon in this test"); +}; + +// jsdom has no EventSource, and the dashboard subscribes to the daemon's event +// stream the moment it mounts. An inert stand-in keeps this test about routing +// rather than about the stream. +class InertEventSource { + close() {} +} +globalThis.EventSource = InertEventSource; + +function navCurrent(path) { + return document.querySelector(`a.nav-item[href="#${path}"]`)?.getAttribute("aria-current"); +} + +function title() { + return document.querySelector(".page-title")?.textContent; +} + +async function navigate(hash) { + location.hash = hash; + // jsdom queues its own hashchange for the assignment; waitFor lets it land. + await new Promise((resolve) => setTimeout(resolve, 0)); +} + +test("the app routes deep links and keeps the navigation highlight honest", async (t) => { + document.body.innerHTML = '
'; + location.hash = "#/tasks/42"; + await import("../src/main.jsx"); + await waitFor(() => assert.equal(title(), "Task #42")); + + await t.test("a per-task route renders the run page and keeps Tasks current", () => { + assert.equal(title(), "Task #42"); + assert.ok(document.querySelector(".run-restart"), "the run controls should render"); + assert.equal( + navCurrent("/tasks"), + "page", + "W9: a detail route must hand the nav its section, or Tasks silently loses aria-current", + ); + }); + + await t.test("the tasks list route still works", async () => { + await navigate("#/tasks"); + await waitFor(() => assert.equal(title(), "Tasks")); + assert.equal(navCurrent("/tasks"), "page"); + assert.equal(document.querySelector(".tab-bar"), null, "the run page is no longer mounted"); + }); + + // W10: #/tasks?task=N and #/tasks?status=... are pinned deep links. The steps + // below enter this route from the run page on purpose: the query string is an + // entry state, so a navigation that only changes the query of the page already + // mounted keeps the operator's own filter selection instead. + await t.test("a tab and attempt in the query string open that panel", async () => { + await navigate("#/tasks/7?tab=log&attempt=1"); + await waitFor(() => assert.equal(title(), "Task #7")); + const selected = [...document.querySelectorAll('[role="tab"]')].find( + (tab) => tab.getAttribute("aria-selected") === "true", + ); + assert.equal(selected.textContent, "Log"); + // The panels read one attempt, and this deployment answered no reads at + // all -- so the panel says that rather than claiming there is no attempt. + await waitFor(() => assert.match(document.body.textContent, /Could not load this task's attempts/)); + assert.equal(navCurrent("/tasks"), "page"); + }); + + // The real router, not a reconstruction of it: show() renders the run page with + // Preact's render() into one long-lived outlet, so two task ids on the same + // matched route must still be two component instances. Without a key on the + // page element the second id diffs the first one in place and the operator's + // Log tab from task 7 is still open on task 8. + await t.test("moving to another task id does not keep the previous task's panel", async () => { + await navigate("#/tasks/8"); + await waitFor(() => assert.equal(title(), "Task #8")); + const selected = [...document.querySelectorAll('[role="tab"]')].find( + (tab) => tab.getAttribute("aria-selected") === "true", + ); + assert.equal( + selected.textContent, + "Stages", + "W11: a new task id must remount the page, not inherit the previous task's open tab", + ); + assert.equal(navCurrent("/tasks"), "page"); + }); + + await t.test("the existing task deep links keep working", async () => { + await navigate("#/tasks?task=7&status=needs_you"); + await waitFor(() => assert.equal(title(), "Tasks")); + assert.equal(document.querySelector(".task-filter").value, "needs_you"); + assert.equal(navCurrent("/tasks"), "page"); + }); + + await t.test("an unmatched path falls back to the dashboard", async () => { + await navigate("#/nope/deep"); + await waitFor(() => assert.ok(document.querySelector(".hero-title"), "the dashboard should render")); + assert.equal(document.querySelector(".tab-bar"), null); + assert.equal(navCurrent("/"), "page"); + }); +}); diff --git a/ui/test/routing.test.js b/ui/test/routing.test.js new file mode 100644 index 000000000..c9cdcf245 --- /dev/null +++ b/ui/test/routing.test.js @@ -0,0 +1,57 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { matchRoute, navPath } from "../src/routing.jsx"; + +// The route table mirrors main.jsx's: a literal section and the parameterised +// detail page declared after it, which is the ordering that stops /tasks/:id +// from swallowing /tasks. +const routes = [ + { path: "/", label: "Dashboard" }, + { path: "/tasks", label: "Tasks", view: () => null }, + { path: "/tasks/:id", label: "Task run", view: () => null, nav: false, navPath: "/tasks" }, + { path: "/logs", label: "Logs", view: () => null }, +]; + +test("a literal path matches its own route, not a parameterised one", () => { + const match = matchRoute(routes, "/tasks"); + assert.equal(match.route.path, "/tasks"); + assert.deepEqual(match.params, {}); +}); + +test("a path segment is captured as a route param", () => { + const match = matchRoute(routes, "/tasks/42"); + assert.equal(match.route.path, "/tasks/:id"); + assert.deepEqual(match.params, { id: "42" }); +}); + +test("the query string is not part of the path", () => { + const match = matchRoute(routes, "/tasks/42?tab=changes&attempt=2"); + assert.equal(match.route.path, "/tasks/:id"); + assert.equal(match.params.id, "42"); +}); + +test("a trailing slash names the same route", () => { + assert.equal(matchRoute(routes, "/tasks/").route.path, "/tasks"); + assert.equal(matchRoute(routes, "/tasks/42/").params.id, "42"); +}); + +// A prefix rule would send every unknown path under a section to that section's +// page, so a typo would render something plausible instead of the dashboard. +test("an unmatched path matches nothing rather than the nearest prefix", () => { + assert.equal(matchRoute(routes, "/nope"), null); + assert.equal(matchRoute(routes, "/tasks/42/extra"), null); + assert.equal(matchRoute(routes, "/task"), null); +}); + +test("an encoded segment is decoded into the param", () => { + assert.equal(matchRoute(routes, "/tasks/a%20b").params.id, "a b"); +}); + +// W9: a detail route is not a nav entry, so it names the section it belongs to. +// Without this the Tasks item loses aria-current the moment the operator opens +// a run, and the whole nav reads as "nothing is current". +test("a parameterised route reports the section it keeps current", () => { + assert.equal(navPath(routes[2]), "/tasks"); + assert.equal(navPath(routes[1]), "/tasks"); + assert.equal(navPath(undefined), "/"); +}); diff --git a/ui/test/stage-rail.test.js b/ui/test/stage-rail.test.js new file mode 100644 index 000000000..56b5de388 --- /dev/null +++ b/ui/test/stage-rail.test.js @@ -0,0 +1,229 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { render, cleanup } from "@testing-library/preact"; +import { StageRail } from "../src/tasks/stage-rail.jsx"; + +// The frozen shape of GET /api/tasks/{id}/attempts. Attempt 1 failed on +// `implement`; attempt 2 is still running. The attempt-level duration_ms is +// present on purpose: the rail must not render it. +const ATTEMPTS = { + task_id: 42, + current_attempt: 2, + unattributed_events: 3, + attempts: [ + { + attempt: 1, + status: "failed", + started_at: "2026-09-18T07:00:00.000Z", + finished_at: "2026-09-18T07:04:00.000Z", + duration_ms: 1_000_000, + event_count: 14, + stages: [ + { name: "prepare", seq: 0, status: "ok", started_at: "2026-09-18T07:00:00.123Z", duration_ms: 1200, error: "" }, + { + name: "implement", + seq: 1, + status: "failed", + started_at: "2026-09-18T07:00:01.323Z", + duration_ms: 230000, + error: "stage implement: builder exited 1", + }, + ], + }, + { + attempt: 2, + status: "running", + started_at: "2026-09-18T07:05:00.000Z", + event_count: 2, + stages: [{ name: "analyse", seq: 0, status: "running", started_at: "2026-09-18T07:05:00.000Z" }], + }, + ], +}; + +function mount(props) { + const { container, unmount } = render(); + return { root: container, unmount }; +} + +function stageRow(root, name) { + return [...root.querySelectorAll(".run-stage")].find( + (row) => row.querySelector(".run-stage-name")?.textContent === name, + ); +} + +test("each stage renders its name, duration and terminal status", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events: [] }); + const prepare = stageRow(root, "prepare"); + assert.ok(prepare, "the prepare stage should render"); + assert.match(prepare.textContent, /prepare/); + assert.match(prepare.textContent, /ok/); + assert.match(prepare.textContent, /ran for 1\.2 s/); + const implement = stageRow(root, "implement"); + assert.match(implement.textContent, /ran for 3 min 50 s/); + assert.match(implement.textContent, /stage implement: builder exited 1/); + unmount(); +}); + +// W2: merging attempts by stage name is the failure this whole feature exists to +// prevent. +test("the rail shows only the selected attempt's stages", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events: [] }); + assert.ok(stageRow(root, "prepare")); + assert.ok(stageRow(root, "implement")); + assert.equal(stageRow(root, "analyse"), undefined, "attempt 2's stages must not appear in attempt 1's rail"); + assert.match(root.textContent, /Attempt 1/); + unmount(); +}); + +test("an interrupted stage is not labelled failed", () => { + const state = { + ...ATTEMPTS, + attempts: [ + { + attempt: 1, + status: "interrupted", + started_at: "2026-09-18T07:00:00.000Z", + stages: [{ name: "implement", seq: 0, status: "interrupted", duration_ms: 4200, error: "context canceled" }], + }, + ], + }; + const { root, unmount } = mount({ state, attemptNumber: 1, events: [] }); + const row = stageRow(root, "implement"); + assert.match(row.textContent, /interrupted/); + assert.doesNotMatch(row.textContent, /failed/); + unmount(); +}); + +test("a stage with no recorded start shows no invented duration", () => { + const state = { + ...ATTEMPTS, + attempts: [ + { + attempt: 1, + status: "ok", + stages: [{ name: "commit", seq: 0, status: "ok" }], + }, + ], + }; + const { root, unmount } = mount({ state, attemptNumber: 1, events: [] }); + const row = stageRow(root, "commit"); + assert.match(row.textContent, /duration not recorded/); + assert.doesNotMatch(row.textContent, /ran for/); + unmount(); +}); + +// F3: waiting_human can span days, so an attempt's wall time is not a duration +// of work and the page must not present it as one. +test("the attempt's own duration is never rendered", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events: [] }); + assert.doesNotMatch(root.textContent, /ran for 16 min/); + assert.doesNotMatch(root.textContent, /1,000,000|1000000/); + unmount(); +}); + +test("events with no attempt are reported rather than guessed at", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events: [] }); + assert.match(root.textContent, /3 events on this task predate attempt attribution/); + unmount(); +}); + +// F1: a stage is `ok` when its function returned without error. There is no +// exit code and no verification, and the agent's own verdict is a separate +// claim -- neither may be presented as a check result. +test("the agent's own verdict is shown separately from the stage's status", () => { + const events = [ + { + kind: "agent_finish", + attempt: 1, + stage: "implement", + data: { status: "passed", iterations: 7, tokens: 1234, model: "openai/gpt-5.6-luna" }, + }, + ]; + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events }); + const row = stageRow(root, "implement"); + assert.match(row.textContent, /Agent's own report, not verified by archie/); + assert.match(row.textContent, /Agent passed: implement/); + assert.match(row.textContent, /failed/, "the stage keeps its own terminal status"); + assert.doesNotMatch(row.textContent, /exit code|exit status/i); + unmount(); +}); + +test("an agent report for another attempt is not attached to this attempt's stage", () => { + const events = [ + { kind: "agent_finish", attempt: 2, stage: "implement", data: { status: "passed" } }, + ]; + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events }); + assert.doesNotMatch(root.textContent, /Agent's own report/); + unmount(); +}); + +test("the rail says what ok means instead of implying a gate ran", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 1, events: [] }); + assert.match(root.textContent, /ok means the stage returned without error/); + assert.match(root.textContent, /does not verify/); + unmount(); +}); + +test("an attempt with no stages says so instead of showing an empty rail", () => { + const state = { + task_id: 42, + current_attempt: 1, + unattributed_events: 0, + attempts: [{ attempt: 1, status: "unknown", stages: [] }], + }; + const { root, unmount } = mount({ state, attemptNumber: 1, events: [] }); + assert.match(root.textContent, /No stages recorded for this attempt/); + unmount(); +}); + +test("a task with no attempts says so", () => { + const { root, unmount } = mount({ + state: { task_id: 42, current_attempt: 0, unattributed_events: 0, attempts: [] }, + attemptNumber: null, + events: [], + }); + assert.match(root.textContent, /No attempts recorded/); + unmount(); +}); + +test("a selected attempt that was never recorded is reported, not faked", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 9, events: [] }); + assert.match(root.textContent, /Attempt 9 is not recorded for this task/); + assert.match(root.textContent, /attempt 1, 2/); + unmount(); +}); + +// A deployment where every event predates the attempt column answers with no +// attempts at all -- but the events are still there, unattributed. The count +// must be surfaced in the EMPTY rail too, not only beside a populated one, or +// the page presents unattributable history as "nothing happened". +test("unattributed events are surfaced even when no attempt is recorded", () => { + const { root, unmount } = mount({ + state: { task_id: 42, current_attempt: 0, unattributed_events: 4, attempts: [] }, + attemptNumber: null, + events: [], + }); + assert.match(root.textContent, /No attempts recorded/); + assert.match(root.textContent, /4 events on this task predate attempt attribution/); + unmount(); +}); + +test("unattributed events are surfaced when the selected attempt is not recorded", () => { + const { root, unmount } = mount({ state: ATTEMPTS, attemptNumber: 9, events: [] }); + assert.match(root.textContent, /Attempt 9 is not recorded/); + assert.match(root.textContent, /3 events on this task predate attempt attribution/); + unmount(); +}); + +test("loading and failure states are distinct, and the failure offers a retry", () => { + const loading = mount({ state: undefined, attemptNumber: null, events: [] }); + assert.match(loading.root.textContent, /Loading/); + loading.unmount(); + + const failed = mount({ state: null, attemptNumber: null, events: [], onRetry: () => {} }); + assert.match(failed.root.textContent, /Could not load this task's attempts/); + assert.equal(failed.root.querySelector("button").textContent, "Retry"); + failed.unmount(); +}); + +test.after(() => cleanup()); diff --git a/ui/test/task-detail.test.js b/ui/test/task-detail.test.js new file mode 100644 index 000000000..10050dec9 --- /dev/null +++ b/ui/test/task-detail.test.js @@ -0,0 +1,466 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { render, cleanup, fireEvent, waitFor } from "@testing-library/preact"; +import { render as preactRender } from "preact"; +import { api, ApiError } from "../src/base/api.jsx"; +import { taskDetailPage } from "../src/tasks/task-detail.jsx"; + +const CONFIG_SCHEMA = "archie/task-config@1"; + +const TASK = { + id: 42, + title: "Fix the flaky test", + status: "parked", + owner: "o", + repo: "r", + workflow: "tdd", + attempt: 2, + actions: ["retry", "abandon", "reject"], + repo_url: "https://forge.example.internal/o/r", + issue_url: "https://forge.example.internal/o/r/issues/5", + issue_number: 5, + pr_number: 7, + pr_url: "https://forge.example.internal/o/r/pull/7", +}; + +const ATTEMPTS = { + task_id: 42, + current_attempt: 2, + unattributed_events: 0, + attempts: [ + { + attempt: 1, + status: "failed", + started_at: "2026-09-18T07:00:00.000Z", + finished_at: "2026-09-18T07:04:00.000Z", + duration_ms: 240333, + event_count: 3, + stages: [ + { name: "prepare", seq: 0, status: "ok", started_at: "2026-09-18T07:00:00.123Z", duration_ms: 1200, error: "" }, + { name: "implement", seq: 1, status: "failed", duration_ms: 230000, error: "stage implement: builder exited 1" }, + ], + }, + { + attempt: 2, + status: "running", + started_at: "2026-09-18T07:05:00.000Z", + event_count: 1, + stages: [{ name: "analyse", seq: 0, status: "running", started_at: "2026-09-18T07:05:00.000Z" }], + }, + ], +}; + +const EVENTS = [ + { + kind: "config_captured", + attempt: 2, + at: "2026-09-18T07:05:00.100Z", + stage: "", + data: { schema: CONFIG_SCHEMA, document: { BotUser: "archie", Models: { main: "openai/gpt" } } }, + }, + { kind: "stage_start", attempt: 2, stage: "analyse", at: "2026-09-18T07:05:00.000Z", data: {} }, +]; + +function install(overrides = {}) { + const original = { + tasks: api.tasks, + task: api.task, + taskAttempts: api.taskAttempts, + taskLogs: api.taskLogs, + taskChanges: api.taskChanges, + taskDebug: api.taskDebug, + taskAction: api.taskAction, + }; + const calls = { tasks: 0, task: 0, attempts: 0, logs: [], changes: [], debug: [], actions: [] }; + api.tasks = async () => { + calls.tasks += 1; + return [TASK]; + }; + api.task = async (id) => { + calls.task += 1; + return EVENTS; + }; + api.taskAttempts = async (id) => { + calls.attempts += 1; + return ATTEMPTS; + }; + api.taskLogs = async (id, params) => { + calls.logs.push(params); + return { found: true, attempt: params?.attempt ?? 2, disabled: false, entries: [{ level: "info", msg: "line", time: "2026-09-18T07:05:00Z" }] }; + }; + api.taskChanges = async (id, params) => { + calls.changes.push(params); + return { task_id: 42, attempt: params?.attempt ?? 2, found: false, captures: [] }; + }; + api.taskDebug = async (id, params) => { + calls.debug.push(params); + return { task_id: 42, attempt: params?.attempt ?? 2, task: TASK, events: EVENTS }; + }; + api.taskAction = async (id, action) => { + calls.actions.push({ id, action }); + return {}; + }; + for (const [key, value] of Object.entries(overrides)) api[key] = value; + const restore = () => Object.assign(api, original); + return { calls, restore }; +} + +function mount(queryString, id = "42") { + const { container, unmount } = render( + taskDetailPage(new URLSearchParams(queryString), { id }), + ); + return { root: container, unmount }; +} + +test("the page offers every panel as a tab and opens Stages by default", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab="); + await waitFor(() => assert.ok(root.querySelector(".run-stages"), "the rail should render")); + const tabs = [...root.querySelectorAll('[role="tab"]')].map((tab) => tab.textContent); + assert.deepEqual(tabs, ["Stages", "Log", "Changed files", "Configuration", "Debug"]); + assert.equal(root.querySelector('[role="tab"]').getAttribute("aria-selected"), "true"); + // The panel is bound to the selected tab. + const panel = root.querySelector('[role="tabpanel"]'); + assert.equal(panel.getAttribute("aria-labelledby"), root.querySelector('[role="tab"]').id); + unmount(); + restore(); +}); + +test("the panel element is the selected tab's panel", () => { + const { root, unmount } = mount("tab=changes"); + const selected = [...root.querySelectorAll('[role="tab"]')].find( + (tab) => tab.getAttribute("aria-selected") === "true", + ); + assert.equal(selected.textContent, "Changed files"); + assert.equal(root.querySelector('[role="tabpanel"]').id, selected.getAttribute("aria-controls")); + unmount(); +}); + +// R8: the tabs are deep-linkable, so the query string alone decides which panel +// opens -- including on a reload with no client state. +test("?tab= decides which panel opens", async () => { + const { restore, calls } = install(); + const { root, unmount } = mount("tab=debug"); + await waitFor(() => assert.ok(root.querySelector(".run-json"), "the debug view should render")); + const json = root.querySelector(".run-json").textContent; + assert.match(json, /"title": "Fix the flaky test"/); + assert.match(json, /"attempt": 2/); + assert.match(root.textContent, /Attempt 2 is the one selected above/); + assert.deepEqual(calls.debug, [{ attempt: 2 }]); + // The debug envelope is only fetched for the visible tab. + assert.equal(calls.changes.length, 0); + unmount(); + restore(); +}); + +test("the debug view states that its event list is unfiltered", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab=debug"); + await waitFor(() => assert.ok(root.querySelector(".run-json"))); + assert.match(root.textContent, /Events are unfiltered on purpose/); + unmount(); + restore(); +}); + +test("the default attempt is the task's current one", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + assert.match(root.textContent, /Attempt 2/); + assert.equal( + [...root.querySelectorAll(".run-stage-name")].map((n) => n.textContent).join(","), + "analyse", + "attempt 1's stages must not appear on the current attempt's rail", + ); + const chips = [...root.querySelectorAll(".run-attempt")]; + assert.equal(chips.length, 2); + assert.equal(chips[1].getAttribute("aria-pressed"), "true"); + unmount(); + restore(); +}); + +test("?attempt= pins an earlier attempt and the rail follows it", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab=stages&attempt=1"); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + assert.deepEqual( + [...root.querySelectorAll(".run-stage-name")].map((n) => n.textContent), + ["prepare", "implement"], + ); + assert.equal(root.querySelectorAll(".run-attempt")[0].getAttribute("aria-pressed"), "true"); + unmount(); + restore(); +}); + +test("selecting another attempt re-reads the panels for that attempt", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + fireEvent.click(root.querySelectorAll(".run-attempt")[0]); + await waitFor(() => + assert.deepEqual( + [...root.querySelectorAll(".run-stage-name")].map((n) => n.textContent), + ["prepare", "implement"], + ), + ); + unmount(); + restore(); +}); + +test("the log pane sends the selected attempt and the filters to the server", async () => { + const { restore, calls } = install(); + const { root, unmount } = mount("tab=log&attempt=1"); + await waitFor(() => assert.ok(root.querySelector(".log-list"))); + assert.deepEqual(calls.logs, [{ attempt: 1, level: "", stage: "", limit: 500 }]); + + const stageSelect = [...root.querySelectorAll(".task-log-filter select")][1]; + fireEvent.change(stageSelect, { target: { value: "prepare" } }); + await waitFor(() => assert.equal(calls.logs.length, 2)); + assert.deepEqual(calls.logs[1], { attempt: 1, level: "", stage: "prepare", limit: 500 }); + await waitFor(() => assert.match(root.textContent, /A stage filter matches only log lines that record a stage/)); + unmount(); + restore(); +}); + +// R4: the Config tab consumes the events response the page already holds, so it +// must issue no request of its own. +test("the configuration tab reads the captured document from the fetched events", async () => { + const { restore, calls } = install(); + const { root, unmount } = mount("tab=config"); + await waitFor(() => assert.ok(root.querySelector(".run-json"))); + assert.match(root.querySelector(".run-json").textContent, /"BotUser": "archie"/); + assert.equal(calls.task, 1, "the events are fetched once, by the page"); + assert.equal(calls.changes.length, 0); + assert.equal(calls.debug.length, 0); + unmount(); + restore(); +}); + +test("the configuration tab says nothing was captured for an attempt with no record", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab=config&attempt=1"); + await waitFor(() => + assert.equal(root.querySelector(".empty-title").textContent, "Not captured for this run"), + ); + unmount(); + restore(); +}); + +test("changed files are read for the selected attempt and say a capture is missing", async () => { + const { restore, calls } = install(); + const { root, unmount } = mount("tab=changes&attempt=1"); + await waitFor(() => + assert.equal(root.querySelector(".empty-title").textContent, "No change capture was recorded for this attempt"), + ); + assert.deepEqual(calls.changes, [{ attempt: 1 }]); + unmount(); + restore(); +}); + +// R6: the control is labelled as a new run, and the copy says what it destroys. +test("the new-run control states that the previous attempt's commits are discarded", async () => { + const { restore } = install(); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".run-restart"))); + const button = root.querySelector(".run-restart button"); + assert.equal(button.textContent, "Start a new run"); + assert.match(root.textContent, /The previous attempt's commits are discarded/); + assert.match(root.textContent, /fresh worktree reset onto the base branch/); + unmount(); + restore(); +}); + +test("a declined confirmation starts no run", async () => { + const { restore, calls } = install(); + const originalConfirm = window.confirm; + let asked = ""; + window.confirm = (text) => { + asked = text; + return false; + }; + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".run-restart button"))); + fireEvent.click(root.querySelector(".run-restart button")); + assert.match(asked, /previous attempt's commits are discarded/); + assert.deepEqual(calls.actions, []); + unmount(); + window.confirm = originalConfirm; + restore(); +}); + +test("a confirmed new run drops the old attempt's caches and selects the new run", async () => { + const NEW_ATTEMPTS = { + task_id: 42, + current_attempt: 3, + unattributed_events: 0, + attempts: [ + ...ATTEMPTS.attempts, + { attempt: 3, status: "running", started_at: "2026-09-18T07:09:00.000Z", event_count: 1, stages: [{ name: "bootstrap", seq: 0, status: "ok", duration_ms: 500 }] }, + ], + }; + let attemptReads = 0; + const { restore, calls } = install({ + taskAttempts: async () => { + attemptReads += 1; + return attemptReads === 1 ? ATTEMPTS : NEW_ATTEMPTS; + }, + }); + const originalConfirm = window.confirm; + window.confirm = () => true; + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + fireEvent.click(root.querySelector(".run-restart button")); + await waitFor(() => assert.equal(root.querySelectorAll(".run-attempt").length, 3)); + await waitFor(() => + assert.deepEqual( + [...root.querySelectorAll(".run-stage-name")].map((n) => n.textContent), + ["bootstrap"], + "the new run's stages are shown, not the previous attempt's", + ), + ); + assert.deepEqual(calls.actions, [{ id: 42, action: "retry" }]); + assert.equal(root.querySelectorAll(".run-attempt")[2].getAttribute("aria-pressed"), "true"); + assert.equal(calls.task, 2, "the ended attempt's events are refetched for the new run"); + unmount(); + window.confirm = originalConfirm; + restore(); +}); + +test("a task outside the listed rows is reported honestly rather than blank", async () => { + const { restore } = install({ tasks: async () => [] }); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + assert.match(root.textContent, /not among the tasks this dashboard lists/); + assert.match(root.textContent, /Debug tab holds the stored record verbatim/); + assert.match(root.textContent, /operator controls could not be read/); + unmount(); + restore(); +}); + +test("a deployment that lists no tasks for this id still shows the recorded run", async () => { + const { restore } = install({ tasks: async () => [] }); + const { root, unmount } = mount("tab=stages&attempt=1"); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + assert.match(root.textContent, /Task #42/); + assert.match(root.textContent, /prepare/); + unmount(); + restore(); +}); + +test("an unknown task renders an honest failure, not an empty page", async () => { + const { restore } = install({ + taskAttempts: async () => { + throw new ApiError("no such task", 404); + }, + }); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.ok(root.querySelector(".page-title"))); + assert.match(root.querySelector(".page-title").textContent, /Task not found/); + assert.match(root.textContent, /No task with id 42/); + unmount(); + restore(); +}); + +test("a non-numeric id is refused without asking the server anything", () => { + const { restore, calls } = install(); + const { root, unmount } = mount("tab=stages", "not-an-id"); + assert.match(root.textContent, /is not a task id/); + assert.deepEqual(calls, { tasks: 0, task: 0, attempts: 0, logs: [], changes: [], debug: [], actions: [] }); + unmount(); + restore(); +}); + +test("a task with no attempts says so on every panel", async () => { + const { restore } = install({ + taskAttempts: async () => ({ task_id: 42, current_attempt: 0, unattributed_events: 4, attempts: [] }), + }); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.match(root.textContent, /No attempts recorded/)); + fireEvent.click([...root.querySelectorAll('[role="tab"]')][3]); + await waitFor(() => assert.match(root.textContent, /No attempt recorded/)); + unmount(); + restore(); +}); + +test("a failure to load the attempts offers a retry", async () => { + let reads = 0; + const { restore } = install({ + taskAttempts: async () => { + reads += 1; + if (reads === 1) throw new Error("boom"); + return ATTEMPTS; + }, + }); + const { root, unmount } = mount("tab=stages"); + await waitFor(() => assert.match(root.textContent, /Could not load this task's attempts/)); + fireEvent.click([...root.querySelectorAll(".run-error button")][0]); + await waitFor(() => assert.ok(root.querySelector(".run-stages"))); + unmount(); + restore(); +}); + +// The router renders the run page with Preact's own render() into one long-lived +// outlet (main.jsx, show()), so moving from one task id to another diffs the same +// component in place rather than mounting a fresh one. Every piece of task-scoped +// state therefore has to be re-established when the id changes -- otherwise the +// new task is shown with the previous task's tab, pinned attempt, run history and +// events. RunDetail's own comment relies on this ("the route remounts it when +// that changes"), so navigating between two ids is the case to pin. +test("navigating to another task id re-establishes the task-scoped reads and selections", async () => { + const attemptReads = []; + const eventReads = []; + const { restore } = install({ + taskAttempts: async (id) => { + attemptReads.push(String(id)); + return ATTEMPTS; + }, + task: async (id) => { + eventReads.push(String(id)); + return EVENTS; + }, + }); + const host = document.createElement("div"); + document.body.appendChild(host); + + // Task 1, opened pinned to its earlier attempt and to the Log tab. + preactRender(taskDetailPage(new URLSearchParams("tab=log&attempt=1"), { id: "1" }), host); + await waitFor(() => assert.equal(attemptReads.length, 1)); + const selectedTab = () => + [...host.querySelectorAll('[role="tab"]')].find( + (tab) => tab.getAttribute("aria-selected") === "true", + ); + const pressedAttempt = () => + [...host.querySelectorAll(".run-attempt")].find( + (chip) => chip.getAttribute("aria-pressed") === "true", + ); + assert.equal(selectedTab().textContent, "Log"); + assert.match(pressedAttempt().textContent, /Attempt 1/); + + // The router's own navigation: the same matched route, a different captured id, + // the same outlet. Nothing unmounts, so no state is cleared for free. + preactRender(taskDetailPage(new URLSearchParams(""), { id: "2" }), host); + + await waitFor(() => + assert.equal(attemptReads.length, 2, "the new task's run history must be re-read"), + ); + assert.equal(attemptReads[1], "2", "the run history must be read for the new task's id"); + assert.equal(eventReads.length, 2, "the new task's events must be re-read"); + assert.equal(eventReads[1], "2", "the events must be read for the new task's id"); + + assert.equal( + selectedTab().textContent, + "Stages", + "the previous task's tab must not carry over to the new task", + ); + assert.match( + pressedAttempt().textContent, + /Attempt 2/, + "the previous task's pinned attempt must not carry over to the new task", + ); + + preactRender(null, host); + host.remove(); + restore(); +}); + +test.after(() => cleanup()); diff --git a/ui/test/task-logs.test.js b/ui/test/task-logs.test.js index a97410851..69891c4dc 100644 --- a/ui/test/task-logs.test.js +++ b/ui/test/task-logs.test.js @@ -1,10 +1,20 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { render, cleanup } from "@testing-library/preact"; -import { TaskLogPanel, taskLogDownloadURL } from "../src/tasks/task-logs.jsx"; +import { render, cleanup, fireEvent } from "@testing-library/preact"; +import { TaskLogPanel, logCacheKey, taskLogDownloadURL } from "../src/tasks/task-logs.jsx"; function renderPanel(state, opts = {}) { - const { container, unmount } = render(); + const { container, unmount } = render( + , + ); return { root: container, unmount }; } @@ -103,3 +113,136 @@ test("a panel for an attempt with no log offers no download", () => { assert.equal(root.querySelector(".task-log-download"), null, "there is nothing to download"); unmount(); }); + +// W7: the filter controls must sit ABOVE the three read outcomes. Below the +// disabled early return they would replace the deployment-level message with an +// empty filtered pane in exactly the deployment that cannot read logs. +const FILTER_OPTS = { filters: { level: "", stage: "" }, onFilterChange: () => {}, stages: ["prepare"] }; + +test("the three read outcomes survive with the filter bar rendered above them", () => { + const disabled = renderPanel({ disabled: true, entries: [] }, FILTER_OPTS); + assert.ok(disabled.root.querySelector(".task-log-filters"), "the filter bar renders first"); + assert.match(disabled.root.textContent, /No persisted log for this attempt/); + assert.match(disabled.root.textContent, /cannot read task logs/); + disabled.unmount(); + + const absent = renderPanel({ found: false, entries: [], attempt: 0 }, FILTER_OPTS); + assert.match(absent.root.textContent, /No log recorded for this attempt/); + assert.doesNotMatch(absent.root.textContent, /cannot read task logs/); + absent.unmount(); + + const filtered = renderPanel({ disabled: false, found: true, entries: [], attempt: 0 }, FILTER_OPTS); + assert.equal(filtered.root.querySelector(".empty-title").textContent, "Nothing recorded"); + filtered.unmount(); +}); + +// W6: one cache entry per task could not represent two attempts, so a retry +// served the previous run's log under the new run's id. +test("the log cache key is keyed by task, attempt and filters", () => { + assert.equal(logCacheKey(7, 1), "7|1||"); + assert.notEqual(logCacheKey(7, 1), logCacheKey(7, 2), "two attempts must not share a cache entry"); + assert.notEqual(logCacheKey(7, 1), logCacheKey(71, 1), "two tasks must not share a cache entry"); + assert.notEqual( + logCacheKey(7, 1, { level: "ERROR", stage: "" }), + logCacheKey(7, 1, { level: "", stage: "" }), + "a filtered read is a different response and needs its own entry", + ); +}); + +// F2: a stage filter narrows to lines a stage tagged and nothing more. Agent and +// tool output has no stage, so a sparse result must be explained next to the +// control rather than left to look broken. +test("a stage filter states its coverage limit beside the control", () => { + const { root, unmount } = renderPanel( + { found: true, entries: [], attempt: 1 }, + { ...FILTER_OPTS, filters: { level: "", stage: "prepare" }, stages: ["prepare", "implement"] }, + ); + assert.match(root.textContent, /A stage filter matches only log lines that record a stage/); + assert.match(root.textContent, /Agent and tool output carries none/); + unmount(); +}); + +test("an attempt with no recorded stage names says the stage filter has nothing to match", () => { + const { root, unmount } = renderPanel( + { found: true, entries: [], attempt: 1 }, + { ...FILTER_OPTS, stages: [] }, + ); + assert.match(root.textContent, /recorded no stage names/); + unmount(); +}); + +test("changing a filter reports the whole filter set to the page", () => { + const seen = []; + const { root, unmount } = renderPanel( + { found: true, entries: [], attempt: 1 }, + { ...FILTER_OPTS, onFilterChange: (next) => seen.push(next) }, + ); + const level = root.querySelectorAll("select")[0]; + const stage = root.querySelectorAll("select")[1]; + fireEvent.change(level, { target: { value: "ERROR" } }); + fireEvent.change(stage, { target: { value: "prepare" } }); + assert.deepEqual(seen, [ + { level: "ERROR", stage: "" }, + { level: "", stage: "prepare" }, + ]); + unmount(); +}); + +// The pane names the attempt it is showing so it can never present attempt 1's +// log as attempt 2's. +test("the pane names the attempt it is showing", () => { + const explicit = renderPanel({ found: true, attempt: 1, entries: [] }, { attempt: 1 }); + assert.match(explicit.root.textContent, /Attempt 1/); + explicit.unmount(); + + const resolved = renderPanel({ found: true, attempt: 4, entries: [] }, { attempt: null, taskId: 42 }); + assert.match(resolved.root.textContent, /Attempt 4/); + assert.equal( + resolved.root.querySelector(".task-log-download").getAttribute("href"), + "/api/tasks/42/logs/download?attempt=4", + "a download follows the attempt the pane is showing, not whatever is current", + ); + resolved.unmount(); +}); + +test("a panel without a page to act on a filter renders no filter controls", () => { + const { root, unmount } = renderPanel({ found: true, entries: [], attempt: 1 }); + assert.equal(root.querySelector("select"), null, "a control that filters nothing is worse than none"); + assert.match(root.textContent, /Attempt 1/); + unmount(); +}); + +// R9: the pane carries one live region announcing its STATE, never a line at a +// time. A per-line live region would read the whole log aloud on every load, +// and a pane that loads 500 entries would be unusable with a screen reader. +test("the pane announces its state once, not every log line", () => { + const { root, unmount } = renderPanel({ + found: true, + attempt: 2, + entries: [ + { level: "info", msg: "one" }, + { level: "info", msg: "two" }, + ], + }); + const live = root.querySelector("[aria-live]"); + assert.ok(live, "the pane should carry a live region"); + assert.equal(live.getAttribute("role"), "status"); + assert.equal(live.getAttribute("aria-atomic"), "true"); + assert.match(live.textContent, /2 log entries/); + assert.ok(live.className.includes("visually-hidden"), "the live text is for assistive technology only"); + assert.equal(root.querySelector(".log-list").contains(live), false, "the live region is not the list itself"); + unmount(); +}); + +test("the live region says which of the log-unavailable cases applies", () => { + const disabled = renderPanel({ disabled: true, entries: [] }); + assert.match(disabled.root.querySelector("[aria-live]").textContent, /cannot read task logs/); + disabled.unmount(); + + const absent = renderPanel({ found: false, entries: [], attempt: 0 }); + assert.match(absent.root.querySelector("[aria-live]").textContent, /No log recorded for this attempt/); + assert.doesNotMatch(absent.root.querySelector("[aria-live]").textContent, /cannot read task logs/); + absent.unmount(); +}); + +test.after(() => cleanup()); diff --git a/ui/test/task-tabs.test.js b/ui/test/task-tabs.test.js new file mode 100644 index 000000000..9fd656690 --- /dev/null +++ b/ui/test/task-tabs.test.js @@ -0,0 +1,115 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { render, cleanup, fireEvent } from "@testing-library/preact"; +import { TabBar, panelId, tabId } from "../src/tasks/tab-bar.jsx"; + +const TABS = [ + { id: "stages", label: "Stages" }, + { id: "log", label: "Log" }, + { id: "changes", label: "Changed files" }, +]; + +import { useState } from "preact/hooks"; + +function Harness({ initial = "stages", onSelect }) { + const [active, setActive] = useState(initial); + return ( + { + onSelect?.(id); + setActive(id); + }} + prefix="run" + /> + ); +} + +function mount(active = "stages", onSelect) { + const { container, unmount } = render(); + return { root: container, unmount }; +} + +test("the tab list is a tablist of tabs with the active one selected", () => { + const { root, unmount } = mount("log"); + const list = root.querySelector('[role="tablist"]'); + assert.ok(list, "a tablist should render"); + const tabs = [...root.querySelectorAll('[role="tab"]')]; + assert.equal(tabs.length, 3); + assert.equal(tabs[0].getAttribute("aria-selected"), "false"); + assert.equal(tabs[1].getAttribute("aria-selected"), "true"); + assert.equal(tabs[0].textContent, "Stages"); + unmount(); +}); + +// The panel is a separate element in the page, so the relationship has to be +// declared explicitly or assistive technology cannot connect them. +test("each tab points at the panel it controls", () => { + const { root, unmount } = mount("stages"); + const tabs = [...root.querySelectorAll('[role="tab"]')]; + const expected = ["stages", "log", "changes"].map((id) => panelId("run", id)); + assert.deepEqual(tabs.map((tab) => tab.getAttribute("aria-controls")), expected); + assert.deepEqual(tabs.map((tab) => tab.id), ["stages", "log", "changes"].map((id) => tabId("run", id))); + unmount(); +}); + +// Roving tabindex: the tab list is one stop in the page's tab order, not three. +test("only the active tab is in the page tab order", () => { + const { root, unmount } = mount("changes"); + const tabs = [...root.querySelectorAll('[role="tab"]')]; + assert.deepEqual(tabs.map((tab) => tab.getAttribute("tabindex")), ["-1", "-1", "0"]); + unmount(); +}); + +test("clicking a tab selects it", () => { + const selected = []; + const { root, unmount } = mount("stages", (id) => selected.push(id)); + fireEvent.click(root.querySelectorAll('[role="tab"]')[2]); + assert.deepEqual(selected, ["changes"]); + unmount(); +}); + +test("arrow keys move between tabs, wrap around, and select as they go", () => { + const selected = []; + const { root, unmount } = mount("stages", (id) => selected.push(id)); + const first = root.querySelectorAll('[role="tab"]')[0]; + first.focus(); + fireEvent.keyDown(first, { key: "ArrowRight" }); + fireEvent.keyDown(root.querySelectorAll('[role="tab"]')[1], { key: "ArrowRight" }); + fireEvent.keyDown(root.querySelectorAll('[role="tab"]')[2], { key: "ArrowRight" }); + assert.deepEqual(selected, ["log", "changes", "stages"], "arrow-right wraps to the first tab"); + unmount(); +}); + +test("Home and End jump to the ends of the tab list", () => { + const selected = []; + const { root, unmount } = mount("log", (id) => selected.push(id)); + const active = root.querySelectorAll('[role="tab"]')[1]; + fireEvent.keyDown(active, { key: "End" }); + fireEvent.keyDown(root.querySelectorAll('[role="tab"]')[2], { key: "Home" }); + assert.deepEqual(selected, ["changes", "stages"]); + unmount(); +}); + +// Keyboard focus must follow selection: a roving-tabindex widget that moves the +// selection but leaves focus behind loses the keyboard user. +test("an arrow key moves keyboard focus with the selection", () => { + const { root, unmount } = mount("stages"); + const first = root.querySelectorAll('[role="tab"]')[0]; + first.focus(); + fireEvent.keyDown(first, { key: "ArrowRight" }); + const tabs = [...root.querySelectorAll('[role="tab"]')]; + assert.equal(document.activeElement, tabs[1]); + unmount(); +}); + +test("an unrelated key does nothing", () => { + const selected = []; + const { root, unmount } = mount("stages", (id) => selected.push(id)); + fireEvent.keyDown(root.querySelectorAll('[role="tab"]')[0], { key: "a" }); + assert.deepEqual(selected, []); + unmount(); +}); + +test.after(() => cleanup()); diff --git a/ui/test/tasks-actions.test.js b/ui/test/tasks-actions.test.js index 9139eaadf..2f6361b44 100644 --- a/ui/test/tasks-actions.test.js +++ b/ui/test/tasks-actions.test.js @@ -1,7 +1,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { register } from "node:module"; -import { render, waitFor } from "@testing-library/preact"; +import { render, waitFor, fireEvent } from "@testing-library/preact"; const cssLoad = "data:text/javascript," + encodeURIComponent(` export async function load(url, context, nextLoad) { @@ -186,3 +186,107 @@ test("a link-kind action renders an anchor to the forge", async () => { assert.equal(link.textContent, "Open PR"); assert.equal(link.getAttribute("href"), "https://forge.example.internal/sam/archie/pull/42"); }); + +// The stuck-pane case: an open log pane whose row is collapsed while the task +// is retried. If the pane only ever loaded from the click that opened it, the +// new attempt's pane would sit on "Loading…" with nothing fetching it. +test("a log pane left open across a retry loads the new attempt when the row is reopened", async () => { + const first = { id: 9, title: "Restart me", status: "parked", repo: "sam/archie", workflow: "tdd", attempt: 1, actions: ["retry"] }; + const second = { ...first, attempt: 2, status: "running" }; + const original = { tasks: api.tasks, task: api.task, taskAction: api.taskAction, taskLogs: api.taskLogs }; + let listReads = 0; + const logReads = []; + api.tasks = async () => { + listReads += 1; + return [listReads === 1 ? first : second]; + }; + api.task = async () => [ + { kind: "stage_start", attempt: listReads, stage: listReads === 1 ? "prepare" : "bootstrap", at: "2026-09-18T07:00:00Z" }, + ]; + api.taskLogs = async (id, params) => { + logReads.push(params); + return { found: true, attempt: params.attempt, disabled: false, entries: [{ level: "info", msg: "line" }] }; + }; + api.taskAction = async () => ({}); + try { + const { container } = render(tasksPage(new URLSearchParams("task=9"))); + await waitFor(() => assert.match(container.textContent, /Started stage: prepare/)); + fireEvent.click(container.querySelector(".task-logs-section button")); + await waitFor(() => assert.equal(logReads.length, 1)); + + // Collapse the row, retry from the collapsed row, then reopen it. + fireEvent.click(container.querySelector(".task-expand")); + fireEvent.click(container.querySelector(".task-actions button")); + await waitFor(() => assert.equal(listReads, 2)); + fireEvent.click(container.querySelector(".task-expand")); + + await waitFor(() => assert.match(container.textContent, /Started stage: bootstrap/)); + await waitFor(() => assert.equal(logReads.length, 2), { timeout: 2000 }); + assert.deepEqual(logReads[1], { attempt: 2, limit: 500 }); + assert.doesNotMatch(container.textContent, /Loading attempt log/); + } finally { + Object.assign(api, original); + } +}); + +// R8: the run detail page is a per-task route, and the list is how an operator +// reaches it. The existing #/tasks?task=N deep link is a different affordance +// and stays working (pinned in operator-controls.test.js). +test("a task row links to its run detail page", async () => { + const root = await renderTask({ id: 7, title: "Fix the flaky test", status: "parked", repo: "sam/archie", actions: [] }); + const link = root.querySelector(".task-detail-link"); + assert.ok(link, "the title should link to the run detail page"); + assert.equal(link.getAttribute("href"), "#/tasks/7"); + assert.equal(link.textContent, "Fix the flaky test"); +}); + +// W8: the per-task caches used to be written and never invalidated, so a retry +// left the previous attempt's timeline (and, because the log cache was keyed by +// task, its log) on screen under the new run. +test("a retry drops the ended attempt's caches and reloads the new run", async () => { + const first = { id: 8, title: "Flaky", status: "parked", repo: "sam/archie", workflow: "tdd", attempt: 1, actions: ["retry"] }; + const second = { ...first, attempt: 2, status: "running" }; + const original = { tasks: api.tasks, task: api.task, taskAction: api.taskAction, taskLogs: api.taskLogs }; + let listReads = 0; + const timelineReads = []; + const logReads = []; + api.tasks = async () => { + listReads += 1; + return [listReads === 1 ? first : second]; + }; + api.task = async () => { + timelineReads.push(timelineReads.length + 1); + const attempt = timelineReads.length; + return [ + { + kind: "stage_start", + attempt, + stage: attempt === 1 ? "prepare" : "bootstrap", + at: "2026-09-18T07:00:00Z", + }, + ]; + }; + api.taskLogs = async (id, params) => { + logReads.push(params); + return { found: true, attempt: params.attempt, disabled: false, entries: [{ level: "info", msg: "line" }] }; + }; + api.taskAction = async () => ({}); + try { + const { container } = render(tasksPage(new URLSearchParams("task=8"))); + await waitFor(() => assert.match(container.textContent, /Started stage: prepare/)); + + fireEvent.click(container.querySelector(".task-logs-section button")); + await waitFor(() => assert.equal(logReads.length, 1)); + assert.deepEqual(logReads[0], { attempt: 1, limit: 500 }); + + fireEvent.click(container.querySelector(".task-actions button")); + await waitFor(() => assert.match(container.textContent, /Started stage: bootstrap/)); + assert.equal(timelineReads.length, 2, "the timeline is refetched, not kept from the ended attempt"); + assert.doesNotMatch(container.textContent, /Started stage: prepare/); + + await waitFor(() => assert.equal(logReads.length, 2), { timeout: 2000 }); + assert.deepEqual(logReads[1], { attempt: 2, limit: 500 }, "the log pane follows the new attempt"); + } finally { + Object.assign(api, original); + } +}); diff --git a/ui/test/tasks-focus.test.js b/ui/test/tasks-focus.test.js new file mode 100644 index 000000000..e31abbf98 --- /dev/null +++ b/ui/test/tasks-focus.test.js @@ -0,0 +1,73 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { register } from "node:module"; +import { render, waitFor } from "@testing-library/preact"; + +// tasks.jsx imports its feature CSS, which node cannot load; the same inline +// loader the sibling tasks tests register lets the module be imported here. +const cssLoad = "data:text/javascript," + encodeURIComponent(` + export async function load(url, context, nextLoad) { + if (url.endsWith(".css")) { + return { format: "module", shortCircuit: true, source: "export default {};" }; + } + return nextLoad(url, context); + } +`); +register(cssLoad, import.meta.url); + +const { api } = await import("../src/base/api.jsx"); +const { tasksPage } = await import("../src/tasks/tasks.jsx"); + +// jsdom implements neither matchMedia nor scrollIntoView, so both are provided +// here to observe the one decision under test: which scroll behaviour a +// deep-linked row is revealed with. +function stubMotion(reduced) { + window.matchMedia = (query) => ({ + matches: Boolean(reduced) && String(query).includes("prefers-reduced-motion: reduce"), + media: String(query), + onchange: null, + addEventListener() {}, + removeEventListener() {}, + addListener() {}, + removeListener() {}, + dispatchEvent() { + return false; + }, + }); +} + +async function revealWithMotion(reduced) { + const seen = []; + const originalScroll = Element.prototype.scrollIntoView; + const originalMatchMedia = window.matchMedia; + const originalTasks = api.tasks; + Element.prototype.scrollIntoView = (opts) => seen.push(opts); + stubMotion(reduced); + api.tasks = async () => [ + { id: 7, title: "Deep link", status: "running", repo: "o/r", workflow: "tdd", actions: [], attempt: 1 }, + ]; + try { + const { unmount } = render(tasksPage(new URLSearchParams("task=7"))); + await waitFor(() => assert.ok(seen.length, "the deep-linked row should be revealed")); + unmount(); + return seen[0]; + } finally { + Element.prototype.scrollIntoView = originalScroll; + window.matchMedia = originalMatchMedia; + api.tasks = originalTasks; + } +} + +// The global reduced-motion rule switches CSS transitions, NOT JS smooth +// scrolling: a deep-linked row is revealed by scrollIntoView, so the behaviour +// has to be chosen in JS or a reduced-motion user still gets an animated scroll. +test("a revealed row scrolls smoothly only when motion is not reduced", async () => { + const opts = await revealWithMotion(false); + assert.equal(opts.behavior, "smooth"); + assert.equal(opts.block, "center"); +}); + +test("a revealed row scrolls instantly when motion is reduced", async () => { + const opts = await revealWithMotion(true); + assert.equal(opts.behavior, "auto"); +}); diff --git a/ui/test/timeline-event.test.js b/ui/test/timeline-event.test.js index b5f0258e4..5045ca25a 100644 --- a/ui/test/timeline-event.test.js +++ b/ui/test/timeline-event.test.js @@ -102,6 +102,26 @@ test("cancelled stages are described as interrupted rather than failed", () => { ); }); +// Condition (d): the two provenance events render as human timeline lines and +// must never dump the captured payload inline -- the Configuration tab renders +// the document; the timeline only says that it was captured. +test("capture events describe themselves without dumping their payload", () => { + const config = describeTimelineEvent({ + kind: "config_captured", + data: { schema: "archie/task-config@1", document: { BotUser: "archie" } }, + }); + assert.equal(config.title, "Configuration captured"); + assert.doesNotMatch(config.detail, /BotUser/); + + const changes = describeTimelineEvent({ + kind: "changes_captured", + data: { captured_after: "commit", totals: { files: 3, additions: 40, deletions: 5 } }, + }); + assert.equal(changes.title, "Change capture recorded"); + assert.match(changes.detail, /3 files changed/); + assert.match(changes.detail, /captured after commit/); +}); + test("unknown event kinds become readable labels", () => { assert.deepEqual(describeTimelineEvent({ kind: "human_approved", detail: "approved via dashboard" }), { title: "Human Approved",