fix: close the duplicate-work loop and the dead paths around it
Applies the four-reviewer pass over the forge/dashboard-actions work. The through-line is that several capabilities were wired but inert, and one of them could cost real work. DUPLICATE WORK. "Closes #N" was dropped from PR bodies in favour of LinkBranch, which is sidebar linkage on Gitea and a no-op stub on GitHub -- neither closes anything, and nothing else did either. So a merged task left its issue open, labelled and assigned; the next poll re-enqueued it, and once the dashboard's Clear removed the task row that became a second implementation and a second PR for work already merged. reconcilePRs now closes the issue on merge, and a rejected task closes its issue too. A PR closed without merging deliberately leaves the issue open: that usually means "try again". MAX RETRIES. Configured, defaulted and reported by /api/config, and enforced nowhere -- markDead was unreachable and EffectiveMaxRetries had no callers, so the dashboard's retry incremented retry_count forever. The retry action now retires a task to dead at the cap. DEAD ON ARRIVAL. Tasks() never selected plan or source, so the "Decision required" panel could not render and chat tasks -- whose issue number is synthetic -- linked to forge issues that do not exist. COSMETIC FAILURE, FATAL RESULT. OpenPR failed the whole stage when LinkBranch errored, so the pull request was never opened and the task parked; a retry re-links the same branch, which Gitea answers with a conflict, so every retry parked again. It is best-effort now. INVISIBLE ACTIONS. Approve/retry/reject wrote store rows and nothing else, so the timeline and activity stream never showed that a human had intervened. They emit events now. Also: store write failures answer 500 rather than 409; the dashboard surfaces the server's actual reason instead of "409 Conflict"; action buttons stop propagation (acting on a task no longer also expands it), disable in flight, keep per-task errors instead of one shared string, and confirm before rejecting. Removed: the maybeRetryParked shim and markDead with their now-vacuous tests, WaitingTasks (no consumers; its tests were rewritten to assert the same routing through TaskByID), write-only Daemon.Runtime, and dir/dirs response bloat from /api/skills. skillSource checked workDir before sharedDir, mislabelling every shared skill when the two are equal. DefaultRoots now dedupes roots differing only by a trailing separator. The air build rule claiming to keep ui/dist current never ran -- it required one file to satisfy include_dir and include_file together, and ui/ is excluded from the walk. Deleted with the comment that promised it. task test:ui joins task check and CI; it ran nowhere before, so the dashboard suite could rot silently. Docs corrected where they described behaviour that no longer exists: parks no longer comment on the issue, state labels no longer drive retries, and forgerpc's doc claimed four proxied methods while listing three of five.
This commit is contained in:
1 parent
a751be66b3
commit
170fe0250b
60 files changed
+2081
-768
No files matched your search
@@ -19,8 +19,7 @@ Do not begin with `task check` (mutates via `gofumpt -w .`/`go fix ./...`).
|
||||
Compile, then run:
|
||||
|
||||
```bash
|
||||
env GOTMPDIR=/tmp GOCACHE=/tmp/archie-debug-gocache \
|
||||
GIT_CONFIG_GLOBAL=/dev/null go test ./PATH/TO/PACKAGE -run '^TestName$' -count=1 -v
|
||||
GIT_CONFIG_GLOBAL=/dev/null go test ./PATH/TO/PACKAGE -run '^TestName$' -count=1 -v
|
||||
```
|
||||
|
||||
Classify: compile-only, listener failure, read-only tmp, code regression.
|
||||
@@ -53,10 +52,6 @@ go version
|
||||
go env GOTMPDIR GOCACHE GOPATH GOMODCACHE GOENV
|
||||
```
|
||||
|
||||
This checkout can inherit `GOTMPDIR=/work/tmp`; that path is read-only in some
|
||||
sandboxes. Setting `GOTMPDIR=/tmp` and a task-specific `GOCACHE` is diagnostic
|
||||
isolation.
|
||||
|
||||
Listener-dependent tests include embedded NATS, `httptest.NewServer`, and SMTP
|
||||
listeners:
|
||||
|
||||
@@ -70,13 +65,9 @@ repository-local mitigation. `worktree.Manager.setIdentity` pins
|
||||
`commit.gpgsign=false`. Isolate ambient global config:
|
||||
|
||||
```bash
|
||||
env GOTMPDIR=/tmp GOCACHE=/tmp/archie-worktree-gocache \
|
||||
GIT_CONFIG_GLOBAL=/dev/null go test ./internal/worktree -count=1
|
||||
GIT_CONFIG_GLOBAL=/dev/null go test ./internal/worktree -count=1
|
||||
```
|
||||
|
||||
**Fixed history:** `.gotmp/` once held a workaround for tmpfs quota pressure and
|
||||
was accidentally committed. It is ignored now.
|
||||
|
||||
## Confirm the current known regression
|
||||
|
||||
As of 2026-07-28:
|
||||
@@ -231,4 +222,3 @@ root-identity-bound; `SubprocessRunner` expects stdin JSON protocol.
|
||||
| Skill catalog | Warn, continue without tool |
|
||||
| Worktree augmentation | Log error, use startup registry |
|
||||
| Workspace indexing | **Open:** no production `indexing.NewManager` call |
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
# /api and /events here -- so this watcher deliberately ignores ui/. Watching
|
||||
# it would rebuild the Go binary on every keystroke in a CSS file, and
|
||||
# rebuilding on ui/dist changes would loop against `task ui`.
|
||||
#
|
||||
# ui/dist is NOT rebuilt here. During development the Vite server serves the
|
||||
# frontend directly with HMR, so dist is not what you are looking at; it only
|
||||
# matters for the embedded build, and `task ui` produces it before a commit.
|
||||
# An earlier rule here claimed to keep dist current and never ran: air
|
||||
# requires a file to satisfy include_dir AND include_file together, and ui/ is
|
||||
# excluded from the walk anyway.
|
||||
root = "."
|
||||
tmp_dir = ".air"
|
||||
|
||||
|
||||
+2
-1
@@ -1,4 +1,5 @@
|
||||
export:
|
||||
auto: true
|
||||
no-git-ops: true
|
||||
sync.remote: git+https://git.catlow.cloud/sam/archie-core.git
|
||||
# Remote sync intentionally disabled: Beads memories and issue history may
|
||||
# contain confidential infrastructure or operational details.
|
||||
@@ -253,3 +253,7 @@
|
||||
{"id":"int-0acabfbc83fa1bd117fca76693a7846c","kind":"field_change","created_at":"2026-08-04T12:48:09.945490827Z","actor":"Sam Catlow","issue_id":"archie-core-iyx","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}}
|
||||
{"id":"int-ada12b543691cdbcf87cc50c0ee0f3ff","kind":"field_change","created_at":"2026-08-04T12:48:10.334971684Z","actor":"Sam Catlow","issue_id":"archie-core-8u8.2","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Closed"}}
|
||||
{"id":"int-2f6f4fe49056cd5f69cff38279f533b0","kind":"field_change","created_at":"2026-08-04T13:33:08.314758463Z","actor":"Sam Catlow","issue_id":"archie-core-ky6","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Closed"}}
|
||||
{"id":"int-290db7fb3dcd58215f7aa807c027d4a8","kind":"field_change","created_at":"2026-08-04T15:28:28.018920198Z","actor":"Sam Catlow","issue_id":"archie-core-5oa","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
|
||||
{"id":"int-255bca6bd2735fff9704e54087ad3598","kind":"field_change","created_at":"2026-08-04T15:28:28.194396619Z","actor":"Sam Catlow","issue_id":"archie-core-g4c","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
|
||||
{"id":"int-bc32e8e1d480f244e4d321f6a5614514","kind":"field_change","created_at":"2026-08-04T15:28:28.367302939Z","actor":"Sam Catlow","issue_id":"archie-core-3dn","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
|
||||
{"id":"int-aaac30bcbe470bad73f365ecd86530c2","kind":"field_change","created_at":"2026-08-04T15:28:28.557167416Z","actor":"Sam Catlow","issue_id":"archie-core-hiy","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass."}}
|
||||
+5
-1
@@ -58,6 +58,9 @@
|
||||
{"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"closed","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-28T17:04:41Z","closed_at":"2026-07-28T17:04:41Z","close_reason":"Superseded by merged work: all 32 children complete (32/32, bd flags it 'eligible for close'). MemoryProvider interface, built-in file-backed memory, MemoryManager, scrubber, drain and threat scanning all landed in internal/memory. Nothing left in scope.","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-5oa","title":"Disable automatic forge comments and state labels","description":"Remove automatic plan/progress/retry/dead/state-label noise from normal execution. Preserve internal logs/events and retain only comments explicitly required by an operator decision flow, exposed through messaging or Web UI.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:02Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:08:20Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-5oa","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:12Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-g4c","title":"Link pushed task branch to source issue before opening PR","description":"After the task branch is successfully pushed, call the forge branch-link operation for the source issue, then create the PR without relying on a PR comment or Closes directive to associate it. Propagate link failures and cover Gitea plus forge RPC behavior.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:01Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:08:19Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-g4c","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-hiy","title":"Quiet autonomous execution and correct forge linkage","description":"Reduce Archie forge noise and make issue/branch/PR lifecycle authoritative. Automatic plan/progress/retry/state-label comments must be disabled; human decisions must remain available through messaging and the Web UI; pushed task branches must be linked to their source issues through the forge API before PR creation.","acceptance_criteria":"No automatic plan/progress/retry/state-label comments are emitted; configured human decisions remain actionable through messaging or Web UI; the source issue has a forge branch link after push; PR creation does not rely on a comment or closing directive for linkage; focused tests cover both in-process and RPC forge paths.","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:01Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:29Z","closed_at":"2026-08-04T15:28:29Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-x35","title":"fix(gateway): resolve() orphans a session when it loses the double-check race","description":"CONFIRMED by execution with a blocking store decorator. sessionTracker.resolve calls sessions.Save BEFORE cacheActive, which may then discard the ID in favour of a racing caller's. The write is not rolled back.\n\nInterleaving: goroutine A misses the cache and GetByChannel returns empty; meanwhile /new saves a UUID session and setActives it; A resumes, saves the deterministic session 'chat-y', then cacheActive returns the UUID. Store holds 2 sessions; 'chat-y' is unreachable, shows up in /sessions and /topic listings as '(untitled)', and per the newest-first bug can be silently resurrected on restart.\n\nApplies equally to a racing /resume, /branch or /topic \u003cid\u003e -- the daemon genuinely runs commands on lane goroutines while submitTurn resolves on the bot worker.\n\nNote the synchronization itself is correct: all four accesses to sessionTracker.active are guarded, and stripping the locks produces 12 race-detector reports plus an assertion failure, so the test is load-bearing. This is a logic bug inside the guarded code, not a race.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:31Z","created_by":"Sam Catlow","updated_at":"2026-08-04T12:25:27Z","started_at":"2026-08-04T12:15:33Z","closed_at":"2026-08-04T12:25:27Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-i6q","title":"fix(gateway): redelivery dedups the stored turn but still re-runs the model","description":"archie-core-963 made SaveMessage idempotent, but nothing upstream consults the result. cmd/archied/telegram_setup.go:158 respond() calls SaveMessage (now a no-op on redelivery) then unconditionally loads history, calls the model, and saves the reply -- which carries no SourceID, so it always gets a fresh random ID and always appends.\n\nCONFIRMED at store level on both backends: redelivering tg-1 leaves [ping, pong, pong], plus a second billed model turn with any tool side effects executed twice.\n\nThe bead's stated problem ('a re-delivered Telegram update appends a duplicate turn') is half fixed. SaveMessage returns no already-seen signal for the caller to act on.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:30Z","created_by":"Sam Catlow","updated_at":"2026-08-04T12:25:28Z","started_at":"2026-08-04T12:21:24Z","closed_at":"2026-08-04T12:25:28Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-jex","title":"fix(gateway): /topic off poisons the tracker cache with an empty session ID","description":"CONFIRMED by execution. handleTopic (session_commands.go:200) 'off' does setActive(chan, \"\", getActive(chan, threadID)). With no session cached for (chan, threadID), getActive returns \"\" and that empty string is stored. resolve treats map presence as authoritative ('id, ok := t.active[key]; if ok { return id }'), and cacheActive also returns the empty existing value, so nothing can repair it.\n\nReachable when /topic off is the first message on the webhook (webhook.go:169) or email (email.go:207) channel -- both call router.Route directly and never call ResolveSessionKey first, unlike telegram's submitTurn.\n\nBlast radius: every later message in that chat persists under session ID \"\", history is shared with any other poisoned chat, and the turn-lane key becomes \"\" so /stop in one chat kills a turn in another.\n\nSame line is also non-atomic: setActive(...getActive(...)) is two critical sections, so a concurrent /resume or /branch is silently clobbered.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:18Z","created_by":"Sam Catlow","updated_at":"2026-08-04T12:25:27Z","started_at":"2026-08-04T12:14:00Z","closed_at":"2026-08-04T12:25:27Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
@@ -81,7 +84,7 @@
|
||||
{"_type":"issue","id":"archie-core-u4v","title":"Wire secret engines into provider discovery and execution","description":"Production creates only the env registry, never loads secret-engine plugins, and Provider lacks the documented api_key SecretRef. Implement startup plugin loading, backwards-compatible provider secret references, resolved provider discovery/runtime/container propagation, tests, release, and Carina deployment.","acceptance_criteria":"Provider api_key SecretRefs resolve through loaded engines at startup; existing api_key_env remains compatible; discovered providers, chat runtime, taskrun and containers receive resolved credentials without logging or serializing secret values; production composition tests and task check pass.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-30T17:52:08Z","created_by":"Sam Catlow","updated_at":"2026-07-30T22:48:38Z","started_at":"2026-07-30T17:52:13Z","closed_at":"2026-07-30T22:48:38Z","close_reason":"Live BWS discovery verified and ai-sdk openai-compatible fallback restored; 4+ provider catalog can now surface; full gate and final adversarial review pass","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-6he","title":"Telegram rejects model confirmation when clearing inline keyboard","description":"Selecting a model calls editMessageText with a typed nil reply_markup; Telegram rejects it as object expected, leaving the picker visible. Omit reply_markup when no keyboard is required and cover the request shape.","acceptance_criteria":"Selecting any model replaces the picker with metadata confirmation and the Telegram edit request omits reply_markup when clearing controls.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-30T17:46:25Z","created_by":"Sam Catlow","updated_at":"2026-07-30T17:47:08Z","started_at":"2026-07-30T17:46:29Z","closed_at":"2026-07-30T17:47:08Z","close_reason":"Telegram confirmation edits now omit nil reply_markup; regression test passes","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-v8x","title":"Unify Telegram provider and model selection around SDK catalog","description":"Replace the separate /provider and static configured-model surfaces with one /model provider-to-model wizard. Build the usable provider catalog from the local ai-sdk models.dev catalog plus environment credentials and explicit overrides, cache the filtered tool-capable catalog under the active config directory, and use the same resolved provider/model state across chat and execution paths. Remove the handwritten WellKnown table and remove external-framework references from the Archie tree.","acceptance_criteria":"/model first shows usable providers, then paginated tool-capable models, then atomically switches provider/model and reports model metadata and scope. /provider is absent from executable/menu/help surfaces. Catalog refresh is downloaded at daemon startup and cached beside configuration with safe cached fallback. Environment discovery and explicit overrides flow through chat, identities, subprocess and container/taskrun paths. Focused and composition tests cover discovery, pagination, callbacks and execution parity. A case-insensitive repository scan outside the explicit .references source tree finds no forbidden external-framework name.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-30T17:10:38Z","created_by":"Sam Catlow","updated_at":"2026-07-30T17:39:37Z","started_at":"2026-07-30T17:10:59Z","closed_at":"2026-07-30T17:39:37Z","close_reason":"Implemented SDK-backed provider discovery, unified Telegram model picker, safe catalog caching, and execution composition tests","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ky6","title":"One optional MCP provider failing takes down the whole daemon","description":"internal/tools/provider/provider.go Start() is atomic by design -- 'Any failure rolls the complete family back' -- so a single failing provider unregisters every other provider including the builtins, capabilityHost.Start returns the error, and cmd/archied/main.go:655 exits 1. Under compose restart or systemd Restart=on-failure that is a crash loop. Observed 2026-07-30 on carina: mcp.desktop-commander could not start (missing unzip in the runtime image, fixed in 455fd6f) and archied restarted continuously, losing chat, the gateway and every builtin tool over one third-party npm package.\\n\\nAtomicity is correct for a provider the daemon requires. It is wrong for an external MCP server pulled from a registry at runtime, which is exactly the category that should be allowed to be absent -- the same reasoning applied to the forge in 518a1a0, where a missing credential now disables the capability rather than the daemon.","design":"Needs a required/optional distinction on the registration or manifest, which does not exist today. Keep the all-or-nothing path for required providers; the atomic batch semantics for tool visibility (tools appear only after Start and Discover both succeed) should hold per-provider either way. Relates to the plugin engine rule in ARCHITECTURE.md: failure isolation is explicitly the owning manager's responsibility.","acceptance_criteria":"A provider can be declared optional. An optional provider that fails to start or discover is logged, excluded from the running set, and does not roll back the family or stop the daemon. A required provider keeps today's atomic rollback. Provider health reflects the degraded state so the failure is visible rather than silent. Regression test starts a family containing one failing optional provider and asserts the other providers' tools remain registered and Start returns nil.","notes":"Fixed 2026-08-04 in a8c9483.\n\nRegistry.RegisterOptional marks a provider the daemon can run without; Register is unchanged and keeps atomic rollback. The distinction lives on the registration rather than the manifest: required-vs-optional is a deployment fact, not a property of the code, and keeping it out of plugin.Manifest preserves the metadata-only rule.\n\nAn optional provider failing Start, Discover or index registration is stopped (so a half-started child process is not leaked), excluded from the running set, and recorded in Skipped(). The family carries on. Per-provider atomic tool visibility still holds either way: tools appear only after Start and Discover both succeed.\n\nDependency cascade: a provider whose dependency was skipped cannot run. Optional dependents are skipped with the reason; a required dependent is a hard failure, since it declared it cannot work without something now absent.\n\nVisibility: Health returns degraded naming each excluded provider and its cause, Skipped() exposes the set programmatically, and cmd/archied logs one error line per exclusion after capability host startup.\n\nmain.go now registers every [[tools.mcp_servers]] entry with RegisterOptional, and a registration error warns and continues rather than exiting.\n\nVerified: TestCarinaScenarioThroughCapabilityHost drives the real plugin.Host, the path main.go calls. Registered as required it fails with 'start plugin module \"archie.tools\": start tool provider \"mcp.desktop-commander\": npx exec: unzip: not found' -- verbatim the crash loop. As optional the host starts, read/shell/edit/memory_edit stay registered, and health is degraded carrying the cause.\n\nCLAUDE.md's per-package trap note updated; it documented the old hard-failure behaviour.\n\nNOT DONE, deliberately: there is no per-server required/optional switch in config. Every MCP server is optional. An operator who genuinely depends on one gets a degraded daemon and an error log rather than a refusal to start, which matches the forge and container precedent. Add a config knob only if a real deployment needs it.","status":"open","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-30T06:49:26Z","created_by":"Sam Catlow","updated_at":"2026-08-04T13:33:08Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ky6","title":"One optional MCP provider failing takes down the whole daemon","description":"internal/tools/provider/provider.go Start() is atomic by design -- 'Any failure rolls the complete family back' -- so a single failing provider unregisters every other provider including the builtins, capabilityHost.Start returns the error, and cmd/archied/main.go:655 exits 1. Under compose restart or systemd Restart=on-failure that is a crash loop. Observed 2026-07-30 on carina: mcp.desktop-commander could not start (missing unzip in the runtime image, fixed in 455fd6f) and archied restarted continuously, losing chat, the gateway and every builtin tool over one third-party npm package.\\n\\nAtomicity is correct for a provider the daemon requires. It is wrong for an external MCP server pulled from a registry at runtime, which is exactly the category that should be allowed to be absent -- the same reasoning applied to the forge in 518a1a0, where a missing credential now disables the capability rather than the daemon.","design":"Needs a required/optional distinction on the registration or manifest, which does not exist today. Keep the all-or-nothing path for required providers; the atomic batch semantics for tool visibility (tools appear only after Start and Discover both succeed) should hold per-provider either way. Relates to the plugin engine rule in ARCHITECTURE.md: failure isolation is explicitly the owning manager's responsibility.","acceptance_criteria":"A provider can be declared optional. An optional provider that fails to start or discover is logged, excluded from the running set, and does not roll back the family or stop the daemon. A required provider keeps today's atomic rollback. Provider health reflects the degraded state so the failure is visible rather than silent. Regression test starts a family containing one failing optional provider and asserts the other providers' tools remain registered and Start returns nil.","notes":"Fixed 2026-08-04 in a8c9483.\n\nRegistry.RegisterOptional marks a provider the daemon can run without; Register is unchanged and keeps atomic rollback. The distinction lives on the registration rather than the manifest: required-vs-optional is a deployment fact, not a property of the code, and keeping it out of plugin.Manifest preserves the metadata-only rule.\n\nAn optional provider failing Start, Discover or index registration is stopped (so a half-started child process is not leaked), excluded from the running set, and recorded in Skipped(). The family carries on. Per-provider atomic tool visibility still holds either way: tools appear only after Start and Discover both succeed.\n\nDependency cascade: a provider whose dependency was skipped cannot run. Optional dependents are skipped with the reason; a required dependent is a hard failure, since it declared it cannot work without something now absent.\n\nVisibility: Health returns degraded naming each excluded provider and its cause, Skipped() exposes the set programmatically, and cmd/archied logs one error line per exclusion after capability host startup.\n\nmain.go now registers every [[tools.mcp_servers]] entry with RegisterOptional, and a registration error warns and continues rather than exiting.\n\nVerified: TestCarinaScenarioThroughCapabilityHost drives the real plugin.Host, the path main.go calls. Registered as required it fails with 'start plugin module \"archie.tools\": start tool provider \"mcp.desktop-commander\": npx exec: unzip: not found' -- verbatim the crash loop. As optional the host starts, read/shell/edit/memory_edit stay registered, and health is degraded carrying the cause.\n\nCLAUDE.md's per-package trap note updated; it documented the old hard-failure behaviour.\n\nNOT DONE, deliberately: there is no per-server required/optional switch in config. Every MCP server is optional. An operator who genuinely depends on one gets a degraded daemon and an error log rather than a refusal to start, which matches the forge and container precedent. Add a config knob only if a real deployment needs it.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-30T06:49:26Z","created_by":"Sam Catlow","updated_at":"2026-08-04T13:33:08Z","closed_at":"2026-08-04T13:33:08Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-qa4.5","title":"Phase 5: the 56 lint findings Phase 4 left behind","description":"Discovered as a side effect of the 6d4e0be audit (archie-core-ifi), not as its\ngoal: running golangci-lint over the two packages I had touched showed findings\nin files nobody had flagged, so I ran it repo-wide.\n\nAll four children of archie-core-qa4 are closed and the epic reports \"4/4\ncomplete (100%) -- eligible for close\", but `golangci-lint run ./...` still\nreports 56 issues. The epic must not be closed on that prompt; its own\ndescription says the gate is RED until it closes, so closing it early declares\na green gate that does not exist.\n\nBreakdown: noctx 11, gocognit 11, gocritic 6, errcheck 6, nilerr 4, recvcheck 3,\nnestif 3, godox 3, sloglint 2, predeclared 2, funlen 2, gofumpt 1, cyclop 1,\nstaticcheck 0 (the one hit, configtemplate.go:6, is fixed).\n\nThe gocognit remainder is concentrated in exactly the functions Phase 4 named as\ndeferred -- cmd/archied/main.go run (106, the description predicted \"108-\u003e30\nremaining\" and it did not land), internal/workflow AgentStage.Stage (68),\nFeasibility and TDD (funlen), cmd/archie-agent startMCPProviders (45) -- plus\nthe whole of internal/tools/builtin: grepFallback 58, runFindGoFallback 57,\nmakeReadExecutor 56, makeGrepExecutor 41, makeShellExecutor 40, makeWriteExecutor\n38, suggestPaths 36. tomlwrite.Apply (82) is new, uncommitted-until-7fab597 code.\n\nREAD archie-core-qa4's notes before starting. Both known behaviour regressions\nfrom this epic came out of structural extraction, and every remaining gocognit\nsite is a structural extraction waiting to happen. The nilerr findings in\ngrep.go are not noise either -- see archie-core-ts9, where the same swallow in\nfind.go is a live false-negative bug. Fixing nilerr by \"returning the error\"\nwithout deciding what the caller does with it will change tool behaviour.","acceptance_criteria":"golangci-lint run ./... reports 0 issues, or every remaining finding has an explicit nolint with a reason. Each structural extraction lands with a behavioural test for the function it splits, per the discipline recorded in archie-core-qa4's notes.","status":"open","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:26:57Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:57Z","dependencies":[{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-qa4","type":"parent-child","created_at":"2026-07-30T02:26:57Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-ts9","type":"blocks","created_at":"2026-07-30T02:27:02Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-qa4.5","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:26:57Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-0d6","title":"[BUG] /model \u003cname\u003e asked the router for a doubled model name","description":"The nestif extraction in 651de0a pulled --provider parsing out of parseModelRest into extractProviderFlag, which took the modelParts slice by pointer and appended every non-provider field to it. The caller's own loop then appended the same fields again, so every field of the model name was duplicated: '/model gpt-5.6' resolved to 'gpt-5.6 gpt-5.6' and SetActiveModel rejected it as an unknown model. '/model gpt-5.6 --provider openai' was worse -- the space-separated provider value was no longer consumed with its flag, giving 'gpt-5.6 gpt-5.6 openai'. Direct model switching over Telegram was broken for anything but a bare --refresh or a provider-only switch. Found while auditing 6d4e0be for archie-core-ifi: the naked return in the same function could not be regression-tested until the function produced correct values.","design":"Two ways to fix the double append were available. Rejected: keep the helper\nsignature and delete the caller's default-branch append. That restores correct\noutput but leaves the shape intact -- a helper holding a pointer to the\ncaller's accumulator, with two loops over the same fields -- so the next person\nwho adds a field type has the same trap waiting. It also does not fix the\nspace-separated provider value, because the helper returns early on the first\n--provider and never sees the fields after it.\n\nChosen: splitProviderFlag returns (provider, remaining) and is the sole\naccumulator. One loop owns the fields, and there is no shared slice to append\nto twice. The index loop is kept deliberately -- i++ after reading a\nspace-separated value is what removes it with its flag, and converting that to\na range loop is precisely what 651de0a did wrong.\n\nLast --provider wins if repeated, matching the pre-651de0a behaviour rather\nthan the buggy helper's first-wins. Not worth a flag: /model does not document\nrepeating it.","acceptance_criteria":"parseModelRest returns the model name exactly once for bare names, scope flags, and both --provider spellings, with a regression test asserting field count rather than string equality.","notes":"Fixed by making splitProviderFlag the sole accumulator of surviving fields and returning them, so the shared-slice shape that allowed the double append is structurally impossible. Tests: TestParseModelRestDoesNotDoubleTheModelName, TestParseModelRestReturnsDeclaredValuesInOrder.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-29T16:18:46Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:26:09Z","closed_at":"2026-07-29T16:19:23Z","dependencies":[{"issue_id":"archie-core-0d6","depends_on_id":"archie-core-ifi","type":"discovered-from","created_at":"2026-07-30T02:18:46Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-ewk.1","title":"Export configuration.Validate for archied setup to call","description":"The ewk epic's acceptance criteria (and archie-core-cbk's, by inheritance) require: \"Every config it writes passes configuration.Validate, verified by a test that runs setup non-interactively and validates the output.\" That identifier does not exist. internal/infrastructure/configuration/validate.go defines only an unexported validate(cfg *config.Config) error, called from one place: loader.go:178 inside Loader.Load's own decode-then-validate sequence. There is no way for code outside the configuration package -- e.g. `archied setup` after it builds a config.Config in memory but before writing it to disk -- to run the same validation.\n\nDiscovered while implementing archie-core-rs9 (TOML write strategy). Not fixed there: rs9's scope was the text-patching mechanism, not wiring setup's actual validation step, and exporting validate() is really part of cbk's job (the thing that needs to call it).","acceptance_criteria":"configuration package exposes a callable that runs the same checks as the current unexported validate() against a config.Config value in memory (either export validate itself, or add a thin Validate(cfg *config.Config) error wrapper -- whichever fits the package's existing exported-surface conventions). Loader.Load continues to use it internally with no behavior change. A test outside the package (e.g. in cbk's setup tests) can call it directly without going through file I/O.","status":"open","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-29T16:18:36Z","created_by":"Sam Catlow","updated_at":"2026-07-29T16:18:36Z","dependencies":[{"issue_id":"archie-core-ewk.1","depends_on_id":"archie-core-ewk","type":"parent-child","created_at":"2026-07-30T02:18:36Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":1,"comment_count":0}
|
||||
@@ -198,6 +201,7 @@
|
||||
{"_type":"issue","id":"archie-core-s1r","title":"Test forge fakes missing LinkBranch method broke go vet/test for whole module","description":"forge.Forge gained LinkBranch(ctx, owner, repo, issueNumber, branch) error in the branch-linking feature (ff4c51e) but the hand-rolled test doubles (stubForge in cmd/archied/main_test.go, prCapturingForge in cmd/archie-agent/taskrun_test.go, testForge in internal/daemon/daemon_test.go, fakeForge in internal/forgerpc/forgerpc_test.go) never got the method added, so they stopped satisfying forge.Forge. This broke go vet ./... and go test ./... for the entire module, not just those 4 packages, since go vet type-checks all test files as part of module vet. Fixed by adding LinkBranch stubs to all four fakes.","status":"closed","priority":1,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:04:53Z","created_by":"Sam Catlow","updated_at":"2026-07-24T03:04:58Z","closed_at":"2026-07-24T03:04:58Z","close_reason":"Added LinkBranch stub methods to stubForge, prCapturingForge, testForge, and fakeForge. go build/vet/test ./... now clean across the whole module.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-633","title":"config.docker.toml missing required fields, no overlay merge implemented","description":"config.docker.toml was rewritten to be a docs-as-overlay file (comment says base+overlay merge) but internal/config.Load has no merge logic and docker-compose.yml mounts only config.docker.toml at /etc/archie/config.toml. It is missing bot_user, [forge], [dispatch], [models], [providers], [budgets] which Load requires -\u003e daemon fails to start in docker as currently configured. Implement real base+overlay config loading (or restore a full standalone docker config) so there is one source of truth.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-24T02:42:07Z","created_by":"Sam Catlow","updated_at":"2026-07-24T02:44:53Z","started_at":"2026-07-24T02:42:11Z","closed_at":"2026-07-24T02:44:53Z","close_reason":"Implemented config.LoadOverlay (base decode + overlay decode into same struct, then shared finalize/validate), wired -config-overlay flag in cmd/archied, fixed docker-compose.yml to mount both base config.toml and config.docker.toml overlay, minimized config.docker.toml to true diff-only overlay, added tests proving overlay-omitted required fields (bot_user, repos) still come from base.","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-u64","title":"Daemon: process multiple tasks concurrently (max_concurrency enforcement)","description":"Daemon currently processes one task at a time (docs/prds/archie-core-v2-architecture.md Phase 2). This is the core blocker between current state and any multi-agent scaling mode — needed before container max_concurrency or same-repo concurrency can matter. Wire the daemon's dispatch loop to run N tasks in parallel, respecting a configurable max_concurrency.","design":"internal/container/pool.go already enforces max_concurrency for container lifecycle — reuse that limit/pattern in the daemon's task dispatch rather than inventing a second concurrency control.","acceptance_criteria":"Daemon dispatch loop runs multiple tasks concurrently up to a configured max_concurrency limit; single-task-at-a-time behavior is gone.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-23T19:36:31Z","created_by":"Sam Catlow","updated_at":"2026-07-23T21:37:42Z","started_at":"2026-07-23T21:29:41Z","closed_at":"2026-07-23T21:37:42Z","close_reason":"Implemented concurrent SQLite and NATS task dispatch using containers.max_concurrency, with default same-repo serialization and race-tested dispatcher coverage.","dependency_count":0,"dependent_count":2,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3dn","title":"Expose quiet execution and decision controls in messaging and Web UI","description":"Make the no-comment/no-label behavior and human approval or retry decisions controllable through existing messaging channels and the Web UI. Do not reintroduce issue comments as the control plane; show the same persisted task state and actions in both surfaces.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-04T15:08:02Z","created_by":"Sam Catlow","updated_at":"2026-08-04T15:28:28Z","started_at":"2026-08-04T15:28:27Z","closed_at":"2026-08-04T15:28:28Z","close_reason":"Implemented quiet forge lifecycle, removed automatic state-label/comment noise, added Web UI approval/retry/reject actions, and linked pushed branches to source issues before PR creation. Full task check and UI tests pass.","dependencies":[{"issue_id":"archie-core-3dn","depends_on_id":"archie-core-hiy","type":"parent-child","created_at":"2026-08-05T01:08:13Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.8","title":"Make activity and task context navigable","description":"The dashboard's live activity entries are not clickable, task detail does not provide a source-task/forge link, and the Tasks KPI strip sits directly against the table. Make activity events navigate to the relevant dashboard area, expose a clear source task action that opens the task's forge page when available, and restore visual separation between KPI cards and the task table. Add focused UI/runtime tests.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:25:09Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:27:58Z","started_at":"2026-08-03T16:25:10Z","closed_at":"2026-08-03T16:27:58Z","close_reason":"Implemented activity-to-task navigation, task source links using configured forge host, and Tasks KPI/table spacing. UI tests, build, and diff checks pass.","dependencies":[{"issue_id":"archie-core-3cf.8","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T02:25:09Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-3cf.7","title":"Discover user-installed global skills alongside project skills","description":"The Web UI currently scans only the daemon work directory, so skills installed under the user's global ~/.agents/skills are invisible. Add global-skill discovery alongside project skills, preserve deterministic precedence for duplicate names, expose source/path in the API/UI, and keep workflow activation using the same merged catalogue. Add tests for configured and default roots.","status":"closed","priority":2,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-03T16:13:45Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:17:41Z","started_at":"2026-08-03T16:14:04Z","closed_at":"2026-08-03T16:17:41Z","close_reason":"Implemented layered project/shared/user-global skill discovery, deterministic precedence, global activation support, UI messaging, and tests.","dependencies":[{"issue_id":"archie-core-3cf.7","depends_on_id":"archie-core-3cf","type":"parent-child","created_at":"2026-08-04T02:13:45Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
{"_type":"issue","id":"archie-core-7ve","title":"test(gateway): the conformance suite does not pin what it claims, and the backends already drift","description":"The commit message for 3eb00db claims the shared suite means NellDB and SQLite 'cannot drift'. Two confirmed divergences it does not catch:\n\n1. testReplaceMessagesIsFailureSafe (sessionstore_conformance_test.go:769) never induces a failure -- four happy-path cases asserting the post-condition of a SUCCESSFUL call. Swapping the write and delete loops in session_store.go:696-708 would leave it green. Only SQLite has a real abort test, and it pins rollback, the opposite failure mode. The backends genuinely differ here: SQLite is atomic (failure -\u003e clean rollback), NellDB is not (failure -\u003e duplicates). SQLite's semantics are better; the point is the suite does not know.\n\n2. NellDB's lastTS cache is never invalidated by deletes; SQLite recomputes MAX(ts). Save at 13:00, delete it, save with At=12:00 -\u003e NellDB persists 13:00:00.001Z, SQLite persists 12:00:00Z. Both pass the suite.\n\n3. GetByChannel ordering differs between backends and is unpinned (see the newest-first bead).\n\n4. applyCompress has zero test coverage: no test in the package calls it, none of its three error returns is exercised, and fakeSessionStore.ReplaceMessages is a slice assignment that cannot observe ordering or identity.","status":"open","priority":2,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-08-03T16:01:53Z","created_by":"Sam Catlow","updated_at":"2026-08-03T16:01:53Z","dependency_count":0,"dependent_count":0,"comment_count":0}
|
||||
|
||||
@@ -23,6 +23,11 @@ jobs:
|
||||
with:
|
||||
go-version: "1.26"
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Quality gate
|
||||
run: |
|
||||
gofumpt -w .
|
||||
@@ -31,6 +36,13 @@ jobs:
|
||||
go build ./...
|
||||
go test ./... -count=1
|
||||
|
||||
# The dashboard suite runs in CI too, or it only ever runs when
|
||||
# someone remembers to; the Go steps above never touch it.
|
||||
- name: Dashboard tests
|
||||
run: |
|
||||
npm ci --prefix ui || npm install --prefix ui
|
||||
npm test --prefix ui
|
||||
|
||||
- name: Release tags must match changelogs
|
||||
run: |
|
||||
set -e
|
||||
|
||||
@@ -27,6 +27,8 @@ node_modules/
|
||||
.codex/
|
||||
.pi-subagents/
|
||||
.playwright-mcp/
|
||||
# Design reference screenshots, kept locally rather than in the repo.
|
||||
opspulse.jpeg
|
||||
|
||||
# Frontend
|
||||
/ui/node_modules/
|
||||
|
||||
+3
-1
@@ -147,7 +147,9 @@ A thin abstraction over GitHub (Gitea planned):
|
||||
| `VerifyPush` | Confirm push permission at startup |
|
||||
|
||||
State labels (`archie:queued`, `archie:working`, etc.) are created on demand,
|
||||
removed when transitioning.
|
||||
removed when transitioning. They report state; they do not drive it. Removing
|
||||
a label no longer retries a parked task -- retries are an explicit operator
|
||||
action from the dashboard or chat, capped by `max_retries`.
|
||||
|
||||
## Worktree Manager
|
||||
|
||||
|
||||
@@ -166,7 +166,10 @@ boundaries. Summary of what's evolved since that doc was last fully accurate:
|
||||
**Task lifecycle** (from ARCHITECTURE.md, still current):
|
||||
`queued → running(workflow:stage) → pr_open → merged|rejected`, with
|
||||
`waiting_human` and `parked` side states. Crash recovery re-queues anything left
|
||||
`running`; parks always post a comment with the reason — never fail silently.
|
||||
`running`. A park records its reason on the task, which the dashboard and
|
||||
`/api/tasks` surface; it no longer comments on the forge issue. Retries are an
|
||||
explicit operator action (dashboard or chat), capped by `max_retries`, not a
|
||||
label a human removes.
|
||||
|
||||
**Config** is daemon-level TOML (see `config.example.toml`), not per-repo files
|
||||
in this repo. Two live instances run on a separate host (`carina`), each with a
|
||||
|
||||
+29
-1
@@ -32,6 +32,12 @@ tasks:
|
||||
- npm install --no-audit --no-fund
|
||||
- npm run build
|
||||
|
||||
test:ui:
|
||||
desc: Run the dashboard's node tests (DOM-building primitives)
|
||||
dir: ui
|
||||
cmds:
|
||||
- npm test
|
||||
|
||||
dev:
|
||||
desc: "Develop: archied live-reload + Vite HMR together. Open http://localhost:5173"
|
||||
summary: |
|
||||
@@ -59,6 +65,25 @@ tasks:
|
||||
- npm install --no-audit --no-fund
|
||||
- npm run dev
|
||||
|
||||
dev:mobile:
|
||||
desc: Serve the dashboard on your LAN (token-protected) for phone viewing
|
||||
summary: |
|
||||
Starts archied with the [web] bind on 0.0.0.0 so the dashboard is
|
||||
reachable from your phone, printing the URL (LAN IP + token) and a QR
|
||||
code to scan. Stop `task dev` first: both use port 8484, and two daemons
|
||||
sharing the bot identity would double-poll the forge. Frontend served is
|
||||
the embedded dist, so run `task ui` if you changed the frontend.
|
||||
deps:
|
||||
- ui
|
||||
cmds:
|
||||
- cmd: |
|
||||
IP=$(hostname -I | awk '{print $1}')
|
||||
TOKEN=$(cat "${XDG_DATA_HOME:-$HOME/.local/share}/archie/web-token" 2>/dev/null)
|
||||
URL="http://$IP:8484/?t=$TOKEN"
|
||||
echo "Phone URL: $URL"
|
||||
echo "$URL" | qrencode -t ANSIUTF8
|
||||
- go run ./cmd/archied -config-overlay ~/.config/archie/mobile.toml
|
||||
|
||||
build:
|
||||
desc: Build archied and archie-agent binaries
|
||||
sources:
|
||||
@@ -78,13 +103,16 @@ tasks:
|
||||
- go test ./... -count=1
|
||||
|
||||
check:
|
||||
desc: "Full quality gate: fmt, go fix, vet, build, test (matches [[repos.gate]] in config.toml)"
|
||||
desc: "Full quality gate: fmt, go fix, vet, build, test, ui tests (matches [[repos.gate]] in config.toml)"
|
||||
cmds:
|
||||
- task: fmt
|
||||
- go fix ./...
|
||||
- task: vet
|
||||
- task: build
|
||||
- task: test
|
||||
# The dashboard's suite runs here too. Left out of the gate it rots
|
||||
# silently: nothing else executes it, so a broken DOM primitive ships.
|
||||
- task: test:ui
|
||||
|
||||
release:preview:
|
||||
desc: "Show the release notes that would be generated (VERSION=1.2.0, or GATEWAY=/RUNTIME= to version the two components separately)"
|
||||
|
||||
@@ -94,7 +94,7 @@ func (f *prCapturingForge) VerifyPush(context.Context, string, string) error {
|
||||
}
|
||||
|
||||
func (f *prCapturingForge) LinkBranch(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
return nil
|
||||
}
|
||||
|
||||
// newLocalRemote mirrors worktree_test.go's helper: a bare repo with one
|
||||
|
||||
+6
-3
@@ -294,7 +294,11 @@ func run() int {
|
||||
// row id) and then fanned out to live dashboard connections.
|
||||
bus := events.NewBus()
|
||||
defer bus.Close()
|
||||
web := &webui.Server{Store: st, Log: log, Cfg: &cfg}
|
||||
web := &webui.Server{Store: st, Log: log, Cfg: &cfg, Events: bus}
|
||||
// The dashboard closes the forge issue behind a rejected task, or the
|
||||
// issue is re-polled and the work is done again. It gets only that one
|
||||
// method, not the forge client.
|
||||
web.Issues = forgeClient
|
||||
sink := bus.Subscribe(256)
|
||||
go func() {
|
||||
for e := range sink.C {
|
||||
@@ -649,7 +653,7 @@ func run() int {
|
||||
// Skill catalog → skill_activate tool (progressive disclosure: the
|
||||
// catalog's name+description is always in the tool schema; the full
|
||||
// SKILL.md body loads only when the model activates one).
|
||||
if catalog, err := skill.Catalog(cfg.WorkDir); err != nil {
|
||||
if catalog, err := skill.CatalogRoots(skill.DefaultRoots(cfg.WorkDir, cfg.SkillsDir)...); err != nil {
|
||||
log.Warn("skill catalog load failed", "err", err)
|
||||
} else if entry := skill.ActivateTool(cfg.WorkDir, catalog); entry != nil {
|
||||
if err := toolReg.Register(*entry); err != nil {
|
||||
@@ -668,7 +672,6 @@ func run() int {
|
||||
Bus: bus,
|
||||
Forge: forgeClient,
|
||||
Trees: trees,
|
||||
Runtime: llm,
|
||||
Agent: agentRunner,
|
||||
Workflows: registry,
|
||||
CapabilityHost: capabilityHost,
|
||||
|
||||
@@ -524,6 +524,7 @@ func (stubForge) CreatePR(context.Context, string, string, string, string, strin
|
||||
return 1, nil
|
||||
}
|
||||
func (stubForge) SetStateLabel(context.Context, string, string, int, string, []string) {}
|
||||
func (stubForge) LinkBranch(context.Context, string, string, int, string) error { return nil }
|
||||
func (stubForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
func (stubForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
@@ -546,10 +547,6 @@ func (stubForge) CreateIssue(context.Context, string, string, string, string, []
|
||||
}
|
||||
func (stubForge) React(context.Context, string, string, int, string) error { panic("unexpected call") }
|
||||
func (stubForge) VerifyPush(context.Context, string, string) error { panic("unexpected call") }
|
||||
func (stubForge) LinkBranch(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func startEmbeddedNATS(t *testing.T) *server.Server {
|
||||
t.Helper()
|
||||
srv := natssrv.RunRandClientPortServer()
|
||||
|
||||
+4
-2
@@ -12,7 +12,9 @@ poll_interval = "60s"
|
||||
label = "archie"
|
||||
bot_user = "vectis-labs-archie"
|
||||
diff_cap_lines = 400
|
||||
# max_retries = 3 # how many times a parked task is retried before permanent park (global default; set per-repo to override)
|
||||
# max_retries = 3 # how many operator-triggered retries a parked task gets
|
||||
# before it moves to dead (global default; set per-repo to
|
||||
# override). Enforced by the dashboard's retry action.
|
||||
|
||||
[forge]
|
||||
type = "github"
|
||||
@@ -29,7 +31,7 @@ working = "archie:working"
|
||||
waiting = "archie:waiting"
|
||||
pr = "archie:pr"
|
||||
parked = "archie:parked"
|
||||
# dead = "archie:dead" # applied when a task exhausts max_retries
|
||||
# dead = "archie:dead" # state label for a task that exhausted max_retries
|
||||
|
||||
[models] # role -> ai-sdk runtime ref (used by agent workflows, Phase 4b)
|
||||
triage = "openai/gpt-5.4"
|
||||
|
||||
+24
-196
@@ -10,14 +10,10 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/ai-sdk/core"
|
||||
"github.com/samcharles93/ai-sdk/runtime"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
@@ -53,7 +49,6 @@ type Daemon struct {
|
||||
Store store.TaskStore
|
||||
Forge forge.Forge
|
||||
Trees *worktree.Manager
|
||||
Runtime *runtime.Runtime
|
||||
Agent agentexec.Runner
|
||||
Bus *events.Bus
|
||||
Workflows workflow.Registry
|
||||
@@ -318,7 +313,6 @@ func (d *Daemon) Cycle(ctx context.Context) {
|
||||
d.cleanupExpiredStorage(ctx)
|
||||
d.poll(ctx)
|
||||
d.reconcilePRs(ctx)
|
||||
d.checkWaiting(ctx)
|
||||
if d.Tasks != nil {
|
||||
d.drainNATS(ctx)
|
||||
} else {
|
||||
@@ -509,19 +503,19 @@ func (d *Daemon) pollSQLite(ctx context.Context, fg forge.Forge, repo config.Rep
|
||||
d.acknowledge(ctx, fg, repo, is)
|
||||
return
|
||||
}
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
// Existing tasks are left untouched. Retry and approval are explicit
|
||||
// operator actions in messaging or the Web UI, not forge-side label edits.
|
||||
}
|
||||
|
||||
// pollNATS publishes discovered issues to NATS (new flow).
|
||||
func (d *Daemon) pollNATS(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue, labels, identity string) {
|
||||
// Read-only existence check -- needed for maybeRetryParked.
|
||||
// Read-only existence check prevents rediscovering an existing task.
|
||||
existing, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
|
||||
if err != nil {
|
||||
d.Log.Error("task lookup failed", "repo", repo.FullName(), "issue", is.Number, "err", err)
|
||||
return
|
||||
}
|
||||
if existing != nil {
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
return
|
||||
}
|
||||
// Classify and encode here: the envelope, its routing kind and its
|
||||
@@ -558,7 +552,7 @@ func (d *Daemon) publishTask(ctx context.Context, task workintake.TaskEnvelope)
|
||||
return d.Tasks.PublishUnique(ctx, task.Subject(), task.IdempotencyKey(), payload)
|
||||
}
|
||||
|
||||
// acknowledge posts the pickup reaction, state label, and queued event
|
||||
// acknowledge posts the pickup reaction and queued event
|
||||
// using fg -- the forge client that owns repo (identity-scoped or root).
|
||||
func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, repo config.Repo, is forge.Issue) {
|
||||
d.Log.Info("issue queued", "repo", repo.FullName(), "issue", is.Number, "title", is.Title)
|
||||
@@ -567,7 +561,6 @@ func (d *Daemon) acknowledge(ctx context.Context, fg forge.Forge, repo config.Re
|
||||
d.Log.Warn("ack reaction failed", "issue", is.Number, "err", err)
|
||||
}
|
||||
}
|
||||
fg.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindTaskQueued, Repo: repo.FullName(),
|
||||
Issue: is.Number, Detail: is.Title,
|
||||
@@ -678,74 +671,20 @@ func (d *Daemon) pollEither(ctx context.Context, repo config.Repo) []forge.Issue
|
||||
return out
|
||||
}
|
||||
|
||||
// maybeRetryParked requeues a parked task whose state label a human has
|
||||
// removed -- the forge-native retry trigger. When retry_count reaches the
|
||||
// configured max_retries the task moves to dead instead of requeuing.
|
||||
// The forge client is resolved from the task's own Identity via forgeFor
|
||||
// (not passed in) since that's authoritative for which forge client owns it.
|
||||
func (d *Daemon) maybeRetryParked(ctx context.Context, repo config.Repo, is forge.Issue) {
|
||||
if hasLabel(is.Labels, d.Cfg.Dispatch.StateLabel("parked")) {
|
||||
// closeResolvedIssue closes the forge issue behind a finished task.
|
||||
//
|
||||
// A chat task's issue number is synthetic and matches no forge issue, so it
|
||||
// is skipped. Failure is logged rather than returned: the task's own state is
|
||||
// already correct, and the next reconcile pass will not retry, so a warning
|
||||
// is the honest outcome -- the issue simply stays open.
|
||||
func (d *Daemon) closeResolvedIssue(ctx context.Context, fg forge.Forge, task *store.Task, comment string) {
|
||||
if !task.IsForgeBacked() {
|
||||
return
|
||||
}
|
||||
task, err := d.Store.TaskByIssue(ctx, repo.Owner, repo.Name, is.Number)
|
||||
if err != nil || task == nil || task.Status != store.StatusParked {
|
||||
return
|
||||
if err := fg.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
|
||||
d.Log.Warn("closing resolved issue failed; it stays open and will be re-polled",
|
||||
"repo", task.Owner+"/"+task.Repo, "issue", task.IssueNumber, "err", err)
|
||||
}
|
||||
fg := d.forgeFor(task)
|
||||
|
||||
maxRetries := repo.EffectiveMaxRetries(d.Cfg.MaxRetries)
|
||||
|
||||
if task.RetryCount >= maxRetries {
|
||||
d.markDead(ctx, repo, task, maxRetries)
|
||||
return
|
||||
}
|
||||
|
||||
if err := d.Store.Requeue(ctx, task.ID, store.StatusParked, ""); err != nil {
|
||||
d.Log.Error("label-triggered requeue failed", "issue", is.Number, "err", err)
|
||||
return
|
||||
}
|
||||
if err := d.Store.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
d.Log.Error("increment retry_count failed", "issue", is.Number, "err", err)
|
||||
}
|
||||
d.Log.Info("parked task requeued via label removal", "repo", repo.FullName(), "issue", is.Number, "retry_count", task.RetryCount+1, "max_retries", maxRetries)
|
||||
fg.SetStateLabel(ctx, repo.Owner, repo.Name, is.Number, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: "task_retried", TaskID: task.ID,
|
||||
Repo: repo.FullName(), Issue: is.Number, Detail: "parked label removed",
|
||||
})
|
||||
}
|
||||
|
||||
// markDead permanently parks a task that has exhausted its max_retries.
|
||||
func (d *Daemon) markDead(ctx context.Context, repo config.Repo, task *store.Task, maxRetries int) {
|
||||
fg := d.forgeFor(task)
|
||||
reason := fmt.Sprintf("max retries reached (%d/%d) -- task parked permanently", task.RetryCount, maxRetries)
|
||||
if err := d.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
|
||||
d.Log.Error("transition to dead failed", "task", task.ID, "err", err)
|
||||
return
|
||||
}
|
||||
if task.IsForgeBacked() {
|
||||
fg.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber,
|
||||
d.Cfg.Dispatch.StateLabel("dead"), d.Cfg.Dispatch.LabelValues())
|
||||
}
|
||||
d.Log.Warn("task permanently parked after max retries",
|
||||
"issue", task.IssueNumber, "retry_count", task.RetryCount, "max_retries", maxRetries)
|
||||
if task.IsForgeBacked() {
|
||||
body := fmt.Sprintf("**Max retries reached (%d/%d) -- task parked permanently.**\n\n"+
|
||||
"The task failed %d times and has been moved to `dead` status. "+
|
||||
"Manual intervention is required to recover this task.",
|
||||
task.RetryCount, maxRetries, task.RetryCount)
|
||||
if _, err := fg.Comment(ctx, task.Owner, task.Repo, task.IssueNumber, body); err != nil {
|
||||
d.Log.Error("failed to post dead comment", "issue", task.IssueNumber, "err", err)
|
||||
}
|
||||
}
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindTaskDead, TaskID: task.ID,
|
||||
Repo: repo.FullName(), Issue: task.IssueNumber, Detail: reason,
|
||||
})
|
||||
}
|
||||
|
||||
func hasLabel(labels []string, want string) bool {
|
||||
return slices.Contains(labels, want)
|
||||
}
|
||||
|
||||
// reconcilePRs moves pr_open tasks to merged/rejected from GitHub state
|
||||
@@ -772,9 +711,15 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
case "merged":
|
||||
_ = d.Store.Transition(ctx, t.ID, store.StatusPROpen, store.StatusMerged, "")
|
||||
_ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber)
|
||||
if t.IsForgeBacked() {
|
||||
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
|
||||
}
|
||||
// Close the issue ourselves rather than relying on the forge
|
||||
// noticing a "Closes #N" in the PR body. Nothing else closes it:
|
||||
// LinkBranch is sidebar linkage on Gitea and a no-op on GitHub.
|
||||
// Left open the issue stays labelled and assigned, the next poll
|
||||
// re-enqueues it, and once the dashboard's Clear removes the task
|
||||
// row that is a second implementation and a second PR for work
|
||||
// already merged.
|
||||
d.closeResolvedIssue(ctx, fg, &t, fmt.Sprintf(
|
||||
"Closed by #%d, merged by archie.", t.PRNumber))
|
||||
d.Log.Info("PR merged", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindPRMerged, TaskID: t.ID,
|
||||
@@ -784,9 +729,6 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
case "closed":
|
||||
_ = d.Store.Transition(ctx, t.ID, store.StatusPROpen, store.StatusRejected, "PR closed without merge")
|
||||
_ = trees.Cleanup(t.Owner, t.Repo, t.IssueNumber)
|
||||
if t.IsForgeBacked() {
|
||||
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
|
||||
}
|
||||
d.Log.Info("PR rejected", "repo", t.Owner+"/"+t.Repo, "pr", t.PRNumber)
|
||||
d.emit(events.Event{
|
||||
Kind: events.KindPRRejected, TaskID: t.ID,
|
||||
@@ -797,113 +739,6 @@ func (d *Daemon) reconcilePRs(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// checkWaiting looks for human replies on waiting_human tasks and asks
|
||||
// an LLM -- not keyword matching -- whether the reply is a go-ahead.
|
||||
// Approved tasks requeue under the implement workflow; rejections close
|
||||
// the issue with the human's reasoning acknowledged.
|
||||
func (d *Daemon) checkWaiting(ctx context.Context) {
|
||||
tasks, err := d.Store.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
d.Log.Error("waiting query failed", "err", err)
|
||||
return
|
||||
}
|
||||
for _, t := range tasks {
|
||||
if !t.IsForgeBacked() {
|
||||
// Chat-sourced waiting_human tasks resolve via /approve and
|
||||
// /cancel, not forge issue replies -- there is no issue
|
||||
// to poll.
|
||||
continue
|
||||
}
|
||||
fg := d.forgeFor(&t)
|
||||
replies, err := fg.RepliesAfter(ctx, t.Owner, t.Repo, t.IssueNumber, t.WatchCommentID, d.Cfg.BotUser)
|
||||
if err != nil {
|
||||
d.Log.Warn("reply check failed", "issue", t.IssueNumber, "err", err)
|
||||
continue
|
||||
}
|
||||
if len(replies) == 0 {
|
||||
continue
|
||||
}
|
||||
var sb strings.Builder
|
||||
for _, r := range replies {
|
||||
fmt.Fprintf(&sb, "%s: %s\n", r.User, r.Body)
|
||||
}
|
||||
verdict, reason, err := d.judgeReply(ctx, t.Plan, sb.String())
|
||||
if err != nil {
|
||||
d.Log.Error("reply judge failed", "issue", t.IssueNumber, "err", err)
|
||||
continue
|
||||
}
|
||||
d.Log.Info("human reply judged", "issue", t.IssueNumber, "verdict", verdict)
|
||||
switch verdict {
|
||||
case "approve":
|
||||
if err := d.Store.Requeue(ctx, t.ID, store.StatusWaitingHuman, "implement"); err != nil {
|
||||
d.Log.Error("requeue failed", "issue", t.IssueNumber, "err", err)
|
||||
continue
|
||||
}
|
||||
_, _ = fg.Comment(ctx, t.Owner, t.Repo, t.IssueNumber,
|
||||
"**Go-ahead received -- implementation is queued.** ("+reason+")")
|
||||
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, d.Cfg.Dispatch.StateLabel("queued"), d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: "human_approved", TaskID: t.ID,
|
||||
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Detail: reason,
|
||||
})
|
||||
case "reject":
|
||||
_ = d.Store.Transition(ctx, t.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, reason)
|
||||
_ = fg.CloseIssue(ctx, t.Owner, t.Repo, t.IssueNumber,
|
||||
"**Understood -- closing without implementation.** ("+reason+")")
|
||||
fg.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, "", d.Cfg.Dispatch.LabelValues())
|
||||
d.emit(events.Event{
|
||||
Kind: "human_rejected", TaskID: t.ID,
|
||||
Repo: t.Owner + "/" + t.Repo, Issue: t.IssueNumber, Detail: reason,
|
||||
})
|
||||
default:
|
||||
// Unclear: keep waiting; the humans can be more explicit.
|
||||
d.Log.Info("reply unclear -- still waiting", "issue", t.IssueNumber, "reason", reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// judgeReply classifies the human's response to a PRD as approve,
|
||||
// reject, or unclear.
|
||||
func (d *Daemon) judgeReply(ctx context.Context, prd, replies string) (verdict, reason string, err error) {
|
||||
if d.Runtime == nil {
|
||||
return "", "", fmt.Errorf("no LLM runtime configured")
|
||||
}
|
||||
model := d.Cfg.Models["triage"]
|
||||
if model == "" {
|
||||
model = d.Cfg.Models["planner"]
|
||||
}
|
||||
if model == "" {
|
||||
return "", "", fmt.Errorf("no triage or planner model configured")
|
||||
}
|
||||
res, err := d.Runtime.Chat(ctx, model, core.GenerateOptions{
|
||||
System: "You classify a project owner's reply to a proposed PRD. Answer with exactly one line: " +
|
||||
"APPROVE, REJECT, or UNCLEAR, followed by ' - ' and a one-sentence justification. " +
|
||||
"APPROVE only when the reply expresses a go-ahead (with or without caveats). " +
|
||||
"REJECT when it declines or shelves the proposal. Anything ambiguous is UNCLEAR.",
|
||||
Prompt: "PRD (abridged):\n" + clip(prd, 3000) + "\n\nOwner's reply:\n" + clip(replies, 2000),
|
||||
})
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
line := strings.TrimSpace(res.Text)
|
||||
word, rest, _ := strings.Cut(line, "-")
|
||||
switch strings.ToUpper(strings.TrimSpace(strings.Trim(word, " :*"))) {
|
||||
case "APPROVE":
|
||||
return "approve", strings.TrimSpace(rest), nil
|
||||
case "REJECT":
|
||||
return "reject", strings.TrimSpace(rest), nil
|
||||
default:
|
||||
return "unclear", line, nil
|
||||
}
|
||||
}
|
||||
|
||||
func clip(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n] + "…"
|
||||
}
|
||||
|
||||
func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
// Register before any work starts so the task is stoppable for its
|
||||
// whole life, including the slow setup -- clone, worktree prepare,
|
||||
@@ -971,13 +806,6 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) {
|
||||
defer d.ContainerPool.Release(ctx, ctr)
|
||||
}
|
||||
|
||||
// Set the working label only after successful container setup (or when no
|
||||
// container is needed). This prevents label/database divergence on failure.
|
||||
// Chat-sourced tasks have no real forge issue to label.
|
||||
if task.IsForgeBacked() {
|
||||
fg.SetStateLabel(ctx, task.Owner, task.Repo, task.IssueNumber, d.Cfg.Dispatch.StateLabel("working"), d.Cfg.Dispatch.LabelValues())
|
||||
}
|
||||
|
||||
// Sandboxed path: hand the whole task to archie-agent in one NATS round
|
||||
// trip instead of running the stage loop here. archie-agent proxies
|
||||
// Store/Forge/worktree-push calls back to archied over storerpc/
|
||||
|
||||
+117
-206
@@ -6,7 +6,6 @@ import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -530,24 +529,18 @@ func TestRunViaAgentSendsExpectedRequest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasLabelUsesExactNames(t *testing.T) {
|
||||
labels := []string{"bug", "archie:parked-old", "feature", "custom,label"}
|
||||
if hasLabel(labels, "archie:parked") {
|
||||
t.Fatal("hasLabel matched a label-name substring")
|
||||
}
|
||||
if !hasLabel(labels, "custom,label") {
|
||||
t.Fatal("hasLabel did not preserve a label containing a comma")
|
||||
}
|
||||
labels = append(labels, "archie:parked")
|
||||
if !hasLabel(labels, "archie:parked") {
|
||||
t.Fatal("hasLabel did not match the exact label name")
|
||||
}
|
||||
}
|
||||
|
||||
// testForge implements forge.Forge for daemon tests.
|
||||
type testForge struct {
|
||||
comments []commentCall
|
||||
stateLabels []stateLabelCall
|
||||
comments []commentCall
|
||||
stateLabels []stateLabelCall
|
||||
closedIssues []closeIssueCall
|
||||
prStates map[int]string
|
||||
}
|
||||
|
||||
type closeIssueCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
comment string
|
||||
}
|
||||
|
||||
type commentCall struct {
|
||||
@@ -589,12 +582,16 @@ func (f *testForge) CreatePR(context.Context, string, string, string, string, st
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *testForge) PRState(context.Context, string, string, int) (string, error) {
|
||||
func (f *testForge) PRState(_ context.Context, _, _ string, number int) (string, error) {
|
||||
if state, ok := f.prStates[number]; ok {
|
||||
return state, nil
|
||||
}
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (f *testForge) CloseIssue(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
func (f *testForge) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
|
||||
f.closedIssues = append(f.closedIssues, closeIssueCall{owner, repo, number, comment})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *testForge) CreateIssue(context.Context, string, string, string, string, []string) (int, error) {
|
||||
@@ -627,114 +624,14 @@ func testDaemon(t *testing.T, maxRetries, _ int) (*Daemon, *store.Store, *testFo
|
||||
Cfg: cfg,
|
||||
Store: s,
|
||||
Forge: fg,
|
||||
// Reconcile paths call Trees.Cleanup, which dereferences the
|
||||
// manager. A zero Manager is enough: cleanup of a worktree that was
|
||||
// never created is a no-op.
|
||||
Trees: &worktree.Manager{},
|
||||
Log: log,
|
||||
}, s, fg
|
||||
}
|
||||
|
||||
func setupParkedTask(t *testing.T, s *store.Store, retryCount int) *store.Task {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "todo", 1, "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 err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "parked"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range retryCount {
|
||||
if err := s.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
task, err = s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
func TestMaybeRetryParkedUnderThreshold(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
_ = setupParkedTask(t, s, 0)
|
||||
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
if task.Status != store.StatusQueued {
|
||||
t.Fatalf("expected status queued, got %s", task.Status)
|
||||
}
|
||||
if task.RetryCount != 1 {
|
||||
t.Fatalf("expected retry_count=1, got %d", task.RetryCount)
|
||||
}
|
||||
if len(fg.stateLabels) != 1 || fg.stateLabels[0].label != "archie:queued" {
|
||||
t.Fatalf("expected queued state label, got %+v", fg.stateLabels)
|
||||
}
|
||||
if len(fg.comments) != 0 {
|
||||
t.Fatalf("expected no comments, got %d", len(fg.comments))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeRetryParkedAtThreshold(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
_ = setupParkedTask(t, s, 3)
|
||||
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
if task.Status != store.StatusDead {
|
||||
t.Fatalf("expected status dead, got %s", task.Status)
|
||||
}
|
||||
if len(fg.stateLabels) != 1 || fg.stateLabels[0].label != "archie:dead" {
|
||||
t.Fatalf("expected dead state label, got %+v", fg.stateLabels)
|
||||
}
|
||||
if len(fg.comments) != 1 || !strings.Contains(fg.comments[0].body, "Max retries reached") {
|
||||
t.Fatalf("expected dead comment, got %+v", fg.comments)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeRetryParkedSkipsDead(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
task := setupParkedTask(t, s, 0)
|
||||
if err := s.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, "manual"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
if len(fg.stateLabels) != 0 {
|
||||
t.Fatalf("expected no state label calls, got %d", len(fg.stateLabels))
|
||||
}
|
||||
if len(fg.comments) != 0 {
|
||||
t.Fatalf("expected no comments, got %d", len(fg.comments))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewIdentityRunnerPopulatesFromConfig(t *testing.T) {
|
||||
// Identity names come from config, not hardcoded by the daemon.
|
||||
tests := []struct {
|
||||
@@ -843,40 +740,6 @@ func TestDaemonStoresIdentityRunners(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeRetryParkedStillParked(t *testing.T) {
|
||||
d, _, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
is := forge.Issue{Number: 1, Labels: []string{"archie:parked", "bug"}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo"}
|
||||
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
if len(fg.stateLabels) != 0 {
|
||||
t.Fatalf("expected no state label calls, got %d", len(fg.stateLabels))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaybeRetryParkedRepoOverride(t *testing.T) {
|
||||
d, s, _ := testDaemon(t, 3, 1)
|
||||
ctx := context.Background()
|
||||
|
||||
_ = setupParkedTask(t, s, 1)
|
||||
|
||||
is := forge.Issue{Number: 1, Labels: []string{}}
|
||||
repo := config.Repo{Owner: "acme", Name: "todo", MaxRetries: 1}
|
||||
|
||||
d.maybeRetryParked(ctx, repo, is)
|
||||
|
||||
task, err := s.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue = (%+v, %v)", task, err)
|
||||
}
|
||||
if task.Status != store.StatusDead {
|
||||
t.Fatalf("expected status dead with repo override, got %s", task.Status)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Multi-identity isolation (archie-core-abg.37) ──────────────────────
|
||||
//
|
||||
// Two identities ("archie" and "winter") are both configured to work the
|
||||
@@ -940,60 +803,14 @@ func TestAcknowledgeUsesOwningIdentityForgeNotRoot(t *testing.T) {
|
||||
|
||||
// archie's poll cycle acknowledges via its own forge client.
|
||||
d.acknowledge(ctx, archieFg, repo, is)
|
||||
if len(archieFg.stateLabels) != 1 {
|
||||
t.Fatalf("archie forge got %d state label calls, want 1", len(archieFg.stateLabels))
|
||||
if len(archieFg.stateLabels) != 0 {
|
||||
t.Fatalf("archie forge got %d state label calls, want 0", len(archieFg.stateLabels))
|
||||
}
|
||||
if len(winterFg.stateLabels) != 0 || len(rootFg.stateLabels) != 0 {
|
||||
t.Fatal("acknowledge leaked a state label call to winter's or root's forge client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkDeadResolvesForgeFromTaskIdentityNotCaller(t *testing.T) {
|
||||
d, s, rootFg, archieFg, winterFg := twoIdentityDaemon(t)
|
||||
ctx := context.Background()
|
||||
|
||||
// Two tasks for the SAME owner/repo, owned by different identities.
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "shared", 1, "t1", "b", "", "archie"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "shared", 2, "t2", "b", "", "winter"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archieTask, err := s.TaskByIssue(ctx, "acme", "shared", 1)
|
||||
if err != nil || archieTask == nil {
|
||||
t.Fatalf("TaskByIssue(1) = (%+v, %v)", archieTask, err)
|
||||
}
|
||||
winterTask, err := s.TaskByIssue(ctx, "acme", "shared", 2)
|
||||
if err != nil || winterTask == nil {
|
||||
t.Fatalf("TaskByIssue(2) = (%+v, %v)", winterTask, err)
|
||||
}
|
||||
if err := s.Transition(ctx, archieTask.ID, store.StatusQueued, store.StatusParked, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Transition(ctx, winterTask.ID, store.StatusQueued, store.StatusParked, "test"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archieTask, _ = s.TaskByIssue(ctx, "acme", "shared", 1)
|
||||
winterTask, _ = s.TaskByIssue(ctx, "acme", "shared", 2)
|
||||
|
||||
repo := config.Repo{Owner: "acme", Name: "shared"}
|
||||
d.markDead(ctx, repo, archieTask, 0)
|
||||
d.markDead(ctx, repo, winterTask, 0)
|
||||
|
||||
if len(archieFg.stateLabels) != 1 || archieFg.stateLabels[0].number != 1 {
|
||||
t.Fatalf("archie forge state labels = %+v, want exactly issue 1", archieFg.stateLabels)
|
||||
}
|
||||
if len(winterFg.stateLabels) != 1 || winterFg.stateLabels[0].number != 2 {
|
||||
t.Fatalf("winter forge state labels = %+v, want exactly issue 2", winterFg.stateLabels)
|
||||
}
|
||||
if len(rootFg.stateLabels) != 0 {
|
||||
t.Fatal("markDead used the root forge client instead of the owning identity's")
|
||||
}
|
||||
if len(archieFg.comments) != 1 || len(winterFg.comments) != 1 {
|
||||
t.Fatalf("expected one dead-comment per identity, got archie=%d winter=%d", len(archieFg.comments), len(winterFg.comments))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRepoForPrefersOwningIdentityRepoList(t *testing.T) {
|
||||
d, _, _, _, _ := twoIdentityDaemon(t)
|
||||
|
||||
@@ -1025,3 +842,97 @@ func mustCoreConn(t *testing.T, c *arnats.Client) *natsio.Conn {
|
||||
}
|
||||
return conn
|
||||
}
|
||||
|
||||
// A merged PR must close the forge issue.
|
||||
//
|
||||
// "Closes #N" was removed from PR bodies in favour of LinkBranch, which is
|
||||
// sidebar linkage on Gitea and a no-op stub on GitHub -- neither closes
|
||||
// anything. So the issue stayed open, labelled and assigned, and the next
|
||||
// poll re-enqueued it. Once the operator uses the dashboard's Clear, which
|
||||
// deletes the task row, that is a second implementation and a second PR for
|
||||
// work already merged.
|
||||
func TestReconcilePRsClosesTheIssueOnMerge(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
prState string
|
||||
wantClosed bool
|
||||
}{
|
||||
{name: "merged closes the issue", prState: "merged", wantClosed: true},
|
||||
// A PR closed without merging usually means "try again", so the
|
||||
// issue stays open deliberately.
|
||||
{name: "closed without merge leaves it open", prState: "closed"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
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)
|
||||
}
|
||||
task.PRNumber = 7
|
||||
if err := s.Update(ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusPROpen, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fg.prStates = map[int]string{7: tc.prState}
|
||||
|
||||
d.reconcilePRs(ctx)
|
||||
|
||||
if tc.wantClosed {
|
||||
if len(fg.closedIssues) != 1 {
|
||||
t.Fatalf("CloseIssue calls = %d, want 1: the issue stays open "+
|
||||
"and is re-polled, so the work is done twice", len(fg.closedIssues))
|
||||
}
|
||||
got := fg.closedIssues[0]
|
||||
if got.owner != "acme" || got.repo != "widget" || got.number != 42 {
|
||||
t.Errorf("closed %s/%s#%d, want acme/widget#42", got.owner, got.repo, got.number)
|
||||
}
|
||||
if got.comment == "" {
|
||||
t.Error("closed with no comment")
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(fg.closedIssues) != 0 {
|
||||
t.Errorf("CloseIssue called %d times for a PR closed without merge",
|
||||
len(fg.closedIssues))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A chat task's issue number is synthetic, so closing it would close an
|
||||
// unrelated issue or error.
|
||||
func TestReconcilePRsSkipsChatTasks(t *testing.T) {
|
||||
d, s, fg := testDaemon(t, 3, 0)
|
||||
ctx := context.Background()
|
||||
|
||||
task, err := s.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", 900001)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.PRNumber = 8
|
||||
if err := s.Update(ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusPROpen, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fg.prStates = map[int]string{8: "merged"}
|
||||
|
||||
d.reconcilePRs(ctx)
|
||||
|
||||
if len(fg.closedIssues) != 0 {
|
||||
t.Errorf("CloseIssue called for a chat task: issue number is synthetic")
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,14 @@ const (
|
||||
KindPRMerged = "pr_merged"
|
||||
KindPRRejected = "pr_rejected"
|
||||
KindTaskDead = "task_dead"
|
||||
KindLog = "log" // data: level, msg
|
||||
// Operator actions taken from the dashboard. Without these an
|
||||
// intervention is recorded in the tasks table but invisible on the
|
||||
// timeline and the activity stream -- the one kind of event most worth
|
||||
// seeing, because it explains why a task changed course.
|
||||
KindHumanApproved = "human_approved"
|
||||
KindHumanRejected = "human_rejected"
|
||||
KindTaskRetried = "task_retried"
|
||||
KindLog = "log" // data: level, msg
|
||||
)
|
||||
|
||||
// Event is the single wire type: task lifecycle, stage progress, agent
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
// Package forgerpc lets archie-agent call the four forge.Forge methods
|
||||
// workflow stages invoke mid-run (Comment, CloseIssue, CreatePR,
|
||||
// SetStateLabel) over core NATS request/reply, instead of the agent
|
||||
// container holding a live forge API token. archied remains the sole
|
||||
// holder of forge credentials and the sole caller of forge.Forge.
|
||||
// Package forgerpc lets archie-agent call the forge methods workflow stages
|
||||
// invoke mid-run -- CloseIssue, CreatePR and LinkBranch, the workflow.Forger
|
||||
// set -- over core NATS request/reply, instead of the agent container holding
|
||||
// a live forge API token. archied remains the sole holder of forge credentials
|
||||
// and the sole caller of forge.Forge.
|
||||
//
|
||||
// Only these four methods are proxied -- the rest of forge.Forge (issue
|
||||
// polling, invitations, reactions, PR-state reconciliation) is used
|
||||
// exclusively by the daemon's own poll/reconcile loops, never from inside
|
||||
// a workflow stage, so there's nothing for archie-agent to call.
|
||||
// The rest of forge.Forge (issue polling, invitations, reactions, PR-state
|
||||
// reconciliation) is used exclusively by the daemon's own poll/reconcile
|
||||
// loops, never from inside a workflow stage, so there is nothing for
|
||||
// archie-agent to call.
|
||||
//
|
||||
// The server also still answers Comment and SetStateLabel. No current agent
|
||||
// calls them; the handlers exist so an older archie-agent image keeps working
|
||||
// against a newer daemon. The compatibility is one-directional: a NEW agent
|
||||
// against an OLD daemon has no LinkBranch handler to reach, and the request
|
||||
// times out, so an image skew that way parks tasks. Note it in release notes
|
||||
// rather than assuming either side can lag.
|
||||
package forgerpc
|
||||
|
||||
import (
|
||||
@@ -27,6 +34,7 @@ const (
|
||||
SubjectComment = "archie.forge.comment"
|
||||
SubjectCloseIssue = "archie.forge.close_issue"
|
||||
SubjectCreatePR = "archie.forge.create_pr"
|
||||
SubjectLinkBranch = "archie.forge.link_branch"
|
||||
SubjectSetStateLabel = "archie.forge.set_state_label"
|
||||
)
|
||||
|
||||
@@ -56,6 +64,12 @@ type CreatePRResponse struct {
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
type LinkBranchRequest struct {
|
||||
Owner, Repo string
|
||||
IssueNumber int
|
||||
Branch string
|
||||
}
|
||||
|
||||
type SetStateLabelRequest struct {
|
||||
Owner, Repo string
|
||||
Number int
|
||||
@@ -74,13 +88,14 @@ type Server struct {
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// Register subscribes all four handlers on nc. The returned func
|
||||
// Register subscribes all handlers on nc. The returned func
|
||||
// unsubscribes all of them.
|
||||
func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) {
|
||||
return natsrpc.RegisterAll(nc, []natsrpc.Registration{
|
||||
{Subject: SubjectComment, Handler: s.handleComment},
|
||||
{Subject: SubjectCloseIssue, Handler: s.handleCloseIssue},
|
||||
{Subject: SubjectCreatePR, Handler: s.handleCreatePR},
|
||||
{Subject: SubjectLinkBranch, Handler: s.handleLinkBranch},
|
||||
{Subject: SubjectSetStateLabel, Handler: s.handleSetStateLabel},
|
||||
})
|
||||
}
|
||||
@@ -115,13 +130,22 @@ func (s *Server) handleCreatePR(msg *nats.Msg) {
|
||||
s.respond(msg, CreatePRResponse{Number: num, Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleLinkBranch(msg *nats.Msg) {
|
||||
var req LinkBranchRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode link_branch request: %w", err))})
|
||||
return
|
||||
}
|
||||
err := s.Forge.LinkBranch(context.Background(), req.Owner, req.Repo, req.IssueNumber, req.Branch)
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(err)})
|
||||
}
|
||||
|
||||
func (s *Server) handleSetStateLabel(msg *nats.Msg) {
|
||||
var req SetStateLabelRequest
|
||||
if err := json.Unmarshal(msg.Data, &req); err != nil {
|
||||
s.respond(msg, Response{Envelope: natsrpc.NewEnvelope(fmt.Errorf("decode set_state_label request: %w", err))})
|
||||
return
|
||||
}
|
||||
// SetStateLabel has no error return in forge.Forge -- nothing to propagate.
|
||||
s.Forge.SetStateLabel(context.Background(), req.Owner, req.Repo, req.Number, req.Label, req.KnownLabels)
|
||||
s.respond(msg, Response{})
|
||||
}
|
||||
@@ -141,6 +165,11 @@ type Client struct {
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
// Comment and SetStateLabel are not in workflow.Forger, so no current agent
|
||||
// calls them. They stay as the client half of handlers kept for image skew
|
||||
// (see the package doc) -- and as the only way to exercise those handlers
|
||||
// end to end, which is why removing them would leave the compatibility path
|
||||
// untested rather than merely unused.
|
||||
func (c *Client) Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
req := CommentRequest{Owner: owner, Repo: repo, Number: number, Body: body}
|
||||
resp, err := natsrpc.Call[CommentResponse](ctx, c.rpc(), SubjectComment, req)
|
||||
@@ -174,9 +203,17 @@ func (c *Client) CreatePR(ctx context.Context, owner, repo, title, head, base, b
|
||||
return resp.Number, nil
|
||||
}
|
||||
|
||||
// SetStateLabel matches forge.Forge's signature (no error return). RPC or
|
||||
// server-side failures are logged by the server; the daemon still owns
|
||||
// SetStateLabel's fire-and-forget semantics.
|
||||
func (c *Client) LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error {
|
||||
req := LinkBranchRequest{Owner: owner, Repo: repo, IssueNumber: issueNumber, Branch: branch}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectLinkBranch, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// SetStateLabel remains available for RPC compatibility with older workers;
|
||||
// the current workflow deliberately never calls it.
|
||||
func (c *Client) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string) {
|
||||
req := SetStateLabelRequest{Owner: owner, Repo: repo, Number: number, Label: label, KnownLabels: knownLabels}
|
||||
_, _ = natsrpc.Call[Response](ctx, c.rpc(), SubjectSetStateLabel, req)
|
||||
|
||||
@@ -39,6 +39,7 @@ type fakeForge struct {
|
||||
closes []closeCall
|
||||
prs []prCall
|
||||
stateLabels []stateLabelCall
|
||||
branches []branchCall
|
||||
|
||||
commentErr error
|
||||
closeErr error
|
||||
@@ -64,6 +65,10 @@ type stateLabelCall struct {
|
||||
label string
|
||||
knownLabels []string
|
||||
}
|
||||
type branchCall struct {
|
||||
owner, repo, branch string
|
||||
number int
|
||||
}
|
||||
|
||||
func (f *fakeForge) Comment(_ context.Context, owner, repo string, number int, body string) (int64, error) {
|
||||
f.comments = append(f.comments, commentCall{owner, repo, number, body})
|
||||
@@ -90,6 +95,11 @@ func (f *fakeForge) SetStateLabel(_ context.Context, owner, repo string, number
|
||||
f.stateLabels = append(f.stateLabels, stateLabelCall{owner, repo, number, label, knownLabels})
|
||||
}
|
||||
|
||||
func (f *fakeForge) LinkBranch(_ context.Context, owner, repo string, number int, branch string) error {
|
||||
f.branches = append(f.branches, branchCall{owner: owner, repo: repo, number: number, branch: branch})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) AcceptInvitations(context.Context) error { panic("unexpected call") }
|
||||
func (f *fakeForge) AssignedIssues(context.Context, string, string, string) ([]forge.Issue, error) {
|
||||
panic("unexpected call")
|
||||
@@ -115,9 +125,6 @@ func (f *fakeForge) React(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (f *fakeForge) VerifyPush(context.Context, string, string) error { panic("unexpected call") }
|
||||
func (f *fakeForge) LinkBranch(context.Context, string, string, int, string) error {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T) (*fakeForge, *Client) {
|
||||
t.Helper()
|
||||
@@ -179,6 +186,17 @@ func TestClientCreatePRPersistsViaServer(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientLinkBranchPersistsViaServer(t *testing.T) {
|
||||
f, client := newTestServer(t)
|
||||
|
||||
if err := client.LinkBranch(context.Background(), "acme", "widget", 4, "fix/4-bug"); err != nil {
|
||||
t.Fatalf("LinkBranch: %v", err)
|
||||
}
|
||||
if len(f.branches) != 1 || f.branches[0] != (branchCall{owner: "acme", repo: "widget", number: 4, branch: "fix/4-bug"}) {
|
||||
t.Fatalf("branch link did not reach server, got %+v", f.branches)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientSetStateLabelPersistsViaServer(t *testing.T) {
|
||||
fg, client := newTestServer(t)
|
||||
|
||||
|
||||
@@ -376,26 +376,6 @@ func (a *Adapter) IncrementRetryCount(ctx context.Context, taskID int64) error {
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// WaitingTasks returns tasks in waiting_human state.
|
||||
func (a *Adapter) WaitingTasks(ctx context.Context) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []store.Task
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Status != store.StatusWaitingHuman {
|
||||
continue
|
||||
}
|
||||
out = append(out, *t)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// OpenPRs returns tasks in pr_open state.
|
||||
func (a *Adapter) OpenPRs(ctx context.Context) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
|
||||
@@ -100,13 +100,15 @@ func TestChatTaskLifecyclePreservesRouting(t *testing.T) {
|
||||
if err := s.Transition(ctx, task.ID, store.StatusQueued, store.StatusWaitingHuman, "await approval"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waiting, err := s.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// Routing metadata must survive a status transition: a chat task that
|
||||
// stops for approval still has to come back to the identity that owns it.
|
||||
waiting, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || waiting == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", waiting, err)
|
||||
}
|
||||
if len(waiting) != 1 || waiting[0].Source != store.SourceChat ||
|
||||
waiting[0].Identity != "reviewer" {
|
||||
t.Fatalf("WaitingTasks() = %+v, want chat/reviewer routing", waiting)
|
||||
if waiting.Status != store.StatusWaitingHuman || waiting.Source != store.SourceChat ||
|
||||
waiting.Identity != "reviewer" {
|
||||
t.Fatalf("waiting task = %+v, want waiting_human chat/reviewer routing", waiting)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,15 +284,6 @@ func TestEmptyStoreOperations(t *testing.T) {
|
||||
t.Errorf("Tasks on empty store should be empty, got %d", len(tasks))
|
||||
}
|
||||
|
||||
// WaitingTasks on empty store.
|
||||
waiting, err := s.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
t.Errorf("WaitingTasks on empty store: %v", err)
|
||||
}
|
||||
if len(waiting) != 0 {
|
||||
t.Errorf("WaitingTasks on empty store should be empty, got %d", len(waiting))
|
||||
}
|
||||
|
||||
// OpenPRs on empty store.
|
||||
prs, err := s.OpenPRs(ctx)
|
||||
if err != nil {
|
||||
|
||||
@@ -75,6 +75,41 @@ func TestCatalogMissingDirReturnsEmpty(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCatalogRootsUsesPrecedenceAndTracksRoot(t *testing.T) {
|
||||
project := t.TempDir()
|
||||
global := t.TempDir()
|
||||
writeSkill := func(root, name, description string) {
|
||||
dir := filepath.Join(root, ".agents", "skills", name)
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
content := "---\nname: " + name + "\ndescription: " + description + "\n---\nBody.\n"
|
||||
if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
writeSkill(project, "shared-name", "project copy")
|
||||
writeSkill(project, "project-only", "project skill")
|
||||
writeSkill(global, "shared-name", "global copy")
|
||||
writeSkill(global, "global-only", "global skill")
|
||||
|
||||
entries, err := CatalogRoots(project, global)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 3 {
|
||||
t.Fatalf("got %d catalog entries, want 3", len(entries))
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name == "shared-name" {
|
||||
if entry.Description != "project copy" || entry.Root != project {
|
||||
t.Fatalf("shared-name = %#v, want project entry", entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── archie-wf-* naming convention ────────────────────────────────────
|
||||
|
||||
func TestSkillsUseArchiewfNaming(t *testing.T) {
|
||||
|
||||
@@ -37,6 +37,7 @@ type CatalogEntry struct {
|
||||
Description string
|
||||
Workflow string // from metadata.archie.workflow -- which workflow this skill handles
|
||||
Dir string // skill directory name
|
||||
Root string // catalog root containing .agents/skills
|
||||
}
|
||||
|
||||
// Catalog scans dir/.agents/skills/*/SKILL.md and returns catalog entries
|
||||
@@ -83,11 +84,70 @@ func Catalog(dir string) ([]CatalogEntry, error) {
|
||||
Description: fm.Description,
|
||||
Workflow: wf,
|
||||
Dir: name,
|
||||
Root: dir,
|
||||
})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CatalogRoots merges catalogues from roots in precedence order. The first
|
||||
// root containing a skill name wins, so callers can layer project skills over
|
||||
// shared and user-global skills deterministically.
|
||||
func CatalogRoots(roots ...string) ([]CatalogEntry, error) {
|
||||
seen := make(map[string]struct{})
|
||||
var out []CatalogEntry
|
||||
for _, root := range roots {
|
||||
entries, err := Catalog(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if _, ok := seen[entry.Name]; ok {
|
||||
continue
|
||||
}
|
||||
seen[entry.Name] = struct{}{}
|
||||
out = append(out, entry)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// DefaultRoots returns the discovery roots for a daemon. Explicit project and
|
||||
// shared roots take precedence over the user's global skills directory.
|
||||
func DefaultRoots(workDir, sharedDir string) []string {
|
||||
var roots []string
|
||||
for _, root := range []string{workDir, sharedDir} {
|
||||
if root != "" && !containsRoot(roots, root) {
|
||||
roots = append(roots, root)
|
||||
}
|
||||
}
|
||||
if home, err := os.UserHomeDir(); err == nil && home != "" && !containsRoot(roots, home) {
|
||||
roots = append(roots, home)
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
// containsRoot compares roots after normalising trailing separators, so
|
||||
// "/srv/skills" and "/srv/skills/" are one root rather than two -- otherwise
|
||||
// the same directory is scanned twice and every skill in it appears twice.
|
||||
func containsRoot(roots []string, root string) bool {
|
||||
target := normaliseRoot(root)
|
||||
for _, existing := range roots {
|
||||
if normaliseRoot(existing) == target {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func normaliseRoot(root string) string {
|
||||
if root == "" {
|
||||
return root
|
||||
}
|
||||
return filepath.Clean(root)
|
||||
}
|
||||
|
||||
// SkillForWorkflow returns the catalog entry whose Workflow field matches
|
||||
// the given workflow name, or nil if no skill declares that workflow.
|
||||
// Replaces hardcoded workflow→skill lookup tables.
|
||||
|
||||
@@ -23,10 +23,14 @@ func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry {
|
||||
names := make([]any, len(catalog))
|
||||
descByName := make(map[string]string, len(catalog))
|
||||
dirByName := make(map[string]string, len(catalog))
|
||||
rootByName := make(map[string]string, len(catalog))
|
||||
for i, e := range catalog {
|
||||
names[i] = e.Name
|
||||
descByName[e.Name] = e.Description
|
||||
dirByName[e.Name] = e.Dir
|
||||
if e.Root != "" {
|
||||
rootByName[e.Name] = e.Root
|
||||
}
|
||||
}
|
||||
|
||||
return &tools.ToolEntry{
|
||||
@@ -53,7 +57,11 @@ func ActivateTool(dir string, catalog []CatalogEntry) *tools.ToolEntry {
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("skill_activate: unknown skill %q", name)
|
||||
}
|
||||
body := LoadBody(dir, skillDir)
|
||||
root := dir
|
||||
if catalogRoot := rootByName[name]; catalogRoot != "" {
|
||||
root = catalogRoot
|
||||
}
|
||||
body := LoadBody(root, skillDir)
|
||||
if body == "" {
|
||||
return nil, fmt.Errorf("skill_activate: %q has no body (SKILL.md missing or empty)", name)
|
||||
}
|
||||
|
||||
@@ -81,6 +81,25 @@ func TestActivateToolHandlerReturnsFullBody(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivateToolHandlerLoadsFromCatalogEntryRoot(t *testing.T) {
|
||||
global := t.TempDir()
|
||||
writeSkill(t, global, "global-only", "global skill", "global body")
|
||||
|
||||
catalog, err := CatalogRoots(global)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entry := ActivateTool(t.TempDir(), catalog)
|
||||
|
||||
out, err := entry.Handler(context.Background(), map[string]any{"name": "global-only"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out != "global body" {
|
||||
t.Errorf("body = %v, want global body", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActivateToolHandlerRejectsUnknownSkill(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeSkill(t, dir, "alpha", "does alpha things", "alpha body")
|
||||
|
||||
@@ -101,7 +101,7 @@ func (s *Store) Tasks(ctx context.Context, limit int) (tasks []Task, retErr erro
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, owner, repo, issue_number, title, status, workflow, stage,
|
||||
pr_number, tokens_used, iterations, attempt, park_reason, retry_count,
|
||||
created_at, updated_at
|
||||
created_at, updated_at, plan, source
|
||||
FROM tasks ORDER BY updated_at DESC LIMIT ?`, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -111,10 +111,15 @@ func (s *Store) Tasks(ctx context.Context, limit int) (tasks []Task, retErr erro
|
||||
}()
|
||||
for rows.Next() {
|
||||
var t Task
|
||||
// Plan and Source are read by the dashboard: Plan gates the
|
||||
// "Decision required" panel on a waiting_human task, and Source
|
||||
// decides whether an issue link is rendered at all -- a chat task's
|
||||
// issue number is synthetic and links nowhere.
|
||||
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title,
|
||||
&t.Status, &t.Workflow, &t.Stage, &t.PRNumber, &t.TokensUsed,
|
||||
&t.Iterations, &t.Attempt, &t.ParkReason, &t.RetryCount,
|
||||
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt}); err != nil {
|
||||
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt},
|
||||
&t.Plan, &t.Source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
|
||||
@@ -35,7 +35,6 @@ type TaskLifecycle interface {
|
||||
type TaskQueries interface {
|
||||
TaskByIssue(ctx context.Context, owner, repo string, number int) (*Task, error)
|
||||
TaskByID(ctx context.Context, taskID int64) (*Task, error)
|
||||
WaitingTasks(ctx context.Context) ([]Task, error)
|
||||
OpenPRs(ctx context.Context) ([]Task, error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
Tasks(ctx context.Context, limit int) ([]Task, error)
|
||||
|
||||
@@ -32,7 +32,7 @@ func TestTaskByIssue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitingTasksAndRequeue(t *testing.T) {
|
||||
func TestRequeueFromWaitingHuman(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -44,16 +44,12 @@ func TestWaitingTasksAndRequeue(t *testing.T) {
|
||||
t.Fatalf("claim = (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
if waiting, err := s.WaitingTasks(ctx); err != nil || len(waiting) != 0 {
|
||||
t.Fatalf("WaitingTasks before transition = (%+v, %v)", waiting, err)
|
||||
}
|
||||
|
||||
if err := s.Transition(ctx, task.ID, StatusRunning, StatusWaitingHuman, "needs input"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waiting, err := s.WaitingTasks(ctx)
|
||||
if err != nil || len(waiting) != 1 || waiting[0].ID != task.ID {
|
||||
t.Fatalf("WaitingTasks = (%+v, %v)", waiting, err)
|
||||
waiting, err := s.TaskByID(ctx, task.ID)
|
||||
if err != nil || waiting == nil || waiting.Status != StatusWaitingHuman {
|
||||
t.Fatalf("after transition = (%+v, %v), want waiting_human", waiting, err)
|
||||
}
|
||||
|
||||
// Requeue with a workflow forces it (waiting_human -> approved -> implement).
|
||||
|
||||
+3
-26
@@ -169,8 +169,9 @@ func OpenTest(t interface{ TempDir() string }) *Store {
|
||||
return s
|
||||
}
|
||||
|
||||
// IncrementRetryCount atomically bumps retry_count by 1. Called after
|
||||
// a parked task is requeued by maybeRetryParked.
|
||||
// IncrementRetryCount atomically bumps retry_count by 1. Called when an
|
||||
// operator retries a parked task; the caller enforces max_retries against
|
||||
// the resulting count.
|
||||
func (s *Store) IncrementRetryCount(ctx context.Context, taskID int64) error {
|
||||
_, err := s.db.ExecContext(ctx,
|
||||
`UPDATE tasks SET retry_count = retry_count + 1, updated_at = datetime('now') WHERE id = ?`, taskID)
|
||||
@@ -348,30 +349,6 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*Task, error) {
|
||||
return t, err
|
||||
}
|
||||
|
||||
// WaitingTasks returns tasks blocked on human input.
|
||||
func (s *Store) WaitingTasks(ctx context.Context) (tasks []Task, retErr error) {
|
||||
rows, err := s.db.QueryContext(ctx, `
|
||||
SELECT id, owner, repo, issue_number, title, body, plan, workflow,
|
||||
watch_comment_id, status, source, identity
|
||||
FROM tasks WHERE status='waiting_human'`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
retErr = errors.Join(retErr, rows.Close())
|
||||
}()
|
||||
for rows.Next() {
|
||||
var t Task
|
||||
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title,
|
||||
&t.Body, &t.Plan, &t.Workflow, &t.WatchCommentID, &t.Status,
|
||||
&t.Source, &t.Identity); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tasks = append(tasks, t)
|
||||
}
|
||||
return tasks, rows.Err()
|
||||
}
|
||||
|
||||
// Requeue puts a task back on the queue. A non-empty workflow forces it
|
||||
// (the waiting_human → approved → implement handoff); empty keeps the
|
||||
// task's current workflow (retrying a parked task).
|
||||
|
||||
@@ -387,13 +387,15 @@ func TestLifecycleQueriesPreserveChatTaskRouting(t *testing.T) {
|
||||
if err := s.Transition(ctx, waiting.ID, StatusQueued, StatusWaitingHuman, "await approval"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
waitingTasks, err := s.WaitingTasks(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
// Routing metadata must survive a status transition: a chat task that
|
||||
// stops for approval still has to come back to the identity that owns it.
|
||||
waitingTask, err := s.TaskByID(ctx, waiting.ID)
|
||||
if err != nil || waitingTask == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", waitingTask, err)
|
||||
}
|
||||
if len(waitingTasks) != 1 || waitingTasks[0].Source != SourceChat ||
|
||||
waitingTasks[0].Identity != "reviewer" {
|
||||
t.Fatalf("WaitingTasks() = %+v, want chat/reviewer routing", waitingTasks)
|
||||
if waitingTask.Status != StatusWaitingHuman || waitingTask.Source != SourceChat ||
|
||||
waitingTask.Identity != "reviewer" {
|
||||
t.Fatalf("waiting task = %+v, want waiting_human chat/reviewer routing", waitingTask)
|
||||
}
|
||||
|
||||
pr, err := s.EnqueueChatTask(ctx, "acme", "todo", "open PR", "", "implement", "builder", 999_002)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Tasks() is what the dashboard's task list is built from, and the UI reads
|
||||
// two fields the query never selected: Plan, which gates the "Decision
|
||||
// required" panel on a waiting_human task, and Source, which decides whether
|
||||
// to render a forge issue link at all.
|
||||
//
|
||||
// Both came back as the zero value, so the panel could never appear and a
|
||||
// chat-sourced task -- whose issue_number is synthetic -- rendered a link to
|
||||
// an issue that does not exist. Neither failed loudly; the features were
|
||||
// simply dead.
|
||||
func TestTasksSelectsFieldsTheUIReads(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
s := OpenTest(t)
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "o", "r", 7, "forge task", "body", "", ""); err != nil {
|
||||
t.Fatalf("EnqueueIssue: %v", err)
|
||||
}
|
||||
forgeTaskRow, err := s.TaskByIssue(ctx, "o", "r", 7)
|
||||
if err != nil || forgeTaskRow == nil {
|
||||
t.Fatalf("TaskByIssue: %v", err)
|
||||
}
|
||||
forgeID := forgeTaskRow.ID
|
||||
|
||||
chatTaskRow, err := s.EnqueueChatTask(ctx, "o", "r", "chat task", "body", "", "", 900001)
|
||||
if err != nil {
|
||||
t.Fatalf("EnqueueChatTask: %v", err)
|
||||
}
|
||||
chatID := chatTaskRow.ID
|
||||
|
||||
// A plan is what an operator approves or rejects, so it has to survive
|
||||
// the read the approval UI is built on.
|
||||
const plan = "1. add the thing\n2. test the thing"
|
||||
forgeTaskRow.Plan = plan
|
||||
if err := s.Update(ctx, forgeTaskRow); err != nil {
|
||||
t.Fatalf("Update: %v", err)
|
||||
}
|
||||
|
||||
tasks, err := s.Tasks(ctx, 50)
|
||||
if err != nil {
|
||||
t.Fatalf("Tasks: %v", err)
|
||||
}
|
||||
|
||||
byID := make(map[int64]Task, len(tasks))
|
||||
for _, task := range tasks {
|
||||
byID[task.ID] = task
|
||||
}
|
||||
|
||||
forgeTask, ok := byID[forgeID]
|
||||
if !ok {
|
||||
t.Fatalf("forge task %d missing from Tasks()", forgeID)
|
||||
}
|
||||
if forgeTask.Plan != plan {
|
||||
t.Errorf("Plan = %q, want %q: the approval panel is gated on this and "+
|
||||
"can never render while it is empty", forgeTask.Plan, plan)
|
||||
}
|
||||
if forgeTask.Source != SourceForge {
|
||||
t.Errorf("Source = %q, want %q", forgeTask.Source, SourceForge)
|
||||
}
|
||||
|
||||
chatTask, ok := byID[chatID]
|
||||
if !ok {
|
||||
t.Fatalf("chat task %d missing from Tasks()", chatID)
|
||||
}
|
||||
if chatTask.Source != SourceChat {
|
||||
t.Errorf("Source = %q, want %q: without it the UI links a synthetic "+
|
||||
"issue number to a forge issue that does not exist",
|
||||
chatTask.Source, SourceChat)
|
||||
}
|
||||
if chatTask.IsForgeBacked() {
|
||||
t.Error("IsForgeBacked() is true for a chat task read through Tasks()")
|
||||
}
|
||||
}
|
||||
@@ -19,26 +19,17 @@ type SkillView struct {
|
||||
// beyond what is in the source. It answers the same question a fresh
|
||||
// operator would ask by reading internal/skill/, without the reading.
|
||||
//
|
||||
// The catalogue is scanned from cfg.SkillsDir when configured (a shared
|
||||
// directory meant to be pointed at deliberately), falling back to
|
||||
// cfg.WorkDir's own .agents/skills/ otherwise. Both are legitimate --
|
||||
// skill.Catalog treats a missing directory as "no skills," not an error --
|
||||
// so an unconfigured deployment gets an empty, explained list rather than a
|
||||
// failure.
|
||||
// The catalogue layers project, explicitly shared, and user-global skills.
|
||||
// Earlier roots win when names collide. Missing roots are legitimate and
|
||||
// produce an empty or partial catalogue rather than a failed dashboard.
|
||||
func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Cfg == nil {
|
||||
writeJSON(w, map[string]any{"skills": []SkillView{}, "dir": ""})
|
||||
writeJSON(w, map[string]any{"skills": []SkillView{}})
|
||||
return
|
||||
}
|
||||
|
||||
dir := s.Cfg.SkillsDir
|
||||
source := "shared skills directory"
|
||||
if dir == "" {
|
||||
dir = s.Cfg.WorkDir
|
||||
source = "bundled with this project"
|
||||
}
|
||||
|
||||
catalog, err := skill.Catalog(dir)
|
||||
roots := skill.DefaultRoots(s.Cfg.WorkDir, s.Cfg.SkillsDir)
|
||||
catalog, err := skill.CatalogRoots(roots...)
|
||||
if err != nil {
|
||||
http.Error(w, "failed to read skill catalogue: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -50,9 +41,28 @@ func (s *Server) handleSkills(w http.ResponseWriter, r *http.Request) {
|
||||
Name: entry.Name,
|
||||
Description: entry.Description,
|
||||
Workflow: entry.Workflow,
|
||||
Source: source,
|
||||
Source: skillSource(entry.Root, s.Cfg.WorkDir, s.Cfg.SkillsDir),
|
||||
})
|
||||
}
|
||||
|
||||
writeJSON(w, map[string]any{"skills": views, "dir": dir})
|
||||
// Each skill already carries its own Source, which is what the page
|
||||
// renders. A top-level dir/dirs pair had no consumer and implied the
|
||||
// catalog came from one place when it is merged from several.
|
||||
writeJSON(w, map[string]any{"skills": views})
|
||||
}
|
||||
|
||||
// skillSource labels where a skill was loaded from.
|
||||
//
|
||||
// sharedDir is checked first: when it equals workDir the roots collapse to one
|
||||
// entry, and matching workDir first labelled every shared skill as a project
|
||||
// skill.
|
||||
func skillSource(root, workDir, sharedDir string) string {
|
||||
switch root {
|
||||
case sharedDir:
|
||||
return "shared skills"
|
||||
case workDir:
|
||||
return "project skills"
|
||||
default:
|
||||
return "user-global skills"
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,14 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func (s *Server) handleSummary(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -64,3 +70,196 @@ func (s *Server) handleTask(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, evs)
|
||||
}
|
||||
|
||||
type taskActionRequest struct {
|
||||
Action string `json:"action"`
|
||||
}
|
||||
|
||||
func (s *Server) handleTaskAction(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
||||
if err != nil {
|
||||
http.Error(w, "bad id", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var req taskActionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid action", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
task, err := s.Store.TaskByID(r.Context(), id)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if task == nil {
|
||||
http.Error(w, "task not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// Each action reports the event to record, or writes its own error
|
||||
// response and returns nothing. Keeping the dispatch flat here and the
|
||||
// rules in one function each is what stops this growing back into a
|
||||
// single branch nobody can read.
|
||||
ctx := r.Context()
|
||||
var outcome *actionOutcome
|
||||
switch req.Action {
|
||||
case "approve":
|
||||
outcome = s.approveTask(ctx, w, task)
|
||||
case "retry":
|
||||
outcome = s.retryTask(ctx, w, task)
|
||||
case "reject":
|
||||
outcome = s.rejectTask(ctx, w, task)
|
||||
default:
|
||||
http.Error(w, "unknown action", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if outcome == nil {
|
||||
return
|
||||
}
|
||||
|
||||
s.emit(events.Event{
|
||||
Kind: outcome.kind, TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber,
|
||||
Detail: outcome.detail,
|
||||
})
|
||||
writeJSON(w, map[string]any{"ok": true, "action": req.Action, "task_id": id})
|
||||
}
|
||||
|
||||
// actionOutcome is what a completed operator action should record.
|
||||
type actionOutcome struct {
|
||||
kind string
|
||||
detail string
|
||||
}
|
||||
|
||||
// storeFailed writes the response for a failed store write and reports
|
||||
// whether it did. A store write that fails is not the caller's fault;
|
||||
// answering 409 made the UI say "conflict" for a broken database.
|
||||
func storeFailed(w http.ResponseWriter, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) approveTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
|
||||
if task.Status != store.StatusWaitingHuman {
|
||||
http.Error(w, "task is not awaiting approval", http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusWaitingHuman, "implement")) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{events.KindHumanApproved, "approved via the dashboard"}
|
||||
}
|
||||
|
||||
// retryTask requeues a parked task, or retires it once max_retries is spent.
|
||||
//
|
||||
// max_retries was configured, defaulted and reported by /api/config while
|
||||
// nothing enforced it: retry_count climbed forever, so a task that fails
|
||||
// every time could be retried without limit. At the cap the task belongs in
|
||||
// dead, which is what the setting exists to say.
|
||||
func (s *Server) retryTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
|
||||
if task.Status != store.StatusParked {
|
||||
http.Error(w, "task is not parked", http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
if limit := s.maxRetriesFor(task); limit > 0 && task.RetryCount >= limit {
|
||||
s.retireTask(ctx, task, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit))
|
||||
http.Error(w, fmt.Sprintf("max retries reached (%d/%d)", task.RetryCount, limit), http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.Requeue(ctx, task.ID, store.StatusParked, "")) {
|
||||
return nil
|
||||
}
|
||||
if storeFailed(w, s.Store.IncrementRetryCount(ctx, task.ID)) {
|
||||
return nil
|
||||
}
|
||||
return &actionOutcome{events.KindTaskRetried, "retried via the dashboard"}
|
||||
}
|
||||
|
||||
// retireTask moves a spent task to dead. Failure is logged, not returned:
|
||||
// the caller is already answering with the reason it refused the retry.
|
||||
func (s *Server) retireTask(ctx context.Context, task *store.Task, reason string) {
|
||||
if err := s.Store.Transition(ctx, task.ID, store.StatusParked, store.StatusDead, reason); err != nil {
|
||||
s.logf("transition to dead failed", "task", task.ID, "err", err)
|
||||
return
|
||||
}
|
||||
s.emit(events.Event{
|
||||
Kind: events.KindTaskDead, TaskID: task.ID,
|
||||
Repo: task.Owner + "/" + task.Repo, Issue: task.IssueNumber, Detail: reason,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) rejectTask(ctx context.Context, w http.ResponseWriter, task *store.Task) *actionOutcome {
|
||||
if task.Status != store.StatusWaitingHuman {
|
||||
http.Error(w, "task is not awaiting approval", http.StatusConflict)
|
||||
return nil
|
||||
}
|
||||
err := s.Store.Transition(ctx, task.ID, store.StatusWaitingHuman, store.StatusClosedWontDo, "rejected via Web UI")
|
||||
if storeFailed(w, err) {
|
||||
return nil
|
||||
}
|
||||
s.closeRejectedIssue(ctx, task)
|
||||
return &actionOutcome{events.KindHumanRejected, "rejected via the dashboard"}
|
||||
}
|
||||
|
||||
// maxRetriesFor resolves the retry cap for a task, honouring a per-repo
|
||||
// override. Zero means unlimited.
|
||||
func (s *Server) maxRetriesFor(task *store.Task) int {
|
||||
if s.Cfg == nil {
|
||||
return 0
|
||||
}
|
||||
for _, repo := range s.Cfg.Repos {
|
||||
if repo.Owner == task.Owner && repo.Name == task.Repo {
|
||||
return repo.EffectiveMaxRetries(s.Cfg.MaxRetries)
|
||||
}
|
||||
}
|
||||
return s.Cfg.MaxRetries
|
||||
}
|
||||
|
||||
// closeRejectedIssue closes the forge issue behind a task the operator has
|
||||
// declined.
|
||||
//
|
||||
// Without this the issue stays open, labelled and assigned, so the next poll
|
||||
// re-enqueues it -- and once the operator uses Clear, which deletes the task
|
||||
// row, that is a second implementation and a second PR for work already
|
||||
// refused. Approve and retry deliberately leave the issue open: the task is
|
||||
// going back to work.
|
||||
//
|
||||
// Failure is logged, not returned. The operator's decision is already
|
||||
// recorded, and reporting an error would invite them to click again.
|
||||
func (s *Server) closeRejectedIssue(ctx context.Context, task *store.Task) {
|
||||
if s.Issues == nil {
|
||||
s.logf("task rejected but no forge is wired; the issue stays open and will be re-polled",
|
||||
"task", task.ID, "issue", task.IssueNumber)
|
||||
return
|
||||
}
|
||||
// A chat task's issue number is synthetic and matches no forge issue.
|
||||
if !task.IsForgeBacked() {
|
||||
return
|
||||
}
|
||||
const comment = "Closing: this was rejected from the archie dashboard. " +
|
||||
"Reopen the issue to have archie pick it up again."
|
||||
if err := s.Issues.CloseIssue(ctx, task.Owner, task.Repo, task.IssueNumber, comment); err != nil {
|
||||
s.logf("closing rejected issue failed; it stays open and will be re-polled",
|
||||
"task", task.ID, "issue", task.IssueNumber, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// emit publishes an operator action so it reaches the task timeline and the
|
||||
// live activity stream. A nil publisher is not an error: the action is still
|
||||
// recorded in the store.
|
||||
func (s *Server) emit(e events.Event) {
|
||||
if s.Events == nil || e.Kind == "" {
|
||||
return
|
||||
}
|
||||
s.Events.Publish(e)
|
||||
}
|
||||
|
||||
func (s *Server) logf(msg string, args ...any) {
|
||||
if s.Log == nil {
|
||||
return
|
||||
}
|
||||
s.Log.Warn(msg, args...)
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// recordingCloser captures the forge issue-closure calls an action makes.
|
||||
type recordingCloser struct {
|
||||
calls []closeCall
|
||||
err error
|
||||
}
|
||||
|
||||
type closeCall struct {
|
||||
owner, repo string
|
||||
number int
|
||||
comment string
|
||||
}
|
||||
|
||||
func (r *recordingCloser) CloseIssue(_ context.Context, owner, repo string, number int, comment string) error {
|
||||
r.calls = append(r.calls, closeCall{owner, repo, number, comment})
|
||||
return r.err
|
||||
}
|
||||
|
||||
// actionServer builds a dashboard server with a task in the given state, plus
|
||||
// the collaborators the action path needs.
|
||||
func actionServer(t *testing.T, status, parkReason string) (*Server, *store.Task, *recordingCloser, *events.Bus, *events.Sub) {
|
||||
t.Helper()
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, status, parkReason); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
closer := &recordingCloser{}
|
||||
bus := events.NewBus()
|
||||
t.Cleanup(bus.Close)
|
||||
sub := bus.Subscribe(16)
|
||||
|
||||
srv.Issues = closer
|
||||
srv.Events = bus
|
||||
srv.Cfg = &config.Config{MaxRetries: 3}
|
||||
return srv, task, closer, bus, sub
|
||||
}
|
||||
|
||||
func postAction(t *testing.T, srv *Server, id int64, action string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action",
|
||||
bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
return w
|
||||
}
|
||||
|
||||
// max_retries is configured, defaulted and shown in /api/config, but nothing
|
||||
// enforced it: the Web UI retry incremented retry_count with no cap, so a
|
||||
// task that fails every time could be retried forever. At the cap the task
|
||||
// belongs in dead, which is what the setting exists to express.
|
||||
func TestRetryEnforcesMaxRetries(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
priorCount int
|
||||
maxRetries int
|
||||
wantStatus int
|
||||
wantTask string
|
||||
}{
|
||||
{name: "under the cap", priorCount: 0, maxRetries: 3, wantStatus: http.StatusOK, wantTask: store.StatusQueued},
|
||||
{name: "one below the cap", priorCount: 2, maxRetries: 3, wantStatus: http.StatusOK, wantTask: store.StatusQueued},
|
||||
{name: "at the cap", priorCount: 3, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: store.StatusDead},
|
||||
{name: "past the cap", priorCount: 5, maxRetries: 3, wantStatus: http.StatusConflict, wantTask: store.StatusDead},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, store.StatusParked, "it broke")
|
||||
srv.Cfg = &config.Config{MaxRetries: tc.maxRetries}
|
||||
ctx := t.Context()
|
||||
for range tc.priorCount {
|
||||
if err := srv.Store.IncrementRetryCount(ctx, task.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
w := postAction(t, srv, task.ID, "retry")
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body)
|
||||
}
|
||||
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != tc.wantTask {
|
||||
t.Errorf("status = %q, want %q", got.Status, tc.wantTask)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Rejecting a task must stop the forge issue coming back. It stays open,
|
||||
// labelled and assigned otherwise, so the next poll re-enqueues it -- and if
|
||||
// the operator has used the dashboard's Clear, which deletes the row, that is
|
||||
// a second implementation and a second PR for work already declined.
|
||||
func TestRejectClosesTheForgeIssue(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
if len(closer.calls) != 1 {
|
||||
t.Fatalf("CloseIssue calls = %d, want 1: the issue stays open and is "+
|
||||
"re-polled, so the work is done twice", len(closer.calls))
|
||||
}
|
||||
call := closer.calls[0]
|
||||
if call.owner != "acme" || call.repo != "widget" || call.number != 11 {
|
||||
t.Errorf("closed %s/%s#%d, want acme/widget#11", call.owner, call.repo, call.number)
|
||||
}
|
||||
if call.comment == "" {
|
||||
t.Error("closed with no comment: an issue that closes itself with no " +
|
||||
"explanation reads as archie losing the work")
|
||||
}
|
||||
}
|
||||
|
||||
// Approve and retry put the task back to work, so the issue must stay open.
|
||||
func TestApproveAndRetryDoNotCloseTheIssue(t *testing.T) {
|
||||
for _, tc := range []struct{ action, status, reason string }{
|
||||
{"approve", store.StatusWaitingHuman, "review"},
|
||||
{"retry", store.StatusParked, "it broke"},
|
||||
} {
|
||||
t.Run(tc.action, func(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, tc.status, tc.reason)
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called %d times for %s; the task is going "+
|
||||
"back to work", len(closer.calls), tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A chat-sourced task has a synthetic issue number that matches no forge
|
||||
// issue, so closing it would either error or close an unrelated issue.
|
||||
func TestRejectDoesNotCloseAChatTaskIssue(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
closer := &recordingCloser{}
|
||||
srv.Issues = closer
|
||||
srv.Cfg = &config.Config{MaxRetries: 3}
|
||||
|
||||
task, err := srv.Store.EnqueueChatTask(ctx, "acme", "widget", "chat task", "", "", "", 900001)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := srv.Store.ClaimNext(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
if len(closer.calls) != 0 {
|
||||
t.Errorf("CloseIssue called for a chat task: issue number %d is synthetic",
|
||||
task.IssueNumber)
|
||||
}
|
||||
}
|
||||
|
||||
// A forge that cannot close the issue must not fail the action: the operator's
|
||||
// decision is already recorded in the store, and reporting failure would
|
||||
// invite them to click again.
|
||||
func TestRejectSurvivesAForgeFailure(t *testing.T) {
|
||||
srv, task, closer, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
closer.err = errors.New("forge unreachable")
|
||||
|
||||
if w := postAction(t, srv, task.ID, "reject"); w.Code != http.StatusOK {
|
||||
t.Fatalf("reject status = %d, want 200: the store transition succeeded", w.Code)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(t.Context(), task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusClosedWontDo {
|
||||
t.Errorf("status = %q, want %q", got.Status, store.StatusClosedWontDo)
|
||||
}
|
||||
}
|
||||
|
||||
// Actions wrote store rows and nothing else, so the activity stream and the
|
||||
// task timeline never showed that a human had intervened -- the one kind of
|
||||
// event most worth seeing.
|
||||
func TestActionsEmitEvents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
action string
|
||||
status string
|
||||
reason string
|
||||
wantMsg string
|
||||
}{
|
||||
{name: "approve", action: "approve", status: store.StatusWaitingHuman, reason: "review", wantMsg: "approve"},
|
||||
{name: "retry", action: "retry", status: store.StatusParked, reason: "it broke", wantMsg: "retry"},
|
||||
{name: "reject", action: "reject", status: store.StatusWaitingHuman, reason: "review", wantMsg: "reject"},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, sub := actionServer(t, tc.status, tc.reason)
|
||||
|
||||
if w := postAction(t, srv, task.ID, tc.action); w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body %s", w.Code, w.Body)
|
||||
}
|
||||
|
||||
select {
|
||||
case ev := <-sub.C:
|
||||
if ev.TaskID != task.ID {
|
||||
t.Errorf("event TaskID = %d, want %d", ev.TaskID, task.ID)
|
||||
}
|
||||
if ev.Kind == "" {
|
||||
t.Error("event Kind is empty")
|
||||
}
|
||||
default:
|
||||
t.Fatalf("%s emitted no event: the activity stream and timeline "+
|
||||
"never show that a human intervened", tc.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Error mapping. A store failure is not the client's fault, and returning 409
|
||||
// tells the UI to say "conflict" for what is actually a broken database.
|
||||
func TestTaskActionErrorMapping(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
setup func(t *testing.T, srv *Server, id int64)
|
||||
id func(id int64) string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "unknown action",
|
||||
body: `{"action":"detonate"}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "malformed body",
|
||||
body: `not json`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "non-numeric id",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "banana" },
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "unknown task",
|
||||
body: `{"action":"approve"}`,
|
||||
id: func(int64) string { return "424242" },
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "wrong state",
|
||||
body: `{"action":"retry"}`,
|
||||
// The task is waiting_human, not parked.
|
||||
wantStatus: http.StatusConflict,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
srv, task, _, _, _ := actionServer(t, store.StatusWaitingHuman, "review")
|
||||
if tc.setup != nil {
|
||||
tc.setup(t, srv, task.ID)
|
||||
}
|
||||
path := strconv.FormatInt(task.ID, 10)
|
||||
if tc.id != nil {
|
||||
path = tc.id(task.ID)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
|
||||
"/api/tasks/"+path+"/action", bytes.NewBufferString(tc.body))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != tc.wantStatus {
|
||||
t.Fatalf("status = %d, want %d (body %s)", w.Code, tc.wantStatus, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A store write failure is a 500, not a 409.
|
||||
func TestTaskActionStoreFailureIs500(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := base.Store.EnqueueIssue(ctx, "acme", "widget", 11, "a task", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := base.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("ClaimNext = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := base.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, requeueErr: errors.New("db locked")},
|
||||
Log: base.Log,
|
||||
Cfg: &config.Config{MaxRetries: 3},
|
||||
}
|
||||
w := postAction(t, srv, task.ID, "approve")
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500: a store failure is not a conflict", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package webui
|
||||
|
||||
// Tests for the task-timeline route. The dashboard's "Click a row for its
|
||||
// timeline" interaction depends on GET /api/tasks/{id} returning exactly that
|
||||
// task's events, ordered, and on the literal /api/tasks/clear route beating
|
||||
// the {id} wildcard.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Approve requeues from the task's own recorded state rather than anything
|
||||
// the caller supplies, so a stale dashboard cannot approve a task twice.
|
||||
func TestHandleTaskActionApproveUsesRecordedState(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "approve me", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusWaitingHuman, "review"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"approve"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("approve status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusQueued || got.Workflow != "implement" {
|
||||
t.Fatalf("approved task = %+v, want queued/implement", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleTaskActionRetriesParkedTask(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
if _, err := srv.Store.EnqueueIssue(ctx, "acme", "widget", 1, "retry me", "", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := srv.Store.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%+v, %v)", task, err)
|
||||
}
|
||||
if err := srv.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "failed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodPost, "/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewBufferString(`{"action":"retry"}`))
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("retry status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
got, err := srv.Store.TaskByID(ctx, task.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID = (%+v, %v)", got, err)
|
||||
}
|
||||
if got.Status != store.StatusQueued || got.RetryCount != 1 {
|
||||
t.Fatalf("retried task = %+v, want queued/retry_count=1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskIsolatesTasks returns the timeline for one task, and only
|
||||
// that task: another task's events must not leak into the response.
|
||||
func TestHandleTaskIsolatesTasks(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
for _, ev := range []events.Event{
|
||||
{TaskID: 7, Kind: "stage_start", Stage: "plan", Detail: "bootstrap"},
|
||||
{TaskID: 7, Kind: "stage_end", Stage: "plan"},
|
||||
{TaskID: 8, Kind: "stage_start", Stage: "implement"},
|
||||
} {
|
||||
if _, err := srv.Store.InsertEvent(ctx, ev); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/api/tasks/7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, body = %s", w.Code, w.Body)
|
||||
}
|
||||
var got []events.Event
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("timeline has %d events, want 2 (task 8 must not leak in)", len(got))
|
||||
}
|
||||
if got[0].Kind != "stage_start" || got[0].Stage != "plan" {
|
||||
t.Errorf("first event = %+v, want stage_start/plan", got[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskUnknownID returns an empty list, not an error, for a task id
|
||||
// that has no events yet -- the UI renders "No events yet" from that.
|
||||
func TestHandleTaskUnknownID(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/999", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if body := strings.TrimSpace(w.Body.String()); body != "null" && body != "[]" {
|
||||
t.Fatalf("body = %s, want an empty timeline", body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleTaskBadID is covered in webui_test.go (400 on a non-numeric id).
|
||||
|
||||
// TestHandleTaskStoreError proves a store failure surfaces as 500 -- the UI
|
||||
// shows its "Could not load timeline" state and offers a retry.
|
||||
func TestHandleTaskStoreError(t *testing.T) {
|
||||
base := newTestServer(t)
|
||||
srv := &Server{
|
||||
Store: &stubStore{TaskStore: base.Store, taskEventsErr: fmt.Errorf("db locked")},
|
||||
Log: base.Log,
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/7", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleClearTasksProvenance proves the literal /api/tasks/clear route is
|
||||
// not captured by the {id} wildcard (which would 400 on "clear").
|
||||
func TestHandleClearTasksProvenance(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/tasks/clear", nil)
|
||||
w := httptest.NewRecorder()
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d, want 200 — /api/tasks/clear was captured by {id}", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -39,10 +39,33 @@ type Server struct {
|
||||
// stay frictionless -- see IsLoopback.
|
||||
Token string
|
||||
|
||||
// Issues closes the forge issue behind a rejected task. Optional: the
|
||||
// action still records the operator's decision without it, and says so
|
||||
// in the log. Deliberately the narrowest interface that does the job
|
||||
// rather than the whole forge client -- the dashboard has no business
|
||||
// commenting, labelling or opening PRs.
|
||||
Issues IssueCloser
|
||||
|
||||
// Events publishes operator actions so they reach the task timeline and
|
||||
// the live activity stream. Optional: nil means the action is recorded
|
||||
// in the store but invisible to anyone watching.
|
||||
Events EventPublisher
|
||||
|
||||
mu sync.Mutex
|
||||
conns map[chan events.Event]struct{}
|
||||
}
|
||||
|
||||
// IssueCloser closes the forge issue behind a task.
|
||||
type IssueCloser interface {
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
}
|
||||
|
||||
// EventPublisher accepts events for the store and the live stream. The bus
|
||||
// in cmd/archied satisfies it.
|
||||
type EventPublisher interface {
|
||||
Publish(events.Event)
|
||||
}
|
||||
|
||||
// Broadcast fans an (ID-stamped) event out to every connected SSE
|
||||
// client; stalled clients drop events rather than blocking the caller.
|
||||
func (s *Server) Broadcast(e events.Event) {
|
||||
@@ -61,6 +84,7 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.HandleFunc("GET /api/summary", s.handleSummary)
|
||||
mux.HandleFunc("GET /api/setup", s.handleSetup)
|
||||
mux.HandleFunc("GET /api/tasks", s.handleTasks)
|
||||
mux.HandleFunc("POST /api/tasks/{id}/action", s.handleTaskAction)
|
||||
mux.HandleFunc("GET /api/tasks/{id}", s.handleTask)
|
||||
mux.HandleFunc("GET /api/tasks/clear", s.handleClearTasks)
|
||||
mux.HandleFunc("GET /api/workflows", s.handleWorkflows)
|
||||
|
||||
@@ -49,6 +49,15 @@ type stubStore struct {
|
||||
stageStatsErr error
|
||||
tokensByDayErr error
|
||||
eventsSinceErr error
|
||||
taskEventsErr error
|
||||
requeueErr error
|
||||
}
|
||||
|
||||
func (s *stubStore) Requeue(ctx context.Context, id int64, from, workflow string) error {
|
||||
if s.requeueErr != nil {
|
||||
return s.requeueErr
|
||||
}
|
||||
return s.TaskStore.Requeue(ctx, id, from, workflow)
|
||||
}
|
||||
|
||||
func (s *stubStore) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error) {
|
||||
@@ -79,6 +88,13 @@ func (s *stubStore) EventsSince(ctx context.Context, sinceID int64, limit int) (
|
||||
return s.TaskStore.EventsSince(ctx, sinceID, limit)
|
||||
}
|
||||
|
||||
func (s *stubStore) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error) {
|
||||
if s.taskEventsErr != nil {
|
||||
return nil, s.taskEventsErr
|
||||
}
|
||||
return s.TaskStore.TaskEvents(ctx, taskID)
|
||||
}
|
||||
|
||||
func TestHandleSummary(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
ctx := t.Context()
|
||||
|
||||
@@ -62,8 +62,7 @@ func Feasibility() Workflow {
|
||||
tc.decision = &decision{Fit: *captured.Fit, Reasons: captured.Reasons}
|
||||
if !tc.decision.Fit {
|
||||
if tc.Task.IsForgeBacked() {
|
||||
comment := fmt.Sprintf("**archie assessed this feature as not a fit -- closing as won't-do.**\n\n%s\n\n_Reopen and re-assign if you disagree._", tc.decision.Reasons)
|
||||
if err := tc.Forge.CloseIssue(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, comment); err != nil {
|
||||
if err := tc.Forge.CloseIssue(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -94,18 +93,9 @@ func Feasibility() Workflow {
|
||||
},
|
||||
}.Stage(),
|
||||
|
||||
// Deliver the PRD and block on Sam: issue comment (the reply
|
||||
// channel the daemon watches) plus the notify webhook (n8n →
|
||||
// email).
|
||||
// Persist the PRD and block on Sam. Messaging and the Web UI are
|
||||
// the decision surfaces; the forge issue is not a chat log.
|
||||
{Name: "deliver", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
if tc.Task.IsForgeBacked() {
|
||||
body := fmt.Sprintf("**archie's PRD -- awaiting your go/no-go.** Reply on this issue; I'll read your answer.\n\n%s", tc.Task.Plan)
|
||||
commentID, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tc.Task.WatchCommentID = commentID
|
||||
}
|
||||
notify(ctx, tc, "feasibility_prd")
|
||||
tc.Outcome = Outcome{Status: store.StatusWaitingHuman, Detail: "PRD delivered, awaiting go/no-go"}
|
||||
return nil
|
||||
|
||||
@@ -119,13 +119,6 @@ func Implement() Workflow {
|
||||
},
|
||||
OnResult: func(tc *TaskContext, res agentexec.Result) error {
|
||||
tc.Task.Plan = res.Summary
|
||||
if !tc.Task.IsForgeBacked() {
|
||||
return nil
|
||||
}
|
||||
body := fmt.Sprintf("**archie's plan** (review now if you want to veto -- building starts immediately):\n\n%s", res.Summary)
|
||||
if _, err := tc.Forge.Comment(context.Background(), tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil {
|
||||
tc.Log.Warn("failed to post plan comment", "err", err)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}.Stage(),
|
||||
@@ -166,8 +159,7 @@ func Implement() Workflow {
|
||||
StageDiffCap(),
|
||||
StageOpenPR(func(tc *TaskContext) string {
|
||||
return fmt.Sprintf("%s\n\n---\n*workflow: implement · %d iterations · %d tokens*",
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed) +
|
||||
issueClosureReference(tc.Task)
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,9 +2,10 @@ package workflow
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
@@ -13,6 +14,9 @@ import (
|
||||
type fakeForge struct {
|
||||
closed int
|
||||
commented []string
|
||||
calls []string
|
||||
linkErr error
|
||||
prNumber int
|
||||
}
|
||||
|
||||
func (f *fakeForge) CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error {
|
||||
@@ -40,7 +44,11 @@ func (f *fakeForge) IssuesWithLabel(ctx context.Context, owner, repo, label stri
|
||||
}
|
||||
|
||||
func (f *fakeForge) CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error) {
|
||||
return 0, nil
|
||||
f.calls = append(f.calls, "pr:"+head)
|
||||
// A real forge never answers 0, and returning it let a test pass while
|
||||
// the PR number was never recorded.
|
||||
f.prNumber++
|
||||
return f.prNumber, nil
|
||||
}
|
||||
|
||||
func (f *fakeForge) PRState(ctx context.Context, owner, repo string, number int) (string, error) {
|
||||
@@ -57,6 +65,11 @@ func (f *fakeForge) RepliesAfter(ctx context.Context, owner, repo string, number
|
||||
|
||||
func (f *fakeForge) SetStateLabel(ctx context.Context, owner, repo string, number int, label string, known []string) {
|
||||
}
|
||||
|
||||
func (f *fakeForge) LinkBranch(ctx context.Context, owner, repo string, number int, branch string) error {
|
||||
f.calls = append(f.calls, "link:"+branch)
|
||||
return f.linkErr
|
||||
}
|
||||
func (f *fakeForge) VerifyPush(ctx context.Context, owner, repo string) error { return nil }
|
||||
|
||||
// TestStageCommitPushClosesIssueWhenBuildNoChanges verifies that
|
||||
@@ -94,15 +107,24 @@ func TestStageCommitPushClosesIssueWhenBuildNoChanges(t *testing.T) {
|
||||
t.Log("Outcome set to Merged (workflow stops)")
|
||||
}
|
||||
|
||||
found := false
|
||||
for _, c := range f.commented {
|
||||
if strings.Contains(c, "no changes required") {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if len(f.commented) != 0 {
|
||||
t.Errorf("expected no forge comments, got %d", len(f.commented))
|
||||
}
|
||||
if !found {
|
||||
t.Error("expected a comment about no changes required")
|
||||
}
|
||||
|
||||
func TestOpenPRLinksSourceBranchBeforeCreatingPR(t *testing.T) {
|
||||
f := &fakeForge{}
|
||||
tc := &TaskContext{
|
||||
Forge: f,
|
||||
Task: &store.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",
|
||||
}
|
||||
if err := OpenPR(context.Background(), tc, "summary"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(f.calls) != 2 || f.calls[0] != "link:fix/42-bug" || f.calls[1] != "pr:fix/42-bug" {
|
||||
t.Fatalf("forge calls = %v, want [link:fix/42-bug pr:fix/42-bug]", f.calls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,19 +155,43 @@ func TestStageCommitPushDoesNotUseSyntheticIssueForChatNoOp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssueClosureReferenceOnlyForForgeTasks(t *testing.T) {
|
||||
// LinkBranch is cosmetic: it puts the branch in the issue's sidebar on Gitea
|
||||
// and does nothing at all on GitHub. Failing the stage on it meant the pull
|
||||
// request -- the entire point of the run -- was never opened, and the task
|
||||
// parked. Worse, a retry re-links the same branch, which Gitea answers with
|
||||
// a conflict, so every retry parked again.
|
||||
func TestOpenPRSurvivesALinkBranchFailure(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
task *store.Task
|
||||
want string
|
||||
name string
|
||||
linkErr error
|
||||
}{
|
||||
{name: "forge", task: &store.Task{IssueNumber: 42}, want: "\n\nCloses #42"},
|
||||
{name: "chat", task: &store.Task{IssueNumber: 999_001, Source: store.SourceChat}, want: ""},
|
||||
{name: "already linked", linkErr: errors.New("409 Conflict: branch already linked")},
|
||||
{name: "endpoint unavailable", linkErr: errors.New("404 Not Found")},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := issueClosureReference(tt.task); got != tt.want {
|
||||
t.Errorf("issueClosureReference() = %q, want %q", got, tt.want)
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fakeForge{linkErr: tc.linkErr}
|
||||
taskCtx := &TaskContext{
|
||||
Forge: f,
|
||||
Task: &store.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",
|
||||
}
|
||||
|
||||
if err := OpenPR(context.Background(), taskCtx, "summary"); err != nil {
|
||||
t.Fatalf("OpenPR: %v\nthe PR is the load-bearing step; cosmetic "+
|
||||
"linkage must not stop it", err)
|
||||
}
|
||||
if taskCtx.Outcome.Status != store.StatusPROpen {
|
||||
t.Errorf("Outcome.Status = %q, want %q", taskCtx.Outcome.Status, store.StatusPROpen)
|
||||
}
|
||||
if taskCtx.Task.PRNumber == 0 {
|
||||
t.Error("PRNumber is 0: the pull request was never opened")
|
||||
}
|
||||
// The link is still attempted -- it is useful when it works.
|
||||
if len(f.calls) != 2 || f.calls[0] != "link:fix/42-bug" {
|
||||
t.Errorf("forge calls = %v, want the link attempted before the PR", f.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
+16
-13
@@ -69,10 +69,6 @@ func closeNoChangesIssue(ctx context.Context, tc *TaskContext) error {
|
||||
tc.Outcome = Outcome{Status: store.StatusMerged, Detail: "completed -- no changes required"}
|
||||
return nil
|
||||
}
|
||||
body := fmt.Sprintf("**archie closed this issue -- no changes required.**\n\n%s", tc.BuildSummary)
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, body); err != nil {
|
||||
tc.Log.Warn("no-op close comment failed", "err", err)
|
||||
}
|
||||
if err := tc.Forge.CloseIssue(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.IssueNumber, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -182,6 +178,21 @@ func StageYaegiGate() Stage {
|
||||
func OpenPR(ctx context.Context, tc *TaskContext, body string) error {
|
||||
t := tc.Task
|
||||
title := fmt.Sprintf("%s (archie)", t.Title)
|
||||
if t.IsForgeBacked() {
|
||||
// Best-effort. The link is cosmetic -- it puts the branch in the
|
||||
// issue's sidebar on Gitea and does nothing on GitHub -- so failing
|
||||
// the stage on it meant the pull request, the entire point of the
|
||||
// run, was never opened and the task parked. A retry then re-links
|
||||
// the same branch, which Gitea answers with a conflict, so every
|
||||
// retry parked again.
|
||||
if err := tc.Forge.LinkBranch(ctx, t.Owner, t.Repo, t.IssueNumber, tc.Branch); err != nil {
|
||||
if tc.Log != nil {
|
||||
tc.Log.Warn("link branch to issue failed; opening the PR anyway",
|
||||
"repo", t.Owner+"/"+t.Repo, "issue", t.IssueNumber,
|
||||
"branch", tc.Branch, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
num, err := tc.Forge.CreatePR(ctx, t.Owner, t.Repo, title, tc.Branch, tc.Repo.BaseBranch(), body)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -198,13 +209,6 @@ func StageOpenPR(body func(*TaskContext) string) Stage {
|
||||
}}
|
||||
}
|
||||
|
||||
func issueClosureReference(task *store.Task) string {
|
||||
if !task.IsForgeBacked() {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("\n\nCloses #%d", task.IssueNumber)
|
||||
}
|
||||
|
||||
func taskPromptBlock(task *store.Task) string {
|
||||
if task.IsForgeBacked() {
|
||||
return fmt.Sprintf("<issue number=%d>\n# %s\n\n%s\n</issue>",
|
||||
@@ -250,8 +254,7 @@ func Bootstrap() Workflow {
|
||||
}),
|
||||
StageDiffCap(),
|
||||
StageOpenPR(func(tc *TaskContext) string {
|
||||
return "Deterministic bootstrap PR from archie's plumbing walk-through." +
|
||||
issueClosureReference(tc.Task)
|
||||
return "Deterministic bootstrap PR from archie's plumbing walk-through."
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -132,17 +132,10 @@ func TDD() Workflow {
|
||||
// evidence the bug was reproduced before the fix.
|
||||
{Name: "open-pr", Run: func(ctx context.Context, tc *TaskContext) error {
|
||||
body := fmt.Sprintf("%s\n\n---\n*workflow: tdd (failing repro committed first) · %d iterations · %d tokens*",
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed) +
|
||||
issueClosureReference(tc.Task)
|
||||
tc.BuildSummary, tc.Task.Iterations, tc.Task.TokensUsed)
|
||||
if err := OpenPR(ctx, tc, body); err != nil {
|
||||
return err
|
||||
}
|
||||
if tc.ReproProof != "" {
|
||||
proof := fmt.Sprintf("**Proof the repro tests failed before the fix** (commit 1 of this PR):\n\n```\n%s\n```", tc.ReproProof)
|
||||
if _, err := tc.Forge.Comment(ctx, tc.Task.Owner, tc.Task.Repo, tc.Task.PRNumber, proof); err != nil {
|
||||
tc.Log.Warn("failed to post repro proof", "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
},
|
||||
|
||||
@@ -23,10 +23,9 @@ import (
|
||||
// forge.Forge (the daemon's real implementations) and forgerpc.Client
|
||||
// (archie-agent's NATS-backed proxy) both satisfy it.
|
||||
type Forger interface {
|
||||
Comment(ctx context.Context, owner, repo string, number int, body string) (int64, error)
|
||||
CloseIssue(ctx context.Context, owner, repo string, number int, comment string) error
|
||||
CreatePR(ctx context.Context, owner, repo, title, head, base, body string) (int, error)
|
||||
SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string)
|
||||
LinkBranch(ctx context.Context, owner, repo string, issueNumber int, branch string) error
|
||||
}
|
||||
|
||||
// Trees is the subset of *worktree.Manager that workflow stages call
|
||||
@@ -220,50 +219,16 @@ func finish(ctx context.Context, tc *TaskContext, log *slog.Logger) {
|
||||
}
|
||||
_ = tc.Store.Update(ctx, t)
|
||||
_ = tc.Store.Transition(ctx, t.ID, store.StatusRunning, tc.Outcome.Status, tc.Outcome.Detail)
|
||||
if t.IsForgeBacked() {
|
||||
tc.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, stateLabelFor(tc.Cfg.Dispatch, tc.Outcome.Status), tc.Cfg.Dispatch.LabelValues())
|
||||
}
|
||||
tc.Emit(events.KindOutcome, t.Stage, tc.Outcome.Detail, map[string]any{"status": tc.Outcome.Status})
|
||||
log.Info("workflow finished", "status", tc.Outcome.Status)
|
||||
}
|
||||
|
||||
// stateLabelFor maps a terminal workflow status to its forge label by
|
||||
// looking up the configured [dispatch.labels]; empty clears (done states
|
||||
//
|
||||
// -- the issue closes or the PR speaks).
|
||||
func stateLabelFor(d config.Dispatch, status string) string {
|
||||
switch status {
|
||||
case store.StatusPROpen:
|
||||
return d.StateLabel("pr")
|
||||
case store.StatusWaitingHuman:
|
||||
return d.StateLabel("waiting")
|
||||
case store.StatusParked:
|
||||
return d.StateLabel("parked")
|
||||
case store.StatusDead:
|
||||
return d.StateLabel("dead")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func park(ctx context.Context, tc *TaskContext, reason string) {
|
||||
t := tc.Task
|
||||
t.ParkReason = reason
|
||||
_ = tc.Store.Update(ctx, t)
|
||||
_ = tc.Store.Transition(ctx, t.ID, store.StatusRunning, store.StatusParked, reason)
|
||||
tc.Emit(events.KindParked, t.Stage, reason, nil)
|
||||
if !t.IsForgeBacked() {
|
||||
// Chat-sourced tasks have no real forge issue to label or
|
||||
// comment on; the park reason is visible via /status and the
|
||||
// task's ParkReason field instead.
|
||||
return
|
||||
}
|
||||
tc.Forge.SetStateLabel(ctx, t.Owner, t.Repo, t.IssueNumber, tc.Cfg.Dispatch.StateLabel("parked"), tc.Cfg.Dispatch.LabelValues())
|
||||
body := fmt.Sprintf("**archie parked this task.**\n\n```\n%s\n```\n\nThe worktree is kept for inspection.",
|
||||
clip(reason, 3000))
|
||||
if _, err := tc.Forge.Comment(ctx, t.Owner, t.Repo, t.IssueNumber, body); err != nil {
|
||||
tc.Log.Error("failed to post park comment", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func clip(s string, n int) string {
|
||||
|
||||
Vendored
+1
-1
@@ -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);padding-right:var(--sp-4);font-weight:500}.nav-item .nav-label{display:none}.nav-item[aria-current=page] .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)}.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;baLine 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}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);padding-right:var(--sp-4);font-weight:500}.nav-item .nav-label{display:none}.nav-item[aria-current=page] .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)}.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;baLine truncated
|
||||
Vendored
+3
-2
@@ -1,8 +1,9 @@
|
||||
(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:`<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>`,tasks:`<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>`,logs:`<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>`,skills:`<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>`,workflows:`<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>`,memory:`<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>`,channels:`<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>`,settings:`<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>`,search:`<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>`,moon:`<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>`,sun:`<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>`,refresh:`<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>`,bell:`<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>`,trendUp:`<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>`,trendDown:`<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>`,check:`<path d="M4.5 12.5l5 5 10-11"/>`,help:`<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>`};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`}});if(t.status===401)throw new f(`unauthorised`,401);if(!t.ok)throw new f(`${t.status} ${t.statusText}`,t.status);return t.json()}function d(e){let t=new URLSearchParamLine 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)}})();function e(e,n,...r){let[i,...a]=e.split(`.`),o=document.createElement(i||`div`);a.length&&(o.className=a.join(` `)),n!==void 0&&(typeof n!=`object`||n instanceof Node)&&(r.unshift(n),n=null);for(let[e,t]of Object.entries(n||{}))t!=null&&t!==!1&&(e.startsWith(`on`)&&typeof t==`function`?o.addEventListener(e.slice(2).toLowerCase(),t):e===`class`?o.className=[o.className,t].filter(Boolean).join(` `):e===`html`?o.innerHTML=t:o.setAttribute(e,t===!0?``:String(t)));return t(o,r),o}function t(e,t){for(let n of t.flat(1/0))n!=null&&n!==!1&&e.append(n instanceof Node?n:document.createTextNode(String(n)))}function n(e,...n){return e.replaceChildren(),t(e,n),e}function r(t,n=`idle`){return e(`span.pill.pill-${n}`,t)}function i(e){switch(e){case`running`:return`info`;case`merged`:case`pr_open`:return`ok`;case`parked`:case`waiting_human`:return`warn`;case`dead`:case`rejected`:return`danger`;default:return`idle`}}function a(e){if(!e)return`—`;let t=e instanceof Date?e:new Date(e),n=Math.floor((Date.now()-t.getTime())/1e3);if(!Number.isFinite(n))return`—`;if(n<45)return`just now`;let r=[[`min`,60],[`hr`,3600],[`day`,86400],[`wk`,604800]],i=`min`,a=60;for(let[e,t]of r)n>=t&&([i,a]=[e,t]);let o=Math.floor(n/a);return`${o} ${i}${o===1?``:`s`} ago`}function o(e){return e==null||Number.isNaN(e)?`—`:new Intl.NumberFormat(void 0,{notation:`compact`,maximumFractionDigits:1}).format(e)}function s(t,n){return e(`div.empty`,e(`div.empty-title`,t),n&&e(`div`,n))}var c={dashboard:`<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>`,tasks:`<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6l1 1 2-2M4 12l1 1 2-2M4 18l1 1 2-2"/>`,logs:`<path d="M4 5h16M4 10h16M4 15h10M4 20h7"/>`,skills:`<path d="M12 3l2.6 5.6 6.1.8-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6L3.3 9.4l6.1-.8z"/>`,workflows:`<path d="M4 7h6a3 3 0 0 1 3 3v4a3 3 0 0 0 3 3h4"/><path d="M17 4l3 3-3 3"/><path d="M7 21l-3-3 3-3"/>`,memory:`<circle cx="12" cy="12" r="3.2"/><path d="M12 3v3.4M12 17.6V21M3 12h3.4M17.6 12H21M5.6 5.6l2.4 2.4M16 16l2.4 2.4M18.4 5.6L16 8M8 16l-2.4 2.4"/>`,channels:`<rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3.5 7l8.5 6 8.5-6"/>`,settings:`<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.9l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-2.9 1.2V21a2 2 0 1 1-4 0v-.1A1.7 1.7 0 0 0 7 19.4a1.7 1.7 0 0 0-1.9.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1A1.7 1.7 0 0 0 3 15H3a2 2 0 1 1 0-4h.1A1.7 1.7 0 0 0 4.6 7a1.7 1.7 0 0 0-.3-1.9l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1A1.7 1.7 0 0 0 9 3.6V3a2 2 0 1 1 4 0v.1A1.7 1.7 0 0 0 15 4.6h.1a1.7 1.7 0 0 0 1.9-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.9V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>`,search:`<circle cx="11" cy="11" r="7"/><path d="M20 20l-3.6-3.6"/>`,moon:`<path d="M20 14.5A8.5 8.5 0 0 1 9.5 4a8.5 8.5 0 1 0 10.5 10.5z"/>`,sun:`<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M2 12h2M20 12h2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M19.1 4.9l-1.4 1.4M6.3 17.7l-1.4 1.4"/>`,refresh:`<path d="M20 11a8 8 0 1 0-1.2 5.2"/><path d="M20 4v7h-7"/>`,bell:`<path d="M18 9a6 6 0 1 0-12 0c0 6-2 7-2 7h16s-2-1-2-7"/><path d="M13.7 20a2 2 0 0 1-3.4 0"/>`,trendUp:`<path d="M4 17L10 11l4 4 6-6"/><path d="M14 7h6v6"/>`,trendDown:`<path d="M4 7l6 6 4-4 6 6"/><path d="M14 17h6v-6"/>`,check:`<path d="M4.5 12.5l5 5 10-11"/>`,help:`<circle cx="12" cy="12" r="9"/><path d="M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.4"/><path d="M12 17.2h.01"/>`};function l(e,{size:t=18,className:n=``}={}){let r=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);return r.setAttribute(`viewBox`,`0 0 24 24`),r.setAttribute(`width`,String(t)),r.setAttribute(`height`,String(t)),r.setAttribute(`fill`,`none`),r.setAttribute(`stroke`,`currentColor`),r.setAttribute(`stroke-width`,`1.6`),r.setAttribute(`stroke-linecap`,`round`),r.setAttribute(`stroke-linejoin`,`round`),r.setAttribute(`aria-hidden`,`true`),r.setAttribute(`class`,`ico ${n}`.trim()),r.innerHTML=c[e]||c.dashboard,r}async function u(e){let t=await fetch(e,{headers:{Accept:`application/json`},signal:AbortSignal.timeout(15e3)});if(t.status===401)throw new p(`unauthorised`,401);if(!t.ok)throw new p(`${t.status} ${t.statusText}`,t.status);return t.jsoLine truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var p=class extends Error{constructor(e,t){super(e),this.status=t}},m={summary:()=>u(`/api/summary`),tasks:()=>u(`/api/tasks`),task:e=>u(`/api/tasks/${e}`),taskAction:async(e,t)=>{let n=await fetch(`/api/tasks/${e}/action`,{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({action:t}),signal:AbortSignal.timeout(15e3)});if(!n.ok)throw new p(await f(n),n.status);return n.json()},setup:()=>u(`/api/setup`),workflows:()=>u(`/api/workflows`),skills:()=>u(`/api/skills`),channels:()=>u(`/api/channels`),config:()=>u(`/api/config`),logs:e=>u(`/api/logs`+d(e)),memory:()=>u(`/api/memory`)};function h(e,t){let n=new EventSource(`/events`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function g({label:t,value:n,unit:r,trend:i,compare:a,series:o=[],goodDirection:s=`up`}){let c=i==null?null:i>=0?`up`:`down`,u=c==null?null:c===s;return e(`div.card.stat`,e(`div.stat-head`,e(`span.stat-label`,t),c&&e(`span.stat-trend.${u?`up`:`down`}`,l(c===`up`?`trendUp`:`trendDown`,{size:13}),`${Math.abs(i).toFixed(1)}%`)),e(`div.stat-value`,n,r&&e(`span.stat-unit`,r)),a&&e(`div.stat-compare`,a),o.length>1&&_(o,u===!1?`var(--danger)`:`var(--ok)`))}function _(t,n=`var(--ok)`,{width:r=220,height:i=34}={}){let a=Math.max(...t,1),o=Math.min(...t,0),s=a-o||1,c=t.length>1?r/(t.length-1):r,l=t.map((e,t)=>`${(t*c).toFixed(1)},${(i-(e-o)/s*i).toFixed(1)}`).join(` `),u=e(`svg.spark`,{viewBox:`0 0 ${r} ${i}`,preserveAspectRatio:`none`,"aria-hidden":`true`});return u.innerHTML=`<polyline points="${l}" fill="none" stroke="${n}" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`,u}function v({value:t,label:n,size:r=168}){let i=Math.max(0,Math.min(100,Number(t)||0)),a=i>=90?`var(--ok)`:i>=70?`var(--warn)`:`var(--danger)`,o=r/2,s=r/2,c=2*Math.PI*62*(240/360),l=(e,t)=>{let n=e*Math.PI/180,r=(e+t)*Math.PI/180,i=+(t>180);return[`M ${o+62*Math.cos(n)} ${s+62*Math.sin(n)}`,`A 62 62 0 ${i} 1 ${o+62*Math.cos(r)} ${s+62*Math.sin(r)}`].join(` `)},u=e(`svg.gauge`,{viewBox:`0 0 ${r} ${r*.78}`,role:`img`,"aria-label":`${n}: ${i}%`});return u.innerHTML=`
|
||||
<path d="${l(150,240)}" fill="none" stroke="var(--border)"
|
||||
stroke-width="12" stroke-linecap="round"/>
|
||||
<path d="${l(150,240)}" fill="none" stroke="${a}"
|
||||
stroke-width="12" stroke-linecap="round"
|
||||
stroke-dasharray="${c}"
|
||||
stroke-dashoffset="${c*(1-i/100)}"
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function v(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}function y(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div`),f=e(`div.hero-actions-inner`),g=e(`h1.hero-title`,x()),_=r(`connecting`,`idle`);y(),T();let v=m(e=>b(i,e),e=>{_.className=`pill pill-${e===`live`?`ok`:`warn`}`,_.textContent=e});t.addEventListener(`archie:teardown`,v);function y(){n(t,e(`div.hero`,e(`div`,g,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,f)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),e(`div.dash-top`,c,u)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,d,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),_),e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i))))),n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))))}async function T(){try{let[e,t,n]=await Promise.all([p.summary(),p.setup().catch(()=>null),p.workflows().catch(()=>null)]);E(e),g.textContent=t?.operator?`${x()}, ${t.operator}`:x(),D(e),O(t),k(e,n),A(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t))))}}function E(t){let r=t?.statuses||{},i=(r.parked||0)+(r.waiting_human||0),a=r.running||0;n(f,i>0&&e(`a.btn.btn-attention`,{href:`#/tasks`},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:`#/tasks`},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:T},l(`refresh`,{size:15}),`Refresh`))}function D(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,h({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),h({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),h({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),h({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:w(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function O(t){if(!t?.steps?.length)return n(c);let r=t.steps.filter(e=>!e.done);if(!r.length)return n(c);let i=Math.round((t.steps.length-r.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${i}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${i}%`})),e(`ul.setup-list`,...t.steps.map(j))))}function k(e,t){S(u,e,t)}function A(e){C(d,e)}function j(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function b(t,n){t.firstElementChild?.querySelector(`.empty`)&&t.replaceChildren();let r=e(`tr`,e(`td.strong`,e(`span`,n.kind||n.type||`event`)),e(`td.mono`,n.task_id?`#${n.task_id}`:`—`),e(`td`,n.detail||n.message||``),e(`td`,a(n.at||Date.now())));for(t.prepend(r);t.children.length>50;)t.lastElementChild.remove()}function x(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`Good morning`:e<18?`Good afternoon`:`Good evening`}function S(t,i,a){let o=a?.workflows||[],c=o.reduce((e,t)=>e+(t.runs||0),0),l=o.reduce((e,t)=>e+(t.merged||0)+(t.pr_open||0),0),u=o.reduce((e,t)=>e+(t.parked||0),0);if(!c){n(t,e(`div.card`,e(`div.card-head`,e(`h2.card-title`,`Gate pulse`)),s(`No completed runs yet`,`Once Archie finishes a task, its gate pass rate appears here.`)));return}let d=l/c*100;n(t,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Gate pulse`),e(`p.card-sub`,`Work that passed its quality gates`))),_({value:d,label:`pass rate`}),e(`ul.pulse-list`,...o.slice(0,3).map(t=>e(`li.pulse-item`,e(`span.pulse-name`,t.workflow||`workflow`),r(`${t.merged||0}/${t.runs||0}`,(t.merged||0)===(t.runs||0)?`ok`:(t.parked||0)>0?`warn`:`info`))),u>0&&e(`li.pulse-item`,e(`span.pulse-name`,`Parked, awaiting you`),r(String(u),`warn`)))))}functi
Line truncated
|
||||
class="gauge-value"/>`,e(`div.gauge-wrap`,u,e(`div.gauge-center`,e(`div.gauge-pct`,`${Math.round(i)}%`),e(`div.gauge-label`,n)))}function y(t){let n=t.reduce((e,t)=>e+(t.value||0),0)||1;return e(`div`,e(`div.segbar`,...t.filter(e=>e.value>0).map(t=>e(`span`,{class:`segbar-part segbar-${t.kind||`idle`}`,style:`width:${(t.value/n*100).toFixed(1)}%`,title:`${t.label}: ${t.value}`}))),e(`div.segbar-legend`,...t.map(t=>e(`span.segbar-key`,e(`span`,{class:`segbar-dot segbar-${t.kind||`idle`}`}),t.label))))}function b(){let t=e(`div`),i=e(`tbody`),a=e(`div.grid.grid-4`),c=e(`div`),u=e(`div`),d=e(`div.dash-top`,c,u),f=e(`div`),p=e(`div.hero-actions-inner`),_=e(`h1.hero-title`,C()),v=r(`connecting`,`idle`),y=[],b=new Map;D(),k();let S=h(e=>{y.unshift(e),y.splice(50),O()},e=>{v.className=`pill pill-${e===`live`?`ok`:`warn`}`,v.textContent=e});t.addEventListener(`archie:teardown`,S);function D(){n(t,e(`div.hero`,e(`div`,_,e(`p.hero-sub`,`Your agent's control room — what it is working on, what needs you, and what it is spending.`)),e(`div.hero-actions`,p)),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Health`)),d),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Throughput`),e(`span.dash-section-note`,`Across all repositories`)),a),e(`div.dash-section`,e(`div.dash-section-head`,e(`h2.dash-section-title`,`Right now`)),e(`div.dash-split`,f,e(`div.card`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Live activity`),e(`p.card-sub`,`Last 50, newest first`)),v),e(`div.table-scroll`,e(`table.table`,e(`thead`,e(`tr`,...[`Event`,`Task`,`Detail`,`When`].map(t=>e(`th`,t)))),i)))))),O()}function O(){if(!y.length){n(i,e(`tr`,e(`td`,{colspan:4},s(`Waiting for activity`,`Events appear here as Archie works.`))));return}n(i,...y.map(e=>x(e,b)))}async function k(){try{let[e,t,n,r]=await Promise.all([m.summary(),m.setup().catch(()=>null),m.workflows().catch(()=>null),m.tasks().catch(()=>[])]);b.clear();for(let e of r)e.owner&&e.repo&&e.issue_number&&b.set(`${e.owner}/${e.repo}#${e.issue_number}`,e.id);O(),A(e),_.textContent=t?.operator?`${C()}, ${t.operator}`:C(),j(e),M(t),N(e,n),P(e)}catch(t){n(a,e(`div.card`,s(`Cannot reach archied`,String(t.message||t)))),n(p,e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Retry`))}}function A(t){let r=t?.statuses||{},i=(r.parked||0)+(r.waiting_human||0),a=r.running||0;n(p,i>0&&e(`a.btn.btn-attention`,{href:`#/tasks`},l(`tasks`,{size:15}),`${i} need${i===1?`s`:``} you`),a>0&&e(`a.btn`,{href:`#/tasks`},l(`workflows`,{size:15}),`${a} running`),e(`a.btn`,{href:`#/logs`},l(`logs`,{size:15}),`Logs`),e(`button.btn.btn-primary`,{onclick:k},l(`refresh`,{size:15}),`Refresh`))}function j(e){let t=e?.statuses||{},r=(t.merged||0)+(t.pr_open||0),i=(t.parked||0)+(t.waiting_human||0),s=Object.values(t).reduce((e,t)=>e+t,0),c=e?.tokens_by_day||[];n(a,g({label:`Working now`,value:t.running||0,compare:`${t.queued||0} waiting to start`,series:c.map(e=>e.tokens||0)}),g({label:`Needs you`,value:i,compare:i?`Parked or awaiting a reply`:`Nothing is blocked`,goodDirection:`down`}),g({label:`Delivered`,value:r,compare:s?`${Math.round(r/s*100)}% of all tasks`:`No tasks yet`}),g({label:`Tokens used`,value:o(c.reduce((e,t)=>e+(t.tokens||0),0)),compare:`Across ${c.length||0} days`,trend:E(c.map(e=>e.tokens||0)),goodDirection:`down`,series:c.map(e=>e.tokens||0)}))}function M(t){let r=!t?.steps?.length;if(d.classList.toggle(`dash-top-standalone`,r),r)return n(c);let i=t.steps.filter(e=>!e.done);if(i.length){let r=Math.round((t.steps.length-i.length)/t.steps.length*100);n(c,e(`div.card.setup`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Finish setting up`),e(`p.card-sub`,`Archie needs these before it can work on its own.`)),e(`span.setup-pct`,`${r}%`)),e(`div.setup-bar`,e(`div.setup-bar-fill`,{style:`width:${r}%`})),e(`ul.setup-list`,...t.steps.map(F))));return}d.classList.remove(`dash-top-standalone`),n(c,e(`div.card.setup.setup-done`,e(`div.card-head`,e(`div`,e(`h2.card-title`,`Setup complete`),e(`p.card-sub`,`Archie is configured and ready to work.`)),e(`span.setup-pct`,l(`check`,{size:16})))))}function N(e,t){w(u,e,t)}function P(e){T(f,e)}function F(t){return e(`li.setup-step${t.done?`.done`:``}`,e(`span.setup-check`,t.done?l(`check`,{size:12}):``),e(`div`,e(`div.setup-step-title`,t.title),t.detail&&e(`div.setup-step-detail`,t.detail)))}return t}function x(t,n){let r=S(t,n),i=r>0,o=()=>{i&&(location.hash=`#/tasks?task=${encodeURIComponent(r)}`)};return e(`tr${i?`.activity-row`:``}`,i?{role:`link`,tabindex:`0`,title:`Open task details`,onclick:o,onkeydown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}}:void 0,e(`td.strong`,e(`span`,t.kind||t.type||`event`)),e(`td.mono`,i?`#${r}`:`—`),e(`td`,t.detail||t.message||``),e(`td`,a(t.at||Date.now())))}function S(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 C(){let e=new Date().getHours();return e<5?`Still up?`:e<12?`GooLine truncated
|
||||
+2
-1
@@ -4,7 +4,8 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
"build": "vite build",
|
||||
"test": "node --test \"test/*.test.js\""
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^8.0.0"
|
||||
|
||||
+31
-1
@@ -2,7 +2,13 @@
|
||||
// through this, so auth handling and error shape live in one file.
|
||||
|
||||
async function req(path) {
|
||||
const res = await fetch(path, { headers: { Accept: "application/json" } });
|
||||
// A daemon that accepts the connection but never answers would otherwise
|
||||
// leave the UI stuck in a loading state with no way back; the retry
|
||||
// affordances rely on fetch settling, so bound it.
|
||||
const res = await fetch(path, {
|
||||
headers: { Accept: "application/json" },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (res.status === 401) {
|
||||
throw new ApiError("unauthorised", 401);
|
||||
}
|
||||
@@ -23,6 +29,20 @@ function qs(params) {
|
||||
return s ? `?${s}` : "";
|
||||
}
|
||||
|
||||
// errorMessage prefers what the server actually said. archied answers these
|
||||
// with http.Error, i.e. a plain-text reason -- "task is not awaiting
|
||||
// approval", "max retries reached (3/3)" -- and discarding it in favour of
|
||||
// "409 Conflict" throws away the only part an operator can act on.
|
||||
async function errorMessage(res) {
|
||||
try {
|
||||
const body = (await res.text()).trim();
|
||||
if (body) return body.split("\n")[0].slice(0, 200);
|
||||
} catch {
|
||||
// Body already consumed or unreadable; fall through to the status.
|
||||
}
|
||||
return `${res.status} ${res.statusText}`;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message, status) {
|
||||
super(message);
|
||||
@@ -34,6 +54,16 @@ export const api = {
|
||||
summary: () => req("/api/summary"),
|
||||
tasks: () => req("/api/tasks"),
|
||||
task: (id) => req(`/api/tasks/${id}`),
|
||||
taskAction: async (id, action) => {
|
||||
const res = await fetch(`/api/tasks/${id}/action`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action }),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
});
|
||||
if (!res.ok) throw new ApiError(await errorMessage(res), res.status);
|
||||
return res.json();
|
||||
},
|
||||
setup: () => req("/api/setup"),
|
||||
workflows: () => req("/api/workflows"),
|
||||
skills: () => req("/api/skills"),
|
||||
|
||||
+4
-1
@@ -11,7 +11,10 @@ export function el(spec, attrs, ...children) {
|
||||
const node = document.createElement(tag || "div");
|
||||
if (classes.length) node.className = classes.join(" ");
|
||||
|
||||
if (attrs && (typeof attrs !== "object" || attrs instanceof Node)) {
|
||||
// A falsy scalar first child (0, "", false) is a value, not a missing
|
||||
// attrs object: unshift it so append() renders it instead of dropping it.
|
||||
// undefined stays "no attrs" so `el("div", undefined, child)` still works.
|
||||
if (attrs !== undefined && (typeof attrs !== "object" || attrs instanceof Node)) {
|
||||
children.unshift(attrs);
|
||||
attrs = null;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
border-radius: var(--radius-lg);
|
||||
padding: var(--sp-5);
|
||||
box-shadow: var(--shadow-sm);
|
||||
/* Wide content (data tables, long values) scrolls inside the card on
|
||||
narrow screens instead of stretching the page. */
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.card-head {
|
||||
@@ -15,6 +18,7 @@
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-3);
|
||||
margin-bottom: var(--sp-4);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.card-title {
|
||||
@@ -34,6 +38,12 @@
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
/* Grid tracks never grow past the viewport: an item that would blow out
|
||||
scrolls inside its own scroll container instead. */
|
||||
.grid > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.grid-4 {
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
|
||||
@@ -6,6 +6,19 @@
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
/* Contained horizontal scrolling for wide tables: the page stays put and the
|
||||
table scrolls inside this wrapper, so a 7-column table is usable at 390px. */
|
||||
.table-scroll {
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.table-scroll > .table {
|
||||
min-width: 42rem;
|
||||
}
|
||||
|
||||
.table th {
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
|
||||
@@ -69,6 +69,10 @@
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.setup-done .setup-pct {
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.setup-bar {
|
||||
height: 5px;
|
||||
border-radius: var(--radius-pill);
|
||||
@@ -168,14 +172,27 @@
|
||||
|
||||
.dash-top {
|
||||
display: grid;
|
||||
grid-template-columns: 1.6fr 1fr;
|
||||
grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr);
|
||||
gap: var(--sp-4);
|
||||
margin-bottom: var(--sp-4);
|
||||
}
|
||||
|
||||
/* Either column must be allowed to shrink below its content width so the
|
||||
other one does not get pushed off-screen on narrow viewports. */
|
||||
.dash-top > *,
|
||||
.dash-split > * {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* No setup panel to show: the gate pulse spans the whole row instead of
|
||||
leaving an empty half. */
|
||||
.dash-top-standalone {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.dash-top {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,14 +317,14 @@
|
||||
|
||||
.dash-split {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.5fr;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr);
|
||||
gap: var(--sp-4);
|
||||
margin-top: var(--sp-4);
|
||||
}
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.dash-split {
|
||||
grid-template-columns: 1fr;
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+103
-23
@@ -19,16 +19,23 @@ export function dashboardPage() {
|
||||
const statsRow = el("div.grid.grid-4");
|
||||
const setupSlot = el("div");
|
||||
const pulseSlot = el("div");
|
||||
const topRow = el("div.dash-top", setupSlot, pulseSlot);
|
||||
const forecastSlot = el("div");
|
||||
const actions = el("div.hero-actions-inner");
|
||||
const title = el("h1.hero-title", greeting());
|
||||
const streamState = pill("connecting", "idle");
|
||||
const activity = [];
|
||||
const taskIDsBySource = new Map();
|
||||
|
||||
render();
|
||||
load();
|
||||
|
||||
const unsubscribe = subscribeEvents(
|
||||
(event) => prependRun(runs, event),
|
||||
(event) => {
|
||||
activity.unshift(event);
|
||||
activity.splice(50);
|
||||
renderActivity();
|
||||
},
|
||||
(state) => {
|
||||
const kind = state === "live" ? "ok" : "warn";
|
||||
streamState.className = `pill pill-${kind}`;
|
||||
@@ -55,7 +62,7 @@ export function dashboardPage() {
|
||||
el(
|
||||
"div.dash-section",
|
||||
el("div.dash-section-head", el("h2.dash-section-title", "Health")),
|
||||
el("div.dash-top", setupSlot, pulseSlot),
|
||||
topRow,
|
||||
),
|
||||
el(
|
||||
"div.dash-section",
|
||||
@@ -83,24 +90,43 @@ export function dashboardPage() {
|
||||
streamState,
|
||||
),
|
||||
el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Event", "Task", "Detail", "When"].map((h) => el("th", h)))),
|
||||
runs,
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Event", "Task", "Detail", "When"].map((h) => el("th", h)))),
|
||||
runs,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
mount(runs, el("tr", el("td", { colspan: 4 }, empty("Waiting for activity", "Events appear here as Archie works."))));
|
||||
renderActivity();
|
||||
}
|
||||
|
||||
function renderActivity() {
|
||||
if (!activity.length) {
|
||||
mount(runs, el("tr", el("td", { colspan: 4 }, empty("Waiting for activity", "Events appear here as Archie works."))));
|
||||
return;
|
||||
}
|
||||
mount(runs, ...activity.map((event) => activityRow(event, taskIDsBySource)));
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [summary, setup, workflows] = await Promise.all([
|
||||
const [summary, setup, workflows, tasks] = await Promise.all([
|
||||
api.summary(),
|
||||
api.setup().catch(() => null),
|
||||
api.workflows().catch(() => null),
|
||||
api.tasks().catch(() => []),
|
||||
]);
|
||||
taskIDsBySource.clear();
|
||||
for (const task of tasks) {
|
||||
if (task.owner && task.repo && task.issue_number) {
|
||||
taskIDsBySource.set(`${task.owner}/${task.repo}#${task.issue_number}`, task.id);
|
||||
}
|
||||
}
|
||||
renderActivity();
|
||||
renderActions(summary);
|
||||
// The greeting is only personalised when the deployment says who it
|
||||
// assists; an unconfigured instance greets without a name rather than
|
||||
@@ -112,6 +138,13 @@ export function dashboardPage() {
|
||||
renderForecast(summary);
|
||||
} catch (err) {
|
||||
mount(statsRow, el("div.card", empty("Cannot reach archied", String(err.message || err))));
|
||||
// The hero actions are only rendered on success, so a failed first load
|
||||
// must offer its own retry rather than leaving the operator without a
|
||||
// recovery path.
|
||||
mount(
|
||||
actions,
|
||||
el("button.btn.btn-primary", { onclick: load }, icon("refresh", { size: 15 }), "Retry"),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,26 +210,50 @@ export function dashboardPage() {
|
||||
}
|
||||
|
||||
function renderSetup(setup) {
|
||||
if (!setup?.steps?.length) return mount(setupSlot);
|
||||
// Unknown setup (endpoint unreachable) or no checklist configured: omit
|
||||
// the panel and let the gate pulse take the full row, so the Health row
|
||||
// never shows an empty half beside the pulse.
|
||||
const omit = !setup?.steps?.length;
|
||||
topRow.classList.toggle("dash-top-standalone", omit);
|
||||
if (omit) return mount(setupSlot);
|
||||
const remaining = setup.steps.filter((s) => !s.done);
|
||||
if (!remaining.length) return mount(setupSlot);
|
||||
|
||||
const pct = Math.round(((setup.steps.length - remaining.length) / setup.steps.length) * 100);
|
||||
if (remaining.length) {
|
||||
const pct = Math.round(((setup.steps.length - remaining.length) / setup.steps.length) * 100);
|
||||
mount(
|
||||
setupSlot,
|
||||
el(
|
||||
"div.card.setup",
|
||||
el(
|
||||
"div.card-head",
|
||||
el(
|
||||
"div",
|
||||
el("h2.card-title", "Finish setting up"),
|
||||
el("p.card-sub", "Archie needs these before it can work on its own."),
|
||||
),
|
||||
el("span.setup-pct", `${pct}%`),
|
||||
),
|
||||
el("div.setup-bar", el("div.setup-bar-fill", { style: `width:${pct}%` })),
|
||||
el("ul.setup-list", ...setup.steps.map(setupStep)),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Every step done: show completion so the row beside the gate pulse is
|
||||
// not an empty hole on an otherwise healthy dashboard.
|
||||
topRow.classList.remove("dash-top-standalone");
|
||||
mount(
|
||||
setupSlot,
|
||||
el(
|
||||
"div.card.setup",
|
||||
"div.card.setup.setup-done",
|
||||
el(
|
||||
"div.card-head",
|
||||
el(
|
||||
"div",
|
||||
el("h2.card-title", "Finish setting up"),
|
||||
el("p.card-sub", "Archie needs these before it can work on its own."),
|
||||
el("h2.card-title", "Setup complete"),
|
||||
el("p.card-sub", "Archie is configured and ready to work."),
|
||||
),
|
||||
el("span.setup-pct", `${pct}%`),
|
||||
el("span.setup-pct", icon("check", { size: 16 })),
|
||||
),
|
||||
el("div.setup-bar", el("div.setup-bar-fill", { style: `width:${pct}%` })),
|
||||
el("ul.setup-list", ...setup.steps.map(setupStep)),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -220,17 +277,40 @@ export function dashboardPage() {
|
||||
return root;
|
||||
}
|
||||
|
||||
function prependRun(tbody, event) {
|
||||
if (tbody.firstElementChild?.querySelector(".empty")) tbody.replaceChildren();
|
||||
function activityRow(event, taskIDsBySource) {
|
||||
const taskID = taskIDForEvent(event, taskIDsBySource);
|
||||
const hasTask = taskID > 0;
|
||||
const openTask = () => {
|
||||
if (hasTask) location.hash = `#/tasks?task=${encodeURIComponent(taskID)}`;
|
||||
};
|
||||
const row = el(
|
||||
"tr",
|
||||
`tr${hasTask ? ".activity-row" : ""}`,
|
||||
hasTask
|
||||
? {
|
||||
role: "link",
|
||||
tabindex: "0",
|
||||
title: "Open task details",
|
||||
onclick: openTask,
|
||||
onkeydown: (e) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
openTask();
|
||||
}
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
el("td.strong", el("span", event.kind || event.type || "event")),
|
||||
el("td.mono", event.task_id ? `#${event.task_id}` : "—"),
|
||||
el("td.mono", hasTask ? `#${taskID}` : "—"),
|
||||
el("td", event.detail || event.message || ""),
|
||||
el("td", ago(event.at || Date.now())),
|
||||
);
|
||||
tbody.prepend(row);
|
||||
while (tbody.children.length > 50) tbody.lastElementChild.remove();
|
||||
return row;
|
||||
}
|
||||
|
||||
function taskIDForEvent(event, taskIDsBySource) {
|
||||
if (Number(event.task_id) > 0) return Number(event.task_id);
|
||||
if (!event.repo || !event.issue) return 0;
|
||||
return Number(taskIDsBySource.get(`${event.repo}#${event.issue}`)) || 0;
|
||||
}
|
||||
|
||||
function greeting() {
|
||||
|
||||
+3
-2
@@ -133,13 +133,14 @@ function start() {
|
||||
else show(path);
|
||||
}
|
||||
|
||||
function show(path) {
|
||||
function show(rawPath) {
|
||||
// Let a page release its subscriptions before it is replaced, so the SSE
|
||||
// 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);
|
||||
mount(outlet, route.view ? route.view() : comingSoon(route));
|
||||
mount(outlet, route.view ? route.view(new URLSearchParams(query)) : comingSoon(route));
|
||||
}
|
||||
|
||||
window.addEventListener("hashchange", () => show(location.hash.slice(1) || "/"));
|
||||
|
||||
+31
-25
@@ -112,21 +112,24 @@ function repositoriesCard(repos) {
|
||||
"Repositories",
|
||||
"Each repository Archie polls, and the quality gate a change must pass before it opens a pull request.",
|
||||
el(
|
||||
"table.table",
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"thead",
|
||||
el("tr", ...["Repository", "Base branch", "Ecosystem", "Quality gate", "Protected paths"].map((h) => el("th", h))),
|
||||
),
|
||||
el(
|
||||
"tbody",
|
||||
...repos.map((r) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td.strong", `${r.owner}/${r.name}`),
|
||||
el("td.mono", r.base),
|
||||
el("td", r.ecosystem || "go"),
|
||||
el("td.mono", gateSummary(r.gate)),
|
||||
el("td.mono", r.protect?.length ? r.protect.join(", ") : "—"),
|
||||
"table.table",
|
||||
el(
|
||||
"thead",
|
||||
el("tr", ...["Repository", "Base branch", "Ecosystem", "Quality gate", "Protected paths"].map((h) => el("th", h))),
|
||||
),
|
||||
el(
|
||||
"tbody",
|
||||
...repos.map((r) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td.strong", `${r.owner}/${r.name}`),
|
||||
el("td.mono", r.base),
|
||||
el("td", r.ecosystem || "go"),
|
||||
el("td.mono", gateSummary(r.gate)),
|
||||
el("td.mono", r.protect?.length ? r.protect.join(", ") : "—"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -149,18 +152,21 @@ function modelsAndProvidersCard(models, providers) {
|
||||
|
||||
const providerRows = providerEntries.length
|
||||
? el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Provider", "Class", "Base URL", "API key env var", "Status"].map((h) => el("th", h)))),
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"tbody",
|
||||
...providerEntries.map(([name, p]) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td.strong", name),
|
||||
el("td", p.class),
|
||||
el("td.mono", p.base_url || "default"),
|
||||
el("td.mono", p.api_key_env || "—"),
|
||||
el("td", p.configured ? pill("configured", "ok") : pill("missing credentials", "warn")),
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Provider", "Class", "Base URL", "API key env var", "Status"].map((h) => el("th", h)))),
|
||||
el(
|
||||
"tbody",
|
||||
...providerEntries.map(([name, p]) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td.strong", name),
|
||||
el("td", p.class),
|
||||
el("td.mono", p.base_url || "default"),
|
||||
el("td.mono", p.api_key_env || "—"),
|
||||
el("td", p.configured ? pill("configured", "ok") : pill("missing credentials", "warn")),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -4,9 +4,9 @@ import { el, empty, mount } from "../base/dom.js";
|
||||
|
||||
/**
|
||||
* What Archie can actually do, beyond what is in the source. Backed by
|
||||
* GET /api/skills, which scans .agents/skills/<name>/SKILL.md (see
|
||||
* internal/skill.Catalog) and returns each skill's name, plain-language
|
||||
* description, and where it was found.
|
||||
* GET /api/skills, which scans project, shared, and user-global
|
||||
* .agents/skills/<name>/SKILL.md files and returns each skill's name,
|
||||
* plain-language description, and where it was found.
|
||||
*
|
||||
* This page exists for someone who has never read the source: a search box
|
||||
* over a card grid, and an empty state that explains what a skill is and
|
||||
@@ -47,7 +47,7 @@ export function skillsPage() {
|
||||
"div.card",
|
||||
el(
|
||||
"div.card-head",
|
||||
el("div", el("h2.card-title", "Catalogue"), el("p.card-sub", "Discovered from .agents/skills/")),
|
||||
el("div", el("h2.card-title", "Catalogue"), el("p.card-sub", "Project, shared, and user-global skills")),
|
||||
searchInput,
|
||||
),
|
||||
cardGrid,
|
||||
@@ -77,7 +77,7 @@ export function skillsPage() {
|
||||
cardGrid,
|
||||
empty(
|
||||
"No skills discovered yet",
|
||||
"Skills live as SKILL.md files under .agents/skills/<name>/. Add one, or point skills_dir in config.toml at a shared skills directory, and it will appear here.",
|
||||
"Skills live as SKILL.md files under project, shared, or user-global .agents/skills/<name>/ directories. Add one and refresh to make it available.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
/* Tasks-only styles. */
|
||||
|
||||
.task-summary {
|
||||
margin-bottom: var(--sp-5);
|
||||
}
|
||||
|
||||
.task-filters {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.task-search,
|
||||
@@ -31,6 +36,85 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.activity-row {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.activity-row:hover td,
|
||||
.activity-row:focus td {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.activity-row:focus {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.task-source-link {
|
||||
color: var(--accent);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.task-source-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.task-actions {
|
||||
display: flex;
|
||||
gap: var(--sp-1);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.btn-small {
|
||||
padding: var(--sp-1) var(--sp-2);
|
||||
font-size: var(--text-xs);
|
||||
}
|
||||
|
||||
.btn-quiet {
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
|
||||
.task-action-error {
|
||||
max-width: 180px;
|
||||
color: var(--danger);
|
||||
font-size: var(--text-xs);
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.task-decision {
|
||||
margin-bottom: var(--sp-4);
|
||||
padding: var(--sp-3);
|
||||
border-left: 3px solid var(--accent);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.task-decision-title {
|
||||
color: var(--fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.task-decision-plan {
|
||||
margin-top: var(--sp-2);
|
||||
color: var(--fg-muted);
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
/* On phones the filter controls take their own row and full width instead of
|
||||
crowding the card title. */
|
||||
@media (max-width: 700px) {
|
||||
.task-filters {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.task-search {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.task-filter {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.task-timeline-row td {
|
||||
background: var(--bg-raised);
|
||||
padding: var(--sp-4);
|
||||
@@ -41,6 +125,18 @@
|
||||
font-size: var(--text-sm);
|
||||
}
|
||||
|
||||
.task-timeline-error {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
|
||||
.task-timeline-error .task-timeline-title {
|
||||
font-weight: 500;
|
||||
color: var(--fg);
|
||||
}
|
||||
|
||||
.task-timeline {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
|
||||
+144
-16
@@ -29,9 +29,9 @@ function statusLabel(status) {
|
||||
* carries created_at/updated_at, so age is shown in the list and once
|
||||
* a row's timeline is loaded, sourced from its most recent event.
|
||||
*/
|
||||
export function tasksPage() {
|
||||
export function tasksPage(params = new URLSearchParams()) {
|
||||
const root = el("div");
|
||||
const summaryRow = el("div.grid.grid-4");
|
||||
const summaryRow = el("div.grid.grid-4.task-summary");
|
||||
const body = el("tbody");
|
||||
const searchInput = el("input.task-search", {
|
||||
type: "search",
|
||||
@@ -56,8 +56,16 @@ export function tasksPage() {
|
||||
let tasks = [];
|
||||
let filterStatus = "";
|
||||
let search = "";
|
||||
let expandedId = null;
|
||||
const requestedTask = Number(params.get("task"));
|
||||
let expandedId = Number.isFinite(requestedTask) && requestedTask > 0 ? requestedTask : null;
|
||||
let forgeHost = "";
|
||||
const eventCache = new Map();
|
||||
// Keyed by task id. A single shared string leaked one row's failure into
|
||||
// every other row's action cell.
|
||||
const actionErrors = new Map();
|
||||
// Tasks with an action in flight, so the buttons can be disabled rather
|
||||
// than letting an impatient second click fire the same action twice.
|
||||
const actionsInFlight = new Set();
|
||||
|
||||
render();
|
||||
load();
|
||||
@@ -83,15 +91,18 @@ export function tasksPage() {
|
||||
el("div.task-filters", searchInput, statusSelect),
|
||||
),
|
||||
el(
|
||||
"table.table",
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"thead",
|
||||
"table.table",
|
||||
el(
|
||||
"tr",
|
||||
...["Repo", "Issue", "Title", "Status", "Workflow", "Stage", "Last activity"].map((h) => el("th", h)),
|
||||
"thead",
|
||||
el(
|
||||
"tr",
|
||||
...["Repo", "Issue", "Title", "Status", "Workflow", "Stage", "Last activity", "Action"].map((h) => el("th", h)),
|
||||
),
|
||||
),
|
||||
body,
|
||||
),
|
||||
body,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -99,12 +110,18 @@ export function tasksPage() {
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
tasks = await api.tasks();
|
||||
[tasks, forgeHost] = await Promise.all([
|
||||
api.tasks(),
|
||||
api.config().then((cfg) => cfg?.identity?.forge_host || "").catch(() => ""),
|
||||
]);
|
||||
renderSummary();
|
||||
renderRows();
|
||||
if (expandedId && tasks.some((task) => String(task.id) === String(expandedId))) {
|
||||
loadTimeline(expandedId);
|
||||
}
|
||||
} catch (err) {
|
||||
mount(summaryRow, el("div.card", empty("Cannot reach archied", String(err.message || err))));
|
||||
mount(body, el("tr", el("td", { colspan: 7 }, empty("Cannot reach archied", String(err.message || err)))));
|
||||
mount(body, el("tr", el("td", { colspan: 8 }, empty("Cannot reach archied", String(err.message || err)))));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,7 +177,7 @@ export function tasksPage() {
|
||||
"tr",
|
||||
el(
|
||||
"td",
|
||||
{ colspan: 7 },
|
||||
{ colspan: 8 },
|
||||
empty("No tasks yet", "Tasks appear here once archied picks up an issue to work."),
|
||||
),
|
||||
),
|
||||
@@ -170,7 +187,7 @@ export function tasksPage() {
|
||||
if (!rows.length) {
|
||||
mount(
|
||||
body,
|
||||
el("tr", el("td", { colspan: 7 }, empty("No matching tasks", "Try a different search or status filter."))),
|
||||
el("tr", el("td", { colspan: 8 }, empty("No matching tasks", "Try a different search or status filter."))),
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -191,8 +208,8 @@ export function tasksPage() {
|
||||
if (expandedId === t.id) loadTimeline(t.id);
|
||||
},
|
||||
},
|
||||
el("td.mono", `${t.owner}/${t.repo}`),
|
||||
el("td.mono", `#${t.issue_number}`),
|
||||
el("td.mono", repoLink(t) ?? `${t.owner}/${t.repo}`),
|
||||
el("td.mono", issueLink(t) ?? `#${t.issue_number}`),
|
||||
el("td.strong", t.title || "(untitled)"),
|
||||
el("td", pill(statusLabel(t.status), statusKind(t.status))),
|
||||
el("td", t.workflow || "—"),
|
||||
@@ -200,6 +217,104 @@ export function tasksPage() {
|
||||
// updated_at moves on every transition, so this reads as "how long has
|
||||
// it been sitting like this" rather than "how old is the task".
|
||||
el("td", { title: t.created_at ? `Created ${ago(t.created_at)}` : "" }, ago(t.updated_at)),
|
||||
el("td", taskActions(t)),
|
||||
);
|
||||
}
|
||||
|
||||
function taskActions(t) {
|
||||
const message = actionErrors.get(t.id);
|
||||
const error = message ? el("span.task-action-error", message) : null;
|
||||
const busy = actionsInFlight.has(t.id);
|
||||
|
||||
// The row itself toggles the timeline on click, so every button has to
|
||||
// stop the event or acting on a task also expands it.
|
||||
const button = (cls, action, label, confirmText) =>
|
||||
el(
|
||||
cls,
|
||||
{
|
||||
type: "button",
|
||||
disabled: busy,
|
||||
onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (confirmText && !window.confirm(confirmText)) return;
|
||||
performAction(t.id, action);
|
||||
},
|
||||
},
|
||||
label,
|
||||
);
|
||||
|
||||
if (t.status === "waiting_human") {
|
||||
return el(
|
||||
"div.task-actions",
|
||||
error,
|
||||
button("button.btn.btn-small", "approve", "Approve"),
|
||||
button(
|
||||
"button.btn.btn-small.btn-quiet",
|
||||
"reject",
|
||||
"Reject",
|
||||
`Reject "${t.title || "this task"}"? This closes the forge issue and cannot be undone from here.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (t.status === "parked") {
|
||||
return el("div.task-actions", error, button("button.btn.btn-small", "retry", "Retry"));
|
||||
}
|
||||
return error || "—";
|
||||
}
|
||||
|
||||
async function performAction(id, action) {
|
||||
actionErrors.delete(id);
|
||||
actionsInFlight.add(id);
|
||||
renderRows();
|
||||
try {
|
||||
await api.taskAction(id, action);
|
||||
actionsInFlight.delete(id);
|
||||
await load();
|
||||
} catch (err) {
|
||||
actionsInFlight.delete(id);
|
||||
actionErrors.set(id, err.message || "Action failed");
|
||||
renderRows();
|
||||
}
|
||||
}
|
||||
|
||||
// Both forge links derive from the same host so they can never drift apart:
|
||||
// one place builds the base, both anchors reuse it.
|
||||
function forgeBase(t) {
|
||||
if (!forgeHost || !t.owner || !t.repo) return null;
|
||||
return `${forgeHost.replace(/\/+$/, "")}/${encodeURIComponent(t.owner)}/${encodeURIComponent(t.repo)}`;
|
||||
}
|
||||
|
||||
function repoLink(t) {
|
||||
const base = forgeBase(t);
|
||||
if (!base) return null;
|
||||
return el(
|
||||
"a.task-source-link",
|
||||
{
|
||||
href: base,
|
||||
target: "_blank",
|
||||
rel: "noreferrer",
|
||||
title: `Open ${t.owner}/${t.repo} on the forge`,
|
||||
onclick: (e) => e.stopPropagation(),
|
||||
},
|
||||
`${t.owner}/${t.repo}`,
|
||||
);
|
||||
}
|
||||
|
||||
function issueLink(t) {
|
||||
const base = forgeBase(t);
|
||||
// A chat-sourced task has no issue on the forge, but its repo may still
|
||||
// exist -- the repo link stays, the issue link does not.
|
||||
if (t.source === "chat" || !base || !t.issue_number) return null;
|
||||
return el(
|
||||
"a.task-source-link",
|
||||
{
|
||||
href: `${base}/issues/${t.issue_number}`,
|
||||
target: "_blank",
|
||||
rel: "noreferrer",
|
||||
title: `Open issue #${t.issue_number} on the forge`,
|
||||
onclick: (e) => e.stopPropagation(),
|
||||
},
|
||||
`#${t.issue_number}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -209,11 +324,24 @@ export function tasksPage() {
|
||||
"tr.task-timeline-row",
|
||||
el(
|
||||
"td",
|
||||
{ colspan: 7 },
|
||||
{ colspan: 8 },
|
||||
t.status === "waiting_human" && t.plan
|
||||
? el("div.task-decision", el("div.task-decision-title", "Decision required"), el("div.task-decision-plan", t.plan))
|
||||
: t.status === "parked" && t.park_reason
|
||||
? el("div.task-decision", el("div.task-decision-title", "Park reason"), el("div.task-decision-plan", t.park_reason))
|
||||
: null,
|
||||
cached === undefined
|
||||
? el("div.task-timeline-loading", "Loading timeline…")
|
||||
: cached === null
|
||||
? empty("Could not load timeline", "archied could not be reached for this task's events.")
|
||||
? el(
|
||||
"div.task-timeline-error",
|
||||
el("div.task-timeline-title", "Could not load timeline"),
|
||||
el(
|
||||
"div.task-timeline-detail",
|
||||
"archied did not answer for this task's events. It may be restarting — retry, or check the daemon.",
|
||||
),
|
||||
el("button.btn", { onclick: () => loadTimeline(t.id) }, "Retry"),
|
||||
)
|
||||
: cached.length
|
||||
? el("ul.task-timeline", ...cached.map(timelineEntry))
|
||||
: empty("No events yet", "This task has not recorded any transitions."),
|
||||
|
||||
@@ -108,31 +108,34 @@ export function workflowsPage() {
|
||||
),
|
||||
),
|
||||
el(
|
||||
"table.table",
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"thead",
|
||||
"table.table",
|
||||
el(
|
||||
"tr",
|
||||
...["Workflow", "Runs", "Success rate", "Avg tokens", "Avg steps"].map((h) => el("th", h)),
|
||||
),
|
||||
),
|
||||
el(
|
||||
"tbody",
|
||||
...workflows.map((w) => {
|
||||
const rate = pct(w.merged, w.runs);
|
||||
return el(
|
||||
"thead",
|
||||
el(
|
||||
"tr",
|
||||
el("td.strong", workflowLabel(w.workflow)),
|
||||
el("td", `${w.runs} run${w.runs === 1 ? "" : "s"}`),
|
||||
el(
|
||||
"td",
|
||||
el("div.wf-rate", `${rate}%`, el("span.wf-rate-sub", `${w.merged} of ${w.runs} merged`)),
|
||||
bar(rate, rate >= 50 ? "ok" : "warn"),
|
||||
),
|
||||
el("td.mono", w.avg_tokens ? w.avg_tokens.toLocaleString() : "—"),
|
||||
el("td.mono", w.avg_steps ? w.avg_steps.toFixed(1) : "—"),
|
||||
);
|
||||
}),
|
||||
...["Workflow", "Runs", "Success rate", "Avg tokens", "Avg steps"].map((h) => el("th", h)),
|
||||
),
|
||||
),
|
||||
el(
|
||||
"tbody",
|
||||
...workflows.map((w) => {
|
||||
const rate = pct(w.merged, w.runs);
|
||||
return el(
|
||||
"tr",
|
||||
el("td.strong", workflowLabel(w.workflow)),
|
||||
el("td", `${w.runs} run${w.runs === 1 ? "" : "s"}`),
|
||||
el(
|
||||
"td",
|
||||
el("div.wf-rate", `${rate}%`, el("span.wf-rate-sub", `${w.merged} of ${w.runs} merged`)),
|
||||
bar(rate, rate >= 50 ? "ok" : "warn"),
|
||||
),
|
||||
el("td.mono", w.avg_tokens ? w.avg_tokens.toLocaleString() : "—"),
|
||||
el("td.mono", w.avg_steps ? w.avg_steps.toFixed(1) : "—"),
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -167,20 +170,23 @@ export function workflowsPage() {
|
||||
el("div", el("h2.card-title", "Slowest stages"), el("p.card-sub", "Average duration, this workflow's stages")),
|
||||
),
|
||||
el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Workflow", "Stage", "Runs", "Avg duration"].map((h) => el("th", h)))),
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"tbody",
|
||||
...byDuration.map((s) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td", workflowLabel(s.workflow)),
|
||||
el("td.strong", s.stage),
|
||||
el("td", `${s.runs}`),
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Workflow", "Stage", "Runs", "Avg duration"].map((h) => el("th", h)))),
|
||||
el(
|
||||
"tbody",
|
||||
...byDuration.map((s) =>
|
||||
el(
|
||||
"td",
|
||||
el("div.wf-rate", formatMs(s.avg_ms)),
|
||||
bar(pct(s.avg_ms, maxMs), "info"),
|
||||
"tr",
|
||||
el("td", workflowLabel(s.workflow)),
|
||||
el("td.strong", s.stage),
|
||||
el("td", `${s.runs}`),
|
||||
el(
|
||||
"td",
|
||||
el("div.wf-rate", formatMs(s.avg_ms)),
|
||||
bar(pct(s.avg_ms, maxMs), "info"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -195,19 +201,22 @@ export function workflowsPage() {
|
||||
),
|
||||
byErrors.length
|
||||
? el(
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Workflow", "Stage", "Failures"].map((h) => el("th", h)))),
|
||||
"div.table-scroll",
|
||||
el(
|
||||
"tbody",
|
||||
...byErrors.map((s) =>
|
||||
el(
|
||||
"tr",
|
||||
el("td", workflowLabel(s.workflow)),
|
||||
el("td.strong", s.stage),
|
||||
"table.table",
|
||||
el("thead", el("tr", ...["Workflow", "Stage", "Failures"].map((h) => el("th", h)))),
|
||||
el(
|
||||
"tbody",
|
||||
...byErrors.map((s) =>
|
||||
el(
|
||||
"td",
|
||||
el("div.wf-rate", `${s.errors} of ${s.runs}`),
|
||||
bar(pct(s.errors, s.runs), "danger"),
|
||||
"tr",
|
||||
el("td", workflowLabel(s.workflow)),
|
||||
el("td.strong", s.stage),
|
||||
el(
|
||||
"td",
|
||||
el("div.wf-rate", `${s.errors} of ${s.runs}`),
|
||||
bar(pct(s.errors, s.runs), "danger"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// Regression coverage for the DOM-building primitives.
|
||||
//
|
||||
// The KPI regression this pins: `el("div.stat-value", 0, ...)` used to treat a
|
||||
// falsy first child (0, "", false) as "no attributes" and drop it, so stat
|
||||
// tiles rendered an empty headline whenever the value was zero. The dashboards
|
||||
// of fresh installs show exactly that -- labels and comparison text, no number.
|
||||
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import "./shim.js";
|
||||
import { el, mount } from "../src/base/dom.js";
|
||||
import { statTile } from "../src/base/statTile.js";
|
||||
|
||||
test("el renders a falsy numeric value instead of dropping it", () => {
|
||||
const node = el("div.stat-value", 0);
|
||||
assert.equal(node.textContent, "0");
|
||||
});
|
||||
|
||||
test("el renders an empty string first child without dropping later children", () => {
|
||||
const node = el("div", "", "tail");
|
||||
assert.equal(node.textContent, "tail");
|
||||
});
|
||||
|
||||
test("el keeps falsy non-child values out of the output but keeps real children", () => {
|
||||
const node = el("div", false, "x");
|
||||
assert.equal(node.textContent, "x");
|
||||
});
|
||||
|
||||
test("el still treats an attrs object as attributes", () => {
|
||||
const node = el("a.btn", { href: "#/tasks", "aria-label": "Tasks" }, "Tasks");
|
||||
assert.equal(node.getAttribute("href"), "#/tasks");
|
||||
assert.equal(node.getAttribute("aria-label"), "Tasks");
|
||||
assert.equal(node.textContent, "Tasks");
|
||||
});
|
||||
|
||||
test("el still treats a Node first argument as a child", () => {
|
||||
const child = el("span", "inner");
|
||||
const node = el("div", child);
|
||||
assert.equal(node.textContent, "inner");
|
||||
});
|
||||
|
||||
test("mount replaces prior children", () => {
|
||||
const root = el("div", "old");
|
||||
mount(root, el("p", "new"));
|
||||
assert.equal(root.textContent, "new");
|
||||
});
|
||||
|
||||
test("statTile renders a zero headline value", () => {
|
||||
const tile = statTile({ label: "Working now", value: 0, compare: "Nothing running" });
|
||||
assert.equal(tile.querySelector(".stat-label").textContent, "Working now");
|
||||
assert.equal(tile.querySelector(".stat-value").textContent, "0");
|
||||
assert.equal(tile.querySelector(".stat-compare").textContent, "Nothing running");
|
||||
});
|
||||
|
||||
test("statTile renders a string headline value", () => {
|
||||
const tile = statTile({ label: "Tokens used", value: "2.4M", compare: "Across 14 days" });
|
||||
assert.equal(tile.querySelector(".stat-value").textContent, "2.4M");
|
||||
});
|
||||
|
||||
test("statTile shows a trend direction only when a trend is supplied", () => {
|
||||
const plain = statTile({ label: "Delivered", value: 3, compare: "3% of all tasks" });
|
||||
assert.equal(plain.querySelector(".stat-trend"), null);
|
||||
const trended = statTile({ label: "Tokens used", value: 5, trend: 12.5, compare: "x", goodDirection: "down" });
|
||||
assert.match(trended.querySelector(".stat-trend").textContent, /12\.5/);
|
||||
});
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
// Minimal DOM stand-in so the DOM-building primitives in src/base can be
|
||||
// unit-tested under `node --test` without a browser or a jsdom dependency.
|
||||
//
|
||||
// It implements exactly the surface that el/mount/icon/statTile touch:
|
||||
// createElement/createElementNS, className, setAttribute, addEventListener,
|
||||
// append/replaceChildren, innerHTML, and enough child traversal for tests to
|
||||
// assert on rendered output. Nothing here is used at runtime.
|
||||
|
||||
class Node {
|
||||
constructor() {
|
||||
this.childNodes = [];
|
||||
this.attrs = {};
|
||||
this._innerHTML = "";
|
||||
}
|
||||
|
||||
append(...cs) {
|
||||
for (const c of cs.flat(Infinity)) {
|
||||
if (c == null || c === false) continue;
|
||||
this.childNodes.push(c instanceof Node ? c : new TextNode(String(c)));
|
||||
}
|
||||
}
|
||||
|
||||
replaceChildren(...cs) {
|
||||
this.childNodes = [];
|
||||
this.append(...cs);
|
||||
}
|
||||
|
||||
setAttribute(k, v) {
|
||||
this.attrs[k] = String(v);
|
||||
}
|
||||
|
||||
getAttribute(k) {
|
||||
return this.attrs[k] ?? null;
|
||||
}
|
||||
|
||||
addEventListener() {}
|
||||
|
||||
set className(v) {
|
||||
this.attrs["class"] = v;
|
||||
}
|
||||
|
||||
get className() {
|
||||
return this.attrs["class"] ?? "";
|
||||
}
|
||||
|
||||
set innerHTML(v) {
|
||||
this._innerHTML = v;
|
||||
}
|
||||
|
||||
get innerHTML() {
|
||||
return this._innerHTML;
|
||||
}
|
||||
|
||||
get textContent() {
|
||||
return this.childNodes.map((c) => c.textContent).join("");
|
||||
}
|
||||
|
||||
get children() {
|
||||
return this.childNodes.filter((c) => c instanceof Element);
|
||||
}
|
||||
|
||||
/** Class-token lookup, enough for assertions to find .stat-value etc. */
|
||||
querySelector(sel) {
|
||||
const token = sel.startsWith(".") ? sel.slice(1) : null;
|
||||
const want = token || sel;
|
||||
const queue = [...this.childNodes];
|
||||
while (queue.length) {
|
||||
const c = queue.shift();
|
||||
if (c instanceof Element) {
|
||||
const classes = (c.attrs["class"] || "").split(/\s+/).filter(Boolean);
|
||||
if (token ? classes.includes(want) : c.tagName.toLowerCase() === sel) return c;
|
||||
queue.push(...c.childNodes);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
class TextNode extends Node {
|
||||
constructor(text) {
|
||||
super();
|
||||
this._text = String(text);
|
||||
}
|
||||
|
||||
get textContent() {
|
||||
return this._text;
|
||||
}
|
||||
}
|
||||
|
||||
class Element extends Node {
|
||||
constructor(tag) {
|
||||
super();
|
||||
this.tagName = tag.toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
globalThis.Node = Node;
|
||||
globalThis.Element = Element;
|
||||
globalThis.TextNode = TextNode;
|
||||
globalThis.document = {
|
||||
createElement: (tag) => new Element(tag),
|
||||
createElementNS: () => new Element("svg"),
|
||||
createTextNode: (text) => new TextNode(String(text)),
|
||||
};
|
||||
Reference in new issue
Block a user