Merge pull request #878 from samcharles93/feat/attempt-attribution

Feat/attempt attribution
This commit is contained in:
sam authored and GitHub committed 2026-09-19 02:48:25 +10:00
commit 2385e81066
104 files changed
+9593 -324

No files matched your search

+4
View File
@@ -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.
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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()
+80 -8
View File
@@ -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)
}
+10
View File
@@ -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
+12 -8
View File
@@ -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"
target = "127.0.0.1:8585"
listen = "127.0.0.1:8585"
+1
View File
@@ -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. |
+16
View File
@@ -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.
+180 -2
View File
@@ -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
+112
View File
@@ -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.<name>].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.<name>]`.
- 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.
+13 -9
View File
@@ -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.<name>]`. 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
+291
View File
@@ -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/<base>` (`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`.
+26 -3
View File
@@ -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)
}
@@ -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
@@ -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)
}
}
+5 -5
View File
@@ -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,
+5 -20
View File
@@ -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
}
+15 -11
View File
@@ -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)
}
}
@@ -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)
+25 -7
View File
@@ -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)
}
+34
View File
@@ -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.<name>].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,
)
}
+58
View File
@@ -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)
}
})
}
}
+1 -1
View File
@@ -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 == "" {
+9 -4
View File
@@ -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)
}
+5 -21
View File
@@ -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))
}
@@ -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")
}
@@ -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 {
+2 -2
View File
@@ -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,
+1 -1
View File
@@ -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.
+125 -3
View File
@@ -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 {
+66 -14
View File
@@ -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.<name>] 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
+225
View File
@@ -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)
}
})
}
}
+130
View File
@@ -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.<name>] 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.<name>].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")
}
+49 -24
View File
@@ -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" +
+64 -7
View File
@@ -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
+331
View File
@@ -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")
}
}
+6 -1
View File
@@ -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")
+588
View File
@@ -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)
}
})
}
}
+1
View File
@@ -111,6 +111,7 @@ func StageBaselineGate() Stage {
if changed {
tc.BuildSummary = res.Summary
tc.BaselineFixed = true
tc.captureChanges(ctx, capturedAfterBaselineFix)
}
}
return nil
@@ -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 {
+99 -1
View File
@@ -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
}
+67
View File
@@ -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
@@ -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)
}
}
}
@@ -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")
}
}
+23 -4
View File
@@ -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)
+49 -10
View File
@@ -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.
+15
View File
@@ -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)
}
}
@@ -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
@@ -210,6 +210,23 @@ func unknownKeys(a, b []string) []string {
return out
}
// unregisteredServiceKeys reports [services.<name>] 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
@@ -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
}
}
}
@@ -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"},
},
}
}
@@ -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)
}
@@ -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)
}
+6 -5
View File
@@ -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),
@@ -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
+1 -1
View File
@@ -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 {
+15
View File
@@ -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
}
+46
View File
@@ -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,
+6 -5
View File
@@ -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.
+21 -3
View File
@@ -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)
+88 -2
View File
@@ -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" {
+343
View File
@@ -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
}
+536
View File
@@ -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)
}
})
}
}
+201
View File
@@ -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
}
+460
View File
@@ -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)
}
}
}
+45
View File
@@ -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})
}
+98
View File
@@ -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)
}
}
+13 -25
View File
@@ -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:
+97
View File
@@ -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)
+3
View File
@@ -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)
}
+121 -9
View File
@@ -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/<base> 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
+332
View File
@@ -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/<base>. 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/<base> 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)
}
}
}
+9
View File
@@ -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
+1 -1
View File
@@ -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(--accenLine truncated
: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}.Line truncated
+8 -8
View File
@@ -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;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),te(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,re(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&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;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=te(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&L(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?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--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),R(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function ee(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=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=Line truncated
`)[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:`ALine truncated
(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;t<e.__k.length;t++)if((n=e.__k[t])!=null&&n.__e!=null)return n.__e;return typeof e.type==`function`?w(e):null}function T(e){if(e.__P&&e.__d){var n=e.__v,r=n.__e,i=[],a=[],o=v({},n);o.__v=n.__v+1,t.vnode&&t.vnode(o),I(e.__P,o,n,e.__n,e.__P.namespaceURI,32&n.__u?[r]:null,i,r??w(n),!!(32&n.__u),a),o.__v=n.__v,o.__.__k[o.__i]=o,te(i,o,a),n.__e=n.__=null,o.__e!=r&&E(o)}}function E(e){if((e=e.__)!=null&&e.__c!=null)return e.__e=e.__c.base=null,e.__k.some(function(t){if(t!=null&&t.__e!=null)return e.__e=e.__c.base=t.__e}),E(e)}function D(e){(!e.__d&&(e.__d=!0)&&r.push(e)&&!O.__r++||i!=t.debounceRendering)&&((i=t.debounceRendering)||a)(O)}function O(){try{for(var e,t=1;r.length;)r.length>t&&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;d<b;d++)(p=n.__k[d])!=null&&(f=p.__i!=-1&&y[p.__i]||m,p.__i=d,v=I(e,p,f,i,a,o,s,c,l,u),g=p.__e,p.ref&&f.ref!=p.ref&&(f.ref&&ne(f.ref,null,p),u.push(p.ref,p.__c||g,p)),_==null&&g!=null&&(_=g),4&p.__u?(c=j(p,c,e),f.__e&&(f.__e=null)):typeof p.type==`function`&&v!==void 0?c=v:g&&(c=g.nextSibling),p.__u&=-7);return n.__e=_,c}function A(e,t,n,r,i){var a,o,s,c,l,u=n.length,d=u,f=0;for(e.__k=Array(i),a=0;a<i;a++)(o=t[a])!=null&&typeof o!=`boolean`&&typeof o!=`function`?(typeof o==`string`||typeof o==`number`||typeof o==`bigint`||o.constructor==String?o=e.__k[a]=x(null,o,null,null,null):_(o)?o=e.__k[a]=x(S,{children:o},null,null,null):o.constructor===void 0&&o.__b>0?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--:i<u&&f++),typeof o.type!=`function`&&(o.__u|=4)):l!=c&&(l==c-1?f--:l==c+1?f++:(l>c?f--:f++,o.__u|=4))):e.__k[a]=null;if(d)for(a=0;a<u;a++)(s=n[a])!=null&&!(2&s.__u)&&(s.__e==r&&(r=w(s)),z(s,s));return r}function j(e,t,n){var r,i;if(typeof e.type==`function`){for(r=e.__k,i=0;r&&i<r.length;i++)r[i]&&(r[i].__=e,t=j(r[i],t,n));return t}e.__e!=t&&(t&&e.type&&!t.parentNode&&(t=w(e)),t=n.insertBefore(e.__e,t||null));do t&&=t.nextSibling;while(t!=null&&t.nodeType==8);return t}function M(e,t,n,r){var i,a,o,s=e.key,c=e.type,l=t[n],u=l!=null&&!(2&l.__u);if(l===null&&s==null||u&&s==l.key&&c==l.type)return n;if(r>+!!u){for(i=n-1,a=n+1;i>=0||a<t.length;)if((l=t[o=i>=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=thiLine truncated
`)[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 Line truncated
<path d="${c(150,240)}" fill="none" stroke="var(--border)"
stroke-width="12" stroke-linecap="round"/>
<path d="${c(150,240)}" fill="none" stroke="${i}"
stroke-width="12" stroke-linecap="round"
stroke-dasharray="${s}"
stroke-dashoffset="${s*(1-r/100)}"
class="gauge-value"/>`,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: Line truncated
`),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_concuLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(U(`p`,pr(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(U(`pre`,U(`code`,a.join(`
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=hr(c),u=e+1<n.length?hr(n[e+1]):null;if(l&&u&&gr(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=hr(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=U(`tbody`);for(let e of r)i.append(U(`tr`,...e.map(e=>U(`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 Line truncated
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 Line truncated
`),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:`alloLine truncated
`),r=[],i=null,a=null,o=()=>{r.length&&(t.append(W(`p`,ni(r.join(` `)))),r=[])},s=()=>{i&&t.append(i),i=null};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.append(W(`pre`,W(`code`,a.join(`
`)))),a=null):a=[];continue}if(a){a.push(c);continue}let l=ii(c),u=e+1<n.length?ii(n[e+1]):null;if(l&&u&&ai(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=ii(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}let i=W(`tbody`);for(let e of r)i.append(W(`tr`,...e.map(e=>W(`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.sear Line truncated
`);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 aLine truncated
`).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 appeLine truncated
+3
View File
@@ -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"),
+12
View File
@@ -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":
+24
View File
@@ -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;
}
+2 -8
View File
@@ -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 => <option key={l.value} value={l.value}>{l.label}</option>)}
{LOG_LEVELS.map(l => <option key={l.value} value={l.value}>{l.label}</option>)}
</select>
<select
className="log-select"
+19 -4
View File
@@ -6,6 +6,7 @@ import { el, mount } from "./base/dom.jsx";
import { icon } from "./base/icons.jsx";
import { dashboardPage } from "./dashboard/dashboard.jsx";
import { tasksPage } from "./tasks/tasks.jsx";
import { taskDetailPage } from "./tasks/task-detail.jsx";
import { skillsPage } from "./skills/skills.jsx";
import { workflowsPage } from "./workflows/workflows.jsx";
import { channelsPage } from "./channels/channels.jsx";
@@ -17,6 +18,7 @@ import { mappingsPage } from "./mappings/mappings.jsx";
import { bindingsPage } from "./bindings/bindings.jsx";
import { memoryPage } from "./memory/memory.jsx";
import { chatPage } from "./chat/chat.jsx";
import { matchRoute, navPath } from "./routing.jsx";
/**
* Routes are declared once here. Adding a section means adding a feature
@@ -32,10 +34,19 @@ import { chatPage } from "./chat/chat.jsx";
// daemon and the extracted UI service -- and a section the serving process
// cannot back would otherwise render as permanently empty rather than as
// absent (archie-core-8cda.5.4).
//
// A route may also carry:
// nav:false -- addressed by URL but not a navigation entry (a detail page
// reached from its section)
// navPath -- the navigation entry this route keeps current; a parameterised
// route is not itself in the nav, so without this the section it
// belongs to would lose its aria-current highlight
// :name -- one captured path segment, e.g. /tasks/:id
const routes = [
{ path: "/", label: "Dashboard", icon: "dashboard", view: dashboardPage },
{ path: "/chat", label: "Chat", icon: "chat", view: chatPage, section: "chat" },
{ path: "/tasks", label: "Tasks", icon: "tasks", view: tasksPage },
{ path: "/tasks/:id", label: "Task run", view: taskDetailPage, nav: false, navPath: "/tasks" },
{ path: "/logs", label: "Logs", icon: "logs", view: logsPage, section: "logs" },
{ path: "/captures", label: "Event inspector", icon: "captures", view: capturesPage, section: "captures" },
{ path: "/mappings", label: "Field mappings", icon: "mappings", view: mappingsPage, section: "mappings" },
@@ -66,6 +77,7 @@ function commandBar(onNavigate, onToggleChat) {
"nav.nav",
...[null].flatMap(() => [
...routes
.filter((route) => route.nav !== false)
.map((route) => {
const item = el(
"a.nav-item",
@@ -135,7 +147,7 @@ function commandBar(onNavigate, onToggleChat) {
}
if (e.key !== "Enter") return;
const q = e.target.value.trim().toLowerCase();
const hit = routes.find((r) => !r.soon && r.label.toLowerCase().startsWith(q));
const hit = routes.find((r) => r.nav !== false && !r.soon && r.label.toLowerCase().startsWith(q));
if (hit) {
onNavigate(hit.path);
e.target.value = "";
@@ -230,8 +242,11 @@ function start() {
// stream does not leak a connection per navigation.
outlet.firstElementChild?.dispatchEvent(new CustomEvent("archie:teardown"));
const [path, query = ""] = rawPath.split("?", 2);
const route = routes.find((r) => r.path === path) || routes[0];
bar.highlight(route.path);
const match = matchRoute(routes, path);
const route = match?.route || routes[0];
// A detail route highlights the section it belongs to, so the nav item for
// Tasks stays current on #/tasks/42 instead of every item losing it.
bar.highlight(navPath(route));
// The chat is a drawer, not a page: /chat opens it rather than mounting a
// second chatPage() (which would duplicate session state and the stream).
if (route.path === "/chat") {
@@ -250,7 +265,7 @@ function start() {
// mount()/replaceChildren() should not alternate on the same outlet
// across navigations, since Preact tracks its own vdom state on the
// container node; if a `soon: true` route is ever added, revisit this.
const rendered = route.view ? route.view(new URLSearchParams(query)) : comingSoon(route);
const rendered = route.view ? route.view(new URLSearchParams(query), match?.params || {}) : comingSoon(route);
if (rendered instanceof Node) {
mount(outlet, rendered);
} else {
+59
View File
@@ -0,0 +1,59 @@
// Hash-route matching.
//
// Every route is declared with a literal path in main.jsx and matched in full:
// `#/tasks` and `#/tasks/42` are different pages, and a prefix rule would send
// every path under a section to the same view, so a typo would render a page
// instead of the dashboard. A segment written `:name` captures exactly one path
// segment, which is how a task id rides in the URL (`#/tasks/42`) rather than
// only in the query string (`#/tasks?task=42` -- an existing deep link that
// keeps working).
//
// This lives in its own module because main.jsx renders on import and cannot be
// imported by a test; the matcher is the piece with decisions in it.
/**
* matchRoute returns `{ route, params }` for the first route whose pattern
* matches, or null. `params` is an object, empty for a literal route.
*/
export function matchRoute(routes, rawPath) {
const path = normalisePath(rawPath);
for (const route of routes) {
const params = matchPattern(route.path, path);
if (params) return { route, params };
}
return null;
}
/**
* navPath is the navigation section a route belongs to. A parameterised route
* is not a nav entry itself, so it names the section it was opened from -- the
* per-task page keeps the Tasks item current instead of blanking the highlight.
*/
export function navPath(route) {
return route?.navPath || route?.path || "/";
}
function normalisePath(rawPath) {
const path = String(rawPath ?? "/").split("?", 1)[0].split("#", 1)[0];
if (!path) return "/";
// A trailing slash names the same route: #/tasks/ is #/tasks, and #/tasks/42/
// is #/tasks/42.
return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
}
function matchPattern(pattern, path) {
const want = String(pattern).split("/");
const got = String(path).split("/");
if (want.length !== got.length) return null;
const params = {};
for (let i = 0; i < want.length; i += 1) {
const segment = want[i];
if (segment.startsWith(":")) {
if (!got[i]) return null;
params[segment.slice(1)] = decodeURIComponent(got[i]);
continue;
}
if (segment !== got[i]) return null;
}
return params;
}
+86
View File
@@ -0,0 +1,86 @@
// The per-attempt effective configuration (R4).
//
// There is no config endpoint: the document arrives inside the task's event
// stream, which this page already fetches for the stage rail's agent reports
// and the timeline. So this panel issues no request of its own and adds nothing
// to the API client contract.
//
// Selection is by kind AND attempt. Selecting by kind alone would show the
// newest attempt's configuration on every attempt, which is exactly the
// merge-attempts bug the attempt column exists to prevent.
export const CONFIG_SCHEMA = "archie/task-config@1";
export function selectConfigEvent(events, attempt) {
return (
(events || []).find(
(ev) => ev && ev.kind === "config_captured" && Number(ev.attempt) === Number(attempt),
) || null
);
}
export function AttemptConfig({ events, attempt, onRetry }) {
if (events === undefined) {
return <div className="run-loading">Loading this task's events…</div>;
}
if (events === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this task's events</div>
<div className="run-error-detail">
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.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
const event = selectConfigEvent(events, attempt);
if (!event) {
return (
<div className="empty">
<div className="empty-title">Not captured for this run</div>
<div>
Archie records the effective configuration when it dispatches an attempt. Attempt {attempt}{" "}
has no such record — it predates the record, or the capture did not run. Nothing here says
the run used the defaults.
</div>
</div>
);
}
const data = event.data || {};
const schema = data.schema || "";
const document = data.document;
return (
<div className="run-config">
<p className="run-config-scope">
This is attempt {event.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.
</p>
<div className="run-config-when">
Captured {event.at || "at an unrecorded time"}
{event.stage ? ` in stage ${event.stage}` : ""}
</div>
{schema === CONFIG_SCHEMA ? (
<pre className="run-json">{JSON.stringify(document ?? {}, null, 2)}</pre>
) : (
<>
<div className="run-config-unknown">
Recorded in an unknown schema{schema ? ` (${schema})` : ""}. The raw payload is shown
verbatim; nothing here reinterprets it.
</div>
<pre className="run-json">{JSON.stringify(data, null, 2)}</pre>
</>
)}
</div>
);
}
+196
View File
@@ -0,0 +1,196 @@
import { ago } from "../base/dom.jsx";
// Changed files for one attempt (R3), from `GET /api/tasks/{id}/changes`.
//
// The capture happens at the producer: archied records the diffstat at the
// moment it commits or pushes an attempt's work. So the honest empty state is
// "no capture was recorded for this attempt", never "no files changed" -- a run
// that predates capture, or one that produced no commit, has no capture and
// nothing here can turn that into a claim about the repository.
const FILE_STATUS = {
added: "Added",
modified: "Modified",
deleted: "Deleted",
renamed: "Renamed",
typechange: "Type changed",
};
export function fileStatusLabel(status) {
return FILE_STATUS[status] || status || "unknown";
}
// The forge links come from the same projection the task list uses: the task's
// own repo/PR URLs, or the capture's if the server attached them. A link is
// rendered only when there is a URL to render -- a capture with no forge
// coordinates shows its owner/repo and PR number as text rather than a dead
// link.
export function captureLinks(capture, task) {
const repo = capture?.repo_url || task?.repo_url || "";
const samePR =
task && String(task.pr_number ?? "") !== "" && String(task.pr_number) === String(capture?.pr_number ?? "");
const pr = capture?.pr_url || (samePR ? task.pr_url || "" : "");
return { repo, pr };
}
export function totalsLabel(totals = {}) {
const files = Number(totals.files) || 0;
const parts = [`${files} file${files === 1 ? "" : "s"}`];
if (totals.additions) parts.push(`+${totals.additions}`);
if (totals.deletions) parts.push(`−${totals.deletions}`);
return parts.join(" · ");
}
function FileTable({ capture }) {
const files = capture.files || [];
const total = Number(capture.totals?.files) || files.length;
if (!files.length) {
return (
<div className="run-changes-empty">
This capture recorded no file entries
{total ? `, though its totals cover ${total} file${total === 1 ? "" : "s"}` : ""}.
</div>
);
}
return (
<>
<table className="table run-changes-table">
<thead>
<tr>
<th>Path</th>
<th>Change</th>
<th className="run-changes-count">Added</th>
<th className="run-changes-count">Deleted</th>
</tr>
</thead>
<tbody>
{files.map((file, i) => (
<tr key={`${file.path}:${i}`}>
<td className="mono run-changes-path">
{file.old_path ? <span className="run-changes-old">{file.old_path} → </span> : null}
{file.path}
</td>
<td>
{fileStatusLabel(file.status)}
{/* binary means "no textual hunks were recorded", not "this is a
binary file on disk": the counts beside it are still real. */}
{file.binary ? <span className="run-changes-hint">no textual hunks</span> : null}
</td>
<td className="run-changes-count mono">{file.additions ? `+${file.additions}` : "—"}</td>
<td className="run-changes-count mono">{file.deletions ? `−${file.deletions}` : "—"}</td>
</tr>
))}
</tbody>
</table>
{capture.truncated ? (
<p className="run-changes-note">
Showing the first {files.length} of {total} files. The totals above cover every file in
this capture.
</p>
) : null}
</>
);
}
function Capture({ capture, task }) {
const links = captureLinks(capture, task);
const prNumber = capture.pr_number;
return (
<section className="run-capture">
<div className="run-capture-head">
<span className="run-capture-when">
{capture.captured_after ? `Captured after ${capture.captured_after}` : "Captured"}
{capture.stage ? ` in stage ${capture.stage}` : ""}
</span>
<span className="run-capture-at">{capture.captured_at ? ago(capture.captured_at) : ""}</span>
</div>
<div className="run-capture-meta">
<span className="mono">
{links.repo ? (
<a className="run-capture-link" href={links.repo} target="_blank" rel="noreferrer">
{capture.owner}/{capture.repo}
</a>
) : (
`${capture.owner || ""}/${capture.repo || ""}`
)}
</span>
{capture.branch ? (
<span className="mono run-capture-branch">
{capture.branch}
{capture.base ? ` → ${capture.base}` : ""}
</span>
) : null}
{capture.head_sha ? <span className="mono run-capture-sha">{String(capture.head_sha).slice(0, 8)}</span> : null}
{prNumber ? (
links.pr ? (
<a className="run-capture-link" href={links.pr} target="_blank" rel="noreferrer">
PR #{prNumber}
</a>
) : (
<span className="mono">PR #{prNumber}</span>
)
) : null}
<span className="run-capture-totals">{totalsLabel(capture.totals)}</span>
</div>
<FileTable capture={capture} />
</section>
);
}
export function ChangedFiles({ state, task, onRetry }) {
if (state === undefined) {
return <div className="run-loading">Loading changed files…</div>;
}
if (state === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this attempt's changed files</div>
<div className="run-error-detail">
archied did not answer for this attempt. It may be restarting — retry, or check the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
const captures = state.captures || [];
// A capture event WAS recorded but its payload could not be read. The server
// reports `found` from the event's existence precisely so this is not
// reported as "no capture was recorded", which would be a false statement
// about a run whose diffstat demonstrably was captured.
if (state.found === true && !captures.length) {
return (
<div className="empty">
<div className="empty-title">A change capture was recorded but could not be read</div>
<div>
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.
</div>
</div>
);
}
if (!state.found || !captures.length) {
return (
<div className="empty">
<div className="empty-title">No change capture was recorded for this attempt</div>
<div>
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".
</div>
</div>
);
}
return (
<div className="run-changes">
{captures.map((capture, i) => (
<Capture key={`${capture.captured_at || ""}:${i}`} capture={capture} task={task} />
))}
</div>
);
}
+41
View File
@@ -0,0 +1,41 @@
// Raw debug view (R7): the stored task record and the task's events, verbatim.
//
// The events are deliberately NOT filtered to the selected attempt. A debug
// view that silently hid events would be worse than useless, so every event is
// shown and each carries its own `attempt` for the operator to attribute. The
// selected attempt is reported in the note and in the envelope's own `attempt`
// field; nothing here is summarised, projected or prettified beyond JSON
// indentation.
export function DebugView({ state, attempt, onRetry }) {
if (state === undefined) {
return <div className="run-loading">Loading the stored record…</div>;
}
if (state === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load the stored record</div>
<div className="run-error-detail">
archied did not answer for this task's debug view. It may be restarting — retry, or check
the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
return (
<div className="run-debug">
<p className="run-debug-note">
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 {attempt}{" "}
is the one selected above.
</p>
<pre className="run-json">{JSON.stringify(state, null, 2)}</pre>
</div>
);
}
+196
View File
@@ -0,0 +1,196 @@
import { Pill } from "../base/pill.jsx";
import { describeTimelineEvent, duration } from "./timeline-event.jsx";
// The per-attempt stage rail (R1).
//
// The rail is built from `GET /api/tasks/{id}/attempts`, which returns each
// attempt with its stages inline, so the selector and the rail can never
// disagree about which attempt is on screen. The rail only ever renders one
// attempt: merging two attempts by stage name is the failure this design
// exists to avoid.
//
// What a stage status means, and what it does not:
//
// a stage fails when its Go function returned an error. There is NO exit
// code, no pass/fail verdict, and no notion of "the work was correct" --
// a stage that returned nil after producing a poor diff is `ok`. So the rail
// never renders a checkmark, a badge or an exit status; it renders the
// status word, the duration and the error text, and says plainly what `ok`
// means. The agent's own self-reported outcome (`agent_finish`) is shown
// separately, labelled as the agent's report rather than as archie's verdict.
//
// A per-run elapsed time is deliberately NOT rendered. `waiting_human` can span
// days, so wall time from an attempt's start is not a duration of work; only
// per-stage durations exist and only those are shown.
const STAGE_STATUS = {
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" },
};
export function stageStatusMeta(status) {
return STAGE_STATUS[status] || { label: status || "unknown", kind: "idle" };
}
// agentReports returns the agent's own account of a stage: the `agent_finish`
// events whose attempt and stage both match. Returning an array rather than one
// value keeps a stage that ran two agents honest instead of showing the last.
export function agentReports(events, attemptNumber, stage) {
return (events || [])
.filter(
(ev) =>
ev &&
ev.kind === "agent_finish" &&
Number(ev.attempt) === Number(attemptNumber) &&
(ev.stage || "") === (stage || ""),
)
.map((ev) => describeTimelineEvent(ev));
}
// An attempt's start is rendered as an absolute instant, never as "started 2
// days ago": on a still-running attempt a relative stamp reads as two days of
// work, which is exactly the elapsed-time claim the design forbids. The
// attempt's own `duration_ms` is never rendered for the same reason -- it is
// wall time, and waiting_human can span days.
function startedAt(value) {
const when = value instanceof Date ? value : new Date(value);
if (Number.isNaN(when.getTime())) return "start time not recorded";
return `started ${when.toISOString().replace("T", " ").slice(0, 16)} UTC`;
}
function StageRow({ stage, attemptNumber, events }) {
const meta = stageStatusMeta(stage.status);
const ran = duration(stage.duration_ms);
const reports = agentReports(events, attemptNumber, stage.name);
return (
<li className="run-stage" data-status={stage.status || "unknown"}>
<span className="run-stage-node" aria-hidden="true" />
<div className="run-stage-body">
<div className="run-stage-head">
<span className="run-stage-name mono">{stage.name || "(unnamed stage)"}</span>
<Pill text={meta.label} kind={meta.kind} />
<span className="run-stage-duration">
{ran ? `ran for ${ran}` : "duration not recorded"}
</span>
</div>
{stage.error ? <div className="run-stage-error">{stage.error}</div> : null}
{reports.map((report, i) => (
<div className="run-agent-report" key={i}>
<span className="run-agent-report-label">Agent's own report, not verified by archie: </span>
{[report.title, report.detail].filter(Boolean).join(" · ")}
</div>
))}
</div>
</li>
);
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
// The events no attempt owns. It renders in EVERY rail state, the empty ones
// included: a deployment where every event predates the attempt column answers
// with no attempts at all, and reporting "No attempts recorded" there without
// the count would present unattributable history as nothing having happened.
function UnattributedNote({ count }) {
const n = Number(count) || 0;
if (!n) return null;
return (
<p className="run-rail-note">
{n} event{n === 1 ? "" : "s"} on this task predate attempt attribution and cannot be assigned to a
run.
</p>
);
}
export function StageRail({ state, attemptNumber, events, onRetry }) {
if (state === undefined) {
return <div className="run-loading">Loading this task's attempts…</div>;
}
if (state === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this task's attempts</div>
<div className="run-error-detail">
archied did not answer for this task's run history. It may be restarting — retry, or check
the daemon.
</div>
{onRetry ? (
<button className="btn" type="button" onClick={onRetry}>
Retry
</button>
) : null}
</div>
);
}
const attempts = state?.attempts || [];
if (!attempts.length) {
return (
<>
<Empty
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."
/>
<UnattributedNote count={state?.unattributed_events} />
</>
);
}
const attempt = attempts.find((a) => Number(a.attempt) === Number(attemptNumber));
if (!attempt) {
return (
<>
<Empty
title={`Attempt ${attemptNumber} is not recorded for this task`}
detail={`This task recorded attempt ${attempts.map((a) => a.attempt).join(", ")}.`}
/>
<UnattributedNote count={state?.unattributed_events} />
</>
);
}
const stages = attempt.stages || [];
const meta = stageStatusMeta(attempt.status);
return (
<div className="run-rail">
<div className="run-rail-head">
<span className="run-rail-attempt">Attempt {attempt.attempt}</span>
<Pill text={meta.label} kind={meta.kind} />
<span className="run-rail-when">{startedAt(attempt.started_at)}</span>
</div>
{stages.length ? (
<ol className="run-stages" aria-label={`Stages recorded in attempt ${attempt.attempt}`}>
{stages.map((stage, i) => (
<StageRow
key={`${stage.seq ?? i}:${stage.name}`}
stage={stage}
attemptNumber={attempt.attempt}
events={events}
/>
))}
</ol>
) : (
<Empty
title="No stages recorded for this attempt"
detail="The attempt exists, but nothing recorded a stage for it."
/>
)}
<p className="run-rail-legend">
<strong>ok</strong> 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.
</p>
<UnattributedNote count={state?.unattributed_events} />
</div>
);
}
+69
View File
@@ -0,0 +1,69 @@
import { useRef } from "preact/hooks";
// A tab bar for the run detail page. There is no other consumer yet, so it
// stays in tasks/ rather than in base (organisation.md extracts on the second
// distinct consumer).
//
// Keyboard behaviour follows the WAI-ARIA tabs pattern with automatic
// activation: the tab list is one stop in the page's tab order (roving
// tabindex), Left/Right move between tabs and select as they go, Home/End jump
// to the ends. Automatic activation is the right choice here because every
// panel is a local render, not a fetch: there is no cost to switching.
export function tabId(prefix, id) {
return `${prefix}-tab-${id}`;
}
export function panelId(prefix, id) {
return `${prefix}-panel-${id}`;
}
export function TabBar({ tabs, active, onSelect, prefix = "run", label = "Run detail views" }) {
const refs = useRef([]);
const select = (index) => {
const tab = tabs[index];
if (!tab) return;
onSelect?.(tab.id);
refs.current[index]?.focus?.();
};
const onKeyDown = (event) => {
const current = tabs.findIndex((tab) => tab.id === active);
if (current < 0) return;
let next;
if (event.key === "ArrowRight") next = (current + 1) % tabs.length;
else if (event.key === "ArrowLeft") next = (current - 1 + tabs.length) % tabs.length;
else if (event.key === "Home") next = 0;
else if (event.key === "End") next = tabs.length - 1;
else return;
event.preventDefault();
select(next);
};
return (
<div className="tab-bar" role="tablist" aria-label={label} onKeyDown={onKeyDown}>
{tabs.map((tab, index) => {
const selected = tab.id === active;
return (
<button
key={tab.id}
ref={(node) => {
refs.current[index] = node;
}}
id={tabId(prefix, tab.id)}
className={`tab${selected ? " is-selected" : ""}`}
type="button"
role="tab"
aria-selected={selected}
aria-controls={panelId(prefix, tab.id)}
tabIndex={selected ? 0 : -1}
onClick={() => onSelect?.(tab.id)}
>
{tab.label}
</button>
);
})}
</div>
);
}
+617
View File
@@ -0,0 +1,617 @@
/* The per-task run detail page.
Colour comes only from the shared tokens in css/tokens.css, so both themes
are covered by construction; the layout is one column of panels that
collapses on narrow viewports. Motion is limited to hover/selection
transitions and is switched off for reduced-motion users. */
.run-meta {
display: flex;
align-items: center;
gap: var(--sp-4);
flex-wrap: wrap;
margin: calc(var(--sp-2) * -1) 0 var(--sp-4);
font-size: var(--text-sm);
}
.run-meta-item {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
}
.run-meta-label {
color: var(--fg-muted);
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.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);
}
/* ── New run ─────────────────────────────────────────────────────────────── */
.run-restart {
display: flex;
align-items: center;
gap: var(--sp-3);
flex-wrap: wrap;
margin-bottom: var(--sp-4);
}
.run-restart-copy {
flex: 1 1 22rem;
margin: 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.run-restart-unavailable {
flex: 1 1 22rem;
margin: 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.run-restart-error {
flex: 1 1 100%;
margin: 0;
font-size: var(--text-sm);
}
.run-restart-error-refused {
color: var(--warn);
}
.run-restart-error-broken {
color: var(--danger);
}
.run-restart-error-session-expired {
color: var(--warn);
}
/* ── Attempt selector ────────────────────────────────────────────────────── */
.run-attempts {
display: flex;
gap: var(--sp-2);
flex-wrap: wrap;
margin-bottom: var(--sp-4);
}
.run-attempt {
display: inline-flex;
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);
}
.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);
}
/* ── Tabs ────────────────────────────────────────────────────────────────── */
.run-card {
padding-top: var(--sp-4);
}
.tab-bar {
display: flex;
gap: var(--sp-1);
border-bottom: 1px solid var(--border);
margin-bottom: var(--sp-4);
overflow-x: auto;
scrollbar-width: thin;
}
.tab {
position: relative;
padding: var(--sp-2) var(--sp-3);
border: 0;
border-bottom: 2px solid transparent;
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
background: transparent;
color: var(--fg-muted);
font: inherit;
font-size: var(--text-sm);
white-space: nowrap;
cursor: pointer;
transition: color var(--transition), background var(--transition);
}
.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;
}
/* ── Shared panel states ─────────────────────────────────────────────────── */
.run-loading {
padding: var(--sp-5) 0;
color: var(--fg-muted);
font-size: var(--text-sm);
}
.run-error {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: var(--sp-2);
padding: var(--sp-3) 0;
}
.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 {
margin: 0;
padding: var(--sp-3);
max-height: 60vh;
overflow: auto;
background: var(--bg-raised);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
font-family: var(--font-mono);
font-size: var(--text-xs);
line-height: 1.5;
/* pre-wrap keeps the indentation the JSON is printed with while letting a
long value wrap instead of forcing the panel to scroll sideways. */
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* ── Stage rail ──────────────────────────────────────────────────────────── */
.run-rail-head {
display: flex;
align-items: center;
gap: var(--sp-3);
flex-wrap: wrap;
margin-bottom: var(--sp-4);
}
.run-rail-attempt {
font-weight: 600;
}
.run-rail-when {
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-stages {
list-style: none;
margin: 0;
padding: 0;
}
.run-stage {
position: relative;
display: grid;
grid-template-columns: 1.75rem 1fr;
gap: var(--sp-2);
padding-bottom: var(--sp-4);
}
/* The rail line: a single vertical stroke behind the stage nodes, so the
sequence reads as one run rather than as unrelated rows. */
.run-stage::before {
content: "";
position: absolute;
left: 0.6875rem;
top: 1rem;
bottom: 0;
width: 1px;
background: var(--border-strong);
}
.run-stage:last-child::before {
display: none;
}
.run-stage-node {
position: relative;
z-index: 1;
width: 0.875rem;
height: 0.875rem;
margin: 0.25rem 0 0 0.25rem;
border-radius: 50%;
border: 2px solid var(--border-strong);
background: var(--bg-raised);
}
.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 {
display: flex;
align-items: center;
gap: var(--sp-2);
flex-wrap: wrap;
}
.run-stage-name {
font-weight: 500;
color: var(--fg);
/* A stage name is one unbroken token often enough that it has to be allowed
to break, or a long one pushes the status and duration off the row. */
overflow-wrap: anywhere;
min-width: 0;
}
.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);
}
/* ── Changed files ───────────────────────────────────────────────────────── */
.run-capture + .run-capture {
margin-top: var(--sp-5);
padding-top: var(--sp-4);
border-top: 1px solid var(--border);
}
.run-capture-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--sp-3);
flex-wrap: wrap;
}
.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 {
display: flex;
align-items: center;
gap: var(--sp-3);
flex-wrap: wrap;
margin: var(--sp-2) 0 var(--sp-3);
color: var(--fg-muted);
font-size: var(--text-xs);
}
.run-capture-link {
color: var(--accent);
}
.run-capture-link:hover {
text-decoration: underline;
}
.run-capture-branch,
.run-capture-sha {
color: var(--fg-muted);
}
.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;
}
/* ── Configuration ───────────────────────────────────────────────────────── */
.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);
}
/* ── Log pane ────────────────────────────────────────────────────────────── */
.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 {
display: inline-flex;
align-items: center;
gap: var(--sp-2);
}
.task-log-filter-label {
color: var(--fg-muted);
font-size: var(--text-xs);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.task-log-filter-note {
flex: 1 1 100%;
margin: 0;
color: var(--fg-muted);
font-size: var(--text-xs);
max-width: 80ch;
}
/* On the detail page the log is the primary content, so it takes the tallest
read surface and a framed edge of its own rather than the bare top rule the
inline list-page pane uses. Scoped to .run-panel so the list-page pane keeps
its 40vh cap. */
.run-panel .task-log-list {
max-height: 62vh;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
background: var(--bg-raised);
padding: 0 var(--sp-2);
}
/* ── Status pills on this page ───────────────────────────────────────────── */
/* The shared .pill palette draws its small status WORD in the semantic hue on
that hue's own tint. Measured against the card this page renders on, that
fails WCAG AA 4.5:1 for small text in the light theme (ok 3.39:1, warn
3.26:1, danger 4.03:1, idle 4.09:1) and for `unknown` in the dark theme
(idle 3.31:1). Raising the shared tokens is an app-wide design change, not
this page's to make, so here the status word is drawn in the full-contrast
foreground colour (>=12.6:1 both themes) and the hue is carried by the dot
the pill already has -- which still clears the 3:1 non-text minimum
(worst pair 3.26:1). */
.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);
}
/* ── Narrow viewports: the rail collapses ────────────────────────────────── */
@media (max-width: 700px) {
.run-meta {
margin-bottom: var(--sp-3);
}
.run-restart {
align-items: flex-start;
}
.run-attempts {
overflow-x: auto;
flex-wrap: nowrap;
padding-bottom: var(--sp-1);
}
/* The connector line and its gutter are what make the rail a timeline; on a
phone they cost the width the stage names need, so the rail becomes a plain
list of stages in order. */
.run-stage {
grid-template-columns: 1fr;
padding-bottom: var(--sp-3);
border-bottom: 1px solid var(--border);
}
.run-stage::before {
display: none;
}
.run-stage-node {
display: none;
}
.run-capture-head {
flex-direction: column;
align-items: flex-start;
gap: var(--sp-1);
}
}
@media (max-width: 480px) {
.tab {
padding: var(--sp-2);
}
.run-json {
max-height: 45vh;
}
}
@media (prefers-reduced-motion: reduce) {
.run-attempt,
.tab {
transition: none;
}
}
+556
View File
@@ -0,0 +1,556 @@
import { useState, useEffect, useRef } from "preact/hooks";
import "./task-detail.css";
import { api, classifyActionError } from "../base/api.jsx";
import { Pill } from "../base/pill.jsx";
import { actionFor, statusKind, statusLabel } from "../base/task-meta.jsx";
import { TabBar, panelId, tabId } from "./tab-bar.jsx";
import { StageRail, stageStatusMeta } from "./stage-rail.jsx";
import { ChangedFiles } from "./changed-files.jsx";
import { AttemptConfig } from "./attempt-config.jsx";
import { DebugView } from "./debug-view.jsx";
import { EMPTY_LOG_FILTERS, TaskLogPanel, logCacheKey } from "./task-logs.jsx";
// The per-task run detail page (R1, R3-R9), reached at #/tasks/{id}.
//
// One page, one task: which run it is showing, what each stage of that run did,
// its log, what it changed, the configuration it ran under, and the raw record.
// The task id rides in the path and the view state (`tab`, `attempt`) rides in
// the query string, so every view of this page is a deep link that survives a
// reload -- #/tasks/42?tab=changes&attempt=2.
//
// The attempt is the unit of every panel. Nothing on this page merges two
// attempts: the rail, the log, the capture and the config are all selected by
// attempt, and the two views of the same task's attempts (the selector and the
// rail) come from a single response.
export const RUN_TABS = [
{ id: "stages", label: "Stages" },
{ id: "log", label: "Log" },
{ id: "changes", label: "Changed files" },
{ id: "config", label: "Configuration" },
{ id: "debug", label: "Debug" },
];
const TAB_PREFIX = "run";
const TAB_IDS = new Set(RUN_TABS.map((tab) => tab.id));
export function parseTaskId(raw) {
const value = String(raw ?? "").trim();
if (!/^\d+$/.test(value)) return null;
const n = Number(value);
return Number.isSafeInteger(n) && n > 0 ? n : null;
}
export function initialTab(query) {
const requested = query?.get?.("tab") || "";
return TAB_IDS.has(requested) ? requested : RUN_TABS[0].id;
}
// `?attempt=2` pins attempt 2. An absent, empty or non-numeric value follows
// whatever the server reports as current, and 0 is the wire's own spelling of
// "the current attempt" (taskLogTarget, internal/webui/api_tasks_logs.go), so it
// selects the current attempt rather than a nonexistent attempt 0.
export function initialAttempt(query) {
const raw = query?.get?.("attempt");
if (raw == null || raw === "") return null;
const n = Number(raw);
return Number.isInteger(n) && n > 0 ? n : null;
}
export function runHash(id, tab, attempt) {
const params = new URLSearchParams();
params.set("tab", tab || RUN_TABS[0].id);
if (attempt) params.set("attempt", String(attempt));
return `#/tasks/${id}?${params.toString()}`;
}
// Selection is written back with replaceState rather than by assigning
// location.hash: replaceState does not fire a hashchange, so the router does not
// remount and refetch the page on every tab click, while the address bar still
// holds the full state for a copy, a bookmark or a reload.
export function writeRunHash(id, tab, attempt) {
try {
window.history.replaceState(null, "", `${location.pathname}${location.search}${runHash(id, tab, attempt)}`);
} catch {
// A deployment that refuses the history write still renders every panel;
// only the shareable URL is lost, and the page never depends on it.
}
}
function attemptKey(id, attempt) {
return `${id}|${Number(attempt) || 0}`;
}
function Empty({ title, detail }) {
return (
<div className="empty">
<div className="empty-title">{title}</div>
{detail && <div>{detail}</div>}
</div>
);
}
function NotFound({ id }) {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Task not found</h1>
<p className="page-sub">No task with id {id} in this deployment.</p>
</div>
<div className="page-actions">
<a className="btn" href="#/tasks">
Back to tasks
</a>
</div>
</div>
<div className="card">
<div className="empty">
<div className="empty-title">Nothing is recorded for task {id}</div>
<div>archied answered that this task does not exist, so there is no run history to show.</div>
</div>
</div>
</div>
);
}
function InvalidId({ raw }) {
return (
<div>
<div className="page-head">
<div>
<h1 className="page-title">Not a task id</h1>
<p className="page-sub">The run view addresses one task by its id: #/tasks/42</p>
</div>
<div className="page-actions">
<a className="btn" href="#/tasks">
Back to tasks
</a>
</div>
</div>
<div className="card">
<div className="empty">
<div className="empty-title">“{raw}” is not a task id</div>
<div>A task id is a positive whole number. Nothing was requested.</div>
</div>
</div>
</div>
);
}
function AttemptSelector({ attempts, selected, onSelect }) {
const list = attempts?.attempts || [];
if (!list.length) return null;
return (
<div className="run-attempts" role="group" aria-label="Attempts of this task">
{list.map((attempt) => {
const meta = stageStatusMeta(attempt.status);
const selectedNow = Number(attempt.attempt) === Number(selected);
return (
<button
key={attempt.attempt}
type="button"
className={`run-attempt${selectedNow ? " is-selected" : ""}`}
aria-pressed={selectedNow}
onClick={() => onSelect(attempt.attempt)}
>
<span className="run-attempt-id">Attempt {attempt.attempt}</span>
<Pill text={meta.label} kind={meta.kind} />
<span className="run-attempt-meta">
{(attempt.stages || []).length} stage{(attempt.stages || []).length === 1 ? "" : "s"}
</span>
</button>
);
})}
</div>
);
}
function RunDetail({ id, query }) {
const [tab, setTab] = useState(() => initialTab(query));
const [requestedAttempt, setRequestedAttempt] = useState(() => initialAttempt(query));
const [taskList, setTaskList] = useState(undefined);
const [attempts, setAttempts] = useState(undefined);
const [missing, setMissing] = useState(false);
const [events, setEvents] = useState(undefined);
const [filters, setFilters] = useState(EMPTY_LOG_FILTERS);
const [logs, setLogs] = useState(new Map());
const [changes, setChanges] = useState(new Map());
const [debug, setDebug] = useState(new Map());
const [retryBusy, setRetryBusy] = useState(false);
const [retryError, setRetryError] = useState(null);
const [refreshToken, setRefreshToken] = useState(0);
const started = useRef(new Set());
const task = Array.isArray(taskList) ? taskList.find((t) => String(t.id) === String(id)) || null : null;
const currentAttempt = Number(attempts?.current_attempt) > 0 ? Number(attempts.current_attempt) : null;
// The wire spells "the task's current attempt" as 0, which is not an attempt
// number: a task with no run at all must not address attempt 0.
const attemptNumber = requestedAttempt ?? currentAttempt;
const selectedAttempt = (attempts?.attempts || []).find(
(a) => Number(a.attempt) === Number(attemptNumber),
);
const stageNames = [
...new Set((selectedAttempt?.stages || []).map((stage) => stage.name).filter(Boolean)),
];
// Every keyed fetch goes through here: the key is what the response belongs
// to, so a late response for an attempt the operator has already left lands
// under its own key and is never shown against another attempt.
const keyedLoad = (cacheKey, fetcher, setter, { force = false } = {}) => {
if (started.current.has(cacheKey) && !force) return;
started.current.add(cacheKey);
setter((prev) => new Map(prev).set(cacheKey, undefined));
fetcher()
.then((res) => setter((prev) => new Map(prev).set(cacheKey, res)))
.catch(() => setter((prev) => new Map(prev).set(cacheKey, null)));
};
const loadTaskList = () => {
setTaskList(undefined);
api
.tasks()
.then((res) => setTaskList(res))
.catch(() => setTaskList(null));
};
const loadAttempts = () => {
setAttempts(undefined);
setMissing(false);
api
.taskAttempts(id)
.then((res) => setAttempts(res))
.catch((err) => {
if (err?.status === 404) setMissing(true);
setAttempts(null);
});
};
const loadEvents = () => {
setEvents(undefined);
api
.task(id)
.then((res) => setEvents(res || []))
.catch(() => setEvents(null));
};
const loadLogs = (attempt, opts) =>
keyedLoad(
logCacheKey(id, attempt, filters),
() =>
api.taskLogs(id, {
attempt: attempt || undefined,
level: filters.level,
stage: filters.stage,
limit: 500,
}),
setLogs,
opts,
);
const loadChanges = (attempt, opts) =>
keyedLoad(attemptKey(id, attempt), () => api.taskChanges(id, { attempt }), setChanges, opts);
const loadDebug = (attempt, opts) =>
keyedLoad(attemptKey(id, attempt), () => api.taskDebug(id, { attempt }), setDebug, opts);
const refreshAll = () => {
// Drop every cache and let the effects refetch: a manual refresh must not
// show a stale capture or log beside fresh attempt history.
started.current = new Set();
setLogs(new Map());
setChanges(new Map());
setDebug(new Map());
loadTaskList();
loadAttempts();
loadEvents();
setRefreshToken((n) => n + 1);
};
useEffect(() => {
loadTaskList();
loadAttempts();
loadEvents();
// The page loads once for the task it was opened for; the route remounts it
// when that changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (attemptNumber == null) return;
// Only the visible tab's lazy payload is fetched: the debug envelope repeats
// the whole event list, so fetching it on every page load would duplicate a
// large body for nothing.
if (tab === "log") loadLogs(attemptNumber);
else if (tab === "changes") loadChanges(attemptNumber);
else if (tab === "debug") loadDebug(attemptNumber);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tab, attemptNumber, filters, refreshToken]);
useEffect(() => {
writeRunHash(id, tab, attemptNumber);
}, [id, tab, attemptNumber]);
const performRetry = async () => {
const title = task?.title || `task ${id}`;
const confirmed = window.confirm(
`Start a new run for "${title}"? This is a new attempt, and the previous attempt's commits are discarded.`,
);
if (!confirmed) return;
setRetryError(null);
setRetryBusy(true);
try {
await api.taskAction(id, "retry");
// A new attempt starts here. Everything cached belongs to the attempt
// that just ended, so it is dropped rather than shown against the new
// run: the attempt history, the events, every cached log, capture and
// debug payload. The new attempt then becomes the selected run without a
// reload.
started.current = new Set();
setLogs(new Map());
setChanges(new Map());
setDebug(new Map());
setRequestedAttempt(null);
loadTaskList();
loadAttempts();
loadEvents();
setRefreshToken((n) => n + 1);
} catch (err) {
setRetryError(classifyActionError(err));
} finally {
setRetryBusy(false);
}
};
if (missing) return <NotFound id={id} />;
const logKey = attemptNumber == null ? null : logCacheKey(id, attemptNumber, filters);
const changeKey = attemptKey(id, attemptNumber);
const debugKey = attemptKey(id, attemptNumber);
const panel = () => {
// The rail owns its own loading, failure and empty-rail states.
if (tab === "stages") {
return (
<StageRail
state={attempts}
attemptNumber={attemptNumber}
events={events}
onRetry={loadAttempts}
/>
);
}
// Every other panel is scoped to one attempt, and "no attempt" is a claim
// only a successful read of the run history can make -- a failed read is
// reported as a failed read.
if (attempts === undefined) {
return <div className="run-loading">Loading this task's attempts…</div>;
}
if (attempts === null) {
return (
<div className="run-error">
<div className="run-error-title">Could not load this task's attempts</div>
<div className="run-error-detail">
This panel reads one attempt, and the task's run history could not be read.
</div>
<button className="btn" type="button" onClick={loadAttempts}>
Retry
</button>
</div>
);
}
if (attemptNumber == null) {
return (
<Empty
title="No attempt recorded"
detail="This task has no recorded run, so there is nothing to read for an attempt."
/>
);
}
switch (tab) {
case "log":
return (
<TaskLogPanel
state={logKey && logs.has(logKey) ? logs.get(logKey) : undefined}
attempt={attemptNumber}
stages={stageNames}
filters={filters}
onFilterChange={setFilters}
taskId={id}
onRetry={() => loadLogs(attemptNumber, { force: true })}
/>
);
case "changes":
return (
<ChangedFiles
state={changes.has(changeKey) ? changes.get(changeKey) : undefined}
task={task}
onRetry={() => loadChanges(attemptNumber, { force: true })}
/>
);
case "config":
return <AttemptConfig events={events} attempt={attemptNumber} onRetry={loadEvents} />;
case "debug":
return (
<DebugView
state={debug.has(debugKey) ? debug.get(debugKey) : undefined}
attempt={attemptNumber}
onRetry={() => loadDebug(attemptNumber, { force: true })}
/>
);
default:
return (
<StageRail
state={attempts}
attemptNumber={attemptNumber}
events={events}
onRetry={loadAttempts}
/>
);
}
};
const retryMeta = actionFor("retry");
const canRetry = Boolean(retryMeta && (task?.actions || []).includes("retry"));
return (
<div className="run-page">
<div className="page-head">
<div>
<h1 className="page-title">{task?.title || `Task #${id}`}</h1>
<p className="page-sub">
One run of task {id}
{task?.workflow ? ` · ${task.workflow} workflow` : ""}
{task?.repo ? ` · ${task.owner}/${task.repo}` : ""}
</p>
</div>
<div className="page-actions">
<a className="btn" href="#/tasks">
Back to tasks
</a>
<button className="btn" type="button" onClick={refreshAll}>
Refresh
</button>
</div>
</div>
<div className="run-meta">
<span className="run-meta-item">
<span className="run-meta-label">Task status</span>
{taskList === undefined ? (
<span className="run-meta-muted">loading…</span>
) : task ? (
<Pill text={statusLabel(task.status)} kind={statusKind(task.status)} />
) : (
<span className="run-meta-muted">not read</span>
)}
</span>
<span className="run-meta-item">
<span className="run-meta-label">Attempt</span>
<span className="run-meta-value">
{attempts === null
? "run history unreadable"
: attempts === undefined
? "loading…"
: attemptNumber == null
? "none recorded"
: `attempt ${attemptNumber} of ${currentAttempt ?? attemptNumber}`}
</span>
</span>
{task?.repo_url ? (
<a className="run-meta-link" href={task.repo_url} target="_blank" rel="noreferrer">
{task.owner}/{task.repo}
</a>
) : null}
{task?.issue_url && task.issue_number ? (
<a className="run-meta-link" href={task.issue_url} target="_blank" rel="noreferrer">
Issue #{task.issue_number}
</a>
) : null}
{task?.pr_url && task.pr_number ? (
<a className="run-meta-link" href={task.pr_url} target="_blank" rel="noreferrer">
PR #{task.pr_number}
</a>
) : null}
</div>
{taskList === null ? (
<p className="run-note">
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.
</p>
) : null}
{Array.isArray(taskList) && !task ? (
<p className="run-note">
Task {id} 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.
</p>
) : null}
<section className="run-restart" aria-label="Start a new run">
<button
className={`btn ${retryMeta?.kind === "primary" ? "btn-primary" : ""}`}
type="button"
disabled={!canRetry || retryBusy}
title="Retry this task as a new run"
onClick={performRetry}
>
{retryBusy ? "Starting…" : "Start a new run"}
</button>
<p className="run-restart-copy">
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.
</p>
{!canRetry && taskList !== undefined ? (
<p className="run-restart-unavailable">
{task
? `A new run can only start from a parked task. This task is ${statusLabel(task.status)}.`
: "This task's operator controls could not be read, so a new run cannot be started from here."}
</p>
) : null}
{retryError ? (
<p className={`run-restart-error run-restart-error-${retryError.kind}`}>
{retryError.kind === "session-expired"
? "Your session has expired. Reload to sign in."
: retryError.kind === "refused"
? `${retryError.message} — this run cannot be restarted from here.`
: `${retryError.message} — try again, or check the daemon.`}
</p>
) : null}
</section>
<AttemptSelector
attempts={attempts}
selected={attemptNumber}
onSelect={(value) => setRequestedAttempt(value)}
/>
<div className="card run-card">
<TabBar tabs={RUN_TABS} active={tab} onSelect={setTab} prefix={TAB_PREFIX} />
<div
className="run-panel"
role="tabpanel"
id={panelId(TAB_PREFIX, tab)}
aria-labelledby={tabId(TAB_PREFIX, tab)}
tabIndex={0}
>
{panel()}
</div>
</div>
</div>
);
}
export function taskDetailPage(query, params) {
const raw = params?.id;
const id = parseTaskId(raw);
if (id === null) return <InvalidId raw={raw ?? ""} />;
// The key is load-bearing, not cosmetic. The router renders this page with
// Preact's own render() into one long-lived outlet (main.jsx, show()), so
// navigating from #/tasks/1 to #/tasks/2 diffs the same element in place and
// RunDetail is never remounted. Without the key every piece of task-scoped
// state -- the open tab, the pinned attempt, the run history, the events, and
// the log/change/debug caches -- stays with the task that was left, and the
// new task is rendered against another task's reads. Keying by id makes the
// remount RunDetail's own comment assumes actually happen.
return <RunDetail key={id} id={id} query={query} />;
}
+176 -44
View File
@@ -1,13 +1,32 @@
import { h } from "preact";
import { useRef, useEffect } from "preact/hooks";
import { logRow as renderLogRow } from "../base/log-row.jsx";
import { logRow as renderLogRow, LOG_LEVELS } from "../base/log-row.jsx";
// A task attempt's log pane (R5).
//
// Three read outcomes are kept apart, because only one of them is about the
// operator's configuration or about this attempt:
//
// disabled -- this process cannot read task logs at all (deployment)
// found: false -- a reader exists and this attempt has no log file
// entries: [] -- a log exists and nothing matches the current filter
//
// The filter controls render ABOVE all three, and above the loading and failed
// states too. Putting them inside the success branch is how a deployment that
// cannot read logs ends up showing an empty filtered pane instead of saying so.
// They render when the page can act on a filter change (the list page's inline
// pane has no filter state, and a control that filters nothing is worse than no
// control); the ordering rule belongs here either way.
//
// The attempt is not a filter here: the page selects the attempt and this pane
// reports which one it is showing, so the pane can never read attempt 1's log
// while claiming attempt 2.
function LogRowNode({ entry }) {
const ref = useRef(null);
useEffect(() => {
if (ref.current) ref.current.replaceChildren(renderLogRow(entry));
}, [entry]);
return <div ref={ref} style={{ display: 'contents' }} />;
return <div ref={ref} style={{ display: "contents" }} />;
}
// Task-log download URL. The attempt is named explicitly so a download matches
@@ -17,66 +36,179 @@ export function taskLogDownloadURL(id, attempt) {
return `/api/tasks/${id}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`);
}
export function TaskLogPanel({ state, onRetry, taskId }) {
export const EMPTY_LOG_FILTERS = { level: "", stage: "" };
// The identity of a log read: a task, an attempt, and the filters that produced
// the response. Keying by task alone cannot represent two attempts -- the bug
// this replaces -- and keying without the filters would serve attempt 2's
// unfiltered log in answer to a filtered request.
export function logCacheKey(id, attempt, filters = EMPTY_LOG_FILTERS) {
const applied = filters || EMPTY_LOG_FILTERS;
return [id, Number(attempt) || 0, applied.level || "", applied.stage || ""].join("|");
}
function FilterBar({ filters, onFilterChange, stages, attempt }) {
const change = (patch) => onFilterChange?.({ ...filters, ...patch });
const shown = Number(attempt) || 0;
return (
<div className="log-filters task-log-filters">
<span className="task-log-attempt">{shown > 0 ? `Attempt ${shown}` : "Current attempt"}</span>
{/* Controls appear only where the page can act on a change: a filter that
filters nothing is worse than no filter. */}
{onFilterChange ? (
<>
<label className="task-log-filter">
<span className="task-log-filter-label">Level</span>
<select
className="task-filter"
value={filters.level}
aria-label="Filter log entries by level"
onChange={(e) => change({ level: e.target.value })}
>
{LOG_LEVELS.map((level) => (
<option key={level.value} value={level.value}>
{level.label}
</option>
))}
</select>
</label>
<label className="task-log-filter">
<span className="task-log-filter-label">Stage</span>
<select
className="task-filter"
value={filters.stage}
aria-label="Filter log entries by stage"
onChange={(e) => change({ stage: e.target.value })}
>
<option value="">All stages</option>
{(stages || []).map((stage) => (
<option key={stage} value={stage}>
{stage}
</option>
))}
</select>
</label>
{/* 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 ? (
<p className="task-log-filter-note">
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.
</p>
) : null}
{!filters.stage && !(stages || []).length ? (
<p className="task-log-filter-note">
This attempt recorded no stage names, so the stage filter has nothing to match.
</p>
) : null}
</>
) : null}
</div>
);
}
// 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 (
<p className="visually-hidden" role="status" aria-live="polite" aria-atomic="true">
{text}
</p>
);
}
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 <div className="task-log-loading">Loading attempt log…</div>;
}
if (state === null) {
return (
status = "Loading this attempt's log";
body = <div className="task-log-loading">Loading attempt log…</div>;
} else if (state === null) {
status = "This attempt's log could not be loaded";
body = (
<div className="task-log-error">
<div className="task-timeline-detail">Could not load this attempt's log.</div>
<button className="btn" onClick={onRetry}>Retry</button>
<button className="btn" onClick={onRetry}>
Retry
</button>
</div>
);
}
// 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 = (
<div className="empty">
<div className="empty-title">No log recorded for this attempt</div>
<div>This attempt produced no output, or it has not started writing yet.</div>
</div>
);
}
// 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 = (
<div className="empty">
<div className="empty-title">No persisted log for this attempt</div>
<div>This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.</div>
</div>
);
} else {
const entries = state.entries || [];
const download = taskId != null ? taskLogDownloadURL(taskId, resolvedAttempt || null) : null;
const footer = download ? (
<a className="btn btn-small task-log-download" href={download} download>
Download log
</a>
) : null;
if (!entries.length) {
status = "This attempt's log has no entries matching the current filter";
body = (
<div className="empty">
<div className="empty-title">Nothing recorded</div>
<div>This attempt's log file has no entries matching the current filter.</div>
{footer}
</div>
);
} else {
status = `${entries.length} log entr${entries.length === 1 ? "y" : "ies"} shown`;
body = (
<>
<div className="log-list task-log-list">
{entries.map((entry, i) => (
<LogRowNode key={i} entry={entry} />
))}
</div>
{footer}
</>
);
}
}
const entries = state.entries || [];
const download = taskId != null ? taskLogDownloadURL(taskId, state.attempt) : null;
const footer = download ? (
<a className="btn btn-small task-log-download" href={download} download>Download log</a>
) : null;
if (!entries.length) {
return (
<div className="empty">
<div className="empty-title">Nothing recorded</div>
<div>This attempt's log file has no entries matching the current filter.</div>
{footer}
</div>
);
}
return (
<>
<div className="log-list task-log-list">
{entries.map((entry, i) => (
<LogRowNode key={i} entry={entry} />
))}
</div>
{footer}
<FilterBar filters={filters} onFilterChange={onFilterChange} stages={stages} attempt={resolvedAttempt} />
<LogStatus text={status} />
{body}
</>
);
}
+13
View File
@@ -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);
+91 -19
View File
@@ -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 <TaskLogPanel state={state} taskId={taskId} attempt={attempt} onRetry={onRetry} />;
}
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 }) {
</button>
</div>
{logsExpandedForTask && (
<TaskLogPanel state={logCache.get(t.id)} taskId={t.id} onRetry={() => loadTaskLogs(t.id)} />
<TaskLogSection
taskId={t.id}
attempt={t.attempt}
state={logCache.has(logKey) ? logCache.get(logKey) : undefined}
onLoad={() => loadTaskLogs(t.id, t.attempt)}
onRetry={() => loadTaskLogs(t.id, t.attempt, { force: true })}
/>
)}
</div>
</td>
@@ -448,7 +512,15 @@ function TasksApp({ query }) {
{issueLink(t) ?? `#${t.issue_number}`}
</td>
<td className="strong" data-label="Title">
{t.title || "(untitled)"}
<a
className="task-detail-link"
href={`#/tasks/${t.id}`}
title="Open the run detail for this task"
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
{t.title || "(untitled)"}
</a>
</td>
<td data-label="Status">
<Pill text={statusLabel(t.status)} kind={statusKind(t.status)} />
+19 -1
View File
@@ -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 || "" };
}
+25
View File
@@ -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),
+111
View File
@@ -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(<AttemptConfig {...props} />);
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());
+169
View File
@@ -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(<ChangedFiles {...props} />);
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());
+112
View File
@@ -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 = '<div id="app"></div>';
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");
});
});
+57
View File
@@ -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), "/");
});
+229
View File
@@ -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(<StageRail {...props} />);
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());
+466
View File
@@ -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());
+146 -3
View File
@@ -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(<TaskLogPanel state={state} onRetry={opts.onRetry} taskId={opts.taskId} />);
const { container, unmount } = render(
<TaskLogPanel
state={state}
onRetry={opts.onRetry}
taskId={opts.taskId}
attempt={opts.attempt}
filters={opts.filters}
onFilterChange={opts.onFilterChange}
stages={opts.stages}
/>,
);
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());
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff. Show more