75 files changed
+2116
-658
No files matched your search
@@ -68,6 +68,26 @@ repo's general "check before doing anything hard to reverse" rule). The deploy
|
||||
workflow reads tags pointing at `HEAD`; pushing the commit without its tag gets images
|
||||
stamped `dev`.
|
||||
|
||||
### After a release, `main` and the working branch have diverged
|
||||
|
||||
The release commit lands on `main` — `tools/release.sh` refuses to run anywhere else
|
||||
— while the working branch keeps advancing. So after every release, `main` is ahead by
|
||||
exactly that commit and the branch is ahead by however far it has moved: **neither tip
|
||||
is an ancestor of the other**, and `--ff-only` fails in both directions. That refusal
|
||||
reads as "the tree is not ready" when in fact the tree is fine.
|
||||
|
||||
Merge the release commit into the branch first, so any conflict is resolved on the
|
||||
branch, where it is reversible and nobody is reading the tip:
|
||||
|
||||
```bash
|
||||
git merge main # on the branch
|
||||
git merge --ff-only <branch> # then, in whichever worktree holds main
|
||||
```
|
||||
|
||||
Confirm which worktree holds `main` with `git worktree list` before the `--ff-only`.
|
||||
A detached worktree sitting at the same commit will accept it and move nothing, which
|
||||
looks like success.
|
||||
|
||||
## What a release publishes
|
||||
|
||||
Tagging one version produces, from a single `deploy` run:
|
||||
|
||||
@@ -208,6 +208,8 @@ tasks:
|
||||
|
||||
Lint a different set of directories directly:
|
||||
go run ./cmd/archie-playbooks lint -dir ./a -dir ./b
|
||||
Lint an EDA playbook directory:
|
||||
go run ./cmd/archie-playbooks lint -eda-dir ./eda-playbooks
|
||||
cmds:
|
||||
- go run ./cmd/archie-playbooks lint -dir ./playbooks
|
||||
|
||||
|
||||
@@ -3,23 +3,22 @@
|
||||
// playbook YAML binding files against the same schema the daemon loads at
|
||||
// startup, so a pre-merge check can never disagree with runtime validation.
|
||||
//
|
||||
// Today it ships one mode (lint). The command dispatch is a table from day
|
||||
// one, so a future serve/lsp mode slots in without restructuring -- both
|
||||
// modes are entrypoints into the same validation source in
|
||||
// internal/domain/workflow.
|
||||
// It ships two modes: lint for CI, and serve, a language server that
|
||||
// publishes the same findings as editor diagnostics. Both call the loaders
|
||||
// the daemon runs.
|
||||
//
|
||||
// Known limitation (as of this slice): findings are file-granular, not
|
||||
// line-granular. The loader decodes playbooks with yaml.Unmarshal into a
|
||||
// plain map, which discards line numbers; a compiler-style file:line
|
||||
// diagnostic needs a yaml.Node decoding upgrade, which is out of scope
|
||||
// here and tracked separately.
|
||||
// A finding about one binding key leads with the key's file:line; a file
|
||||
// that does not parse is reported by path with the YAML parser's message.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/app/archieplaybooks"
|
||||
"github.com/samcharles93/archie-core/internal/buildinfo"
|
||||
@@ -34,7 +33,8 @@ func run(args []string, stderr io.Writer) int {
|
||||
// set and returns an exit code. Adding serve/lsp later is a new entry
|
||||
// here, not a restructuring.
|
||||
commands := map[string]func([]string, io.Writer) int{
|
||||
"lint": runLint,
|
||||
"lint": runLint,
|
||||
"serve": runServe,
|
||||
}
|
||||
|
||||
if len(args) > 0 && (args[0] == "-version" || args[0] == "--version") {
|
||||
@@ -59,27 +59,58 @@ func run(args []string, stderr io.Writer) int {
|
||||
return cmd(args[1:], stderr)
|
||||
}
|
||||
|
||||
// runLint validates one or more playbook directories against the domain
|
||||
// loaders and reports collisions / malformed files / invalid bindings.
|
||||
// runLint validates routing binding directories (-dir) and an EDA playbook
|
||||
// directory (-eda-dir) against the loaders the daemon runs at startup.
|
||||
// Exit codes: 0 clean, 1 findings, 2 usage error.
|
||||
func runLint(args []string, stderr io.Writer) int {
|
||||
flags := flag.NewFlagSet("archie-playbooks lint", flag.ContinueOnError)
|
||||
flags.SetOutput(stderr)
|
||||
var dirs multiFlag
|
||||
flags.Var(&dirs, "dir", "playbook directory to lint (repeatable)")
|
||||
flags.Var(&dirs, "dir", "routing binding directory to lint (repeatable)")
|
||||
edaDir := flags.String("eda-dir", "", "EDA playbook directory to lint (the daemon's eda_playbook_dir)")
|
||||
if err := flags.Parse(args); err != nil {
|
||||
return 2 // flag.ContinueOnError already printed the message
|
||||
}
|
||||
if len(dirs) == 0 {
|
||||
fmt.Fprintln(stderr, "lint: at least one -dir is required")
|
||||
if len(dirs) == 0 && *edaDir == "" {
|
||||
fmt.Fprintln(stderr, "lint: at least one -dir or an -eda-dir is required")
|
||||
flags.Usage()
|
||||
return 2
|
||||
}
|
||||
|
||||
result := archieplaybooks.Lint(dirs, stderr)
|
||||
return result.ExitCode
|
||||
code := 0
|
||||
if len(dirs) > 0 {
|
||||
code = max(code, archieplaybooks.Lint(dirs, stderr).ExitCode)
|
||||
}
|
||||
if *edaDir != "" {
|
||||
code = max(code, archieplaybooks.LintEDA(*edaDir, stderr).ExitCode)
|
||||
}
|
||||
return code
|
||||
}
|
||||
|
||||
// runServe runs the language server on stdin/stdout until the editor
|
||||
// disconnects or the process is signalled.
|
||||
func runServe(args []string, stderr io.Writer) int {
|
||||
if len(args) > 0 {
|
||||
fmt.Fprintln(stderr, "serve: takes no arguments; the editor speaks LSP on stdin/stdout")
|
||||
return 2
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := archieplaybooks.Serve(ctx, stdio{}); err != nil {
|
||||
fmt.Fprintln(stderr, "serve:", err)
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// stdio joins stdin and stdout into the one stream the language server reads
|
||||
// and writes.
|
||||
type stdio struct{}
|
||||
|
||||
func (stdio) Read(p []byte) (int, error) { return os.Stdin.Read(p) }
|
||||
func (stdio) Write(p []byte) (int, error) { return os.Stdout.Write(p) }
|
||||
func (stdio) Close() error { return os.Stdin.Close() }
|
||||
|
||||
// multiFlag collects repeated -dir flags.
|
||||
type multiFlag []string
|
||||
|
||||
|
||||
@@ -73,3 +73,16 @@ func writeFile(t *testing.T, path, content string) {
|
||||
t.Fatalf("write %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
|
||||
// -eda-dir alone is a complete lint request, and its findings set the exit
|
||||
// code.
|
||||
func TestRunLintEDADir(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte("trigger:\n kind: bug\nactions:\n - position: module\n kind: nope\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var stderr bytes.Buffer
|
||||
if code := run([]string{"lint", "-eda-dir", dir}, &stderr); code != 1 {
|
||||
t.Fatalf("run(lint -eda-dir) = %d, want 1; stderr: %s", code, stderr.String())
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ type Binding struct {
|
||||
MappingID // which Mapping resolves payload fields
|
||||
Workflow // registered workflow name to dispatch to
|
||||
Version // bumped on every edit
|
||||
Status // draft | pending_approval | armed
|
||||
Status // pending_approval | armed
|
||||
Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET
|
||||
}
|
||||
```
|
||||
@@ -59,18 +59,21 @@ binding currently says."
|
||||
### State machine
|
||||
|
||||
```
|
||||
draft ---> pending_approval ---> armed
|
||||
^ ^ |
|
||||
| | |
|
||||
+--------------+-----------------+
|
||||
create ---> pending_approval ---> armed
|
||||
^ |
|
||||
+----------------+
|
||||
(any edit to an armed binding drops it back to pending_approval)
|
||||
```
|
||||
|
||||
A binding is created `pending_approval`, so the operator who creates one can
|
||||
approve it immediately. Bindings stored as `draft` by an earlier version are
|
||||
moved to `pending_approval` when the EDA store opens.
|
||||
|
||||
Modeled directly on Telegram's existing `dangerousAction`/`pendingApproval`
|
||||
flow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new
|
||||
approval mechanism invented for this feature. **Only `armed` evaluates
|
||||
against incoming events** (`binding.Matches`, `internal/domain/binding/
|
||||
binding.go`); `draft` and `pending_approval` bindings are inert. An edit to
|
||||
binding.go`); a `pending_approval` binding is inert. An edit to
|
||||
an already-armed binding cannot bypass approval by silent mutation -- it
|
||||
drops back to `pending_approval` and requires an explicit `Approve` call to
|
||||
re-arm.
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"url": "/dev/architecture/bindings/",
|
||||
"title": "Playbook bindings: model and threat model",
|
||||
"section": "Architecture",
|
||||
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // draft | pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (SQLite), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\n`Matcher.Source` is the only predicate today: the path segment a sender\nPOSTs to (e.g. a webhook hitting `.../sentry` matches bindings with\n`Matcher.Source == \"sentry\"`). The storage column is plain `TEXT`, so adding\npredicates later is non-breaking -- extend `Matcher`, don't invent a second\nmatcher shape.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. This\nis schema-by-example in practice: a mapping is authored by pointing at a\nreal captured payload in the dashboard, not by guessing a schema in advance.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ndraft ---\u003e pending_approval ---\u003e armed\n ^ ^ |\n | | |\n +--------------+-----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nModeled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); `draft` and `pending_approval` bindings are inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captured_events.authenticated` is a real column (`internal/store/\n captures.go`), set at capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose source has at least one armed binding** -- an\n unauthenticated capture is never even considered for dispatch.\n\n### 2. Human approval before a binding goes live\n\nCovered by the state machine above. Nothing self-arms: `pending_approval -\u003e\narmed` requires an explicit `Approve` call, and any edit to an armed\nbinding reverts it.\n\n### 3. Rate and volume limits per source\n\nCapture writes are bounded independently of the approval gate, so a flood\nof unauthenticated traffic cannot exhaust disk or drown the inspector:\n`InsertCapture` (`internal/store/captures.go`) prunLine truncated
|
||||
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (SQLite), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\n`Matcher.Source` is the only predicate today: the path segment a sender\nPOSTs to (e.g. a webhook hitting `.../sentry` matches bindings with\n`Matcher.Source == \"sentry\"`). The storage column is plain `TEXT`, so adding\npredicates later is non-breaking -- extend `Matcher`, don't invent a second\nmatcher shape.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. This\nis schema-by-example in practice: a mapping is authored by pointing at a\nreal captured payload in the dashboard, not by guessing a schema in advance.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ncreate ---\u003e pending_approval ---\u003e armed\n ^ |\n +----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nA binding is created `pending_approval`, so the operator who creates one can\napprove it immediately. Bindings stored as `draft` by an earlier version are\nmoved to `pending_approval` when the EDA store opens.\n\nModeled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); a `pending_approval` binding is inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captured_events.authenticated` is a real column (`internal/store/\n captures.go`), set at capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose source has at least one armed binding** -- an\n unauthenticated capture is never even considered for dispatch.\n\n### 2. Human approval before a binding goes live\n\nCovered by the state machine above. Nothing self-arms: `pending_approval -\u003e\narmed` requires an explicit `Approve` call, and any edit to an armed\nbinding reverts it.\n\n### 3. Rate and volume limits per source\n\nCapture writes are bounded independentlyLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/architecture/configuration/",
|
||||
@@ -114,6 +114,12 @@
|
||||
"section": "PRDs",
|
||||
"body": "# PRD writing rules\n\nThese rules apply to every file in `docs/prds/`.\n\n- Search existing PRDs, issues, architecture records, and code first. Do not ask\n the maintainer to repeat recorded requirements.\n- A newer maintainer decision overrides an older design. Mark the old design as\n superseded instead of preserving or defending it.\n- Write plain English. Use a technical term only when the reader needs that\n exact contract or concept.\n- Use the shortest direct sentence. Write “When upgraded, existing instances\n are migrated to the database,” not a description of an importer seeding\n absent resources.\n- State each fact once. Do not repeat a heading, summarize a list before showing\n it, or restate a decision afterward.\n- Every sentence must add a decision, requirement, constraint, evidence, or\n verification step. Delete narration and explanations of obvious text.\n- Do not turn a requested outcome into extra product features. Keep inferences\n open until the maintainer or repository evidence settles them.\n- Do not create a process for a logical boundary. Add one only when it must\n deploy, scale, start, secure, or fail separately.\n- Describe working behavior, not explanatory UI around missing behavior. State\n what users can do and how success is proved.\n- Before approval, use independent read-only reviewers to check a cross-cutting\n PRD for missing behavior and exaggerated claims. Verify and synthesize their\n findings; do not copy their prose.\n- Before requesting approval, review every sentence for complexity, repetition,\n and unsupported scope.\n- Write nothing whose truth expires. No `file.go:123` citations (cite the file\n and the symbol), no progress reports on the work being designed, no dated\n status claims, and no record of how a finding was produced. A phased plan is\n durable design; which phase is finished is not. Do not refer to what this\n document used to say: the reader cannot see it. A supersede marker is fine\n when it names a file, a section or a symbol they can find. `task docs:prds`\n enforces this.\n- Every PRD carries one of three statuses, and nothing else in that field.\n `Draft` until the maintainer explicitly approves it, `Approved` once they\n have and while the work is being built, `Finalised` when the work is\n complete. A finalised PRD does not change; supersede it with a new one\n instead. A revision number belongs in `**Revision:**`, a pointer to the\n authoritative document in `**Authority:**`, and what a past revision changed\n belongs in git.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/action-playbook-run/",
|
||||
"title": "Running action playbooks",
|
||||
"section": "PRDs",
|
||||
"body": "# Running action playbooks\n\n**Status:** Approved\n**Date:** 2026-09-23\n**Parent:** `docs/prds/multi-action-playbooks.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.31`\n\n## Why this exists\n\nAn action playbook loads and type-checks but never runs: `Store.Dispatch`\nskips it and the daemon logs a warning at boot (`multi-action-playbooks.md`,\nD1). This document defines when it runs, what each action does, and how the\n`playbook_dispatches` ledger gates it.\n\n## When a playbook runs\n\nThe daemon runs action playbooks at the point it pins a task's workflow\ndefinition (`Daemon.resolveWorkflowID`), using the same `DispatchInput` the\nworkflow playbooks use. The definition is pinned once per task, so the run\nhappens once per task.\n\n- Every action playbook whose trigger matches runs, in load order. A workflow\n playbook stops at the first match because it chooses one workflow; action\n playbooks choose nothing, so no match suppresses another.\n- A run never changes routing. The task is pinned by the workflow playbooks\n and bindings exactly as when no action playbook exists.\n- An action or playbook failure never parks or fails the task. It is logged\n at warning level with the playbook, the action and the task.\n- A task that already names a workflow (the approval requeue) is skipped, as\n it is for workflow playbooks.\n- Actions run synchronously in the pin path, bounded by the daemon's context.\n The only Module kind, `log`, returns immediately. A slow kind must bring its\n own timeout.\n\n## What one action does\n\nActions run in order against one evaluation context whose `actions` map\nstarts empty.\n\n1. Evaluate `when`. False or an evaluation error skips the action (J3). A\n skipped action records nothing and produces no result.\n2. Evaluate every `args` value. An evaluation error stops the playbook.\n3. Call `playbook.InvokeOnce` with the Module invoke as its function. The\n ledger row is written first. A duplicate row skips the invoke.\n4. An invoke error stops the playbook. The row stays, so the action is not\n retried: the ledger promises at most once, not at least once.\n5. On success, `ModuleRegistry.DecodeResult` converts the result, and it is\n stored as `actions.\u003cid\u003e.result` when the action declares an id.\n\nThe event id in the ledger key is `DispatchInput.TaskID`, the issue's\nidempotency key (`owner/repo/number`). An action therefore runs at most once\nper issue for each playbook version. Editing a playbook changes its version\nand lets it run again for issues it already handled.\n\nA skipped duplicate has no result. A later action that reads it sees a\nmissing field: its `when` evaluates false, or its args fail and the playbook\nstops. This only happens when the same issue is pinned twice under one\nplaybook version.\n\n## Wiring\n\n- `storecontract.PlaybookDispatcher` is lifted onto the daemon from the State\n Store client in `internal/app/archied/bootstrap.go`, the same way\n `BindingDispatcher` is.\n- The daemon's `Playbooks` dependency gains the run method. The Module\n registry is passed to the playbook store at load, so the daemon needs no\n new dependency for it.\n- With no `PlaybookDispatcher` wired, action playbooks do not run, and the\n boot warning names each one. They never run without the ledger.\n- The boot warning that action playbooks do not execute is removed when the\n ledger is wired.\n\n## Verification\n\n- A matching two-action `log` playbook runs both actions in order, and the\n second reads the first's result.\n- Pinning the same task twice under one playbook version invokes each action\n once.\n- A `when` that evaluates false skips that action and the run continues.\n- An invoke error stops the playbook. The task is still pinned to the same\n workflow it would get with no action playbook.\n- A non-matching trigger runs nothing.\n- With no ledger wired, nothing runs and the warning names the playbook.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/adversarial-self-review/",
|
||||
"title": "Adversarial self-review stage -- decision",
|
||||
@@ -190,7 +196,7 @@
|
||||
"url": "/dev/prds/dashboard-live-state/",
|
||||
"title": "Dashboard live state",
|
||||
"section": "PRDs",
|
||||
"body": "# Dashboard live state\n\n**Status:** Approved\n\n## Decision\n\nThe dashboard must not require passive **Refresh** buttons. One app-wide Pinia\nstore owns the existing `/events` EventSource and translates backend events\ninto resource revision counters. Pages load their authoritative HTTP projection\non entry and re-read it when the relevant revision changes. Event payloads are\ninvalidation signals, not substitute read models.\n\nSSE remains the transport. Dashboard updates are server-to-client only, and the\nexisting stream already provides replay, reconnect, and persisted ordering; a\nWebSocket would add a second transport without adding a capability.\n\nThe first slice covers resources for which the backend already emits a truthful\nsignal:\n\n- task events invalidate the dashboard, task board, workflow statistics, and\n the matching task-run page;\n- capture events invalidate the capture list;\n- curator events invalidate curator status, and curator actions also invalidate\n the skill catalogue;\n- update reports invalidate System status;\n- opening a page always loads its resource, and reopening the SSE stream\n invalidates mounted projections after a connection loss.\n\nLogs retain their dedicated SSE tail. Local mutations continue to re-read their\nown resource after success. Configuration, channels, and catalogues that have no\nbackend change event load on route entry; future write contracts must emit an\nowner-specific event rather than introduce polling or restore a button.\n\n## Boundaries\n\nThe Pinia store owns browser connection state and invalidation only. It does not\nbecome an alternate backend cache or copy domain state into a generic global\nobject. Existing feature modules continue to own their DTOs and API reads.\n\nOperational commands are not refresh controls. Channel **Reload** remains an\nexplicit adapter lifecycle action. Authentication recovery is also not a data\nrefresh: a 401 moves the application into shared authentication state; reloading\nthe same URL cannot restore Archie's missing or rotated token and must not be\noffered as a fix.\n\n## Verification\n\n- No passive page action renders the label **Refresh** or **Retry** for a read.\n- Only one shared `/events` EventSource is opened by the application.\n- Resource classification tests distinguish task, capture, curator, skill, and\n update invalidations.\n- UI tests, type checking, generated asset freshness, and `task check` pass.\n"
|
||||
"body": "# Dashboard live state\n\n**Status:** Approved\n\n## Decision\n\nThe dashboard must not require passive **Refresh** buttons. One app-wide Pinia\nstore owns the existing `/api/stream` EventSource and translates backend events\ninto resource revision counters. Pages load their authoritative HTTP projection\non entry and re-read it when the relevant revision changes. Event payloads are\ninvalidation signals, not substitute read models.\n\nSSE remains the transport. Dashboard updates are server-to-client only, and the\nexisting stream already provides replay, reconnect, and persisted ordering; a\nWebSocket would add a second transport without adding a capability.\n\nThe first slice covers resources for which the backend already emits a truthful\nsignal:\n\n- task events invalidate the dashboard, task board, workflow statistics, and\n the matching task-run page;\n- capture events invalidate the capture list;\n- curator events invalidate curator status, and curator actions also invalidate\n the skill catalogue;\n- update reports invalidate System status;\n- opening a page always loads its resource, and reopening the SSE stream\n invalidates mounted projections after a connection loss.\n\nLogs retain their dedicated SSE tail. Local mutations continue to re-read their\nown resource after success. Configuration, channels, and catalogues that have no\nbackend change event load on route entry; future write contracts must emit an\nowner-specific event rather than introduce polling or restore a button.\n\n## Boundaries\n\nThe Pinia store owns browser connection state and invalidation only. It does not\nbecome an alternate backend cache or copy domain state into a generic global\nobject. Existing feature modules continue to own their DTOs and API reads.\n\nOperational commands are not refresh controls. Channel **Reload** remains an\nexplicit adapter lifecycle action. Authentication recovery is also not a data\nrefresh: a 401 moves the application into shared authentication state; reloading\nthe same URL cannot restore Archie's missing or rotated token and must not be\noffered as a fix.\n\n## Verification\n\n- No passive page action renders the label **Refresh** or **Retry** for a read.\n- Only one shared `/api/stream` EventSource is opened by the application.\n- Resource classification tests distinguish task, capture, curator, skill, and\n update invalidations.\n- UI tests, type checking, generated asset freshness, and `task check` pass.\n"
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/dashboard-navigation-groups/",
|
||||
@@ -226,7 +232,7 @@
|
||||
"url": "/dev/prds/eda-playbook-engine/",
|
||||
"title": "EDA playbook engine -- design",
|
||||
"section": "PRDs",
|
||||
"body": "# EDA playbook engine -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Beads epic:** `archie-core-t2db`\n\n## Problem\n\n\"Which workflow runs for which trigger\" is hardcoded Go: a literal\nlabel vocabulary (`workintake.labelKinds`) and a literal label-\u003eworkflow map\n(`workflow/routing.go`), extended only by adding a Go case or shipping a\nskill whose `metadata.archie.workflow` overrides one *named* built-in\nworkflow. Extending the system to a new trigger, a new action, or a new\nevent source means a feature branch, a code change in a hardcoded\npath, and new Go tests -- for every addition. That is the barrier this\ndocument exists to remove.\n\nThe goal: triggers, the actions they run, and the\nconditions that connect them should be **drop-in and load**, not **drop-in\nand touch application code**. Yaegi-evaluated Go is the unit of imperative\n\"do a thing\" logic; YAML playbooks are pure orchestration data -- no logic,\njust \"on this event, with this data, call these actions, in this order,\nunder these conditions.\" The daemon's event coordinator doesn't know what a\n`bugfix` or `image-gen` action does, it resolves the name against a\nregistry and pipes typed data through.\n\nThis is explicitly **not** scoped to code-generation workflows. A playbook\naction can be any registered capability -- run a codegen workflow, send a\nmessage on a channel, open something on a forge, generate an image -- so\nlong as it's implemented behind one of the typed engine families below.\n\n## Relationship to existing decisions\n\n- `docs/prds/event-sources-and-reactions.md` ruled\n that reactions in the two epics it covers are **producer-only** (no veto,\n no mutation of in-flight work) and explicitly rejected a single generic\n `Source` interface as \"the untyped-hook shape the plugin engine rule\n exists to prevent.\" **This document extends that scope**: playbooks can\n dispatch to multiple typed action kinds, not just \"produce a\n `TaskEnvelope`.\" It does not relitigate producer-only-ness (still no\n veto/mutation of in-flight work here) and it does not introduce one\n generic interface -- see \"Typed positions, not one generic hook\" below,\n which is how it stays compliant with the plugin engine rule instead of\n reopening that document's #4.\n- `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`\n governs every extension point\n introduced here. Every position below is a typed domain contract with an\n owning registry, not a generic callback map. This is a hard constraint,\n confirmed against the existing rule text before writing this doc.\n- Yaegi is already a proven in-process extension mechanism\n (`internal/plugin`, `internal/domain/workflow/wfeval/yaegi.go`,\n `internal/gate/gateeval/yaegi.go`, `internal/skill/plugin.go`) -- this\n design generalizes its existing role, it does not introduce a new\n execution mechanism.\n- `internal/domain/workflow/skillbuild.BuildRegistry` already composes a\n `workflow.Registry` from a skills catalog, plugin-defined overriding\n built-in. The playbook loader described here supersedes label routing\n specifically; it does not replace `skillbuild`'s workflow-composition role,\n it becomes an additional input the daemon composes at startup.\n- Webhook event intake is a separate design. This\n document defines the router each webhook-sourced event should be able to\n reach; it does not redesign webhook receipt itself.\n\n## Shape: four logic positions, each a typed engine family\n\nEvery entrypoint kind (mechanism, action, loop, schedule, route, trigger) is itself a schema emitter: defining a new kind produces the\ngenerated contract downstream tooling consumes. The kinds slot into a fixed\nhierarchy of logic positions:\n\n```\nWorkflow -\u003e Module -\u003e Channel (telegram/whatsapp/email/...)\n -\u003e Forge (GitHub/Gitea/GitLab/...)\n```\n\nEach position is its own typed engine family per the plugin engine rule:\nidentity + capability-specific operations, an owning `Registry`/`Manager`,\nexplicit lifecycle where the implementation owns resources, narrow host\naccess. Concretely:\n\n- **Workflow** -- already exists (`internal/domain/workflow`). A playbook\n action of kind `workflow` invokes a registered `workflow.Registry` entry\n by name, unchanged from the existing execution path.\n- **Module** -- the new general-purpose action position. A `Module` is a\n Yaegi-evaluated implementation of a generated interface (args in, typed\n result out) for one declared action kind (e.g. `image-gen`, `notify`,\n `open-pr-comment`). This is the position that makes actions \"not\n restricted to code-generation.\" Full design (schema-per-kind, the\n registry shape, the trust boundary, the recommended first slice):\n `docs/prds/module-position.md`.\n- **Channel** -- already exists as `channels.Channel` (telegram, email,\n webhook). A playbook action of kind `channel` sends through Line truncated
|
||||
"body": "# EDA playbook engine -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Beads epic:** `archie-core-t2db`\n\n## Problem\n\n\"Which workflow runs for which trigger\" is hardcoded Go: a literal\nlabel vocabulary (`workintake.labelKinds`) and a literal label-\u003eworkflow map\n(`workflow/routing.go`), extended only by adding a Go case or shipping a\nskill whose `metadata.archie.workflow` overrides one *named* built-in\nworkflow. Extending the system to a new trigger, a new action, or a new\nevent source means a feature branch, a code change in a hardcoded\npath, and new Go tests -- for every addition. That is the barrier this\ndocument exists to remove.\n\nThe goal: triggers, the actions they run, and the\nconditions that connect them should be **drop-in and load**, not **drop-in\nand touch application code**. Yaegi-evaluated Go is the unit of imperative\n\"do a thing\" logic; YAML playbooks are pure orchestration data -- no logic,\njust \"on this event, with this data, call these actions, in this order,\nunder these conditions.\" The daemon's event coordinator doesn't know what a\n`bugfix` or `image-gen` action does, it resolves the name against a\nregistry and pipes typed data through.\n\nThis is explicitly **not** scoped to code-generation workflows. A playbook\naction can be any registered capability -- run a codegen workflow, send a\nmessage on a channel, open something on a forge, generate an image -- so\nlong as it's implemented behind one of the typed engine families below.\n\n## Relationship to existing decisions\n\n- `docs/prds/event-sources-and-reactions.md` ruled\n that reactions in the two epics it covers are **producer-only** (no veto,\n no mutation of in-flight work) and explicitly rejected a single generic\n `Source` interface as \"the untyped-hook shape the plugin engine rule\n exists to prevent.\" **This document extends that scope**: playbooks can\n dispatch to multiple typed action kinds, not just \"produce a\n `TaskEnvelope`.\" It does not relitigate producer-only-ness (still no\n veto/mutation of in-flight work here) and it does not introduce one\n generic interface -- see \"Typed positions, not one generic hook\" below,\n which is how it stays compliant with the plugin engine rule instead of\n reopening that document's #4.\n- `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`\n governs every extension point\n introduced here. Every position below is a typed domain contract with an\n owning registry, not a generic callback map. This is a hard constraint,\n confirmed against the existing rule text before writing this doc.\n- Yaegi is already a proven in-process extension mechanism\n (`internal/plugin`, `internal/domain/workflow/wfeval/yaegi.go`,\n `internal/gate/gateeval/yaegi.go`, `internal/skill/plugin.go`) -- this\n design generalizes its existing role, it does not introduce a new\n execution mechanism.\n- `internal/domain/workflow/skillbuild.BuildRegistry` already composes a\n `workflow.Registry` from a skills catalog, plugin-defined overriding\n built-in. The playbook loader described here supersedes label routing\n specifically; it does not replace `skillbuild`'s workflow-composition role,\n it becomes an additional input the daemon composes at startup.\n- Webhook event intake is a separate design. This\n document defines the router each webhook-sourced event should be able to\n reach; it does not redesign webhook receipt itself.\n\n## Shape: four logic positions, each a typed engine family\n\nEvery entrypoint kind (mechanism, action, loop, schedule, route, trigger) is itself a schema emitter: defining a new kind produces the\ngenerated contract downstream tooling consumes. The kinds slot into a fixed\nhierarchy of logic positions:\n\n```\nWorkflow -\u003e Module -\u003e Channel (telegram/whatsapp/email/...)\n -\u003e Forge (GitHub/Gitea/GitLab/...)\n```\n\nEach position is its own typed engine family per the plugin engine rule:\nidentity + capability-specific operations, an owning `Registry`/`Manager`,\nexplicit lifecycle where the implementation owns resources, narrow host\naccess. Concretely:\n\n- **Workflow** -- already exists (`internal/domain/workflow`). A playbook\n action of kind `workflow` invokes a registered `workflow.Registry` entry\n by name, unchanged from the existing execution path.\n- **Module** -- the new general-purpose action position. A `Module` is a\n Yaegi-evaluated implementation of a generated interface (args in, typed\n result out) for one declared action kind (e.g. `image-gen`, `notify`,\n `open-pr-comment`). This is the position that makes actions \"not\n restricted to code-generation.\" Full design (schema-per-kind, the\n registry shape, the trust boundary, the recommended first slice):\n `docs/prds/module-position.md`.\n- **Channel** -- already exists as `channels.Channel` (telegram, email,\n webhook). A playbook action of kind `channel` sends through Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/embedded-nats/",
|
||||
@@ -298,7 +304,7 @@
|
||||
"url": "/dev/prds/multi-action-playbooks/",
|
||||
"title": "Multi-action playbooks and typed action results",
|
||||
"section": "PRDs",
|
||||
"body": "# Multi-action playbooks and typed action results\n\n**Status:** Approved\n**Date:** 2026-09-22\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-nx30` (unblocks `archie-core-t2db.27` and `archie-core-t2db.31`)\n\n## Why this exists\n\n`eda-playbook-engine.md`'s hard boundary rejects any playbook that is not\nexactly one `workflow` action, so the parent document's data-flow, Module and\nChannel/Forge decisions have no loadable shape to attach to. The boundary's own\nstated condition is now met: both execution-time gaps are resolved\n(`eda-playbook-engine.md`, \"Execution-time gaps\"; the `playbook_dispatches`\nledger). This document designs the relaxation.\n\n## A playbook is one of two shapes\n\n- A **workflow playbook** is exactly one `workflow` action. Unchanged: it names\n a workflow definition and is routed by the daemon's definition pin.\n- An **action playbook** is one or more `module` actions in order. Each action\n has an optional `id`, a `kind` naming a registered Module kind, `args`, and an\n optional `when`.\n\nOne playbook does not mix the two shapes.\n\n```yaml\ntrigger: { kind: bug }\nactions:\n - id: build\n position: module\n kind: log\n args: { message: '\"build started\"' }\n - id: done\n position: module\n kind: log\n args: { message: '\"done: \" + string(actions.build.result.written)' }\n when: actions.build.result.written == true\n```\n\nThe first Module kind is the side-effect-free `log` kind\n(`module-position.md`, \"Recommended first slice\"). A Module kind with an\nexternal side effect, and the Channel and Forge positions, are out of scope.\n\n## A result type is the kind's generated Result struct\n\nEach Module kind owns a hand-written `Args` and `Result` struct\n(`internal/domain/eda/module/log` is the worked example); `ModuleRegistry.Invoke`\nreturns the result as a flat `map[string]any`. `ModuleRegistry.DecodeResult`\n(`internal/domain/eda/module`) is the single site that converts that map into\nthe kind's `Result` struct before a later expression reads it, so the value the\nchecker validates and the value the run reads have one definition.\n\n`actions.\u003cid\u003e` is typed by the kind of the action that declares `\u003cid\u003e`:\n`{ result: \u003cKindResult\u003e }`. `event` stays `dyn` (J4,\n`playbook-expression-syntax.md`).\n\n## Reject-at-load, preserved\n\nRelaxing the boundary must not make a bad reference resolvable. The load fails,\nnaming the playbook and the offending action, for:\n\n- an `id` missing where a later action references it, duplicated, or outside\n its shape's grammar: a workflow action id keeps the shared\n stable-identifier grammar (J1, already enforced), while a module action id\n must be a lowercase CEL field name writable as `actions.\u003cid\u003e` (so a CEL\n keyword such as `in`, `true`, `false`, or `null` is rejected at load);\n- an `actions.\u003cid\u003e` read of an id no earlier action declares;\n- an `actions` read that is not statically resolvable to an id (any map index,\n literal or dynamic, `in`, a comprehension): the typed `actions` root is an\n object type, so only field selection `actions.\u003cid\u003e` resolves and the\n `actions[\"id\"]` spelling is not accepted;\n- a `result` field the referenced kind's `Result` does not define;\n- a reference to an earlier action that produces no result;\n- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;\n- a field belonging to the other shape (`kind` on a `workflow` action, or\n `workflow` on a `module` action);\n- an arg KEY the kind's `Args` schema does not define. Arg VALUE type-checking\n is tracked as `archie-core-t2db` debt, not shipped here.\n\nDeclaring the kind's `Result` schema to CEL at load makes a result-field typo a\nload failure rather than a dispatch failure. Matching arg keys against the\nkind's `Args` schema makes an arg-key typo a load failure; arg value\ntype-checking is tracked as `archie-core-t2db` debt.\n\n## The environment is per playbook\n\nResult typing depends on the ids a playbook declares and the kind each id runs,\nso the CEL environment is built from one playbook's action list rather than once\nper `Store`, and `expr.NewEnv` takes that list: each declared id becomes a field\nof the `actions` object typed by its kind's `Result`.\n\n## Running an action playbook is out of scope\n\nThis document makes an action playbook load and its references type-check. It\ndoes not invoke a Module kind. Invocation, the `playbook_dispatches` gate, and\nstop-on-first-failure across actions are `archie-core-t2db.31`.\n\n## Decisions\n\n**D1 — dispatch before `t2db.31`.** Settled: an action playbook loads and\nvalidates but is not routed; the definition-pin dispatch reports no match for it,\nand the daemon logs a visible warning naming it.\n\n**D2 — mixing positions.** Settled: one shape per playbook. A `workflow` action\nyields a task, not a rLine truncated
|
||||
"body": "# Multi-action playbooks and typed action results\n\n**Status:** Approved\n**Date:** 2026-09-22\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-nx30` (unblocks `archie-core-t2db.27` and `archie-core-t2db.31`)\n\n## Why this exists\n\n`eda-playbook-engine.md`'s hard boundary rejects any playbook that is not\nexactly one `workflow` action, so the parent document's data-flow, Module and\nChannel/Forge decisions have no loadable shape to attach to. The boundary's own\nstated condition is now met: both execution-time gaps are resolved\n(`eda-playbook-engine.md`, \"Execution-time gaps\"; the `playbook_dispatches`\nledger). This document designs the relaxation.\n\n## A playbook is one of two shapes\n\n- A **workflow playbook** is exactly one `workflow` action. Unchanged: it names\n a workflow definition and is routed by the daemon's definition pin.\n- An **action playbook** is one or more `module` actions in order. Each action\n has an optional `id`, a `kind` naming a registered Module kind, `args`, and an\n optional `when`.\n\nOne playbook does not mix the two shapes.\n\n```yaml\ntrigger: { kind: bug }\nactions:\n - id: build\n position: module\n kind: log\n args: { message: '\"build started\"' }\n - id: done\n position: module\n kind: log\n args: { message: '\"done: \" + string(actions.build.result.written)' }\n when: actions.build.result.written == true\n```\n\nThe first Module kind is the side-effect-free `log` kind\n(`module-position.md`, \"Recommended first slice\"). A Module kind with an\nexternal side effect, and the Channel and Forge positions, are out of scope.\n\n## A result type is the kind's generated Result struct\n\nEach Module kind owns a hand-written `Args` and `Result` struct\n(`internal/domain/eda/module/log` is the worked example); `ModuleRegistry.Invoke`\nreturns the result as a flat `map[string]any`. `ModuleRegistry.DecodeResult`\n(`internal/domain/eda/module`) is the single site that converts that map into\nthe kind's `Result` struct before a later expression reads it, so the value the\nchecker validates and the value the run reads have one definition.\n\n`actions.\u003cid\u003e` is typed by the kind of the action that declares `\u003cid\u003e`:\n`{ result: \u003cKindResult\u003e }`. `event` stays `dyn` (J4,\n`playbook-expression-syntax.md`).\n\n## Reject-at-load, preserved\n\nRelaxing the boundary must not make a bad reference resolvable. The load fails,\nnaming the playbook and the offending action, for:\n\n- an `id` missing where a later action references it, duplicated, or outside\n its shape's grammar: a workflow action id keeps the shared\n stable-identifier grammar (J1, already enforced), while a module action id\n must be a lowercase CEL field name writable as `actions.\u003cid\u003e` (so a CEL\n keyword such as `in`, `true`, `false`, or `null` is rejected at load);\n- an `actions.\u003cid\u003e` read of an id no earlier action declares;\n- an `actions` read that is not statically resolvable to an id (any map index,\n literal or dynamic, `in`, a comprehension): the typed `actions` root is an\n object type, so only field selection `actions.\u003cid\u003e` resolves and the\n `actions[\"id\"]` spelling is not accepted;\n- a `result` field the referenced kind's `Result` does not define;\n- a reference to an earlier action that produces no result;\n- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;\n- a field belonging to the other shape (`kind` on a `workflow` action, or\n `workflow` on a `module` action);\n- an arg KEY the kind's `Args` schema does not define;\n- an arg value whose checked CEL type cannot fill its `Args` field (`'123'`\n for a string field). A `dyn` value, such as an `event` read, passes: its\n type is known only per event, and the module decode refuses a bad one at\n run.\n\nDeclaring the kind's `Result` schema to CEL at load makes a result-field typo a\nload failure rather than a dispatch failure. Matching arg keys against the\nkind's `Args` schema makes an arg-key typo or a wrongly typed value a load\nfailure.\n\n## The environment is per playbook\n\nResult typing depends on the ids a playbook declares and the kind each id runs,\nso the CEL environment is built from one playbook's action list rather than once\nper `Store`, and `expr.NewEnv` takes that list: each declared id becomes a field\nof the `actions` object typed by its kind's `Result`.\n\n## Running an action playbook is out of scope\n\nThis document makes an action playbook load and its references type-check.\nRunning one is designed in `docs/prds/action-playbook-run.md`.\n\n## Decisions\n\n**D1 — dispatch before `t2db.31`.** Superseded by\n`docs/prds/action-playbook-run.md`. Was: an action playbook loads and\nvalidates but is not routed; the definition-pin dispatch reports no match for it,\nand the daemon logs a visible warning naming it.\n\n**D2 — mixing positions.*Line truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/news-and-releases/",
|
||||
@@ -394,7 +400,7 @@
|
||||
"url": "/dev/prds/state-store-contract/",
|
||||
"title": "State Store — contract boundary \u0026 transport (ratification)",
|
||||
"section": "PRDs",
|
||||
"body": "# State Store — contract boundary \u0026 transport (ratification)\n\n**Status:** Approved\n**Revision:** 2e\n**Date:** 2026-09-06\n\nThis is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalize\n`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)\nimplement against.\n**Beads milestone:** archie-core-8cda.4.1\n**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)\n\nThis document fixes the **contract boundary** and **transport** for the State Store service.\nIt does not redesign Archie's domain model, does not invent a second store, and does **not**\nsplit `archie.db`. It records method ownership, DTO/wire representation, error semantics,\nlimits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that\n`.4.2` and `.4.3` have exactly one authoritative surface to build against.\n\n\u003e **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.\n\u003e 4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in\n\u003e `internal/domain/workflow`, the six production workflow files import no `internal/store`\n\u003e symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of\n\u003e `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own\n\u003e service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.\n\n\u003e **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/\n\u003e migration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\n\u003e StepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)\n\u003e **remains the authoritative, open document for the long-term Workflow migration.** This PRD\n\u003e does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface\n\u003e relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);\n\u003e the rest of §4 stays its own migration and stays open.\n\n---\n\n## 1. Decision (the invariant everything follows)\n\nArchie is composed such that a single **`archie-state-store`** service owns the one existing\nSQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is\nexactly one store, one file, one service. No database-per-service, no distributed\ntransactions, no second store abstraction.\n\nTwo adapter families satisfy the contract interfaces:\n\n- **Local adapter** — `*store.Store` (the in-process SQLite implementation).\n- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).\n\nEach adapter carries an explicit compile-time assertion against the contract interfaces it\nserves. Composition picks local vs. remote by the presence of `[services.state].target`\n(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet\nextracted), which is the PRD §3 posture; it differs from the gateway's remote-default only\nbecause the gateway is already a separate deployment and the State Store is not.\n\n\u003e **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**\n\u003e Ownership splits by the consumer's *layer*, per the dependency contract's rule #2\n\u003e (\"a domain defines the smallest interfaces required to perform its work\") and rule #7\n\u003e (\"database rows … MUST NOT leak into domain models\"):\n\u003e\n\u003e - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of\n\u003e store state. It defines its own **consumer-owned** narrow `Store` interface\n\u003e (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus\n\u003e `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the\n\u003e Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4\n\u003e (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion\n\u003e requires it.\n\u003e - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,\n\u003e `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay\n\u003e **producer-owned** in `internal/store`, because those consumers are application and\n\u003e infrastructure layers, not domains — rule #2 does not apply to them.\n\nSo the State Store contract is **not** uniformly producer-owned: the domain-facing workflow\ncontract is consumer-owned (in the domain), while the daemon/webui store surfaces remain in\n`internal/store`. `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/\n`Source` types it persists (persistence → domain, the correct direction), and its `Store`\nimplementation satisfies `workflow.Store`. This is the single decision that makes the whole\nPhase 2 acceptance criterioLine truncated
|
||||
"body": "# State Store — contract boundary \u0026 transport (ratification)\n\n**Status:** Approved\n**Revision:** 2e\n**Date:** 2026-09-06\n\nThis is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalize\n`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)\nimplement against.\n**Beads milestone:** archie-core-8cda.4.1\n**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)\n\nThis document fixes the **contract boundary** and **transport** for the State Store service.\nIt does not redesign Archie's domain model, does not invent a second store, and does **not**\nsplit `archie.db`. It records method ownership, DTO/wire representation, error semantics,\nlimits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that\n`.4.2` and `.4.3` have exactly one authoritative surface to build against.\n\n\u003e **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.\n\u003e 4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in\n\u003e `internal/domain/workflow`, the six production workflow files import no `internal/store`\n\u003e symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of\n\u003e `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own\n\u003e service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.\n\n\u003e **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/\n\u003e migration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\n\u003e StepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)\n\u003e **remains the authoritative, open document for the long-term Workflow migration.** This PRD\n\u003e does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface\n\u003e relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);\n\u003e the rest of §4 stays its own migration and stays open.\n\n---\n\n## 1. Decision (the invariant everything follows)\n\nArchie is composed such that a single **`archie-state-store`** service owns the one existing\nSQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is\nexactly one store, one file, one service. No database-per-service, no distributed\ntransactions, no second store abstraction.\n\nTwo adapter families satisfy the contract interfaces:\n\n- **Local adapter** — `*store.Store` (the in-process SQLite implementation).\n- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).\n\nEach adapter carries an explicit compile-time assertion against the contract interfaces it\nserves. Composition picks local vs. remote by the presence of `[services.state].target`\n(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet\nextracted), which is the PRD §3 posture; it differs from the gateway's remote-default only\nbecause the gateway is already a separate deployment and the State Store is not.\n\n\u003e **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**\n\u003e Ownership splits by the consumer's *layer*, per the dependency contract's rule #2\n\u003e (\"a domain defines the smallest interfaces required to perform its work\") and rule #7\n\u003e (\"database rows … MUST NOT leak into domain models\"):\n\u003e\n\u003e - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of\n\u003e store state. It defines its own **consumer-owned** narrow `Store` interface\n\u003e (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus\n\u003e `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the\n\u003e Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4\n\u003e (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion\n\u003e requires it.\n\u003e - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,\n\u003e `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay\n\u003e **producer-owned** in `internal/store`, because those consumers are application and\n\u003e infrastructure layers, not domains — rule #2 does not apply to them.\n\nSo the State Store contract is **not** uniformly producer-owned: the domain-facing workflow\ncontract is consumer-owned (in the domain), while the daemon/webui store surfaces remain in\n`internal/store`. `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/\n`Source` types it persists (persistence → domain, the correct direction), and its `Store`\nimplementation satisfies `workflow.Store`. This is the single decision that makes the whole\nPhase 2 acceptance criterioLine truncated
|
||||
},
|
||||
{
|
||||
"url": "/dev/prds/status-health-surface/",
|
||||
@@ -521,6 +527,10 @@
|
||||
"title": "PRD writing rules",
|
||||
"url": "/dev/prds/RULES/"
|
||||
},
|
||||
{
|
||||
"title": "Running action playbooks",
|
||||
"url": "/dev/prds/action-playbook-run/"
|
||||
},
|
||||
{
|
||||
"title": "Adversarial self-review stage -- decision",
|
||||
"url": "/dev/prds/adversarial-self-review/"
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# Running action playbooks
|
||||
|
||||
**Status:** Approved
|
||||
**Date:** 2026-09-23
|
||||
**Parent:** `docs/prds/multi-action-playbooks.md`, epic `archie-core-t2db`
|
||||
**Beads issue:** `archie-core-t2db.31`
|
||||
|
||||
## Why this exists
|
||||
|
||||
An action playbook loads and type-checks but never runs: `Store.Dispatch`
|
||||
skips it and the daemon logs a warning at boot (`multi-action-playbooks.md`,
|
||||
D1). This document defines when it runs, what each action does, and how the
|
||||
`playbook_dispatches` ledger gates it.
|
||||
|
||||
## When a playbook runs
|
||||
|
||||
The daemon runs action playbooks at the point it pins a task's workflow
|
||||
definition (`Daemon.resolveWorkflowID`), using the same `DispatchInput` the
|
||||
workflow playbooks use. The definition is pinned once per task, so the run
|
||||
happens once per task.
|
||||
|
||||
- Every action playbook whose trigger matches runs, in load order. A workflow
|
||||
playbook stops at the first match because it chooses one workflow; action
|
||||
playbooks choose nothing, so no match suppresses another.
|
||||
- A run never changes routing. The task is pinned by the workflow playbooks
|
||||
and bindings exactly as when no action playbook exists.
|
||||
- An action or playbook failure never parks or fails the task. It is logged
|
||||
at warning level with the playbook, the action and the task.
|
||||
- A task that already names a workflow (the approval requeue) is skipped, as
|
||||
it is for workflow playbooks.
|
||||
- Actions run synchronously in the pin path, bounded by the daemon's context.
|
||||
The only Module kind, `log`, returns immediately. A slow kind must bring its
|
||||
own timeout.
|
||||
|
||||
## What one action does
|
||||
|
||||
Actions run in order against one evaluation context whose `actions` map
|
||||
starts empty.
|
||||
|
||||
1. Evaluate `when`. False or an evaluation error skips the action (J3). A
|
||||
skipped action records nothing and produces no result.
|
||||
2. Evaluate every `args` value. An evaluation error stops the playbook.
|
||||
3. Call `playbook.InvokeOnce` with the Module invoke as its function. The
|
||||
ledger row is written first. A duplicate row skips the invoke.
|
||||
4. An invoke error stops the playbook. The row stays, so the action is not
|
||||
retried: the ledger promises at most once, not at least once.
|
||||
5. On success, `ModuleRegistry.DecodeResult` converts the result, and it is
|
||||
stored as `actions.<id>.result` when the action declares an id.
|
||||
|
||||
The event id in the ledger key is `DispatchInput.TaskID`, the issue's
|
||||
idempotency key (`owner/repo/number`). An action therefore runs at most once
|
||||
per issue for each playbook version. Editing a playbook changes its version
|
||||
and lets it run again for issues it already handled.
|
||||
|
||||
A skipped duplicate has no result. A later action that reads it sees a
|
||||
missing field: its `when` evaluates false, or its args fail and the playbook
|
||||
stops. This only happens when the same issue is pinned twice under one
|
||||
playbook version.
|
||||
|
||||
## Wiring
|
||||
|
||||
- `storecontract.PlaybookDispatcher` is lifted onto the daemon from the State
|
||||
Store client in `internal/app/archied/bootstrap.go`, the same way
|
||||
`BindingDispatcher` is.
|
||||
- The daemon's `Playbooks` dependency gains the run method. The Module
|
||||
registry is passed to the playbook store at load, so the daemon needs no
|
||||
new dependency for it.
|
||||
- With no `PlaybookDispatcher` wired, action playbooks do not run, and the
|
||||
boot warning names each one. They never run without the ledger.
|
||||
- The boot warning that action playbooks do not execute is removed when the
|
||||
ledger is wired.
|
||||
|
||||
## Verification
|
||||
|
||||
- A matching two-action `log` playbook runs both actions in order, and the
|
||||
second reads the first's result.
|
||||
- Pinning the same task twice under one playbook version invokes each action
|
||||
once.
|
||||
- A `when` that evaluates false skips that action and the run continues.
|
||||
- An invoke error stops the playbook. The task is still pinned to the same
|
||||
workflow it would get with no action playbook.
|
||||
- A non-matching trigger runs nothing.
|
||||
- With no ledger wired, nothing runs and the warning names the playbook.
|
||||
@@ -5,7 +5,7 @@
|
||||
## Decision
|
||||
|
||||
The dashboard must not require passive **Refresh** buttons. One app-wide Pinia
|
||||
store owns the existing `/events` EventSource and translates backend events
|
||||
store owns the existing `/api/stream` EventSource and translates backend events
|
||||
into resource revision counters. Pages load their authoritative HTTP projection
|
||||
on entry and re-read it when the relevant revision changes. Event payloads are
|
||||
invalidation signals, not substitute read models.
|
||||
@@ -46,7 +46,7 @@ offered as a fix.
|
||||
## Verification
|
||||
|
||||
- No passive page action renders the label **Refresh** or **Retry** for a read.
|
||||
- Only one shared `/events` EventSource is opened by the application.
|
||||
- Only one shared `/api/stream` EventSource is opened by the application.
|
||||
- Resource classification tests distinguish task, capture, curator, skill, and
|
||||
update invalidations.
|
||||
- UI tests, type checking, generated asset freshness, and `task check` pass.
|
||||
@@ -167,11 +167,11 @@ a case that should just be visible and fixed by a human. Instead:
|
||||
playbook directories against the exact loaders the daemon uses
|
||||
(`LoadPlaybookDirs`/`LoadKindWorkflowsYAML`/`LoadLabelWorkflowsYAML`),
|
||||
exiting non-zero on any collision / malformed file / invalid binding.
|
||||
Findings are file-granular, not line-granular: the loader decodes with
|
||||
`yaml.Unmarshal` into a plain map, which discards line numbers. A
|
||||
compiler-style file:line diagnostic needs a `yaml.Node` decoding
|
||||
upgrade, tracked separately -- the linter agrees with runtime
|
||||
validation by construction, which is the load-bearing property.
|
||||
A finding about one binding key leads with the key's `file:line`, read
|
||||
from the `yaml.Node` the loader decodes; the linter agrees with runtime
|
||||
validation by construction, which is the load-bearing property. `-eda-dir`
|
||||
lints an `eda_playbook_dir` the same way, through `playbook.Load` with its
|
||||
CEL, action-id and args checks.
|
||||
Discoverable via `task lint:playbooks` or direct `go run
|
||||
./cmd/archie-playbooks lint -dir ...`. The LSP/serve mode is a later
|
||||
entrypoint of the SAME binary, per the shared-package decision above.
|
||||
@@ -180,6 +180,14 @@ a case that should just be visible and fixed by a human. Instead:
|
||||
explicitly in scope per Sam (not deferred), because it's the same schema
|
||||
artifact as the linter's, just a different consumer.
|
||||
|
||||
`archie-playbooks serve` is the language server, over stdio. When a file is
|
||||
opened or saved it lints the file's saved directory with the loader the
|
||||
daemon runs for it (a file with a top-level `trigger` key is an EDA
|
||||
playbook, anything else a routing binding file) and publishes the findings
|
||||
for that file as error diagnostics, each on the line of the key, action,
|
||||
`when` or args key it names; a file-level finding sits on the first line.
|
||||
Unsaved edits are not validated. Hover and completion are later additions.
|
||||
|
||||
The startup log-and-refuse path exists for what the linter/LSP structurally
|
||||
cannot see -- sources composed together only at daemon startup, never
|
||||
checked against each other by either tool. If the linter and LSP do the job
|
||||
@@ -373,14 +381,19 @@ by `internal/store` -- the same shape as `BindingDispatcher`
|
||||
store's schema application (`internal/store/store.go`). No change
|
||||
to `internal/eventbus`; no per-message dedup state on the client.
|
||||
|
||||
**Lifetime: no time-based expiry.** Rows live as long as their playbook
|
||||
exists; when a playbook is removed from the configured directories, the
|
||||
coordinator deletes its rows -- mirroring binding-dispatches-rows-deleted-
|
||||
with-binding (`bindings.go`, same transaction as the delete). The
|
||||
at-most-once guarantee must not silently decay, which is exactly the
|
||||
property that disqualifies `DedupWindow` above; table growth is bounded
|
||||
by distinct (playbook, event, action) pairs over the playbook's lifetime
|
||||
and is accepted, the same tradeoff `binding_dispatches` already makes.
|
||||
**Lifetime: no time-based expiry, and no automatic reclamation.** Rows are
|
||||
retained until an explicit `DeletePlaybookDispatches` for their playbook.
|
||||
Removing a playbook file does not delete its rows: playbooks are read only
|
||||
at boot, so the only place to notice a removal is a boot-time reconcile,
|
||||
and a boot that finds the directory missing or unmounted loads as "no
|
||||
playbooks" and would reclaim the whole ledger, letting redelivered events
|
||||
fire their side effects again. A binding's rows go with an explicit
|
||||
operator delete (`bindings.go`, same transaction); a file disappearing is
|
||||
not an equally deliberate act. The at-most-once guarantee must not
|
||||
silently decay, which is exactly the property that disqualifies
|
||||
`DedupWindow` above; table growth is bounded by distinct (playbook,
|
||||
event, action) pairs and is accepted, the same tradeoff
|
||||
`binding_dispatches` already makes.
|
||||
|
||||
**Redelivery behavior: skip the recorded action and continue the run.**
|
||||
A detected duplicate is not re-invoked, is not reported to the caller as
|
||||
|
||||
@@ -75,13 +75,16 @@ naming the playbook and the offending action, for:
|
||||
- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;
|
||||
- a field belonging to the other shape (`kind` on a `workflow` action, or
|
||||
`workflow` on a `module` action);
|
||||
- an arg KEY the kind's `Args` schema does not define. Arg VALUE type-checking
|
||||
is tracked as `archie-core-t2db` debt, not shipped here.
|
||||
- an arg KEY the kind's `Args` schema does not define;
|
||||
- an arg value whose checked CEL type cannot fill its `Args` field (`'123'`
|
||||
for a string field). A `dyn` value, such as an `event` read, passes: its
|
||||
type is known only per event, and the module decode refuses a bad one at
|
||||
run.
|
||||
|
||||
Declaring the kind's `Result` schema to CEL at load makes a result-field typo a
|
||||
load failure rather than a dispatch failure. Matching arg keys against the
|
||||
kind's `Args` schema makes an arg-key typo a load failure; arg value
|
||||
type-checking is tracked as `archie-core-t2db` debt.
|
||||
kind's `Args` schema makes an arg-key typo or a wrongly typed value a load
|
||||
failure.
|
||||
|
||||
## The environment is per playbook
|
||||
|
||||
@@ -92,13 +95,13 @@ of the `actions` object typed by its kind's `Result`.
|
||||
|
||||
## Running an action playbook is out of scope
|
||||
|
||||
This document makes an action playbook load and its references type-check. It
|
||||
does not invoke a Module kind. Invocation, the `playbook_dispatches` gate, and
|
||||
stop-on-first-failure across actions are `archie-core-t2db.31`.
|
||||
This document makes an action playbook load and its references type-check.
|
||||
Running one is designed in `docs/prds/action-playbook-run.md`.
|
||||
|
||||
## Decisions
|
||||
|
||||
**D1 — dispatch before `t2db.31`.** Settled: an action playbook loads and
|
||||
**D1 — dispatch before `t2db.31`.** Superseded by
|
||||
`docs/prds/action-playbook-run.md`. Was: an action playbook loads and
|
||||
validates but is not routed; the definition-pin dispatch reports no match for it,
|
||||
and the daemon logs a visible warning naming it.
|
||||
|
||||
@@ -110,8 +113,8 @@ yields a task, not a result, so it cannot feed `actions.<id>.result`.
|
||||
by the kind's `Result` struct. `internal/domain/eda/expr` implements it with the
|
||||
generic `actionResultProvider`.
|
||||
|
||||
**D4 — `args` against the kind's `Args` schema.** Settled: arg KEY checking ships
|
||||
now. Arg value type-checking is tracked as `archie-core-t2db` debt.
|
||||
**D4 — `args` against the kind's `Args` schema.** Settled: keys and statically
|
||||
typed values are checked at load; `dyn` values are checked by the module decode.
|
||||
|
||||
**D5 — where the result map becomes the `Result` struct.** Settled:
|
||||
`ModuleRegistry` stays schema-agnostic. `ModuleRegistry.DecodeResult`
|
||||
@@ -123,7 +126,7 @@ now. Arg value type-checking is tracked as `archie-core-t2db` debt.
|
||||
loads; the same read of a field the kind's `Result` does not define fails the
|
||||
load naming the field; a read of an id no earlier action declares fails; a
|
||||
dynamically indexed `actions` read fails.
|
||||
- An arg KEY the kind's `Args` schema does not define fails the load. Arg VALUE
|
||||
type-checking is tracked as `archie-core-t2db` debt.
|
||||
- An arg KEY the kind's `Args` schema does not define fails the load, and so
|
||||
does `message: '123'` for the `log` kind. `message: event.title` loads.
|
||||
- The one-action `workflow` playbook shape, its dispatch, and its existing
|
||||
load-time checks are unchanged.
|
||||
@@ -305,8 +305,9 @@ row is the structural `(playbook_id, playbook_version, event_id, action_id)`
|
||||
tuple, written **before** the action's side effect fires (the reverse of
|
||||
`binding_dispatches`), so a duplicate returns `store.ErrAlreadyDispatched` and
|
||||
the coordinator skips the invoke rather than repeating a non-revocable side
|
||||
effect. `DeletePlaybookDispatches` is the reclamation primitive for a playbook
|
||||
removed from the configured directory. The Go facade is
|
||||
effect. `DeletePlaybookDispatches` is the explicit reclamation primitive; nothing
|
||||
calls it automatically, because a playbook file's absence at boot is not a
|
||||
deliberate removal (`eda-playbook-engine.md`, "Lifetime"). The Go facade is
|
||||
`storecontract.PlaybookDispatcher` (2 methods), carried by `*staterpc.Client`
|
||||
alongside the rest.
|
||||
|
||||
|
||||
@@ -29,12 +29,14 @@ require (
|
||||
github.com/ganigeorgiev/fexpr v0.6.0 // indirect
|
||||
github.com/go-fed/httpsig v1.1.0 // indirect
|
||||
github.com/go-git/gcfg/v2 v2.0.2 // indirect
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 // indirect
|
||||
github.com/go-logr/logr v1.4.4 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/google/go-querystring v1.2.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/kevinburke/ssh_config v1.6.0 // indirect
|
||||
github.com/klauspost/compress v1.20.0 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
|
||||
@@ -95,6 +97,9 @@ require (
|
||||
github.com/pocketbase/pocketbase v0.40.4
|
||||
github.com/samcharles93/ai-sdk v0.1.39
|
||||
github.com/traefik/yaegi v0.16.1
|
||||
go.lsp.dev/jsonrpc2 v1.0.1
|
||||
go.lsp.dev/protocol v1.0.1
|
||||
go.lsp.dev/uri v1.0.1
|
||||
golang.org/x/net v0.59.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/term v0.46.0
|
||||
|
||||
@@ -2,21 +2,16 @@ cel.dev/cel-go v0.32.0 h1:irvpFKr5EuGPyxeME03ERh0rii1TX+BDAnB9eL3IvNk=
|
||||
cel.dev/cel-go v0.32.0/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU=
|
||||
cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0=
|
||||
cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4=
|
||||
cloud.google.com/go/auth v0.23.1/go.mod h1:4DhBRcqvtljQN3dJ57qtqbib5ZGCYE5f2crfiiC2EM0=
|
||||
cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10=
|
||||
code.gitea.io/sdk/gitea v0.25.1 h1:yywxWwoV+SdjHtbC6unBiXojWdZOtoHuGhEazEXeWuE=
|
||||
code.gitea.io/sdk/gitea v0.25.1/go.mod h1:uDFWYBU8dgZsgOHwe6C/6olxvf8FHguNB3wW1i83fgg=
|
||||
github.com/42wim/httpsig v1.2.4 h1:mI5bH0nm4xn7K18fo1K3okNDRq8CCJ0KbBYWyA6r8lU=
|
||||
github.com/42wim/httpsig v1.2.4/go.mod h1:yKsYfSyTBEohkPik224QPFylmzEBtda/kjyIAJjh3ps=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
|
||||
github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM=
|
||||
github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo=
|
||||
github.com/a-h/templ v0.3.1020/go.mod h1:A2DlK61v+K+NRoGnhmYbNYVmtYHcFO5/AisMvBdDxTM=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=
|
||||
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.8.0 h1:bVV5ZAuwaREn4klRSJusYaA+A7NXq8Qi9C/knCaQ2N4=
|
||||
@@ -28,21 +23,17 @@ github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkY
|
||||
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/bwesterb/go-ristretto v1.2.4/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/cloudflare/circl v1.6.5 h1:O64F26HEqNhznd/hrC5KZXVKYuKM2rx4deZDTc4ihQA=
|
||||
github.com/cloudflare/circl v1.6.5/go.mod h1:h5LNyxAc5nTue9DS5jT+48en2PSDYt3zdGnz5OstK6c=
|
||||
github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||
github.com/containerd/typeurl/v2 v2.2.0/go.mod h1:8XOOxnyatxSWuG8OfsZXVnAF4iZfedjS/8UHSPJnX4g=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0 h1:wZo4Q9Pum8dYEj0eMUPrqR+kvuGkeUplbLpNCkBqoWM=
|
||||
github.com/coreos/go-oidc/v3 v3.21.0/go.mod h1:DYCf24+ncYi+XkIH97GY1+dqoRlbaSI26KVTCI9SrY4=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davidmz/go-pageant v1.0.2 h1:bPblRCh5jGU+Uptpz6LgMZGD5hJoOt7otgT454WvHn0=
|
||||
@@ -61,14 +52,12 @@ github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=
|
||||
github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=
|
||||
github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU=
|
||||
github.com/envoyproxy/go-control-plane/envoy v1.39.0/go.mod h1:5e4ylfTZO723MEEFsCpSW4ZEBWR8mwkEyXfwJBTCZ9c=
|
||||
github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4=
|
||||
github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0=
|
||||
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.15 h1:05iP/CYtZ/w455R/KZM6rZ5ieAdh99UPtd+d3YzLmaI=
|
||||
@@ -87,23 +76,21 @@ github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1 h1:gmqi2jvsreu0s8JMLylYDFq4s
|
||||
github.com/go-git/go-git-fixtures/v6 v6.0.0-alpha.1/go.mod h1:ECf1MqJlBdYpKggBrOXjo/0EnvRZx6D++I86UYjPgAQ=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5 h1:sE+OlkHgYWNMVmN1s9sR7uyFgsWLtxcNWse/vBYKxRE=
|
||||
github.com/go-git/go-git/v6 v6.0.0-alpha.5/go.mod h1:3IjhiZnM+uBmUrOGSeqrJpsmi4Vd0H2NZO/uK2a7d0s=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-jose/go-jose/v4 v4.1.5 h1:RjgjO2LOtWOJKUC5wpwY9LR3B3vwVAz6JS2YHfYU6eA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.5/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 h1:KZaTBSyshWX3MP5jukJcNSuXDQTO+rNpt0J564dX/eg=
|
||||
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
|
||||
github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
|
||||
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-telegram/bot v1.27.0 h1:PG9yBDzM8O26oUerE9SZwWlHon4RpH8WcNslZ7CEZmE=
|
||||
github.com/go-telegram/bot v1.27.0/go.mod h1:i2TRs7fXWIeaceF3z7KzsMt/he0TwkVC680mvdTFYeM=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/glog v1.2.5/go.mod h1:6AhwSGph0fcJtXVM/PEHPqZlFeoLxhs7/t5UDAwmO+w=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
@@ -116,18 +103,15 @@ github.com/google/go-querystring v1.2.0 h1:yhqkPbu2/OH+V9BfpCVPZkNmUXhb2gBxJArfh
|
||||
github.com/google/go-querystring v1.2.0/go.mod h1:8IFJqpSRITyJ8QhQ13bmbeMBDfmeEJZD5A0egEOmkqU=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/go-tpm-tools v0.3.13-0.20230620182252-4639ecce2aba/go.mod h1:EFYHy8/1y2KfgTAsx7Luu7NGhoxtuVHnNo8jE7FikKc=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo=
|
||||
github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM=
|
||||
github.com/google/pprof v0.0.0-20260902005441-ca85771921e4 h1:/6mPXfWmhv8eKck12I0YNIcIjwHtxP3YRIMKiEgTjWg=
|
||||
github.com/google/pprof v0.0.0-20260902005441-ca85771921e4/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.21/go.mod h1:L3D/IQExI6LqEjBdXcZQ1WluSgigQmSwBboFstVPM4w=
|
||||
github.com/googleapis/gax-go/v2 v2.23.0/go.mod h1:rBQKOVJCdb8IFEzg+FCwlt1LP/xMDGuqUXhUG+XMXEg=
|
||||
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
|
||||
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/kevinburke/ssh_config v1.6.0 h1:J1FBfmuVosPHf5GRdltRLhPJtJpTlMdKTBjRgTaQBFY=
|
||||
github.com/kevinburke/ssh_config v1.6.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=
|
||||
@@ -154,7 +138,6 @@ github.com/moby/moby/api v1.56.0 h1:GQzua3NA599ASSIICx0iFgiJeO9YkdDARvQsm23ZZuQ=
|
||||
github.com/moby/moby/api v1.56.0/go.mod h1:sZ+THbVWkjOmBPPfbnzdD/G1LuIexWhqlSHHPTDQ1Uk=
|
||||
github.com/moby/moby/client v0.6.0 h1:AJjEB21QPbXSXjDsZorFBoDZPhMrfbpaPLgSMAW9Bgs=
|
||||
github.com/moby/moby/client v0.6.0/go.mod h1:OCo00wNRyA3m4lmJ228W3JbyCN4ZNNYjpOXiJydBdcQ=
|
||||
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.15.0 h1:M99yf0y05rTr46/qc/Is6ZAowI58Ryp2SjufLCUeVJc=
|
||||
@@ -175,7 +158,6 @@ github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
|
||||
github.com/pjbgf/sha1cd v0.6.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pocketbase/dbx v1.12.0 h1:/oLErM+A0b4xI0PWTGPqSDVjzix48PqI/bng2l0PzoA=
|
||||
github.com/pocketbase/dbx v1.12.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
|
||||
@@ -187,14 +169,11 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/russross/blackfriday v1.6.0/go.mod h1:ti0ldHuxg49ri4ksnFxlkCfN+hvslNlmVHqNRXXJNAY=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/samcharles93/ai-sdk v0.1.39 h1:gbNPYeA27MifReCruBiqMgb4fFSjCDi1Zv57a9bo0Vo=
|
||||
github.com/samcharles93/ai-sdk v0.1.39/go.mod h1:u4zrQ9/Q58L5mNEut4bNQ1ks+RCKq71LN5EDz2N/0Zk=
|
||||
github.com/santhosh-tekuri/jsonschema/v5 v5.3.1/go.mod h1:uToXkOrWAZ6/Oc07xWQrPOhJotwFIyu2bBVN41fcDUY=
|
||||
github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=
|
||||
github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=
|
||||
github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
@@ -202,16 +181,20 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||
github.com/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
go.lsp.dev/jsonrpc2 v1.0.1 h1:JZAchpm6RcOuwEOnZ7kF3kA1EpEjdJZ/6rMSfOF3+F4=
|
||||
go.lsp.dev/jsonrpc2 v1.0.1/go.mod h1:WN+TesqrPumBmUdsuWyn9DHq3zl4i85L/qG0NLdj8qg=
|
||||
go.lsp.dev/protocol v1.0.1 h1:kLWUIk1v/deXxo1D0VO4avjZnfeuZ82mouJgJd/NbdU=
|
||||
go.lsp.dev/protocol v1.0.1/go.mod h1:e//i41aEqc9ml32xiNuneUwbjOjuvTA4+uv+AkssJgk=
|
||||
go.lsp.dev/uri v1.0.1 h1:ywxJN1UXoQ+v0I9lkoQNMmsm7lub5G9ZG7KXT8YTx30=
|
||||
go.lsp.dev/uri v1.0.1/go.mod h1:06a0ghafs4PuqkLsJGUmlgPHw6+kH79edRXjOT/rA8s=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0 h1:3g7B90UzBltIDKq1/5mrTGxTnOFDV0ICOhLoxiZ8jlg=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.71.0/go.mod h1:Ef8SuTh59BT7+ofpDxN9z+yOlc4t2GjLmKDgYNJL/NU=
|
||||
go.opentelemetry.io/otel v1.46.0 h1:FHt5/CDyVxi/8IM1CH7VE/rRgq3kLHa2mSTVMO8AWyc=
|
||||
@@ -244,8 +227,6 @@ golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
|
||||
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
@@ -270,18 +251,12 @@ golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
|
||||
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
|
||||
golang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=
|
||||
golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=
|
||||
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
|
||||
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
|
||||
google.golang.org/api v0.293.0/go.mod h1:6n5tjEB1gzwniZTepZ0g5u+wM7Bof5GeULCx/zh8ZE0=
|
||||
google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM=
|
||||
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679 h1:FEp7JNE32DTAwbnI/ixagnmj7Xm1eTONofGEUXFjZ4w=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260918162117-cecb64721679/go.mod h1:52bV8FLAQ9Qmcqaq9ECLmuEHZthk+6OPV45aKBBrsNw=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459 h1:GS9OIt/j7c8bvBjYNgnKQysVfmV7e4jM0H8ZK95G4t8=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260921155816-b14227669459/go.mod h1:PX5/4vemwVoXtwEcRDWwcR1/r0qrosfx3qoVADMwnVE=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260918162117-cecb64721679 h1:KmqdJU4vrNcxy/6qdg3JduZtalEXrJLspVltnR1cE+8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260918162117-cecb64721679/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459 h1:b0xCahf3FK2m2Cv0p4vTozGPWncCvLfwV86UNg8xWU8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260921155816-b14227669459/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc=
|
||||
google.golang.org/grpc v1.85.0-dev.0.20260825072537-93e31b48545e h1:ar+feAPij1Znzug45m6AoShUCc5AaR8FLA3I6LZd94k=
|
||||
@@ -299,27 +274,19 @@ gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
|
||||
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
|
||||
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
|
||||
modernc.org/cc/v4 v4.29.7 h1:q+NXGJ0bK3b4TXFYQQVr9pYETGnmwFWkrUzJnMya/Tg=
|
||||
modernc.org/cc/v4 v4.29.7/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||
modernc.org/ccgo/v4 v4.36.0 h1:T5h7ZMcrw2r94oDLtBcU3YI6e1W8DiUg2SJIs2fwD2s=
|
||||
modernc.org/ccgo/v4 v4.36.0/go.mod h1:rrtGc2QkS239nYb/mQNuBMyjq3/y3ZXWbBjPoV3wqzA=
|
||||
modernc.org/ccgo/v4 v4.36.1 h1:ZNIUZAryN0UgnJwtyxrdEzcFc3yD4Cu4AzjfPXsLsIE=
|
||||
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.5 h1:21ldfPfRYE31Tb7B3mwAK8gy1AxP4+dKjrOQPfqakoc=
|
||||
modernc.org/gc/v3 v3.1.5/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k=
|
||||
modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co=
|
||||
modernc.org/libc v1.77.0 h1:wV+faa9ixRoUNlakU0fHLi/1kV2YLG8D8Ksk3c2mPtY=
|
||||
modernc.org/libc v1.77.0/go.mod h1:BmXDCJcMkRMRbX2EI8+Zhh4fKWlHNbCCZEy0tiZevP4=
|
||||
modernc.org/libc v1.77.1 h1:Ct8j47QtiZ1Enj2DtFXQtUqrPCAjdCmPjtCuvrYQ0Hs=
|
||||
modernc.org/libc v1.77.1/go.mod h1:87/pZ4L6nD1zqW4nItuS12YO7hN1igAah34xjnQo/W0=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.12.1 h1:nFMiWrpStgZczNl6XI9GnIk/rWhYIyHGUaR04pGbp9g=
|
||||
@@ -330,8 +297,6 @@ modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg=
|
||||
modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ=
|
||||
modernc.org/sqlite v1.59.0 h1:X1es1GpqBlS/5T+vbM4HLUdaa8OtQx468DF2vrx+38A=
|
||||
modernc.org/sqlite v1.59.0/go.mod h1:+paeT2A3iPRHkQDwG7oA6Tk0zQd5woMEI8q7orfry8k=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
|
||||
@@ -774,9 +774,8 @@ func (b *boot) loadModules(cfg config.Config, log *slog.Logger) error {
|
||||
// rule -- any malformed playbook, mixed/unsupported action shape, unknown
|
||||
// module kind, when compile failure, or args key failure aborts startup,
|
||||
// matching the routing-file load pattern (not degrade-and-skip). A nonexistent
|
||||
// dir is an empty store. Action playbooks load and type-check but have no run
|
||||
// path yet (t2db.31), so each one is logged as a visible warning here rather
|
||||
// than routed by the definition pin.
|
||||
// dir is an empty store. Action playbooks run through the daemon once
|
||||
// buildDaemon wires the dispatch ledger (docs/prds/action-playbook-run.md).
|
||||
func (b *boot) loadEDAPlaybooks(cfg config.Config, log *slog.Logger) error {
|
||||
var err error
|
||||
b.playbooks, err = playbook.Load(cfg.EDAPlaybookDir, b.modules)
|
||||
@@ -784,11 +783,6 @@ func (b *boot) loadEDAPlaybooks(cfg config.Config, log *slog.Logger) error {
|
||||
log.Error("eda playbook load failed", "dir", cfg.EDAPlaybookDir, "err", err)
|
||||
return err
|
||||
}
|
||||
for _, pb := range b.playbooks.Playbooks {
|
||||
if pb.IsActionPlaybook() {
|
||||
log.Warn("eda action playbook loaded: action playbooks do not execute yet", "playbook", pb.ID)
|
||||
}
|
||||
}
|
||||
log.Info("eda playbooks loaded", "dir", cfg.EDAPlaybookDir, "playbooks", len(b.playbooks.Playbooks))
|
||||
return nil
|
||||
}
|
||||
@@ -1326,9 +1320,25 @@ func (b *boot) buildDaemon() {
|
||||
if btc, ok := b.stateStore.(storecontract.BindingTaskCreator); ok {
|
||||
b.d.BindingTaskCreator = btc
|
||||
}
|
||||
b.d.PlaybookLedger = playbookLedger(b.stateStore, b.playbooks, b.log)
|
||||
b.setupForgeWebhook()
|
||||
}
|
||||
|
||||
// playbookLedger returns source's dispatch ledger, or nil with a warning
|
||||
// naming each action playbook that therefore will not run: an action playbook
|
||||
// never fires without its at-most-once gate.
|
||||
func playbookLedger(source any, playbooks *playbook.Store, log *slog.Logger) storecontract.PlaybookDispatcher {
|
||||
if pd, ok := source.(storecontract.PlaybookDispatcher); ok {
|
||||
return pd
|
||||
}
|
||||
for _, pb := range playbooks.Playbooks {
|
||||
if pb.IsActionPlaybook() {
|
||||
log.Warn("eda action playbook will not run: no dispatch ledger is wired", "playbook", pb.ID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupForgeWebhook starts the forge webhook receiver when intake is "webhook"
|
||||
// or "both". It decodes GitHub issue events into task envelopes and publishes
|
||||
// them through the same path the poller uses, so a labelled or assigned issue
|
||||
|
||||
@@ -2,6 +2,7 @@ package archied
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -10,71 +11,65 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
)
|
||||
|
||||
// TestLoadEDAPlaybooksWarnsOnActionPlaybook pins the D1 visible warning: an
|
||||
// action playbook loads and validates but has no run path yet, so the daemon
|
||||
// logs a warning (not debug) naming it and stating plainly that action
|
||||
// playbooks do not execute yet -- rather than silently loading a playbook that
|
||||
// can never be routed.
|
||||
func TestLoadEDAPlaybooksWarnsOnActionPlaybook(t *testing.T) {
|
||||
type stubPlaybookLedger struct{}
|
||||
|
||||
func (stubPlaybookLedger) RecordPlaybookDispatch(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (stubPlaybookLedger) DeletePlaybookDispatches(context.Context, string) error { return nil }
|
||||
|
||||
func loadBootPlaybooks(t *testing.T, document string) *playbook.Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(`trigger:
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(document), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := &boot{cfg: config.Config{EDAPlaybookDir: dir}, modules: module.New()}
|
||||
if err := b.loadEDAPlaybooks(b.cfg, slog.New(slog.DiscardHandler)); err != nil {
|
||||
t.Fatalf("loadEDAPlaybooks: %v", err)
|
||||
}
|
||||
return b.playbooks
|
||||
}
|
||||
|
||||
const actionPlaybookDoc = `trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
args:
|
||||
message: '"build started"'
|
||||
`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
`
|
||||
|
||||
var buf bytes.Buffer
|
||||
log := slog.New(slog.NewTextHandler(&buf, nil))
|
||||
b := &boot{cfg: config.Config{EDAPlaybookDir: dir}, modules: module.New()}
|
||||
if err := b.loadEDAPlaybooks(b.cfg, log); err != nil {
|
||||
t.Fatalf("loadEDAPlaybooks: %v", err)
|
||||
// An action playbook never runs without the dispatch ledger, and the
|
||||
// operator is told which ones are inert rather than finding out by silence.
|
||||
func TestPlaybookLedger(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source any
|
||||
document string
|
||||
wantLedger bool
|
||||
wantWarn bool
|
||||
}{
|
||||
{name: "ledger wired", source: stubPlaybookLedger{}, document: actionPlaybookDoc, wantLedger: true},
|
||||
{name: "no ledger warns per action playbook", source: struct{}{}, document: actionPlaybookDoc, wantWarn: true},
|
||||
{name: "no ledger, workflow playbook only", source: struct{}{}, document: "trigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n"},
|
||||
}
|
||||
|
||||
out := buf.String()
|
||||
if !strings.Contains(out, "pb.yaml") {
|
||||
t.Errorf("warning output does not name the action playbook: %q", out)
|
||||
}
|
||||
if !strings.Contains(out, "do not execute yet") {
|
||||
t.Errorf("warning output does not state action playbooks do not execute yet: %q", out)
|
||||
}
|
||||
if strings.Contains(out, "level=DEBUG") {
|
||||
t.Errorf("warning output was logged at debug, want a visible warning: %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoadEDAPlaybooksNoWarningOnWorkflowPlaybook is the inverse of the D1
|
||||
// warning: a workflow playbook uses the same two-shape predicate but must not
|
||||
// be logged as a non-routing action playbook.
|
||||
func TestLoadEDAPlaybooksNoWarningOnWorkflowPlaybook(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "pb.yaml"), []byte(`trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: workflow
|
||||
workflow: tdd
|
||||
`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
log := slog.New(slog.NewTextHandler(&buf, nil))
|
||||
b := &boot{cfg: config.Config{EDAPlaybookDir: dir}, modules: module.New()}
|
||||
if err := b.loadEDAPlaybooks(b.cfg, log); err != nil {
|
||||
t.Fatalf("loadEDAPlaybooks: %v", err)
|
||||
}
|
||||
|
||||
out := buf.String()
|
||||
if strings.Contains(out, "do not execute yet") {
|
||||
t.Errorf("workflow playbook was warned as an action playbook: %q", out)
|
||||
}
|
||||
if strings.Contains(out, "level=WARN") {
|
||||
t.Errorf("workflow playbook produced a warning: %q", out)
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
got := playbookLedger(tt.source, loadBootPlaybooks(t, tt.document), slog.New(slog.NewTextHandler(&buf, nil)))
|
||||
if (got != nil) != tt.wantLedger {
|
||||
t.Fatalf("ledger = %v, want wired=%v", got, tt.wantLedger)
|
||||
}
|
||||
out := buf.String()
|
||||
warned := strings.Contains(out, "level=WARN") && strings.Contains(out, "pb.yaml") && strings.Contains(out, "will not run")
|
||||
if warned != tt.wantWarn {
|
||||
t.Fatalf("warning output = %q, want warned=%v", out, tt.wantWarn)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,19 @@
|
||||
// Package archieplaybooks is the application composition for the standalone
|
||||
// playbook-validation CLI (cmd/archie-playbooks). It owns the lint mode's
|
||||
// orchestration: collect the configured directories, run the domain
|
||||
// validator, and shape the outcome for human consumption. All validation
|
||||
// rules live in internal/domain/workflow (LoadKindWorkflowsYAML,
|
||||
// LoadLabelWorkflowsYAML, LoadPlaybookDirs) -- this package only calls them
|
||||
// and formats results; there is deliberately no second validation path
|
||||
// here (per docs/prds/eda-playbook-engine.md and t2db.12).
|
||||
// validators, and shape the outcome for human consumption. The rules live in
|
||||
// internal/domain/workflow (routing binding files) and
|
||||
// internal/domain/eda/playbook (EDA playbooks) -- this package only calls the
|
||||
// loaders the daemon runs and formats results; there is deliberately no
|
||||
// second validation path here (per docs/prds/eda-playbook-engine.md).
|
||||
package archieplaybooks
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
)
|
||||
|
||||
@@ -48,3 +50,13 @@ func Lint(dirs []string, stderr io.Writer) Result {
|
||||
}
|
||||
return Result{ExitCode: 0, Findings: nil}
|
||||
}
|
||||
|
||||
// LintEDA validates an EDA playbook directory (the daemon's eda_playbook_dir)
|
||||
// with playbook.Load, the loader the daemon runs at startup.
|
||||
func LintEDA(dir string, stderr io.Writer) Result {
|
||||
if _, err := playbook.Load(dir, module.New()); err != nil {
|
||||
fmt.Fprintln(stderr, err)
|
||||
return Result{ExitCode: 1, Findings: []string{err.Error()}}
|
||||
}
|
||||
return Result{}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package archieplaybooks
|
||||
|
||||
import (
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// LintEDA refuses exactly what the daemon's EDA loader refuses at startup.
|
||||
func TestLintEDA(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
document string
|
||||
wantErr string
|
||||
}{
|
||||
{name: "valid action playbook", document: "trigger:\n kind: bug\nactions:\n - position: module\n kind: log\n args:\n message: '\"hi\"'\n"},
|
||||
{name: "unknown kind", document: "trigger:\n kind: bug\nactions:\n - position: module\n kind: nope\n", wantErr: "nope"},
|
||||
{name: "wrongly typed arg", document: "trigger:\n kind: bug\nactions:\n - position: module\n kind: log\n args:\n message: '123'\n", wantErr: `args["message"]`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, filepath.Join(dir, "pb.yaml"), tt.document)
|
||||
result := LintEDA(dir, io.Discard)
|
||||
if tt.wantErr == "" {
|
||||
if result.ExitCode != 0 {
|
||||
t.Fatalf("LintEDA exit = %d, findings %q, want clean", result.ExitCode, result.Findings)
|
||||
}
|
||||
return
|
||||
}
|
||||
joined := strings.Join(result.Findings, "\n")
|
||||
if result.ExitCode != 1 || !strings.Contains(joined, "pb.yaml") || !strings.Contains(joined, tt.wantErr) {
|
||||
t.Fatalf("LintEDA = exit %d, findings %q, want exit 1 naming pb.yaml and %q", result.ExitCode, joined, tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -98,11 +98,10 @@ func TestLintReportsLoadErrorAsFinding(t *testing.T) {
|
||||
}
|
||||
joined := strings.Join(result.Findings, "\n")
|
||||
// Both "bug" and "security" collide across the two files; the loader
|
||||
// sorts a file's keys before checking them (routing.go's
|
||||
// loadPlaybookFile), so "bug" -- alphabetically first -- is always the
|
||||
// one reported, deterministically.
|
||||
if !strings.Contains(joined, "bug") {
|
||||
t.Fatalf("Lint() findings = %q, want the colliding key named", joined)
|
||||
// checks a file's keys in document order, so the first line of b.yaml
|
||||
// is always the one reported, deterministically.
|
||||
if want := filepath.Join(dir, "b.yaml") + `:1: label "security"`; !strings.Contains(joined, want) {
|
||||
t.Fatalf("Lint() findings = %q, want %q", joined, want)
|
||||
}
|
||||
// Fail-fast like the daemon: one definition failure is reported (the
|
||||
// loader returns the first), not an enumeration of every collision.
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
package archieplaybooks
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"go.lsp.dev/jsonrpc2"
|
||||
"go.lsp.dev/protocol"
|
||||
"go.lsp.dev/uri"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
// Serve runs the language server over rwc until the client disconnects or
|
||||
// ctx ends. It publishes diagnostics when a playbook file is opened or saved,
|
||||
// by linting the file's saved directory with the loader the daemon runs for
|
||||
// it: the whole directory, because a collision is a cross-file finding.
|
||||
// Unsaved edits are not validated.
|
||||
func Serve(ctx context.Context, rwc io.ReadWriteCloser) error {
|
||||
s := &server{exited: make(chan struct{})}
|
||||
_, conn, client := protocol.NewServer(ctx, s, jsonrpc2.NewStream(rwc))
|
||||
s.client = client
|
||||
select {
|
||||
case <-conn.Done():
|
||||
return nil
|
||||
case <-s.exited:
|
||||
case <-ctx.Done():
|
||||
}
|
||||
return conn.Close()
|
||||
}
|
||||
|
||||
type server struct {
|
||||
protocol.UnimplementedServer
|
||||
client protocol.Client
|
||||
// exited is closed by the exit notification. Serve closes the connection:
|
||||
// closing it from inside the handler would wait on that handler.
|
||||
exited chan struct{}
|
||||
exitOnce sync.Once
|
||||
}
|
||||
|
||||
func (s *server) Initialize(context.Context, *protocol.InitializeParams) (*protocol.InitializeResult, error) {
|
||||
// The server reads files from disk, so it needs opens, closes and saves,
|
||||
// not content changes.
|
||||
openClose, change := true, protocol.TextDocumentSyncKindNone
|
||||
return &protocol.InitializeResult{
|
||||
Capabilities: protocol.ServerCapabilities{
|
||||
TextDocumentSync: &protocol.TextDocumentSyncOptions{
|
||||
OpenClose: &openClose,
|
||||
Change: &change,
|
||||
Save: protocol.Boolean(true),
|
||||
},
|
||||
},
|
||||
ServerInfo: protocol.ServerInfo{Name: "archie-playbooks"},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *server) Shutdown(context.Context) error { return nil }
|
||||
|
||||
func (s *server) Exit(context.Context) error {
|
||||
s.exitOnce.Do(func() { close(s.exited) })
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) DidOpen(ctx context.Context, p *protocol.DidOpenTextDocumentParams) error {
|
||||
return s.client.PublishDiagnostics(ctx, diagnose(p.TextDocument.URI))
|
||||
}
|
||||
|
||||
func (s *server) DidSave(ctx context.Context, p *protocol.DidSaveTextDocumentParams) error {
|
||||
return s.client.PublishDiagnostics(ctx, diagnose(p.TextDocument.URI))
|
||||
}
|
||||
|
||||
func (s *server) DidClose(ctx context.Context, p *protocol.DidCloseTextDocumentParams) error {
|
||||
return s.client.PublishDiagnostics(ctx, &protocol.PublishDiagnosticsParams{URI: p.TextDocument.URI, Diagnostics: []protocol.Diagnostic{}})
|
||||
}
|
||||
|
||||
// diagnose lints the directory holding u's file and returns the findings that
|
||||
// belong to that file: a finding naming another file of the directory belongs
|
||||
// there, and one naming this file without a line (a file-level error) goes on
|
||||
// its first line.
|
||||
func diagnose(u uri.URI) *protocol.PublishDiagnosticsParams {
|
||||
out := &protocol.PublishDiagnosticsParams{URI: u, Diagnostics: []protocol.Diagnostic{}}
|
||||
if !u.IsFile() {
|
||||
return out
|
||||
}
|
||||
path := u.FsPath()
|
||||
var result Result
|
||||
if isEDAPlaybook(path) {
|
||||
result = LintEDA(filepath.Dir(path), io.Discard)
|
||||
} else {
|
||||
result = Lint([]string{filepath.Dir(path)}, io.Discard)
|
||||
}
|
||||
for _, finding := range result.Findings {
|
||||
line, ok := findingLine(finding, path)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
out.Diagnostics = append(out.Diagnostics, protocol.Diagnostic{
|
||||
Range: protocol.Range{Start: protocol.Position{Line: line}, End: protocol.Position{Line: line + 1}},
|
||||
Severity: protocol.DiagnosticSeverityError,
|
||||
Source: protocol.NewOptional("archie-playbooks"),
|
||||
Message: protocol.String(finding),
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// isEDAPlaybook reports whether the file is an EDA playbook document (it has
|
||||
// a top-level `trigger` key) rather than a routing binding file.
|
||||
func isEDAPlaybook(path string) bool {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
var doc map[string]yaml.Node
|
||||
if yaml.NewDecoder(bytes.NewReader(data)).Decode(&doc) != nil {
|
||||
return false
|
||||
}
|
||||
_, ok := doc["trigger"]
|
||||
return ok
|
||||
}
|
||||
|
||||
// findingLine places a finding on path. A compiler-style `path:line:` prefix
|
||||
// gives the 0-based line; a finding naming path without a line goes on line
|
||||
// 0; a finding naming another file is not path's.
|
||||
func findingLine(finding, path string) (uint32, bool) {
|
||||
if m := regexp.MustCompile(regexp.QuoteMeta(path) + `:(\d+):`).FindStringSubmatch(finding); m != nil {
|
||||
n, _ := strconv.ParseUint(m[1], 10, 32)
|
||||
return uint32(max(n, 1) - 1), true
|
||||
}
|
||||
return 0, strings.Contains(finding, path)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package archieplaybooks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.lsp.dev/jsonrpc2"
|
||||
"go.lsp.dev/protocol"
|
||||
"go.lsp.dev/uri"
|
||||
)
|
||||
|
||||
// diagnosticsClient is the editor side: it collects every
|
||||
// publishDiagnostics notification the server sends.
|
||||
type diagnosticsClient struct {
|
||||
protocol.UnimplementedClient
|
||||
diags chan *protocol.PublishDiagnosticsParams
|
||||
}
|
||||
|
||||
func (c *diagnosticsClient) PublishDiagnostics(_ context.Context, p *protocol.PublishDiagnosticsParams) error {
|
||||
c.diags <- p
|
||||
return nil
|
||||
}
|
||||
|
||||
// openInServe starts Serve over an in-memory pipe, initializes it, opens
|
||||
// path, and returns the diagnostics published for it.
|
||||
func openInServe(t *testing.T, path string) *protocol.PublishDiagnosticsParams {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
t.Cleanup(cancel)
|
||||
serverEnd, clientEnd := net.Pipe()
|
||||
go func() { _ = Serve(ctx, serverEnd) }()
|
||||
client := &diagnosticsClient{diags: make(chan *protocol.PublishDiagnosticsParams, 8)}
|
||||
_, conn, server := protocol.NewClient(ctx, client, jsonrpc2.NewStream(clientEnd))
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
|
||||
if _, err := server.Initialize(ctx, &protocol.InitializeParams{}); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
u := uri.File(path)
|
||||
if err := server.DidOpen(ctx, &protocol.DidOpenTextDocumentParams{TextDocument: protocol.TextDocumentItem{URI: u, LanguageID: "yaml", Version: 1}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case p := <-client.diags:
|
||||
if p.URI != u {
|
||||
t.Fatalf("diagnostics for %q, want %q", p.URI, u)
|
||||
}
|
||||
return p
|
||||
case <-ctx.Done():
|
||||
t.Fatal("no publishDiagnostics received")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestServePublishesDiagnostics(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
files map[string]string
|
||||
open string
|
||||
wantLine int // 0-based; -1 means no diagnostics
|
||||
}{
|
||||
{
|
||||
name: "clean routing file",
|
||||
files: map[string]string{"routes.yaml": "bug: tdd\n"},
|
||||
open: "routes.yaml",
|
||||
wantLine: -1,
|
||||
},
|
||||
{
|
||||
name: "routing finding on its key line",
|
||||
files: map[string]string{"routes.yaml": "security: review\n\ndocs: \"\"\n"},
|
||||
open: "routes.yaml",
|
||||
wantLine: 2,
|
||||
},
|
||||
{
|
||||
name: "cross-file collision reported on the opened file",
|
||||
files: map[string]string{"a.yaml": "security: review\n", "b.yaml": "\nsecurity: other\n"},
|
||||
open: "b.yaml",
|
||||
wantLine: 1,
|
||||
},
|
||||
{
|
||||
name: "eda playbook finding on its action line",
|
||||
files: map[string]string{"pb.yaml": "trigger:\n kind: bug\nactions:\n - position: module\n kind: nope\n"},
|
||||
open: "pb.yaml",
|
||||
wantLine: 3,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for name, content := range tt.files {
|
||||
writeFile(t, filepath.Join(dir, name), content)
|
||||
}
|
||||
p := openInServe(t, filepath.Join(dir, tt.open))
|
||||
if tt.wantLine < 0 {
|
||||
if len(p.Diagnostics) != 0 {
|
||||
t.Fatalf("diagnostics = %+v, want none", p.Diagnostics)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(p.Diagnostics) != 1 || int(p.Diagnostics[0].Range.Start.Line) != tt.wantLine {
|
||||
t.Fatalf("diagnostics = %+v, want one on line %d", p.Diagnostics, tt.wantLine)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The exit notification ends Serve. Closing the connection from inside the
|
||||
// exit handler waited on that handler, so an editor quitting left the server
|
||||
// running.
|
||||
func TestServeReturnsAfterExit(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
serverEnd, clientEnd := net.Pipe()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- Serve(ctx, serverEnd) }()
|
||||
_, conn, server := protocol.NewClient(ctx, &diagnosticsClient{}, jsonrpc2.NewStream(clientEnd))
|
||||
defer conn.Close()
|
||||
|
||||
if _, err := server.Initialize(ctx, &protocol.InitializeParams{}); err != nil {
|
||||
t.Fatalf("initialize: %v", err)
|
||||
}
|
||||
if err := server.Shutdown(ctx); err != nil {
|
||||
t.Fatalf("shutdown: %v", err)
|
||||
}
|
||||
if err := server.Exit(ctx); err != nil {
|
||||
t.Fatalf("exit: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-done:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("Serve still running after exit")
|
||||
}
|
||||
}
|
||||
@@ -220,7 +220,11 @@ type Daemon struct {
|
||||
// and routing is exactly the binding behaviour.
|
||||
Playbooks interface {
|
||||
Dispatch(playbook.DispatchInput) (playbook.Decision, bool)
|
||||
Run(context.Context, storecontract.PlaybookDispatcher, *slog.Logger, playbook.DispatchInput) error
|
||||
}
|
||||
// PlaybookLedger is the at-most-once gate action playbooks run through.
|
||||
// Nil means action playbooks do not run: they never fire unguarded.
|
||||
PlaybookLedger storecontract.PlaybookDispatcher
|
||||
|
||||
// WorkflowDefinitions supplies the active database definitions. A task is
|
||||
// pinned once before dispatch; retries reuse the task's stored YAML.
|
||||
@@ -1552,6 +1556,7 @@ func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
d.runActionPlaybooks(ctx, task)
|
||||
if d.WorkflowDefinitions == nil {
|
||||
return d.pinWorkflowFromCollection(ctx, task, workflow.ShippedDefinitions(), 0)
|
||||
}
|
||||
@@ -1562,6 +1567,20 @@ func (d *Daemon) pinWorkflowDefinition(ctx context.Context, task *workflow.Task)
|
||||
return d.pinWorkflowFromCollection(ctx, task, collection, version)
|
||||
}
|
||||
|
||||
// runActionPlaybooks runs the action playbooks matching a task that is about
|
||||
// to be pinned, which happens once per task (docs/prds/action-playbook-run.md).
|
||||
// A run never affects routing and its failure never fails the task. A task
|
||||
// that already names a workflow is the approval requeue and is skipped, as
|
||||
// it is for workflow playbooks.
|
||||
func (d *Daemon) runActionPlaybooks(ctx context.Context, task *workflow.Task) {
|
||||
if d.Playbooks == nil || d.PlaybookLedger == nil || task.Workflow != "" {
|
||||
return
|
||||
}
|
||||
if err := d.Playbooks.Run(ctx, d.PlaybookLedger, d.Log, playbookInput(task)); err != nil {
|
||||
d.Log.Warn("action playbook run failed", "task", task.ID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// resolveWorkflowID picks the definition id to pin. A playbook whose trigger
|
||||
// matches the task decides, ahead of the kind/label bindings; anything else
|
||||
// falls through to workflow.ResolveWorkflowID unchanged.
|
||||
|
||||
@@ -284,13 +284,10 @@ func seedMapping(t *testing.T, s *dispatchStores, sourceHint string, fields ...m
|
||||
return id
|
||||
}
|
||||
|
||||
// seedArmedBinding inserts a binding and walks it draft -> pending_approval
|
||||
// -> armed, matching the operator flow an Approve button on the
|
||||
// dashboard drives. InsertBinding forces status='draft' and the only
|
||||
// sanctioned armed transition is ApproveBinding, so the helper
|
||||
// advances through pending_approval via the store's test-only DB
|
||||
// accessor -- production callers must use the structured methods
|
||||
// (bindings.go) rather than touching the SQL directly.
|
||||
// seedArmedBinding inserts a binding and approves it, matching the operator
|
||||
// flow an Approve button on the dashboard drives: InsertBinding stores
|
||||
// pending_approval and the only sanctioned armed transition is
|
||||
// ApproveBinding.
|
||||
func seedArmedBinding(t *testing.T, s *dispatchStores, source, mappingID string) (string, int) {
|
||||
t.Helper()
|
||||
return seedArmedBindingWithRepo(t, s, source, mappingID, "", "")
|
||||
@@ -313,21 +310,6 @@ func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
}
|
||||
// Edit moves a draft to pending_approval through the real lifecycle,
|
||||
// which is what makes it approvable. The old raw-SQL shortcut reached
|
||||
// into a table the task store no longer owns.
|
||||
if err := s.EdaStore.UpdateBinding(t.Context(), binding.Binding{
|
||||
ID: id,
|
||||
Name: "test " + source,
|
||||
Matcher: binding.Matcher{Source: source},
|
||||
MappingID: mappingID,
|
||||
Workflow: "implement",
|
||||
Owner: owner,
|
||||
Repo: repo,
|
||||
Secret: "0123456789abcdef0123456789abcdef",
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateBinding to pending_approval: %v", err)
|
||||
}
|
||||
if err := s.EdaStore.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding: %v", err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/playbook"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// runRecorder is a playbook set that matches no workflow playbook and records
|
||||
// each action-playbook run, failing it when err is set.
|
||||
type runRecorder struct {
|
||||
runs []playbook.DispatchInput
|
||||
err error
|
||||
}
|
||||
|
||||
func (r *runRecorder) Dispatch(playbook.DispatchInput) (playbook.Decision, bool) {
|
||||
return playbook.Decision{}, false
|
||||
}
|
||||
|
||||
func (r *runRecorder) Run(_ context.Context, _ storecontract.PlaybookDispatcher, _ *slog.Logger, input playbook.DispatchInput) error {
|
||||
r.runs = append(r.runs, input)
|
||||
return r.err
|
||||
}
|
||||
|
||||
type nopPlaybookLedger struct{}
|
||||
|
||||
func (nopPlaybookLedger) RecordPlaybookDispatch(context.Context, string, string, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nopPlaybookLedger) DeletePlaybookDispatches(context.Context, string) error { return nil }
|
||||
|
||||
func TestPinWorkflowDefinitionRunsActionPlaybooks(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ledger storecontract.PlaybookDispatcher
|
||||
workflow string
|
||||
runErr error
|
||||
wantRuns int
|
||||
}{
|
||||
{name: "runs once with a ledger", ledger: nopPlaybookLedger{}, wantRuns: 1},
|
||||
{name: "a failed run leaves routing alone", ledger: nopPlaybookLedger{}, runErr: errors.New("boom"), wantRuns: 1},
|
||||
{name: "never runs without a ledger", wantRuns: 0},
|
||||
{name: "skips a task that already names a workflow", ledger: nopPlaybookLedger{}, workflow: "tdd", wantRuns: 0},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
resources := store.OpenTest(t)
|
||||
defer resources.Close()
|
||||
task := forgeTask(t, resources, "bug")
|
||||
task.Workflow = tt.workflow
|
||||
recorder := &runRecorder{err: tt.runErr}
|
||||
d := &Daemon{
|
||||
Store: resources,
|
||||
WorkflowDefinitions: routableDefinitions(),
|
||||
Log: slog.New(slog.DiscardHandler),
|
||||
Playbooks: recorder,
|
||||
PlaybookLedger: tt.ledger,
|
||||
}
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A second pin reuses the stored definition and must not run again.
|
||||
if err := d.pinWorkflowDefinition(t.Context(), task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recorder.runs) != tt.wantRuns {
|
||||
t.Fatalf("runs = %d, want %d", len(recorder.runs), tt.wantRuns)
|
||||
}
|
||||
if task.Workflow != "tdd" {
|
||||
t.Fatalf("pinned workflow = %q, want tdd (the kind binding, untouched by the run)", task.Workflow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -11,14 +11,13 @@ import (
|
||||
)
|
||||
|
||||
// Status is the binding lifecycle state. Mirrors telegram's
|
||||
// dangerousAction / pendingApproval shape: armed is the only state that
|
||||
// evaluates against incoming events; any edit drops armed back to
|
||||
// pending_approval; only an explicit Approve call moves
|
||||
// pending_approval -> armed.
|
||||
// dangerousAction / pendingApproval shape: a binding is created
|
||||
// pending_approval, armed is the only state that evaluates against incoming
|
||||
// events, any edit drops armed back to pending_approval, and only an
|
||||
// explicit Approve call moves pending_approval -> armed.
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusDraft Status = "draft"
|
||||
StatusPendingApproval Status = "pending_approval"
|
||||
StatusArmed Status = "armed"
|
||||
)
|
||||
@@ -137,16 +136,3 @@ func (m Matcher) Matches(source string, authenticated bool) bool {
|
||||
}
|
||||
return m.Source == source
|
||||
}
|
||||
|
||||
// Normalize clamps an arbitrary string into a recognised Status, falling
|
||||
// back to StatusDraft for any unknown value. The DB CHECK constraint
|
||||
// already rejects bad strings at write time; Normalize is the API-edge
|
||||
// guard for inputs that arrive before they ever reach the store.
|
||||
func Normalize(s Status) Status {
|
||||
switch s {
|
||||
case StatusDraft, StatusPendingApproval, StatusArmed:
|
||||
return s
|
||||
default:
|
||||
return StatusDraft
|
||||
}
|
||||
}
|
||||
@@ -277,53 +277,44 @@ func (e *Env) Compile(src string) (*Program, error) {
|
||||
return nil, err
|
||||
}
|
||||
ids, resolvable := actionReferences(ast)
|
||||
return &Program{prg: prg, actionIDs: ids, resolvable: resolvable}, nil
|
||||
return &Program{prg: prg, actionIDs: ids, resolvable: resolvable, outType: ast.OutputType()}, nil
|
||||
}
|
||||
|
||||
// actionReferences walks the compiled AST once and classifies every read of
|
||||
// actionReferences walks the checked AST once and classifies every read of
|
||||
// the `actions` context root as either a statically-resolvable action id or
|
||||
// not. The invariant is exhaustive by construction: each read of `actions`
|
||||
// consumes exactly one `actions` identifier node, so counting identifier
|
||||
// nodes and counting the reads that match the static access shape (a field
|
||||
// selection on the `actions` ident) yields
|
||||
// not. A root read is an identifier the checker typed as the `actions`
|
||||
// object: matching on type rather than name keeps a comprehension variable
|
||||
// that happens to be called `actions` out of the count. Each root read
|
||||
// consumes exactly one such identifier, so
|
||||
//
|
||||
// resolvable = (identCount == staticCount)
|
||||
//
|
||||
// Any other spelling that mentions `actions` contributes an identifier node
|
||||
// without a matching static access, so it reports unresolvable rather than
|
||||
// slipping through as a runtime miss. The returned ids are the sorted,
|
||||
// de-duplicated ids of the static accesses.
|
||||
//
|
||||
// With the per-playbook object type the CEL checker rejects every non-static
|
||||
// `actions` read at compile time -- a dynamic index, `in`, `size`, or a
|
||||
// method/field selection that is not a declared id never reaches this walk.
|
||||
// The one spelling the checker does NOT reject is a bare `actions` value
|
||||
// read, which compiles as an object value but cannot be pinned to an action
|
||||
// id at load. This walk is retained solely to reject that spelling; the ids
|
||||
// return is now informational (the unknown-id check moved to the checker's
|
||||
// per-playbook object type).
|
||||
// where staticCount is the root reads that are a field selection. The
|
||||
// checker already rejects every other non-static read (a dynamic index,
|
||||
// `in`, `size`, an undeclared id); the spelling it accepts is a bare
|
||||
// `actions` value, which compiles but cannot be pinned to an action id at
|
||||
// load. This walk exists to reject that spelling; the ids return is
|
||||
// informational. The ids are sorted and de-duplicated.
|
||||
func actionReferences(ast *cel.Ast) ([]string, bool) {
|
||||
if ast == nil || ast.NativeRep() == nil {
|
||||
return nil, true
|
||||
}
|
||||
checked := ast.NativeRep()
|
||||
isRoot := func(e celast.Expr) bool {
|
||||
return e.Kind() == celast.IdentKind && checked.GetType(e.ID()).TypeName() == actionsTypeName
|
||||
}
|
||||
var identCount, staticCount int
|
||||
seen := map[string]struct{}{}
|
||||
visitor := celast.NewExprVisitor(func(e celast.Expr) {
|
||||
switch e.Kind() {
|
||||
case celast.IdentKind:
|
||||
if e.AsIdent() == "actions" {
|
||||
identCount++
|
||||
}
|
||||
case celast.SelectKind:
|
||||
sel := e.AsSelect()
|
||||
if !isActionsIdent(sel.Operand()) {
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case isRoot(e):
|
||||
identCount++
|
||||
case e.Kind() == celast.SelectKind && isRoot(e.AsSelect().Operand()):
|
||||
staticCount++
|
||||
seen[sel.FieldName()] = struct{}{}
|
||||
seen[e.AsSelect().FieldName()] = struct{}{}
|
||||
}
|
||||
})
|
||||
celast.PreOrderVisit(ast.NativeRep().Expr(), visitor)
|
||||
celast.PreOrderVisit(checked.Expr(), visitor)
|
||||
ids := make([]string, 0, len(seen))
|
||||
for id := range seen {
|
||||
ids = append(ids, id)
|
||||
@@ -332,16 +323,50 @@ func actionReferences(ast *cel.Ast) ([]string, bool) {
|
||||
return ids, identCount == staticCount
|
||||
}
|
||||
|
||||
// isActionsIdent reports whether e is the `actions` context-root identifier.
|
||||
func isActionsIdent(e celast.Expr) bool {
|
||||
return e.Kind() == celast.IdentKind && e.AsIdent() == "actions"
|
||||
}
|
||||
|
||||
// Program is a compiled, cost-limited playbook expression.
|
||||
type Program struct {
|
||||
prg cel.Program
|
||||
actionIDs []string
|
||||
resolvable bool
|
||||
outType *cel.Type
|
||||
}
|
||||
|
||||
// Fits reports whether the program's checked output type can fill a Go value
|
||||
// of type t. A dyn output fits anything: its type is known only per
|
||||
// evaluation. A Go type with no CEL scalar counterpart is not checked here.
|
||||
func (p *Program) Fits(t reflect.Type) bool {
|
||||
if p.outType == nil || p.outType.Kind() == types.DynKind {
|
||||
return true
|
||||
}
|
||||
want, ok := celScalar(t)
|
||||
return !ok || want.IsExactType(p.outType)
|
||||
}
|
||||
|
||||
// OutputType is the program's checked output type, for error messages.
|
||||
func (p *Program) OutputType() string {
|
||||
if p.outType == nil {
|
||||
return "dyn"
|
||||
}
|
||||
return p.outType.String()
|
||||
}
|
||||
|
||||
// celScalar maps a Go scalar kind to the CEL type an expression must produce
|
||||
// to fill it.
|
||||
func celScalar(t reflect.Type) (*cel.Type, bool) {
|
||||
switch t.Kind() {
|
||||
case reflect.String:
|
||||
return cel.StringType, true
|
||||
case reflect.Bool:
|
||||
return cel.BoolType, true
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return cel.IntType, true
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return cel.UintType, true
|
||||
case reflect.Float32, reflect.Float64:
|
||||
return cel.DoubleType, true
|
||||
default:
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
// ActionReferences reports the action ids the expression reads from the
|
||||
|
||||
@@ -266,6 +266,24 @@ func TestActionReferences(t *testing.T) {
|
||||
wantIDs: nil,
|
||||
wantResolvable: false,
|
||||
},
|
||||
{
|
||||
name: "loop variable named actions is not the root",
|
||||
src: `event.list.exists(actions, actions == 1)`,
|
||||
wantIDs: nil,
|
||||
wantResolvable: true,
|
||||
},
|
||||
{
|
||||
name: "field of a loop variable named actions is not an action id",
|
||||
src: `event.list.exists(actions, actions.a == 1)`,
|
||||
wantIDs: nil,
|
||||
wantResolvable: true,
|
||||
},
|
||||
{
|
||||
name: "bare root still unresolvable beside a shadowing loop",
|
||||
src: `[actions].exists(actions, actions.build.result.written)`,
|
||||
wantIDs: []string{"build"},
|
||||
wantResolvable: false,
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
package playbook
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// An action-level finding names the line of the offending action, `when`
|
||||
// or args key, compiler-style, so the lint tool and the language server can
|
||||
// point at it.
|
||||
func TestLoadFindingsCarryTheOffendingLine(t *testing.T) {
|
||||
const head = "trigger:\n kind: bug\nactions:\n"
|
||||
tests := []struct {
|
||||
name string
|
||||
actions string
|
||||
line int
|
||||
}{
|
||||
{
|
||||
name: "unknown kind on the second action",
|
||||
actions: " - position: module\n kind: log\n - position: module\n kind: nope\n",
|
||||
line: 6,
|
||||
},
|
||||
{
|
||||
name: "when that does not compile",
|
||||
actions: " - position: module\n kind: log\n when: 'event.x =='\n",
|
||||
line: 6,
|
||||
},
|
||||
{
|
||||
name: "args value of the wrong type",
|
||||
actions: " - position: module\n kind: log\n args:\n level: '\"info\"'\n message: '123'\n",
|
||||
line: 8,
|
||||
},
|
||||
{
|
||||
name: "args key the kind does not declare",
|
||||
actions: " - position: module\n kind: log\n args:\n mesage: '\"x\"'\n",
|
||||
line: 7,
|
||||
},
|
||||
{
|
||||
name: "workflow action naming no workflow",
|
||||
actions: " - position: workflow\n when: 'true'\n",
|
||||
line: 4,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := writeFile(t, dir, "pb.yaml", head+tt.actions)
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load = nil, want a finding")
|
||||
}
|
||||
if want := filepath.Clean(path) + ":" + strconv.Itoa(tt.line) + ":"; !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("Load error = %q, want it to name %q", err, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@
|
||||
// - a workflow playbook is exactly one `workflow` action, unchanged from
|
||||
// the original boundary, and is routed by the daemon's definition pin;
|
||||
// - an action playbook is one or more `module` actions in order, each with
|
||||
// a registered `kind`, `args`, and an optional `when`/`id`. It loads and
|
||||
// type-checks now but has no run path yet (t2db.31).
|
||||
// a registered `kind`, `args`, and an optional `when`/`id`. Store.Run
|
||||
// executes it (docs/prds/action-playbook-run.md).
|
||||
//
|
||||
// The two shapes never mix in one playbook. This is an ADDITIONAL routing
|
||||
// source alongside the flat kind/label binding files (t2db.9/.10/.11): the
|
||||
@@ -18,18 +18,19 @@
|
||||
package playbook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
|
||||
"github.com/samcharles93/archie-core/internal/domain/stableid"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
)
|
||||
|
||||
@@ -43,9 +44,19 @@ type KindSchemas interface {
|
||||
KindSchema(kind string) (args, result reflect.Type, ok bool)
|
||||
}
|
||||
|
||||
// Modules is the module source an action playbook loads and runs against:
|
||||
// the kinds' schemas, the invoke, and the result decode. *module.ModuleRegistry
|
||||
// satisfies it.
|
||||
type Modules interface {
|
||||
KindSchemas
|
||||
Invoke(ctx context.Context, kind string, args map[string]any) (map[string]any, error)
|
||||
DecodeResult(kind string, raw map[string]any) (any, error)
|
||||
}
|
||||
|
||||
// Store is the loaded set of playbooks, validated and compiled at load time.
|
||||
type Store struct {
|
||||
Playbooks []*Playbook
|
||||
modules Modules
|
||||
}
|
||||
|
||||
// Playbook is one trigger+actions document.
|
||||
@@ -129,15 +140,45 @@ type rawAction struct {
|
||||
Kind string `yaml:"kind"`
|
||||
When string `yaml:"when"`
|
||||
Args map[string]string `yaml:"args"`
|
||||
|
||||
// Source lines, so a finding names where the author wrote it: the
|
||||
// action's first line, its `when` key, and each args key.
|
||||
line int
|
||||
whenLine int
|
||||
argLines map[string]int
|
||||
}
|
||||
|
||||
// actionIDPattern is the stable-identifier shape a WORKFLOW action id must
|
||||
// match when declared: a lowercase, dotted/dashed identifier (shared with
|
||||
// internal/plugin/host.go:21 and internal/domain/workflow/vocabulary.go:19),
|
||||
// so an id has exactly one spelling and cannot smuggle whitespace or case into
|
||||
// the vocabulary two processes compare. Module action ids are stricter (see
|
||||
// validateModuleActionIDs) because they must also be CEL field selections.
|
||||
var actionIDPattern = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`)
|
||||
// UnmarshalYAML decodes the action as plain data and records its source
|
||||
// lines.
|
||||
func (a *rawAction) UnmarshalYAML(n *yaml.Node) error {
|
||||
type plain rawAction
|
||||
if err := n.Decode((*plain)(a)); err != nil {
|
||||
return err
|
||||
}
|
||||
a.line = n.Line
|
||||
for i := 0; i+1 < len(n.Content); i += 2 {
|
||||
key, val := n.Content[i], n.Content[i+1]
|
||||
switch key.Value {
|
||||
case "when":
|
||||
a.whenLine = key.Line
|
||||
case "args":
|
||||
a.argLines = make(map[string]int, len(val.Content)/2)
|
||||
for j := 0; j+1 < len(val.Content); j += 2 {
|
||||
a.argLines[val.Content[j].Value] = val.Content[j].Line
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// at is path:line, the compiler-style location a finding leads with; a zero
|
||||
// line (a hand-built action) leaves the bare path.
|
||||
func at(path string, line int) string {
|
||||
if line == 0 {
|
||||
return path
|
||||
}
|
||||
return fmt.Sprintf("%s:%d", path, line)
|
||||
}
|
||||
|
||||
// Module action ids are stricter than workflow ids because they must also be
|
||||
// readable as `actions.<id>` in CEL field selection. The authoritative check
|
||||
@@ -157,8 +198,8 @@ func validateActionIDs(actions []rawAction) error {
|
||||
if id == "" {
|
||||
continue
|
||||
}
|
||||
if !actionIDPattern.MatchString(id) {
|
||||
return fmt.Errorf("action id %q is not a valid stable identifier (want %s)", id, actionIDPattern.String())
|
||||
if !stableid.Valid(id) {
|
||||
return fmt.Errorf("action id %q is not a valid stable identifier (want %s)", id, stableid.Pattern)
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return fmt.Errorf("duplicate action id %q", id)
|
||||
@@ -198,10 +239,10 @@ func validateModuleActionIDs(path string, actions []rawAction) error {
|
||||
// compile error, an args key error -- fails the whole load: the reject-at-load
|
||||
// philosophy of the parent design doc. A missing directory is an empty store
|
||||
// (matching the flat binding loaders' convention).
|
||||
func Load(dir string, schemas KindSchemas) (*Store, error) {
|
||||
func Load(dir string, modules Modules) (*Store, error) {
|
||||
entries, err := os.ReadDir(dir)
|
||||
if os.IsNotExist(err) {
|
||||
return &Store{}, nil
|
||||
return &Store{modules: modules}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read playbook dir %s: %w", dir, err)
|
||||
@@ -218,10 +259,10 @@ func Load(dir string, schemas KindSchemas) (*Store, error) {
|
||||
}
|
||||
sort.Strings(names)
|
||||
|
||||
store := &Store{}
|
||||
store := &Store{modules: modules}
|
||||
for _, name := range names {
|
||||
path := filepath.Join(dir, name)
|
||||
pb, err := loadOne(dir, path, schemas)
|
||||
pb, err := loadOne(dir, path, modules)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -291,14 +332,14 @@ func compileActions(path string, raw []rawAction, schemas KindSchemas) ([]Action
|
||||
if len(raw) == 1 && strings.TrimSpace(a.Workflow) != "" {
|
||||
pos = "workflow"
|
||||
} else {
|
||||
return nil, fmt.Errorf("playbook %s: action %d must declare a position (%q or %q)", path, i+1, "workflow", "module")
|
||||
return nil, fmt.Errorf("playbook %s: action %d must declare a position (%q or %q)", at(path, a.line), i+1, "workflow", "module")
|
||||
}
|
||||
}
|
||||
if pos != "workflow" && pos != "module" {
|
||||
return nil, fmt.Errorf("playbook %s: action %d position %q is not supported (want %q or %q)", path, i+1, pos, "workflow", "module")
|
||||
return nil, fmt.Errorf("playbook %s: action %d position %q is not supported (want %q or %q)", at(path, a.line), i+1, pos, "workflow", "module")
|
||||
}
|
||||
a.Position = pos
|
||||
if err := validateActionShapeField(path, i, pos, a); err != nil {
|
||||
if err := validateActionShapeField(at(path, a.line), i, pos, a); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if pos == "workflow" {
|
||||
@@ -349,7 +390,7 @@ func compileWorkflowActions(path string, raw []rawAction) ([]Action, error) {
|
||||
}
|
||||
a := raw[0]
|
||||
if strings.TrimSpace(a.Workflow) == "" {
|
||||
return nil, fmt.Errorf("playbook %s: workflow-kind action must name a workflow", path)
|
||||
return nil, fmt.Errorf("playbook %s: workflow-kind action must name a workflow", at(path, a.line))
|
||||
}
|
||||
|
||||
env := expr.NewEnv()
|
||||
@@ -360,13 +401,13 @@ func compileWorkflowActions(path string, raw []rawAction) ([]Action, error) {
|
||||
env: env,
|
||||
}
|
||||
if strings.TrimSpace(a.When) != "" {
|
||||
prg, err := compileExpr(path, "when condition", a.When, env)
|
||||
prg, err := compileExpr(at(path, a.whenLine), "when condition", a.When, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
action.When = prg
|
||||
}
|
||||
args, err := compileArgs(path, "", "", a.Args, env, nil)
|
||||
args, err := compileArgs(path, a.argLines, "", "", a.Args, env, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -389,11 +430,11 @@ func compileModuleActions(path string, raw []rawAction, schemas KindSchemas) ([]
|
||||
label := actionLabel(i, a.ID)
|
||||
kind := strings.TrimSpace(a.Kind)
|
||||
if kind == "" {
|
||||
return nil, fmt.Errorf("playbook %s: %s must name a kind", path, label)
|
||||
return nil, fmt.Errorf("playbook %s: %s must name a kind", at(path, a.line), label)
|
||||
}
|
||||
argsType, resultType, ok := schemas.KindSchema(kind)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("playbook %s: %s has unknown module kind %q", path, label, kind)
|
||||
return nil, fmt.Errorf("playbook %s: %s has unknown module kind %q", at(path, a.line), label, kind)
|
||||
}
|
||||
|
||||
env := expr.NewEnv(declared...)
|
||||
@@ -404,13 +445,13 @@ func compileModuleActions(path string, raw []rawAction, schemas KindSchemas) ([]
|
||||
env: env,
|
||||
}
|
||||
if strings.TrimSpace(a.When) != "" {
|
||||
prg, err := compileExpr(path, label+" when condition", a.When, env)
|
||||
prg, err := compileExpr(at(path, a.whenLine), label+" when condition", a.When, env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
action.When = prg
|
||||
}
|
||||
args, err := compileArgs(path, label, kind, a.Args, env, argsType)
|
||||
args, err := compileArgs(path, a.argLines, label, kind, a.Args, env, argsType)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -445,6 +486,27 @@ func argsLabel(label, key string) string {
|
||||
return fmt.Sprintf("%s args[%q]", label, key)
|
||||
}
|
||||
|
||||
// checkArgType refuses an args value whose checked CEL type cannot fill the
|
||||
// Args field it names. A dyn value passes: the module decode checks it per
|
||||
// event.
|
||||
func checkArgType(path, label, kind string, argsSchema reflect.Type, key string, prg *expr.Program) error {
|
||||
t := argsSchema
|
||||
if t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
}
|
||||
for field := range t.Fields() {
|
||||
if strings.ToLower(field.Name) != key || prg.Fits(field.Type) {
|
||||
continue
|
||||
}
|
||||
loc := kind + " kind"
|
||||
if label != "" {
|
||||
loc = label + " " + loc
|
||||
}
|
||||
return fmt.Errorf("playbook %s: %s args[%q] is %s, want %s", path, loc, key, prg.OutputType(), field.Type)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// compileArgs compiles every args value as a CEL expression at load, keyed by
|
||||
// arg name. J2 has no literal/expression split: the YAML scalar text IS the
|
||||
// CEL source, so a string literal is quoted inside YAML and a number or
|
||||
@@ -453,12 +515,12 @@ func argsLabel(label, key string) string {
|
||||
// nil and keep free-form args. Each program goes through the same
|
||||
// compile/reference validation as `when`, with label naming the offending
|
||||
// action and the args key naming the offending field.
|
||||
func compileArgs(path, label, kind string, raw map[string]string, env *expr.Env, argsSchema reflect.Type) (map[string]*expr.Program, error) {
|
||||
func compileArgs(path string, lines map[string]int, label, kind string, raw map[string]string, env *expr.Env, argsSchema reflect.Type) (map[string]*expr.Program, error) {
|
||||
if len(raw) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if argsSchema != nil {
|
||||
if err := validateArgsKeys(path, label, kind, argsSchema, raw); err != nil {
|
||||
if err := validateArgsKeys(path, lines, label, kind, argsSchema, raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
@@ -469,10 +531,15 @@ func compileArgs(path, label, kind string, raw map[string]string, env *expr.Env,
|
||||
sort.Strings(keys)
|
||||
args := make(map[string]*expr.Program, len(raw))
|
||||
for _, key := range keys {
|
||||
prg, err := compileExpr(path, argsLabel(label, key), raw[key], env)
|
||||
prg, err := compileExpr(at(path, lines[key]), argsLabel(label, key), raw[key], env)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if argsSchema != nil {
|
||||
if err := checkArgType(at(path, lines[key]), label, kind, argsSchema, key, prg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
args[key] = prg
|
||||
}
|
||||
return args, nil
|
||||
@@ -484,7 +551,7 @@ func compileArgs(path, label, kind string, raw map[string]string, env *expr.Env,
|
||||
// YAML spelling (Message -> message), and the YAML key is compared verbatim:
|
||||
// the decoder also matches literal lower-case keys, so `Message` is rejected
|
||||
// here rather than loading and then failing at dispatch.
|
||||
func validateArgsKeys(path, label, kind string, argsSchema reflect.Type, raw map[string]string) error {
|
||||
func validateArgsKeys(path string, lines map[string]int, label, kind string, argsSchema reflect.Type, raw map[string]string) error {
|
||||
t := argsSchema
|
||||
if t.Kind() == reflect.Pointer {
|
||||
t = t.Elem()
|
||||
@@ -504,7 +571,7 @@ func validateArgsKeys(path, label, kind string, argsSchema reflect.Type, raw map
|
||||
}
|
||||
for _, key := range keys {
|
||||
if _, ok := fields[key]; !ok {
|
||||
return fmt.Errorf("playbook %s: %s args[%q] is not a declared Args field", path, loc, key)
|
||||
return fmt.Errorf("playbook %s: %s args[%q] is not a declared Args field", at(path, lines[key]), loc, key)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
@@ -557,8 +624,8 @@ type DispatchInput struct {
|
||||
// IsActionPlaybook reports whether pb is an action playbook (one or more
|
||||
// module actions), as opposed to a workflow playbook (exactly one workflow
|
||||
// action). It is the single two-shape predicate shared by Dispatch (which
|
||||
// skips action playbooks) and the daemon's D1 load warning (which logs them),
|
||||
// so the two can never disagree.
|
||||
// routes only workflow playbooks) and Run (which executes only action
|
||||
// playbooks), so the two can never disagree.
|
||||
func (pb *Playbook) IsActionPlaybook() bool {
|
||||
return len(pb.Actions) != 1 || pb.Actions[0].Position != "workflow"
|
||||
}
|
||||
@@ -612,9 +679,8 @@ type Decision struct {
|
||||
|
||||
// Dispatch returns the workflow name the first matching workflow playbook
|
||||
// selects for the input, and whether any playbook matched. Action playbooks
|
||||
// are loaded and validated but not routed (multi-action-playbooks.md, D1), so
|
||||
// this considers workflow playbooks only: an action playbook cannot hijack the
|
||||
// definition pin before its run path exists (t2db.31). No match means trigger
|
||||
// choose no workflow, so they are skipped here and executed by Run. No match
|
||||
// means trigger
|
||||
// mismatch or a when condition evaluating false, and the caller keeps its own
|
||||
// routing.
|
||||
//
|
||||
@@ -643,16 +709,8 @@ func (s *Store) Dispatch(input DispatchInput) (Decision, bool) {
|
||||
continue
|
||||
}
|
||||
a := pb.Actions[0]
|
||||
if a.When != nil {
|
||||
val, err := a.env.Eval(a.When, ctx)
|
||||
if err != nil {
|
||||
// J3: evaluation error -> false (skip), caller logs.
|
||||
continue
|
||||
}
|
||||
b, ok := val.(bool)
|
||||
if !ok || !b {
|
||||
continue
|
||||
}
|
||||
if !a.whenHolds(ctx) {
|
||||
continue
|
||||
}
|
||||
return Decision{PlaybookID: pb.ID, Version: pb.Version, Workflow: a.Workflow, ActionID: a.ID, ActionPosition: 1}, true
|
||||
}
|
||||
@@ -670,9 +728,8 @@ func evalContext(input DispatchInput) expr.Context {
|
||||
}
|
||||
|
||||
// EvalArgs evaluates a compiled action's args against the dispatch context,
|
||||
// returning the resulting name->value map. No shipped position consumes args
|
||||
// yet; the consumer arrives with the first side-effecting position (t2db.31).
|
||||
// An action declaring no args evaluates to an empty map, nil-program entries
|
||||
// returning the resulting name->value map. Run evaluates args the same way
|
||||
// against a context that also carries earlier actions' results. An action declaring no args evaluates to an empty map, nil-program entries
|
||||
// are skipped, and the first evaluation error is returned. Nil-receiver-safe
|
||||
// for the pre-load composition phase.
|
||||
//
|
||||
@@ -681,10 +738,29 @@ func evalContext(input DispatchInput) expr.Context {
|
||||
// meaningful substitute and is returned to the caller to abort the dispatch.
|
||||
// Ratifying that rule against a real consumer is tracked by archie-core-1h05.
|
||||
func (s *Store) EvalArgs(a Action, input DispatchInput) (map[string]any, error) {
|
||||
if s == nil || len(a.Args) == 0 {
|
||||
if s == nil {
|
||||
return map[string]any{}, nil
|
||||
}
|
||||
ctx := evalContext(input)
|
||||
return a.evalArgs(evalContext(input))
|
||||
}
|
||||
|
||||
// whenHolds reports whether the action's `when` is absent or evaluates to
|
||||
// true. An evaluation error is false (J3: skip, caller logs).
|
||||
func (a Action) whenHolds(ctx expr.Context) bool {
|
||||
if a.When == nil {
|
||||
return true
|
||||
}
|
||||
val, err := a.env.Eval(a.When, ctx)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
b, ok := val.(bool)
|
||||
return ok && b
|
||||
}
|
||||
|
||||
// evalArgs evaluates the action's args against ctx in key order, returning
|
||||
// the first evaluation error.
|
||||
func (a Action) evalArgs(ctx expr.Context) (map[string]any, error) {
|
||||
out := make(map[string]any, len(a.Args))
|
||||
keys := make([]string, 0, len(a.Args))
|
||||
for key := range a.Args {
|
||||
|
||||
@@ -30,7 +30,7 @@ func writeFile(t *testing.T, dir, name, content string) string {
|
||||
// tests: *module.ModuleRegistry satisfies playbook.KindSchemas. It consults
|
||||
// the built-in kind registry, so no module file needs to be installed for the
|
||||
// schema lookup to work.
|
||||
func testSchemas(t *testing.T) KindSchemas {
|
||||
func testSchemas(t *testing.T) Modules {
|
||||
t.Helper()
|
||||
return module.New()
|
||||
}
|
||||
@@ -520,23 +520,25 @@ func TestValidateActionIDs(t *testing.T) {
|
||||
// whole load, naming the playbook path -- never a runtime miss. Under the
|
||||
// per-playbook object type these forms are rejected at compile time: the
|
||||
// field-selection spelling names the undefined id, while a dynamic index, an
|
||||
// `in` test, or a size read fails with cel-go's overload error (no id name).
|
||||
// `in` test, or a size read fails with cel-go's overload error on the actions
|
||||
// type. wantErr pins that stage, so a case cannot pass on a YAML parse error
|
||||
// or an undeclared root instead.
|
||||
func TestLoadWhenActionsReferenceFails(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
when string
|
||||
wantID string
|
||||
name string
|
||||
when string
|
||||
wantErr string
|
||||
}{
|
||||
{name: "undeclared field selection", when: `actions.build.result.x == true`, wantID: "build"},
|
||||
{name: "dynamic index on actions", when: `actions["a"].result.x == true`},
|
||||
{name: "non-literal index key", when: `actions[key].result.x == true`},
|
||||
{name: "in operator on actions", when: `"notify" in actions`},
|
||||
{name: "size of actions", when: `size(actions) > 0`},
|
||||
{name: "undeclared field selection", when: `actions.build.result.x == true`, wantErr: "undefined field 'build'"},
|
||||
{name: "dynamic index on actions", when: `actions["a"].result.x == true`, wantErr: "'_[_]' applied to '(actions, string)'"},
|
||||
{name: "non-literal index key", when: `actions[event.kind].result.x == true`, wantErr: "'_[_]' applied to '(actions, dyn)'"},
|
||||
{name: "in operator on actions", when: `"notify" in actions`, wantErr: "'@in' applied to '(string, actions)'"},
|
||||
{name: "size of actions", when: `size(actions) > 0`, wantErr: "'size' applied to '(actions)'"},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n when: "+tc.when+"\n")
|
||||
writeFile(t, dir, "pb.yaml", "\ntrigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n when: '"+tc.when+"'\n")
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if err == nil {
|
||||
t.Fatal("Load = nil, want load failure")
|
||||
@@ -544,8 +546,8 @@ func TestLoadWhenActionsReferenceFails(t *testing.T) {
|
||||
if !strings.Contains(err.Error(), "pb.yaml") {
|
||||
t.Errorf("Load error = %q, want the playbook path named", err.Error())
|
||||
}
|
||||
if tc.wantID != "" && !strings.Contains(err.Error(), tc.wantID) {
|
||||
t.Errorf("Load error = %q, want the unknown id %q named", err.Error(), tc.wantID)
|
||||
if !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Errorf("Load error = %q, want %q", err.Error(), tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -699,7 +701,7 @@ func TestCompileArgsReportsFirstKeyDeterministically(t *testing.T) {
|
||||
"a.bad": "event.missing ==",
|
||||
}
|
||||
for range 64 {
|
||||
_, err := compileArgs("pb.yaml", "", "", raw, env, nil)
|
||||
_, err := compileArgs("pb.yaml", nil, "", "", raw, env, nil)
|
||||
if err == nil {
|
||||
t.Fatal("compileArgs = nil, want error")
|
||||
}
|
||||
@@ -725,7 +727,7 @@ func TestValidateArgsKeysReportsFirstKeyDeterministically(t *testing.T) {
|
||||
"a.bad": "x",
|
||||
}
|
||||
for range 64 {
|
||||
err := validateArgsKeys("pb.yaml", "", "log", argsType, raw)
|
||||
err := validateArgsKeys("pb.yaml", nil, "", "log", argsType, raw)
|
||||
if err == nil {
|
||||
t.Fatal("validateArgsKeys = nil, want error")
|
||||
}
|
||||
@@ -1441,3 +1443,36 @@ func TestLoadActionPlaybookRejectsActionReferences(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// An args value whose static CEL type cannot fill the kind's Args field fails
|
||||
// the load, naming the key. A dyn value (an event read) is accepted: its type
|
||||
// is known only per event, and the module decode refuses a bad one at run.
|
||||
func TestLoadArgsValueTypeAgainstArgsSchema(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
message string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "string literal", message: `'"hello"'`},
|
||||
{name: "string concatenation", message: `'"n=" + string(1)'`},
|
||||
{name: "dyn event read", message: `event.title`},
|
||||
{name: "int literal", message: `'123'`, wantErr: true},
|
||||
{name: "bool expression", message: `'1 == 1'`, wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", "trigger:\n kind: bug\nactions:\n - position: module\n kind: log\n args:\n message: "+tt.message+"\n")
|
||||
_, err := Load(dir, testSchemas(t))
|
||||
if !tt.wantErr {
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), `args["message"]`) || !strings.Contains(err.Error(), "string") {
|
||||
t.Fatalf("Load error = %v, want args[\"message\"] refused for not being a string", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package playbook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/expr"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// Run executes every action playbook whose trigger matches input, in load
|
||||
// order (docs/prds/action-playbook-run.md). Each action goes through
|
||||
// InvokeOnce, so it fires at most once per (playbook, version, event,
|
||||
// action). A failure stops only its own playbook; the rest still run, and
|
||||
// the failures are returned joined, each naming its playbook and action.
|
||||
func (s *Store) Run(ctx context.Context, ledger storecontract.PlaybookDispatcher, log *slog.Logger, input DispatchInput) error {
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
var errs []error
|
||||
for _, pb := range s.Playbooks {
|
||||
if !pb.IsActionPlaybook() || !pb.Match(input) {
|
||||
continue
|
||||
}
|
||||
if err := s.runPlaybook(ctx, ledger, log, pb, input); err != nil {
|
||||
errs = append(errs, fmt.Errorf("playbook %s: %w", pb.ID, err))
|
||||
}
|
||||
}
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
// runPlaybook runs one playbook's actions in order against one evaluation
|
||||
// context, so a later action reads an earlier one's result.
|
||||
func (s *Store) runPlaybook(ctx context.Context, ledger storecontract.PlaybookDispatcher, log *slog.Logger, pb *Playbook, input DispatchInput) error {
|
||||
evalCtx := expr.Context{Event: input.Event, Actions: map[string]map[string]any{}}
|
||||
for i, a := range pb.Actions {
|
||||
label := a.ID
|
||||
if label == "" {
|
||||
label = "#" + strconv.Itoa(i+1)
|
||||
}
|
||||
if !a.whenHolds(evalCtx) {
|
||||
continue
|
||||
}
|
||||
args, err := a.evalArgs(evalCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("action %s: %w", label, err)
|
||||
}
|
||||
var raw map[string]any
|
||||
decision := Decision{PlaybookID: pb.ID, Version: pb.Version, ActionID: a.ID, ActionPosition: i + 1}
|
||||
invoked := false
|
||||
err = InvokeOnce(ctx, ledger, log, decision, input, func(ctx context.Context) error {
|
||||
invoked = true
|
||||
raw, err = s.modules.Invoke(ctx, a.Kind, args)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("action %s: %w", label, err)
|
||||
}
|
||||
if !invoked || a.ID == "" {
|
||||
continue
|
||||
}
|
||||
result, err := s.modules.DecodeResult(a.Kind, raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("action %s: %w", label, err)
|
||||
}
|
||||
evalCtx.Actions[a.ID] = map[string]any{"result": result}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package playbook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eda/module"
|
||||
)
|
||||
|
||||
// recordingModules is the real kind-schema source with a fake invoker: it
|
||||
// records each log message and fails any message listed in fail.
|
||||
type recordingModules struct {
|
||||
*module.ModuleRegistry
|
||||
messages []string
|
||||
fail map[string]bool
|
||||
}
|
||||
|
||||
func (m *recordingModules) Invoke(_ context.Context, kind string, args map[string]any) (map[string]any, error) {
|
||||
msg, _ := args["message"].(string)
|
||||
m.messages = append(m.messages, msg)
|
||||
if m.fail[msg] {
|
||||
return nil, errors.New("invoke failed")
|
||||
}
|
||||
return map[string]any{"written": true, "level": "info"}, nil
|
||||
}
|
||||
|
||||
func loadRunStore(t *testing.T, mods *recordingModules, document string) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "pb.yaml", document)
|
||||
store, err := Load(dir, mods)
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
return store
|
||||
}
|
||||
|
||||
const twoLogActions = `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- id: first
|
||||
position: module
|
||||
kind: log
|
||||
args: { message: '"first"' }
|
||||
- id: second
|
||||
position: module
|
||||
kind: log
|
||||
args: { message: '"second saw " + string(actions.first.result.written)' }
|
||||
`
|
||||
|
||||
func bugInput() DispatchInput {
|
||||
return DispatchInput{Labels: []string{"bug"}, Kind: "bug", TaskID: "acme/widget#7", Event: map[string]any{}}
|
||||
}
|
||||
|
||||
func TestRunExecutesActionsInOrderAndFeedsResults(t *testing.T) {
|
||||
mods := &recordingModules{ModuleRegistry: module.New()}
|
||||
store := loadRunStore(t, mods, twoLogActions)
|
||||
|
||||
if err := store.Run(t.Context(), &fakePlaybookLedger{}, slog.New(slog.DiscardHandler), bugInput()); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if want := []string{"first", "second saw true"}; !slices.Equal(mods.messages, want) {
|
||||
t.Fatalf("invoked messages = %q, want %q", mods.messages, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunInvokesEachActionOncePerEvent(t *testing.T) {
|
||||
mods := &recordingModules{ModuleRegistry: module.New()}
|
||||
store := loadRunStore(t, mods, twoLogActions)
|
||||
ledger := &fakePlaybookLedger{}
|
||||
log := slog.New(slog.DiscardHandler)
|
||||
|
||||
if err := store.Run(t.Context(), ledger, log, bugInput()); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
// The repeat skips "first" as a duplicate, so it has no result and
|
||||
// "second" cannot evaluate its args: the playbook stops there
|
||||
// (action-playbook-run.md). Neither action is invoked again.
|
||||
_ = store.Run(t.Context(), ledger, log, bugInput())
|
||||
if len(mods.messages) != 2 {
|
||||
t.Fatalf("invoked messages = %q, want each action once", mods.messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunSkipsAnActionWhoseWhenIsFalse(t *testing.T) {
|
||||
mods := &recordingModules{ModuleRegistry: module.New()}
|
||||
store := loadRunStore(t, mods, `
|
||||
trigger:
|
||||
kind: bug
|
||||
actions:
|
||||
- position: module
|
||||
kind: log
|
||||
when: 'event.kind == "feature"'
|
||||
args: { message: '"skipped"' }
|
||||
- position: module
|
||||
kind: log
|
||||
args: { message: '"ran"' }
|
||||
`)
|
||||
if err := store.Run(t.Context(), &fakePlaybookLedger{}, slog.New(slog.DiscardHandler), DispatchInput{
|
||||
Labels: []string{"bug"}, Kind: "bug", TaskID: "acme/widget#7", Event: map[string]any{"kind": "bug"},
|
||||
}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if want := []string{"ran"}; !slices.Equal(mods.messages, want) {
|
||||
t.Fatalf("invoked messages = %q, want %q", mods.messages, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunStopsThePlaybookOnAnInvokeError(t *testing.T) {
|
||||
mods := &recordingModules{ModuleRegistry: module.New(), fail: map[string]bool{"first": true}}
|
||||
store := loadRunStore(t, mods, twoLogActions)
|
||||
|
||||
err := store.Run(t.Context(), &fakePlaybookLedger{}, slog.New(slog.DiscardHandler), bugInput())
|
||||
if err == nil || !strings.Contains(err.Error(), "pb.yaml") || !strings.Contains(err.Error(), "first") {
|
||||
t.Fatalf("Run error = %v, want one naming the playbook and the action", err)
|
||||
}
|
||||
if want := []string{"first"}; !slices.Equal(mods.messages, want) {
|
||||
t.Fatalf("invoked messages = %q, want the run stopped at %q", mods.messages, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunIgnoresNonMatchingAndWorkflowPlaybooks(t *testing.T) {
|
||||
mods := &recordingModules{ModuleRegistry: module.New()}
|
||||
store := loadRunStore(t, mods, twoLogActions)
|
||||
input := bugInput()
|
||||
input.Labels, input.Kind = []string{"feature"}, "feature"
|
||||
|
||||
if err := store.Run(t.Context(), &fakePlaybookLedger{}, slog.New(slog.DiscardHandler), input); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
workflowStore := loadRunStore(t, mods, "trigger:\n kind: bug\nactions:\n - position: workflow\n workflow: tdd\n")
|
||||
if err := workflowStore.Run(t.Context(), &fakePlaybookLedger{}, slog.New(slog.DiscardHandler), bugInput()); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(mods.messages) != 0 {
|
||||
t.Fatalf("invoked messages = %q, want none", mods.messages)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Package stableid owns the stable-identifier shape shared by plugin
|
||||
// manifests, workflow step types and playbook action ids: a lowercase,
|
||||
// dotted or dashed identifier, so one name has exactly one spelling and
|
||||
// cannot smuggle whitespace or case into a vocabulary two processes compare.
|
||||
package stableid
|
||||
|
||||
import "regexp"
|
||||
|
||||
// Pattern is the stable-identifier grammar, for error messages that quote it.
|
||||
const Pattern = `^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`
|
||||
|
||||
var re = regexp.MustCompile(Pattern)
|
||||
|
||||
// Valid reports whether id is a stable identifier.
|
||||
func Valid(id string) bool { return re.MatchString(id) }
|
||||
@@ -0,0 +1,27 @@
|
||||
package stableid
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValid(t *testing.T) {
|
||||
tests := []struct {
|
||||
id string
|
||||
want bool
|
||||
}{
|
||||
{"tdd", true},
|
||||
{"forge.github", true},
|
||||
{"step-type2.v1", true},
|
||||
{"", false},
|
||||
{"Tdd", false},
|
||||
{"2fa", false},
|
||||
{"a..b", false},
|
||||
{"a.", false},
|
||||
{"-a", false},
|
||||
{"a b", false},
|
||||
{"a_b", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := Valid(tt.id); got != tt.want {
|
||||
t.Errorf("Valid(%q) = %v, want %v", tt.id, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -227,10 +227,10 @@ type BindingTaskCreator interface {
|
||||
// BindingDispatcher.RecordDispatch -- so a duplicate returns
|
||||
// ErrAlreadyDispatched and the caller skips the invoke rather than repeating
|
||||
// a non-revocable side effect. DeletePlaybookDispatches deletes one
|
||||
// playbook's ledger rows and is the reclamation primitive for when a playbook
|
||||
// is removed from the configured directory -- a removal path that does not
|
||||
// exist yet and is tracked by archie-core-t2db.30. There is deliberately no
|
||||
// *sql.Tx: any transaction stays server-side inside internal/store.
|
||||
// playbook's ledger rows on explicit request only: a playbook file missing at
|
||||
// boot may be an unmounted directory, and reclaiming on that would let
|
||||
// redelivered events fire again. There is deliberately no *sql.Tx: any
|
||||
// transaction stays server-side inside internal/store.
|
||||
type PlaybookDispatcher interface {
|
||||
RecordPlaybookDispatch(ctx context.Context, playbookID, playbookVersion, eventID, actionID string) error
|
||||
DeletePlaybookDispatches(ctx context.Context, playbookID string) error
|
||||
|
||||
@@ -66,17 +66,17 @@ func LoadKindWorkflowsYAML(path string) (KindWorkflows, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read kind-workflows file %s: %w", path, err)
|
||||
}
|
||||
raw := map[string]string{}
|
||||
if err := yaml.Unmarshal(data, &raw); err != nil {
|
||||
bindings, err := decodeBindings(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse kind-workflows file %s: %w", path, err)
|
||||
}
|
||||
kw := make(KindWorkflows, len(raw))
|
||||
for k, name := range raw {
|
||||
kind := workintake.Kind(k)
|
||||
kw := make(KindWorkflows, len(bindings))
|
||||
for _, b := range bindings {
|
||||
kind := workintake.Kind(b.key)
|
||||
if err := kind.Validate(); err != nil {
|
||||
return nil, fmt.Errorf("kind-workflows file %s: %w", path, err)
|
||||
return nil, fmt.Errorf("kind-workflows file %s:%d: %w", path, b.line, err)
|
||||
}
|
||||
kw[kind] = name
|
||||
kw[kind] = b.value
|
||||
}
|
||||
return kw, nil
|
||||
}
|
||||
@@ -157,22 +157,12 @@ func loadPlaybookFile(path string, kw KindWorkflows, lw LabelWorkflows) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("read playbook file %s: %w", path, err)
|
||||
}
|
||||
raw := map[string]string{}
|
||||
if err := yaml.Unmarshal(data, &raw); err != nil {
|
||||
bindings, err := decodeBindings(data)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse playbook file %s: %w", path, err)
|
||||
}
|
||||
// Sorted, not range order: LoadPlaybookDirs' doc comment promises a
|
||||
// reproducible error when a file declares more than one colliding key,
|
||||
// which a raw map range (Go's iteration order is randomized) cannot
|
||||
// keep -- the same file could report a different "first" collision on
|
||||
// every run otherwise.
|
||||
keys := make([]string, 0, len(raw))
|
||||
for key := range raw {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
if err := bindPlaybookKey(path, key, raw[key], kw, lw); err != nil {
|
||||
for _, b := range bindings {
|
||||
if err := bindPlaybookKey(fmt.Sprintf("%s:%d", path, b.line), b.key, b.value, kw, lw); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -182,18 +172,19 @@ func loadPlaybookFile(path string, kw KindWorkflows, lw LabelWorkflows) error {
|
||||
// bindPlaybookKey classifies one playbook binding key as a closed-vocabulary
|
||||
// kind or an arbitrary label, then merges it into kw/lw -- applying the same
|
||||
// collision and empty-value rules LoadPlaybookDirs' doc comment describes.
|
||||
func bindPlaybookKey(path, key, value string, kw KindWorkflows, lw LabelWorkflows) error {
|
||||
// pos is the key's file:line, which every finding leads with.
|
||||
func bindPlaybookKey(pos, key, value string, kw KindWorkflows, lw LabelWorkflows) error {
|
||||
trimmed := strings.TrimSpace(key)
|
||||
if trimmed == "" {
|
||||
return fmt.Errorf("playbook file %s: empty binding key", path)
|
||||
return fmt.Errorf("playbook file %s: empty binding key", pos)
|
||||
}
|
||||
if value == "" {
|
||||
return fmt.Errorf("playbook file %s: key %q has no workflow name", path, trimmed)
|
||||
return fmt.Errorf("playbook file %s: key %q has no workflow name", pos, trimmed)
|
||||
}
|
||||
if err := workintake.Kind(trimmed).Validate(); err == nil {
|
||||
// It is a kind binding: the closed Kind vocabulary accepts it.
|
||||
if existing, ok := kw[workintake.Kind(trimmed)]; ok {
|
||||
return fmt.Errorf("playbook dirs: kind %q bound in two sources (%q and %q)", trimmed, existing, value)
|
||||
return fmt.Errorf("playbook file %s: kind %q bound in two sources (%q and %q)", pos, trimmed, existing, value)
|
||||
}
|
||||
kw[workintake.Kind(trimmed)] = value
|
||||
return nil
|
||||
@@ -201,10 +192,10 @@ func bindPlaybookKey(path, key, value string, kw KindWorkflows, lw LabelWorkflow
|
||||
// Otherwise it is an arbitrary-label binding. Reject kind-owned labels
|
||||
// and empty labels with the same rules the single-file loader applies.
|
||||
if _, ok := defaultKindWorkflows[workintake.Kind(trimmed)]; ok {
|
||||
return fmt.Errorf("playbook file %s: label %q is already owned by the kind routing layer", path, trimmed)
|
||||
return fmt.Errorf("playbook file %s: label %q is already owned by the kind routing layer", pos, trimmed)
|
||||
}
|
||||
if existing, ok := lw[trimmed]; ok {
|
||||
return fmt.Errorf("playbook dirs: label %q bound in two sources (%q and %q)", trimmed, existing, value)
|
||||
return fmt.Errorf("playbook file %s: label %q bound in two sources (%q and %q)", pos, trimmed, existing, value)
|
||||
}
|
||||
lw[trimmed] = value
|
||||
return nil
|
||||
@@ -357,13 +348,15 @@ func LoadLabelWorkflowsYAML(path string) (LabelWorkflows, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read label-workflows file %s: %w", path, err)
|
||||
}
|
||||
raw := map[string]string{}
|
||||
if err := yaml.Unmarshal(data, &raw); err != nil {
|
||||
bindings, err := decodeBindings(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse label-workflows file %s: %w", path, err)
|
||||
}
|
||||
lw := make(LabelWorkflows, len(raw))
|
||||
for label, name := range raw {
|
||||
trimmed := strings.TrimSpace(label)
|
||||
lw := make(LabelWorkflows, len(bindings))
|
||||
for _, b := range bindings {
|
||||
path := fmt.Sprintf("%s:%d", path, b.line)
|
||||
name := b.value
|
||||
trimmed := strings.TrimSpace(b.key)
|
||||
if trimmed == "" {
|
||||
return nil, fmt.Errorf("label-workflows file %s: empty label is not a valid binding", path)
|
||||
}
|
||||
@@ -380,3 +373,38 @@ func LoadLabelWorkflowsYAML(path string) (LabelWorkflows, error) {
|
||||
}
|
||||
return lw, nil
|
||||
}
|
||||
|
||||
// binding is one key of a routing file with the line it was declared on.
|
||||
type binding struct {
|
||||
key, value string
|
||||
line int
|
||||
}
|
||||
|
||||
// decodeBindings decodes a routing file's top-level string map in document
|
||||
// order, so the first finding is the same on every run and each can name
|
||||
// its key's line. Values decode exactly as they did into map[string]string,
|
||||
// including yaml.v3's duplicate-key refusal.
|
||||
func decodeBindings(data []byte) ([]binding, error) {
|
||||
var doc yaml.Node
|
||||
if err := yaml.Unmarshal(data, &doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(doc.Content) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
root := doc.Content[0]
|
||||
values := map[string]string{}
|
||||
if err := root.Decode(&values); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bindings := make([]binding, 0, len(values))
|
||||
for i := 0; i+1 < len(root.Content); i += 2 {
|
||||
keyNode := root.Content[i]
|
||||
var key string
|
||||
if err := keyNode.Decode(&key); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bindings = append(bindings, binding{key: key, value: values[key], line: keyNode.Line})
|
||||
}
|
||||
return bindings, nil
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package workflow
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A key-level finding names the file and the line of the offending key, so
|
||||
// the lint tool reports it compiler-style instead of leaving the author to
|
||||
// search the file.
|
||||
func TestBindingFindingsCarryTheKeyLine(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
load func(path string) error
|
||||
line string
|
||||
}{
|
||||
{
|
||||
name: "playbook dir, empty workflow name",
|
||||
content: "# routes\nsecurity: security-review\ndocs: \"\"\n",
|
||||
load: func(path string) error {
|
||||
_, _, err := LoadPlaybookDirs([]string{filepath.Dir(path)})
|
||||
return err
|
||||
},
|
||||
line: ":3:",
|
||||
},
|
||||
{
|
||||
name: "playbook dir, kind with no workflow name",
|
||||
content: "security: security-review\n\n\nbug: \"\"\n",
|
||||
load: func(path string) error {
|
||||
_, _, err := LoadPlaybookDirs([]string{filepath.Dir(path)})
|
||||
return err
|
||||
},
|
||||
line: ":4:",
|
||||
},
|
||||
{
|
||||
name: "label file, kind-owned label",
|
||||
content: "security: security-review\nfeature: other\n",
|
||||
load: func(path string) error {
|
||||
_, err := LoadLabelWorkflowsYAML(path)
|
||||
return err
|
||||
},
|
||||
line: ":2:",
|
||||
},
|
||||
{
|
||||
name: "kind file, unknown kind",
|
||||
content: "bug: tdd\n\nnot-a-kind: x\n",
|
||||
load: func(path string) error {
|
||||
_, err := LoadKindWorkflowsYAML(path)
|
||||
return err
|
||||
},
|
||||
line: ":3:",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "routes.yaml")
|
||||
writeFile(t, path, tt.content)
|
||||
err := tt.load(path)
|
||||
if err == nil {
|
||||
t.Fatal("load error = nil, want a finding")
|
||||
}
|
||||
if want := path + tt.line; !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("error = %q, want it to name %q", err, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,11 @@ import (
|
||||
"fmt"
|
||||
"maps"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// stepTypeIdentifier is the shape a provider name and a step type name must
|
||||
// have: a lowercase, dotted identifier, so a contributed step type cannot
|
||||
// smuggle whitespace or case into the vocabulary two processes compare, and so
|
||||
// one step type has exactly one spelling. It reserves nothing: a contribution
|
||||
// that spells a shipped stage's name is well formed, and what refuses it is
|
||||
// Register's claimed-name check, not this rule.
|
||||
var stepTypeIdentifier = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`)
|
||||
"github.com/samcharles93/archie-core/internal/domain/stableid"
|
||||
)
|
||||
|
||||
// StepType is one named workflow step type: the vocabulary word a YAML
|
||||
// workflow names, plus the factory that builds its stage.
|
||||
@@ -88,7 +81,7 @@ func (m *Manager) Register(provider StepTypeProvider) error {
|
||||
return errors.New("workflow step type provider is nil")
|
||||
}
|
||||
name := provider.Name()
|
||||
if !stepTypeIdentifier.MatchString(name) {
|
||||
if !stableid.Valid(name) {
|
||||
return fmt.Errorf("workflow step type provider name %q is not a stable identifier", name)
|
||||
}
|
||||
|
||||
@@ -97,7 +90,7 @@ func (m *Manager) Register(provider StepTypeProvider) error {
|
||||
order := make([]string, 0, len(contributed))
|
||||
for _, stepType := range contributed {
|
||||
switch {
|
||||
case !stepTypeIdentifier.MatchString(stepType.Name):
|
||||
case !stableid.Valid(stepType.Name):
|
||||
return fmt.Errorf("workflow step type provider %q: step type %q is not a stable identifier", name, stepType.Name)
|
||||
case stepType.Factory == nil:
|
||||
return fmt.Errorf("workflow step type provider %q: step type %q has no factory", name, stepType.Name)
|
||||
|
||||
@@ -194,7 +194,7 @@ func (s *Store) InsertBinding(ctx context.Context, b binding.Binding) (string, e
|
||||
return "", err
|
||||
}
|
||||
r.Set("version", 1)
|
||||
r.Set("status", string(binding.StatusDraft))
|
||||
r.Set("status", string(binding.StatusPendingApproval))
|
||||
if err := s.app.Save(r); err != nil {
|
||||
return "", fmt.Errorf("edastore: insert binding: %w", err)
|
||||
}
|
||||
|
||||
@@ -169,6 +169,9 @@ func TestFailedWritesNotifyNothing(t *testing.T) {
|
||||
|
||||
// Seed one binding and one mapping, then clear the seed-time events.
|
||||
seedID := insertBinding(t, s, bindingInput{Name: "seed", Source: "src-seed", Workflow: "triage"})
|
||||
if err := s.ApproveBinding(t.Context(), seedID); err != nil {
|
||||
t.Fatalf("ApproveBinding(seed) error = %v", err)
|
||||
}
|
||||
mid, err := s.InsertMapping(t.Context(), mapping.Mapping{Name: "seed-map"})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertMapping() error = %v", err)
|
||||
@@ -181,7 +184,7 @@ func TestFailedWritesNotifyNothing(t *testing.T) {
|
||||
t.Fatalf("UpdateBinding() error = %v, want ErrBindingNotFound", err)
|
||||
}
|
||||
})
|
||||
t.Run("ApproveBinding refuses draft", func(t *testing.T) {
|
||||
t.Run("ApproveBinding refuses an armed binding", func(t *testing.T) {
|
||||
if err := s.ApproveBinding(t.Context(), seedID); !errors.Is(err, ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding() error = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
|
||||
@@ -104,9 +104,12 @@ func ensureMappings(app core.App) error {
|
||||
|
||||
func ensureBindings(app core.App) error {
|
||||
c, fresh, err := collection(app, CollBindings)
|
||||
if err != nil || !fresh {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !fresh {
|
||||
return promoteDraftBindings(app)
|
||||
}
|
||||
mappings, err := app.FindCollectionByNameOrId(CollMappings)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: bindings need mappings: %w", err)
|
||||
@@ -119,11 +122,10 @@ func ensureBindings(app core.App) error {
|
||||
&core.TextField{Name: "owner"},
|
||||
&core.TextField{Name: "repo"},
|
||||
&core.NumberField{Name: "version"},
|
||||
// status is the domain's three-state lifecycle, not a local
|
||||
// vocabulary: draft -> pending_approval -> armed. Only
|
||||
// ApproveBinding reaches armed, which is the epic's approval gate.
|
||||
// status is the domain's lifecycle, not a local vocabulary:
|
||||
// pending_approval -> armed. Only ApproveBinding reaches armed,
|
||||
// which is the epic's approval gate.
|
||||
&core.SelectField{Name: "status", MaxSelect: 1, Values: []string{
|
||||
string(binding.StatusDraft),
|
||||
string(binding.StatusPendingApproval),
|
||||
string(binding.StatusArmed),
|
||||
}},
|
||||
@@ -135,6 +137,18 @@ func ensureBindings(app core.App) error {
|
||||
return save(app, c)
|
||||
}
|
||||
|
||||
// promoteDraftBindings moves bindings an earlier version stored as "draft",
|
||||
// a state nothing could leave without an unrelated edit, to
|
||||
// pending_approval so they can be approved. It is a no-op once none remain.
|
||||
func promoteDraftBindings(app core.App) error {
|
||||
_, err := app.DB().NewQuery("UPDATE " + CollBindings + " SET status = {:pending} WHERE status = 'draft'").
|
||||
Bind(map[string]any{"pending": string(binding.StatusPendingApproval)}).Execute()
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: promote draft bindings: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureBindingDispatches(app core.App) error {
|
||||
c, fresh, err := collection(app, CollBindingDispatches)
|
||||
if err != nil || !fresh {
|
||||
|
||||
@@ -71,10 +71,10 @@ func TestPlaybookDispatchIsIdempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBindingStartsAsDraft pins the approval gate from the epic's acceptance
|
||||
// criteria: "A binding cannot go live without explicit human approval." A
|
||||
// binding created without a status must not default to anything live.
|
||||
func TestBindingStartsAsDraft(t *testing.T) {
|
||||
// TestBindingStartsPendingApproval pins the approval gate from the epic's
|
||||
// acceptance criteria: "A binding cannot go live without explicit human
|
||||
// approval." A new binding awaits that approval and is not live.
|
||||
func TestBindingStartsPendingApproval(t *testing.T) {
|
||||
st := newStore(t)
|
||||
id, err := st.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
|
||||
@@ -86,8 +86,8 @@ func TestBindingStartsAsDraft(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
if b.Status != binding.StatusDraft {
|
||||
t.Errorf("new binding status = %q, want %q: a binding must not be live before approval", b.Status, binding.StatusDraft)
|
||||
if b.Status != binding.StatusPendingApproval {
|
||||
t.Errorf("new binding status = %q, want %q: a binding must not be live before approval", b.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ var _ = core.Collection{}
|
||||
// The states are the domain's, not this package's: collapsing them (as an
|
||||
// earlier version of this store did) removes the review step while still
|
||||
// looking like an approval gate, which is the worst of both.
|
||||
func TestBindingLifecycleIsThreeStates(t *testing.T) {
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
st := newStore(t)
|
||||
id, err := st.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
|
||||
@@ -138,23 +138,10 @@ func TestBindingLifecycleIsThreeStates(t *testing.T) {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
|
||||
// A draft cannot skip review.
|
||||
if err := st.ApproveBinding(t.Context(), id); !errors.Is(err, storecontract.ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding(draft) error = %v, want ErrBindingTransition: draft must not skip review", err)
|
||||
}
|
||||
|
||||
// Editing sends it to pending_approval.
|
||||
if err := st.UpdateBinding(t.Context(), binding.Binding{
|
||||
ID: id, Name: "n2", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement",
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
// It is created awaiting review.
|
||||
b, err := st.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
if b.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("status after edit = %q, want %q", b.Status, binding.StatusPendingApproval)
|
||||
if err != nil || b.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("status after insert = %q (err %v), want %q", b.Status, err, binding.StatusPendingApproval)
|
||||
}
|
||||
|
||||
// Approval arms it, and only from pending_approval.
|
||||
@@ -192,3 +179,31 @@ func TestOneBindingPerSource(t *testing.T) {
|
||||
t.Errorf("second InsertBinding() error = %v, want ErrBindingOverlap", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A binding stored as "draft" by an earlier version could never be approved.
|
||||
// Opening the store moves it to pending_approval, so it can be.
|
||||
func TestOpenMovesLegacyDraftBindingsToPendingApproval(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
cfg := edastore.Config{DBPath: filepath.Join(dir, "eda.sqlite"), DataDir: filepath.Join(dir, "pb_data")}
|
||||
st, err := edastore.Open(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, err := st.InsertBinding(t.Context(), binding.Binding{Name: "n", Matcher: binding.Matcher{Source: "sentry"}, Workflow: "implement"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := st.App().DB().NewQuery("UPDATE bindings SET status = 'draft' WHERE id = {:id}").Bind(map[string]any{"id": id}).Execute(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = st.Close()
|
||||
|
||||
st, err = edastore.Open(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = st.Close() })
|
||||
if err := st.ApproveBinding(t.Context(), id); err != nil {
|
||||
t.Fatalf("ApproveBinding(legacy draft) = %v, want it approvable after reopen", err)
|
||||
}
|
||||
}
|
||||
@@ -407,9 +407,12 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
if _, err := ec.ListBindings(ctx); err != nil {
|
||||
t.Fatalf("ListBindings: %v", err)
|
||||
}
|
||||
if err := ec.ApproveBinding(ctx, bindingID); err != nil {
|
||||
t.Fatalf("ApproveBinding from pending_approval = %v", err)
|
||||
}
|
||||
err = ec.ApproveBinding(ctx, bindingID)
|
||||
if !errors.Is(err, store.ErrBindingTransition) {
|
||||
t.Fatalf("ApproveBinding from draft = %v, want ErrBindingTransition", err)
|
||||
t.Fatalf("ApproveBinding when armed = %v, want ErrBindingTransition", err)
|
||||
}
|
||||
err = ec.DeleteBinding(ctx, "rabsent00000000")
|
||||
if !errors.Is(err, store.ErrBindingNotFound) {
|
||||
|
||||
@@ -12,14 +12,14 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/stableid"
|
||||
)
|
||||
|
||||
// HostAPIVersion is the capability-host contract version understood by this
|
||||
// archied binary.
|
||||
const HostAPIVersion = "1.0.0"
|
||||
|
||||
var stableIdentifier = regexp.MustCompile(`^[a-z][a-z0-9]*(?:[.-][a-z0-9]+)*$`)
|
||||
|
||||
var semanticVersion = regexp.MustCompile(
|
||||
`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$`,
|
||||
)
|
||||
@@ -48,7 +48,7 @@ type Manifest struct {
|
||||
|
||||
// Validate checks manifest identity, compatibility, declarations, and schema.
|
||||
func (m Manifest) Validate() error {
|
||||
if !stableIdentifier.MatchString(m.ID) {
|
||||
if !stableid.Valid(m.ID) {
|
||||
return fmt.Errorf("plugin manifest id %q is not a stable identifier", m.ID)
|
||||
}
|
||||
if strings.TrimSpace(m.Name) == "" {
|
||||
@@ -167,7 +167,7 @@ func validateIdentifiers(kind string, values []string, required bool) error {
|
||||
}
|
||||
seen := make(map[string]struct{}, len(values))
|
||||
for _, value := range values {
|
||||
if !stableIdentifier.MatchString(value) {
|
||||
if !stableid.Valid(value) {
|
||||
return fmt.Errorf("plugin manifest %s %q is not a stable identifier", kind, value)
|
||||
}
|
||||
if _, exists := seen[value]; exists {
|
||||
|
||||
@@ -71,7 +71,7 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
Secret: req.Secret,
|
||||
Status: binding.Normalize(binding.StatusDraft),
|
||||
Status: binding.StatusPendingApproval,
|
||||
}
|
||||
if err := b.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
|
||||
@@ -80,8 +80,8 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
|
||||
if created.ID == "" {
|
||||
t.Fatalf("created.ID = 0; body = %s", w.Body.String())
|
||||
}
|
||||
if created.Status != binding.StatusDraft {
|
||||
t.Fatalf("created.Status = %q, want %q", created.Status, binding.StatusDraft)
|
||||
if created.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("created.Status = %q, want %q", created.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
if created.Secret != "" {
|
||||
t.Fatalf("created.Secret = %q, want \"\" (response must strip secret)", created.Secret)
|
||||
@@ -272,7 +272,7 @@ func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) {
|
||||
t.Fatalf("updated.MappingID = %q, want %q", updated.MappingID, mappingID)
|
||||
}
|
||||
// Status MUST not regress from a state the caller never asked for.
|
||||
if updated.Status != binding.StatusDraft && updated.Status != binding.StatusPendingApproval {
|
||||
if updated.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("updated.Status = %q, want draft or pending_approval", updated.Status)
|
||||
}
|
||||
}
|
||||
@@ -306,16 +306,18 @@ func TestHandleBindingUpdateWithEmptySecretPreservesExisting(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveFromDraftRejected(t *testing.T) {
|
||||
func TestHandleBindingApproveArmedRejected(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
if w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil); w.Code != http.StatusOK {
|
||||
t.Fatalf("first approve status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
// draft is NOT a valid source state for approve; the binding must
|
||||
// first land in pending_approval (via PATCH). Approve from draft
|
||||
// returns ErrBindingTransition -> 409.
|
||||
// An armed binding is not a valid source state for approve:
|
||||
// ErrBindingTransition -> 409.
|
||||
w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusConflict, w.Body.String())
|
||||
@@ -323,27 +325,15 @@ func TestHandleBindingApproveFromDraftRejected(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveHappyPath(t *testing.T) {
|
||||
// Per docs/prds/webhook-intake-security.md point 2, ANY edit drops status
|
||||
// to pending_approval. The happy path: POST creates draft, PATCH moves
|
||||
// it to pending_approval, POST /approve moves it to armed. This test
|
||||
// pins the rule end-to-end through the webui handlers.
|
||||
// A created binding awaits approval, and approving it arms it: the
|
||||
// operator who just created one can approve it without an edit.
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
if created.Status != binding.StatusDraft {
|
||||
t.Fatalf("created status = %q, want %q", created.Status, binding.StatusDraft)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, validBindingRequest("renamed", "sentry", mappingID))
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("patch status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var patched binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &patched)
|
||||
if patched.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("patched status = %q, want %q", patched.Status, binding.StatusPendingApproval)
|
||||
if created.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("created status = %q, want %q", created.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodPost, "/api/bindings/"+created.ID+"/approve", nil)
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
//
|
||||
// This handler is transport only: parsing the log format belongs to the
|
||||
// logging package, which owns it. Live output reaches the dashboard over the
|
||||
// existing /events stream; this endpoint exists so the view has history from
|
||||
// existing /api/stream stream; this endpoint exists so the view has history from
|
||||
// before the browser connected, which is the whole reason file logging landed
|
||||
// first.
|
||||
func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -85,7 +85,7 @@ func TestEventPumpKeepsItsWatermarkAcrossAStoreFailure(t *testing.T) {
|
||||
}
|
||||
|
||||
// The bead's headline claim: an event written to the State Store by another
|
||||
// process reaches a browser hanging on /events, with no in-process bus.
|
||||
// process reaches a browser hanging on /api/stream, with no in-process bus.
|
||||
func TestEventPumpReachesALiveSSEClient(t *testing.T) {
|
||||
srv := newRemoteTestServer(t)
|
||||
pump := newTestPump(t, srv)
|
||||
@@ -123,7 +123,7 @@ func TestEventPumpReachesALiveSSEClient(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// newSSETestServer serves the dashboard's real route set, so /events goes
|
||||
// newSSETestServer serves the dashboard's real route set, so /api/stream goes
|
||||
// through requireToken and the mux exactly as a browser reaches it.
|
||||
func newSSETestServer(t *testing.T, srv *Server) *httptest.Server {
|
||||
t.Helper()
|
||||
@@ -132,25 +132,25 @@ func newSSETestServer(t *testing.T, srv *Server) *httptest.Server {
|
||||
return ts
|
||||
}
|
||||
|
||||
// openSSEStream connects to /events and relays each response line on a
|
||||
// openSSEStream connects to /api/stream and relays each response line on a
|
||||
// channel. The request context ends the handler, which is what lets the
|
||||
// test server close.
|
||||
func openSSEStream(t *testing.T, ctx context.Context, ts *httptest.Server) <-chan string {
|
||||
t.Helper()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/events", nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("sse request: %v", err)
|
||||
}
|
||||
resp, err := ts.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET /events: %v", err)
|
||||
t.Fatalf("GET /api/stream: %v", err)
|
||||
}
|
||||
// Closed at cleanup rather than by the reader goroutine: the body is the
|
||||
// live stream and must outlive this function, but it still has exactly
|
||||
// one owner and one close.
|
||||
t.Cleanup(func() { _ = resp.Body.Close() })
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("GET /events = %d, want 200", resp.StatusCode)
|
||||
t.Fatalf("GET /api/stream = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
lines := make(chan string, 64)
|
||||
go func() {
|
||||
@@ -243,3 +243,28 @@ func TestPumpPriming(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A dashboard route reloaded in the browser must get the app shell. The live
|
||||
// stream once sat at /events, the same path as the Events page, so a reload
|
||||
// there rendered the raw event stream instead of the page.
|
||||
func TestDashboardRoutesServeTheAppShell(t *testing.T) {
|
||||
ts := newSSETestServer(t, &Server{})
|
||||
for _, path := range []string{"/events", "/events?tab=inspector"} {
|
||||
t.Run(path, func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("GET %s: %v", path, err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if ct := resp.Header.Get("Content-Type"); strings.HasPrefix(ct, "text/event-stream") {
|
||||
t.Fatalf("GET %s served the event stream, want the app shell", path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -310,7 +310,7 @@ func (s *Server) Handler() http.Handler {
|
||||
s.registerChatRoutes(mux)
|
||||
|
||||
mux.HandleFunc("GET /health/detailed", s.handleHealthDetailed)
|
||||
mux.HandleFunc("GET /events", s.handleSSE)
|
||||
mux.HandleFunc("GET /api/stream", s.handleSSE)
|
||||
mux.Handle("GET /", s.assets())
|
||||
|
||||
top := http.NewServeMux()
|
||||
|
||||
@@ -252,7 +252,7 @@ func TestSSESinceDegradesUnparseableCursorToBeginning(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/events", nil)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/stream", nil)
|
||||
if tt.since != "" {
|
||||
q := req.URL.Query()
|
||||
q.Set("since", tt.since)
|
||||
|
||||
@@ -316,7 +316,7 @@ func TestHandleSSEEventsSinceError(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/events?since=0", nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream?since=0", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -362,7 +362,7 @@ func TestHandleSSEUsesLastEventIDForCatchUp(t *testing.T) {
|
||||
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/events", nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -407,7 +407,7 @@ func TestHandleSSEBacklogAndLive(t *testing.T) {
|
||||
|
||||
// The request carries t.Context() so the SSE stream is torn down when
|
||||
// the test ends rather than leaking the connection and its goroutine.
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/events", nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -454,7 +454,7 @@ func TestHandleSSEFiltersTurnCompletedFromLiveBroadcast(t *testing.T) {
|
||||
ts := httptest.NewServer(srv.Handler())
|
||||
t.Cleanup(ts.Close)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/events", nil)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ts.URL+"/api/stream", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24remLine truncated
|
||||
.identities-page[data-v-8ab739de]{max-width:960px}.identity-create[data-v-8ab739de]{gap:.75rem;margin:1.5rem 0;display:flex}.identity-create input[data-v-8ab739de]{flex:1}.identity-create input[data-v-8ab739de],.identity-create select[data-v-8ab739de],.identity-create button[data-v-8ab739de],.actions button[data-v-8ab739de]{border:1px solid var(--border);background:var(--surface);color:inherit;border-radius:.5rem;padding:.6rem .8rem}.identity-list[data-v-8ab739de]{border-top:1px solid var(--border)}.identity-row[data-v-8ab739de]{border-bottom:1px solid var(--border);justify-content:space-between;align-items:center;gap:1rem;padding:1rem 0;display:flex}.identity-row span[data-v-8ab739de]{color:var(--muted-foreground);text-transform:capitalize;margin-top:.2rem;font-size:.85rem;display:block}.actions[data-v-8ab739de]{gap:.5rem;display:flex}.actions .danger[data-v-8ab739de],.error[data-v-8ab739de]{color:var(--destructive)}@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){:root,:host{--shimmer-angle:20deg}*,:before,:after,::backdrop{--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-space-x-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-outline-style:solid;--tw-blur:initial;--tw-brightness:initial;--tw-contrast:initial;--tw-grayscale:initial;--tw-hue-rotate:initial;--tw-invert:initial;--tw-opacity:initial;--tw-saturate:initial;--tw-sepia:initial;--tw-drop-shadow:initial;--tw-drop-shadow-color:initial;--tw-drop-shadow-alpha:100%;--tw-drop-shadow-size:initial;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-ease:initial;--tw-content:"";--tw-scrollbar-thumb:#0000;--tw-scrollbar-track:#0000;--tw-scale-x:1;--tw-scale-y:1;--tw-scale-z:1;--tw-animation-delay:0s;--tw-animation-direction:normal;--tw-animation-duration:initial;--tw-animation-fill-mode:none;--tw-animation-iteration-count:1;--tw-enter-blur:0;--tw-enter-opacity:1;--tw-enter-rotate:0;--tw-enter-scale:1;--tw-enter-translate-x:0;--tw-enter-translate-y:0;--tw-exit-blur:0;--tw-exit-opacity:1;--tw-exit-rotate:0;--tw-exit-scale:1;--tw-exit-translate-x:0;--tw-exit-translate-y:0;--scroll-fade-t:0;--scroll-fade-b:0;--scroll-fade-s:0;--scroll-fade-e:0;--scroll-fade-mask:initial;--shimmer-image:initial;--shimmer-text-fill:initial}}}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+460-52F,U+1C80-1C8A,U+20B4,U+2DE0-2DFF,U+A640-A69F,U+FE2E-FE2F}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-cyrillic-wght-normal.woff2)format("woff2-variations");unicode-range:U+301,U+400-45F,U+490-491,U+4B0-4B1,U+2116}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-vietnamese-wght-normal.woff2)format("woff2-variations");unicode-range:U+102-103,U+110-111,U+128-129,U+168-169,U+1A0-1A1,U+1AF-1B0,U+300-301,U+303-304,U+308-309,U+323,U+329,U+1EA0-1EF9,U+20AB}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-ext-wght-normal.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Geist Variable;font-style:normal;font-display:swap;font-weight:100 900;src:url(/assets/geist-latin-wght-normal.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@layer theme{:root,:host{--font-sans:"Geist Variable", sans-serif;--color-black:#000;--spacing:.25rem;--container-xs:20rem;--container-sm:24remLine truncated
|
||||
Vendored
+3
-3
@@ -2,7 +2,7 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
|
||||
`&&(e.tagName===`PRE`||e.tagName===`TEXTAREA`)&&(n=n.slice(1));let{textContent:r}=e;r!==n&&r!==n.replace(/\r\n|\r/g,`
|
||||
`)&&(ki(e,0)||yi(),e.textContent=t.children)}if(d){if(_||b||!o||f&48){let t=e.tagName.includes(`-`),i=e.namespaceURI.includes(`svg`)?`svg`:e.namespaceURI.includes(`MathML`)?`mathml`:void 0;for(let a in d)if(_&&(a.endsWith(`value`)||a===`indeterminate`)||c(a)&&!re(a)||a[0]===`.`||t&&!re(a)||u&&u.includes(a)){if(Ei(e,a,d[a]))continue;r(e,a,null,d[a],i,n)}}else if(d.onClick)r(e,`onClick`,null,d.onClick,void 0,n);else if(f&4&&cn(d.style))for(let e in d.style)d.style[e]}let x;(x=d&&d.onVnodeBeforeMount)&&Ns(x,n,t),h&&wr(t,null,n,`beforeMount`),((x=d&&d.onVnodeMounted)||h||l)&&ls(()=>{x&&Ns(x,n,t),l&&g.enter(e),h&&wr(t,null,n,`mounted`)},i)}return e.nextSibling},m=(e,t,r,o,s,c,u)=>{u||=!!t.dynamicChildren;let d=t.children,p=d.length,m=!1;for(let t=0;t<p;t++){let h=u?d[t]:d[t]=As(d[t]),g=h.type===fs;e?(g&&!u&&t+1<p&&As(d[t+1]).type===fs&&(l(i(e.data.slice(h.children.length)),r,a(e)),e.data=h.children),e=f(e,h,o,s,c,u)):g&&!h.children?l(h.el=i(``),r):(m||(m=!0,ki(r,1)||yi()),n(null,h,r,null,o,s,Si(r),c))}return e},h=(e,t,n,r,i,s)=>{let{slotScopeIds:c}=t;c&&(i=i?i.concat(c):c);let d=o(e),f=m(a(e),t,d,n,r,i,s);return f&&Ci(f)&&f.data===`]`?a(t.anchor=f):(yi(),l(t.anchor=u(`]`),d,f),f)},g=(e,t,r,i,c,l)=>{if(ji(e,t)||yi(),t.el=null,l){let t=_(e);for(;;){let n=a(e);if(n&&n!==t)s(n);else break}}let u=a(e),d=o(e);return s(e),n(null,t,d,u,r,i,Si(d),c),r&&(r.vnode.el=t.el,So(r,t.el)),u},_=(e,t=`[`,n=`]`)=>{let r=0;for(;e;)if(e=a(e),e&&Ci(e)&&(e.data===t&&r++,e.data===n)){if(r===0)return a(e);r--}return e},v=(e,t,n)=>{let r=t.parentNode;r&&r.replaceChild(e,t);let i=n;for(;i;)i.vnode.el===t&&(i.vnode.el=i.subTree.el=e),i=i.parent},y=e=>e.nodeType===1&&e.tagName===`TEMPLATE`;return[d,f]}var Ti=new Set([`src`,`srcset`,`href`,`poster`]);function Ei(e,t,n){return Ti.has(t)?e.getAttribute(t)===(n==null?null:`${n}`):!1}var Di=`data-allow-mismatch`,Oi={0:`text`,1:`children`,2:`class`,3:`style`,4:`attribute`};function ki(e,t){if(t===0||t===1)for(;e&&!e.hasAttribute(Di);)e=e.parentElement;return Ai(e&&e.getAttribute(Di),t)}function Ai(e,t){if(e==null)return!1;if(e===``)return!0;{let n=e.split(`,`);return t===0&&n.includes(`children`)?!0:n.includes(Oi[t])}}function ji(e,t){return ki(e.parentElement,1)||Mi(e)||Ni(t)}function Mi(e){return e.nodeType===1&&Ai(e.getAttribute(Di),1)}function Ni({props:e}){let t=e&&e[Di];return typeof t==`string`&&Ai(t,1)}var Pi=ge().requestIdleCallback||(e=>setTimeout(e,1)),Fi=ge().cancelIdleCallback||(e=>clearTimeout(e)),Ii=(e=1e4)=>t=>{let n=Pi(t,{timeout:e});return()=>Fi(n)};function Li(e){let{top:t,left:n,bottom:r,right:i}=e.getBoundingClientRect(),{innerHeight:a,innerWidth:o}=window;return(t>0&&t<a||r>0&&r<a)&&(n>0&&n<o||i>0&&i<o)}var Ri=e=>(t,n)=>{let r=new IntersectionObserver(e=>{for(let n of e)if(n.isIntersecting){r.disconnect(),t();break}},e);return n(e=>{if(e instanceof Element){if(Li(e))return t(),r.disconnect(),!1;r.observe(e)}}),()=>r.disconnect()},zi=e=>t=>{if(e){let n=matchMedia(e);if(n.matches)t();else return n.addEventListener(`change`,t,{once:!0}),()=>n.removeEventListener(`change`,t)}},Bi=(e=[])=>(t,n)=>{b(e)&&(e=[e]);let r=!1,i=e=>{r||(r=!0,a(),t(),e.target.dispatchEvent(new e.constructor(e.type,e)))},a=()=>{n(t=>{for(let n of e)t.removeEventListener(n,i)})};return n(t=>{for(let n of e)t.addEventListener(n,i,{once:!0})}),a};function Vi(e,t){if(Ci(e)&&e.data===`[`){let n=1,r=e.nextSibling;for(;r;){if(r.nodeType===1){if(t(r)===!1)break}else if(Ci(r)){if(r.data===`]`){if(--n===0)break}else r.data===`[`&&n++}r=r.nextSibling}}else t(e)}var Hi=e=>!!e.type.__asyncLoader;function Ui(e){y(e)&&(e={loader:e});let{loader:t,loadingComponent:n,errorComponent:r,delay:i=200,hydrate:a,timeout:o,suspensible:s=!0,onError:c}=e,l=null,u,d=0,f=()=>(d++,l=null,p()),p=()=>{let e;return l||(e=l=t().catch(e=>{if(e=e instanceof Error?e:Error(String(e)),c)return new Promise((t,n)=>{c(e,()=>t(f()),()=>n(e),d+1)});throw e}).then(t=>e!==l&&l?l:(t&&(t.__esModule||t[Symbol.toStringTag]===`Module`)&&(t=t.default),u=t,t)))};return N({name:`AsyncComponentWrapper`,__asyncLoader:p,__asyncHydrate(e,t,n){let r=e.isConnected,i=!1;(t.bu||=[]).push(()=>i=!0);let o=()=>{i||!e.parentNode||r&&!e.isConnected||n()},s=a?()=>{let n=a(o,t=>Vi(e,t));n&&(t.bum||=[]).push(n)}:o;u?s():p().then(()=>!t.isUnmounted&&s())},get __asyncResolved(){return u},setup(){let e=Ls;if(fi(e),u)return()=>Wi(u,e);let t=t=>{l=null,Xn(t,e,13,!r)};if(s&&e.suspense||Ws)return p().then(t=>()=>Wi(t,e)).catch(e=>(t(e),()=>r?V(r,{error:e}):null));let a=k(!1),c=k(),d=k(!!i),f,m;return sa(()=>{f!=null&&clearTimeout(f),m!=null&&clearTimeout(m)}),i&&(m=setTimeout(()=>{e.isUnmounted||(d.value=!1)},i)),o!=null&&(f=setTimeout(()=>{if(!e.isUnmounted&&!a.value&&!c.value){let e=Error(`Async component timed out after ${o}ms.`);t(e),c.value=e}},o)),p().then(()=>{e.isUnmounted||(a.value=!0,e.parent&&Gi(e.parent.vnode)&&e.parent.update())}).catch(n=>{if(e.isUnmounted){l=null;return}t(n),c.value=n}),()=>{if(a.value&&u)return Wi(u,e);if(c.value&&r)return V(r,{error:c.value});if(n&&
Line truncated
|
||||
`))),e[Gl]=Hl(i);let a=r||i.props&&i.props.type===`number`;ll(e,t?`change`:`input`,t=>{t.target.composing||e[Gl](ql(e.value,n,a))}),(n||a)&&ll(e,`change`,()=>{e.value=ql(e.value,n,a)}),t||(ll(e,`compositionstart`,Ul),ll(e,`compositionend`,Wl),ll(e,`change`,Wl))},mounted(e,{value:t,modifiers:{trim:n,number:r}}){let i=t??``,a=e[Kl];delete e[Kl],a!==void 0&&(e.type===`text`||e.type===`textarea`)&&e.value!==a?e[Gl](ql(e.value,n,r)):e.value=i},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:i,number:a}},o){if(e[Gl]=Hl(o),e.composing)return;let s=(a||e.type===`number`)&&!/^0\d/.test(e.value)?pe(e.value):e.value,c=t??``;if(s===c)return;let l=e.getRootNode();(l instanceof Document||l instanceof ShadowRoot)&&l.activeElement===e&&e.type!==`range`&&(r&&t===n||i&&e.value.trim()===c)||(e.value=c)}},Yl={deep:!0,created(e,t,n){e[Gl]=Hl(n),ll(e,`change`,()=>{let t=e._modelValue,n=tu(e),r=e.checked,i=e[Gl];if(m(t)){let e=Me(t,n),a=e!==-1;if(r&&!a)i(t.concat(n));else if(!r&&a){let n=[...t];n.splice(e,1),i(n)}}else if(g(t)){let e=new Set(t);r?e.add(n):e.delete(n),i(e)}else i(nu(e,r))})},mounted:Xl,beforeUpdate(e,t,n){e[Gl]=Hl(n),Xl(e,t,n)}};function Xl(e,{value:t,oldValue:n},r){e._modelValue=t;let i;if(m(t))i=Me(t,r.props.value)>-1;else if(g(t))i=t.has(r.props.value);else{if(t===n)return;i=je(t,nu(e,!0))}e.checked!==i&&(e.checked=i)}var Zl={created(e,{value:t},n){e.checked=je(t,n.props.value),e[Gl]=Hl(n),ll(e,`change`,()=>{e[Gl](tu(e))})},beforeUpdate(e,{value:t,oldValue:n},r){e[Gl]=Hl(r),t!==n&&(e.checked=je(t,r.props.value))}},Ql={deep:!0,created(e,{value:t,modifiers:{number:n}},r){e._modelValue=t,ll(e,`change`,()=>{let t=Array.prototype.filter.call(e.options,e=>e.selected).map(e=>n?pe(tu(e)):tu(e)),r=e.multiple,i=r?g(e._modelValue)?new Set(t):t:t[0],a=e._pendingValue=[r,r?m(i)?t.slice():t:i];try{e[Gl](i)}finally{ar(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[Gl]=Hl(r)},mounted(e,{value:t}){eu(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[Gl]=Hl(n)},updated(e,{value:t}){let n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!$l(t,n[1],n[0]))&&eu(e,t)}};function $l(e,t,n){if(!n||m(e))return je(e,t);if(g(e)){if(e.size!==t.length)return!1;for(let n of t)if(!e.has(n))return!1;return!0}return!1}function eu(e,t){let n=e.multiple,r=m(t);if(!n||r||g(t)){for(let i=0,a=e.options.length;i<a;i++){let a=e.options[i],o=tu(a);if(n){if(r){let e=typeof o;a.selected=e===`string`||e===`number`?t.some(e=>String(e)===String(o)):Me(t,o)>-1}else a.selected=t.has(o)}else if(je(tu(a),t)){e.selectedIndex!==i&&(e.selectedIndex=i);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function tu(e){return`_value`in e?e._value:e.value}function nu(e,t){let n=t?`_trueValue`:`_falseValue`;return n in e?e[n]:t}var ru={created(e,t,n){au(e,t,n,null,`created`)},mounted(e,t,n){au(e,t,n,null,`mounted`)},beforeUpdate(e,t,n,r){au(e,t,n,r,`beforeUpdate`)},updated(e,t,n,r){au(e,t,n,r,`updated`)}};function iu(e,t){switch(e){case`SELECT`:return Ql;case`TEXTAREA`:return Jl;default:switch(t){case`checkbox`:return Yl;case`radio`:return Zl;default:return Jl}}}function au(e,t,n,r,i){let a=iu(e.tagName,n.props&&n.props.type)[i];a&&a(e,t,n,r)}function ou(){Jl.getSSRProps=({value:e})=>({value:e}),Zl.getSSRProps=({value:e},t)=>{if(t.props&&je(t.props.value,e))return{checked:!0}},Yl.getSSRProps=({value:e},t)=>{if(m(e)){if(t.props&&Me(e,t.props.value)>-1)return{checked:!0}}else if(g(e)){if(t.props&&e.has(t.props.value))return{checked:!0}}else if(e)return{checked:!0}},ru.getSSRProps=(e,t)=>{if(typeof t.type!=`string`)return;let n=iu(t.type.toUpperCase(),t.props&&t.props.type);if(n.getSSRProps)return n.getSSRProps(e,t)}}var su=[`ctrl`,`shift`,`alt`,`meta`],cu={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>`button`in e&&e.button!==0,middle:e=>`button`in e&&e.button!==1,right:e=>`button`in e&&e.button!==2,exact:(e,t)=>su.some(n=>e[`${n}Key`]&&!t.includes(n))},lu=(e,t)=>{if(!e)return e;let n=e._withMods||={},r=t.join(`.`);return n[r]||(n[r]=((n,...r)=>{for(let e=0;e<t.length;e++){let r=cu[t[e]];if(r&&r(n,t))return}return e(n,...r)}))},uu={esc:`escape`,space:` `,up:`arrow-up`,left:`arrow-left`,right:`arrow-right`,down:`arrow-down`,delete:`backspace`},du=(e,t)=>{let n=e._withKeys||={},r=t.join(`.`);return n[r]||(n[r]=(n=>{if(!(`key`in n))return;let r=ce(n.key);if(t.some(e=>e===r||uu[e]===r))return e(n)}))},fu=u({patchProp:xl},xc),pu,mu=!1;function hu(){return pu||=Ho(fu)}function gu(){return pu=mu?pu:Uo(fu),mu=!0,pu}var _u=((...e)=>{hu().render(...e)}),vu=((...e)=>{gu().hydrate(...e)}),yu=((...e)=>{let t=hu().createApp(...e),{mount:n}=t;return t.mount=e=>{let r=Su(e);if(!r)return;let i=t._component;!y(i)&&!i.render&&!i.template&&(i.template=r.innerHTML),r.nodeType===1&&(r.textContent=``);let a=n(r,!1,xu(r));return r instanceof Element&&(r.removeAttribute(`v-cloak`),r.setAttribute(`data-v-app`,``)),a},t}),bu=((
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Op;function kp(e){Op=e}var Ap=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function jp(e){let t=e instanceof Ap?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Mp(e,t){let n=await fetch(e,t);if(Op?.(n.status===401),!n.ok)throw new Ap(await Dp(n),n.status);return n}async function Np(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Tp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Mp(e,s);return a?await c.json():void 0}var Y={health:()=>Np(`/health/detailed`),summary:()=>Np(`/api/summary`),tasks:()=>Np(`/api/tasks`),taskMeta:()=>Np(`/api/task-meta`),task:e=>Np(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Np(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/changes`+Ep(t)),taskDebug:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/debug`+Ep(t)),taskAction:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Np(`/api/setup`),capabilities:()=>Np(`/api/capabilities`),workflows:()=>Np(`/api/workflows`),workRequest:e=>Np(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Np(`/api/skills`),channels:()=>Np(`/api/channels`),curators:()=>Np(`/api/curators`),channelReload:e=>Np(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Np(`/api/config`),logs:e=>Np(`/api/logs`+Ep(e)),taskLogs:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/logs`+Ep(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),captures:e=>Np(`/api/captures`+Ep({limit:e})),mappings:()=>Np(`/api/mappings`),mappingCreate:e=>Np(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Np(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Np(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Np(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Np(`/api/bindings`),bindingCreate:e=>Np(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Np(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Np(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Np(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Np(`/api/chat/sessions`),chatMessages:e=>Np(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Np(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Np(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Np(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:wp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Np(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Np(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Np(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Np(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Mp(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Pp(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 Fp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Cp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Ip=`archie.web.chat.channel`;function Lp(){let e=localStorage.getItem(Ip);return e||(e=wp(),localStorage.setItem(Ip,e)),e}var Rp=/(?:^|\s)\/([^\s]*)$/,zp=/(?:^|\s)\/[^\s]*$/,Bp=8;function Vp(e,t,n){let r=t.slice(0,n).match(Rp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Bp)}function Hp(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(zp),o=a<0?r.length:a+ +(r[a]===` `);return{text:`${r.slice(0,o)}${n} ${i}`,cursor:o+n.length+1}}function Up(e,t){let n=t.trim();return e.some(e=>e.command===n)}function Wp(e){return{text:e,sourceID:wp()}}function Gp(e){return{...e}}function Kp(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.trim();return{text:r,turn:n?Gp(e.turn):Wp(r),isRetry:n}}var qp=`chat-panel`,Jp=12e4,Yp=k([]),Xp=k(``),Zp=k([]),Qp=k(``),$p=k(`Ready`),em=k(!1),tm=k(null),nm=k({}),rm=k(``),im=k
Line truncated
|
||||
`)[0].slice(0,200)}catch{}return`${e.status} ${e.statusText}`}var Op;function kp(e){Op=e}var Ap=class extends Error{status;constructor(e,t){super(e),this.name=`ApiError`,this.status=t}};function jp(e){let t=e instanceof Ap?e.status:void 0,n=e instanceof Error&&e.message?e.message:`Action failed`;return t===401?{kind:`session-expired`,message:n}:t!==void 0&&t>=400&&t<500?{kind:`refused`,message:n}:{kind:`broken`,message:n}}async function Mp(e,t){let n=await fetch(e,t);if(Op?.(n.status===401),!n.ok)throw new Ap(await Dp(n),n.status);return n}async function Np(e,t={}){let{method:n=`GET`,body:r,timeoutMs:i=Tp,parse:a=!0}=t,o={Accept:`application/json`},s={method:n,headers:o,signal:AbortSignal.timeout(i)};n!==`GET`&&(o[`Content-Type`]=`application/json`,o[`X-Archie-CSRF`]=`1`),r!==void 0&&(s.body=JSON.stringify(r));let c=await Mp(e,s);return a?await c.json():void 0}var Y={health:()=>Np(`/health/detailed`),summary:()=>Np(`/api/summary`),tasks:()=>Np(`/api/tasks`),taskMeta:()=>Np(`/api/task-meta`),task:e=>Np(`/api/tasks/${encodeURIComponent(e)}`),taskAttempts:e=>Np(`/api/tasks/${encodeURIComponent(e)}/attempts`),taskChanges:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/changes`+Ep(t)),taskDebug:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/debug`+Ep(t)),taskAction:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/action`,{method:`POST`,body:{action:t}}),setup:()=>Np(`/api/setup`),capabilities:()=>Np(`/api/capabilities`),workflows:()=>Np(`/api/workflows`),workRequest:e=>Np(`/api/work-requests`,{method:`POST`,body:e}),skills:()=>Np(`/api/skills`),channels:()=>Np(`/api/channels`),curators:()=>Np(`/api/curators`),channelReload:e=>Np(`/api/channels/${encodeURIComponent(e)}/reload`,{method:`POST`,body:{}}),config:()=>Np(`/api/config`),logs:e=>Np(`/api/logs`+Ep(e)),taskLogs:(e,t)=>Np(`/api/tasks/${encodeURIComponent(e)}/logs`+Ep(t)),taskLogDownloadURL:(e,t)=>`/api/tasks/${encodeURIComponent(e)}/logs/download`+(t==null?``:`?attempt=${t}`),version:()=>Np(`/api/version`),updateSnapshot:()=>Np(`/api/chat/update`),updateInstall:e=>Np(`/api/chat/update/install`,{method:`POST`,body:{snapshot:e},timeoutMs:9e5}),captures:e=>Np(`/api/captures`+Ep({limit:e})),mappings:()=>Np(`/api/mappings`),mappingCreate:e=>Np(`/api/mappings`,{method:`POST`,body:e}),mappingUpdate:(e,t)=>Np(`/api/mappings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),mappingDelete:e=>Np(`/api/mappings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),mappingPreview:(e,t)=>Np(`/api/mappings/preview`,{method:`POST`,body:{capture_id:e,fields:t}}),bindings:()=>Np(`/api/bindings`),bindingCreate:e=>Np(`/api/bindings`,{method:`POST`,body:e}),bindingUpdate:(e,t)=>Np(`/api/bindings/${encodeURIComponent(e)}`,{method:`PATCH`,body:t}),bindingDelete:e=>Np(`/api/bindings/${encodeURIComponent(e)}`,{method:`DELETE`,parse:!1}),bindingApprove:e=>Np(`/api/bindings/${encodeURIComponent(e)}/approve`,{method:`POST`}),chatSessions:()=>Np(`/api/chat/sessions`),chatMessages:e=>Np(`/api/chat/sessions/${encodeURIComponent(e)}/messages`),chatTurns:e=>Np(`/api/chat/sessions/${encodeURIComponent(e)}/turns`),chatCancel:e=>Np(`/api/chat/cancel`,{method:`POST`,body:{session_id:e}}),chatMessage:(e,t)=>Np(`/api/chat/message`,{method:`POST`,body:{channel_id:e,source_id:wp(),text:t,page:location.pathname+location.search||`/`}}),chatPersona:(e,t)=>Np(`/api/chat/persona`,{method:`POST`,body:{session_id:e,name:t}}),chatDangerous:()=>Np(`/api/chat/dangerous`),chatDangerousRequest:(e,t)=>Np(`/api/chat/dangerous/${encodeURIComponent(e)}`,{method:`POST`,body:{spec:t}}),chatDangerousDecision:(e,t)=>Np(`/api/chat/dangerous/${encodeURIComponent(e)}/decision`,{method:`POST`,body:{decision:t}}),chatStream:(e,t={})=>Mp(`/api/chat/stream`,{method:`POST`,headers:{Accept:`text/event-stream`,"Content-Type":`application/json`,"X-Archie-CSRF":`1`},body:JSON.stringify(e),signal:t.signal})};function Pp(e,t){let n=new EventSource(`/api/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(`reconnecting`),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}function Fp(e,t){let n=new EventSource(`/api/logs/stream`);return n.onopen=()=>t?.(`live`),n.onerror=()=>t?.(Cp(n.readyState)),n.onmessage=t=>{try{e(JSON.parse(t.data))}catch{}},()=>n.close()}var Ip=`archie.web.chat.channel`;function Lp(){let e=localStorage.getItem(Ip);return e||(e=wp(),localStorage.setItem(Ip,e)),e}var Rp=/(?:^|\s)\/([^\s]*)$/,zp=/(?:^|\s)\/[^\s]*$/,Bp=8;function Vp(e,t,n){let r=t.slice(0,n).match(Rp);if(!r)return[];let i=r[1].toLowerCase();return e.filter(e=>`${e.command} ${e.description??``}`.toLowerCase().includes(i)).slice(0,Bp)}function Hp(e,t,n){let r=e.slice(0,t),i=e.slice(t),a=r.search(zp),o=a<0?r.length:a+ +(r[a]===` `);return{text:`${r.slice(0,o)}${n} ${i}`,cursor:o+n.length+1}}function Up(e,t){let n=t.trim();return e.some(e=>e.command===n)}function Wp(e){return{text:e,sourceID:wp()}}function Gp(e){return{...e}}function Kp(e,t){let n=!!(e&&typeof e==`object`&&e.turn&&typeof e.turn.text==`string`),r=n?e.turn.text:t.tri
Line truncated
|
||||
|
||||
`);u=r.pop()||``;for(let e of r){let t=e.split(`
|
||||
`).find(e=>e.startsWith(`data: `));if(!t)continue;let n=JSON.parse(t.slice(6));if(n.session_id&&(Xp.value=n.session_id),n.type===`delta`&&(o+=n.text,tm.value=tm.value?{...tm.value,text:o}:null),(n.type===`tool`||n.type===`navigate`)&&(a=[...a,n],tm.value=tm.value?{...tm.value,tools:a}:null),n.type===`done`&&(s=!0,o||=n.text||``),n.type===`error`)throw Error(n.text)}if(t)break}if(!s)throw Error(`chat stream ended before completion`);Zp.value=[...Zp.value,{from:`assistant`,text:o,tool_calls:a}],tm.value=null,$p.value=`Ready`,await gm()}catch(e){let t=e;t.name===`AbortError`&&!c?(tm.value={text:`Turn stopped.`,tools:a,isError:!1,turn:r,isRetry:i},$p.value=`Stopped`):(tm.value={text:`Unable to complete that turn: ${t.message||t}`,tools:a,isError:!0,turn:r?Gp(r):void 0,isRetry:i},$p.value=`Error — retry available`)}finally{clearTimeout(l),mm=null,em.value=!1}}function km(){$p.value=`Stopping…`,Xp.value&&Y.chatCancel(Xp.value).catch(()=>{}),hm()}function Am(){ra(()=>{gm().catch(e=>{$p.value=e.message||`Chat unavailable`})}),sa(()=>{hm()})}var jm=[`aria-label`,`title`,`aria-expanded`,`aria-controls`],Mm=N({__name:`ChatFab`,props:{open:{type:Boolean}},emits:[`toggle`],setup(e,{emit:t}){let n=t;function r(e){return J(`col-start-1 row-start-1 grid place-items-center transition-[opacity,transform] duration-[140ms]`,e?`opacity-100`:`-rotate-45 scale-[0.7] opacity-0`)}return(t,i)=>(L(),R(`button`,{type:`button`,class:`relative z-10 grid size-14 cursor-pointer place-items-center rounded-full bg-linear-to-br from-primary to-[var(--brand-alt)] text-primary-foreground shadow-[var(--shadow-md)] transition-[transform,box-shadow] duration-[140ms] hover:-translate-y-px hover:shadow-[0_12px_34px_var(--primary-soft)] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary active:translate-y-0`,"aria-label":e.open?`Close chat`:`Chat with Archie`,title:e.open?`Close chat`:`Chat with Archie`,"aria-expanded":e.open,"aria-controls":A(qp),onClick:i[0]||=e=>n(`toggle`)},[B(`span`,{"aria-hidden":`true`,class:D(r(!e.open))},[V(A(jd),{size:22})],2),B(`span`,{"aria-hidden":`true`,class:D(r(e.open))},[V(A(qd),{size:22})],2)],8,jm))}});function Nm(e){return typeof e==`string`?`'${e}'`:new Lm().serialize(e)}var Pm=` _-,;:!?.'"()[]{}@*/\\&#%\`^+<=>|~$0123456789abcdefghijklmnopqrstuvwxyz`,Fm=(function(){let e=new Uint8Array(128);for(let t=0;t<69;t++)e[Pm.charCodeAt(t)]=t+1;for(let t=65;t<=90;t++)e[t]=e[t+32];return e})();function Im(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length),r=0;for(let i=0;i<n;i++){let n=e.charCodeAt(i),a=t.charCodeAt(i);if(n===a)continue;let o=n<128&&Fm[n]?Fm[n]:n+128,s=a<128&&Fm[a]?Fm[a]:a+128;if(o!==s)return o<s?-1:1;r===0&&(r=n>a?-1:1)}return e.length===t.length?r:e.length<t.length?-1:1}var Lm=(function(){class e{#e=new Map;compare(e,t){let n=typeof e,r=typeof t;return n===`string`&&r===`string`?Im(e,t):n===`number`&&r===`number`?e-t:Im(this.serialize(e,!0),this.serialize(t,!0))}serialize(e,t){if(e===null)return`null`;switch(typeof e){case`string`:return t?e:`'${e}'`;case`bigint`:return`${e}n`;case`object`:return this.$object(e);case`function`:return this.$function(e)}return String(e)}serializeObject(e){let t=Object.prototype.toString.call(e);if(t!==`[object Object]`)return this.serializeBuiltInType(t.length<10?`unknown:${t}`:t.slice(8,-1),e);let n=e.constructor,r=n===Object||n===void 0?``:n.name;if(r!==``&&globalThis[r]===n)return this.serializeBuiltInType(r,e);if(`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();return r+(typeof t==`object`&&t?this.$object(t):`(${this.serialize(t)})`)}let i=Object.keys(e).sort(Im),a=`${r}{`;for(let t=0;t<i.length;t++){let n=i[t];a+=`${n}:${this.serialize(e[n])}`,t<i.length-1&&(a+=`,`)}return a+`}`}serializeBuiltInType(e,t){let n=this[`$`+e];if(n)return n.call(this,t);if(typeof t.entries==`function`)return this.serializeObjectEntries(e,t.entries());throw Error(`Cannot serialize ${e}`)}serializeObjectEntries(e,t){let n=Array.from(t).sort((e,t)=>this.compare(e[0],t[0])),r=`${e}{`;for(let e=0;e<n.length;e++){let[t,i]=n[e];r+=`${this.serialize(t,!0)}:${this.serialize(i)}`,e<n.length-1&&(r+=`,`)}return r+`}`}$object(e){let t=this.#e.get(e);return t===void 0&&(this.#e.set(e,`#${this.#e.size}`),t=this.serializeObject(e),this.#e.set(e,t)),t}$function(e){let t=Function.prototype.toString.call(e);return t.slice(-15)===`[native code] }`?`${e.name||``}()[native]`:`${e.name}(${e.length})${t.replace(/\s*\n\s*/g,``)}`}$Array(e){let t=`[`;for(let n=0;n<e.length;n++)t+=this.serialize(e[n]),n<e.length-1&&(t+=`,`);return t+`]`}$Date(e){try{return`Date(${e.toISOString()})`}catch{return`Date(null)`}}$ArrayBuffer(e){return`ArrayBuffer[${new Uint8Array(e).join(`,`)}]`}$Set(e){return`Set${this.$Array(Array.from(e).sort((e,t)=>this.compare(e,t)))}`}$Map(e){return this.serializeObjectEntries(`Map`,e.entries())}}for(let t of[`Error`,`RegExp`,`URL`])e.prototype[`$`+t]=function(e){return`${t}(${e})`};for(let t of[`Int8Array`,`Uint8Array`,`Uint8ClampedArray`,`InLine truncated
|
||||
@@ -15,5 +15,5 @@ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],en
|
||||
Defaulting to \`null\`.`),null)}function Tx(e){return Cx(e)&&!Number.isNaN(e)&&e>0?e:(console.error(`Invalid prop \`max\` of value \`${e}\` supplied to \`ProgressRoot\`. Only numbers greater than 0 are valid max values. Defaulting to \`${bx}\`.`),bx)}var Ex=N({__name:`ProgressRoot`,props:{modelValue:{type:[Number,null],required:!1},max:{type:Number,required:!1,default:bx},getValueLabel:{type:Function,required:!1,default:(e,t)=>Cx(e)?`${Math.round(e/t*bx)}%`:void 0},getValueText:{type:Function,required:!1},asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},emits:[`update:modelValue`,`update:max`],setup(e,{emit:t}){let n=e,r=t;X();let i=yh(n,`modelValue`,r,{passive:n.modelValue===void 0}),a=yh(n,`max`,r,{passive:n.max===void 0});M(()=>i.value,async e=>{let t=wx(e,n.max);t!==e&&(await ar(),i.value=t)},{immediate:!0}),M(()=>n.max,e=>{let t=Tx(n.max);t!==e&&(a.value=t)},{immediate:!0});let o=G(()=>Um(i.value)?`indeterminate`:i.value===a.value?`complete`:`loading`);return Sx({modelValue:i,max:a,progressState:o}),(e,t)=>(L(),z(A(Z),{"as-child":e.asChild,as:e.as,"aria-valuemax":A(a),"aria-valuemin":0,"aria-valuenow":Cx(A(i))?A(i):void 0,"aria-valuetext":e.getValueText?.(A(i),A(a)),"aria-label":e.getValueLabel(A(i),A(a)),role:`progressbar`,"data-state":o.value,"data-value":A(i)??void 0,"data-max":A(a)},{default:j(()=>[F(e.$slots,`default`,{modelValue:A(i)})]),_:3},8,[`as-child`,`as`,`aria-valuemax`,`aria-valuenow`,`aria-valuetext`,`aria-label`,`data-state`,`data-value`,`data-max`]))}}),Dx=N({__name:`ProgressIndicator`,props:{asChild:{type:Boolean,required:!1},as:{type:null,required:!1}},setup(e){let t=e,n=xx();return X(),(e,r)=>(L(),z(A(Z),W(t,{"data-state":A(n).progressState.value,"data-value":A(n).modelValue?.value??void 0,"data-max":A(n).max.value}),{default:j(()=>[F(e.$slots,`default`)]),_:3},16,[`data-state`,`data-value`,`data-max`]))}}),Ox=[` `,`Enter`,`ArrowUp`,`ArrowDown`],kx=[` `,`Enter`];function Ax(e,t,n){return e===void 0?!1:Array.isArray(e)?e.some(e=>jx(e,t,n)):jx(e,t,n)}function jx(e,t,n){return e===void 0||t===void 0?!1:typeof e==`string`?e===t:typeof n==`function`?n(e,t):typeof n==`string`?e?.[n]===t?.[n]:Rm(e,t)}function Mx(e){return e==null||e===``||Array.isArray(e)&&e.length===0}var Nx=[`value`],[Px,Fx]=Bm(`SelectRoot`),Ix=N({inheritAttrs:!1,__name:`SelectRoot`,props:{open:{type:Boolean,required:!1,default:void 0},defaultOpen:{type:Boolean,required:!1},defaultValue:{type:null,required:!1},modelValue:{type:null,required:!1,default:void 0},nullableValue:{type:String,required:!1,default:``},by:{type:[String,Function],required:!1},dir:{type:String,required:!1},multiple:{type:Boolean,required:!1},autocomplete:{type:String,required:!1},disabled:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1}},emits:[`update:modelValue`,`update:open`],setup(e,{emit:t}){let n=e,r=t,{required:i,disabled:a,multiple:o,dir:s}=En(n),c=yh(n,`modelValue`,r,{defaultValue:n.defaultValue??(o.value?[]:void 0),passive:n.modelValue===void 0,deep:!0}),l=yh(n,`open`,r,{defaultValue:n.defaultOpen,passive:n.open===void 0}),u=k(),d=k(),f=k({x:0,y:0}),p=G(()=>o.value&&Array.isArray(c.value)?c.value?.length===0:Um(c.value));D_({isProvider:!0});let m=Fh(s),h=Bh(u),g=k(new Set),_=G(()=>Array.from(g.value).map(e=>e.value).join(`;`));function v(e){if(o.value){let t=Array.isArray(c.value)?[...c.value]:[],r=t.findIndex(t=>jx(t,e,n.by));r===-1?t.push(e):t.splice(r,1),c.value=[...t]}else c.value=e}function y(e){return Array.from(g.value).find(t=>Ax(e,t.value,n.by))}return Fx({triggerElement:u,onTriggerChange:e=>{u.value=e},valueElement:d,onValueElementChange:e=>{d.value=e},contentId:``,modelValue:c,onValueChange:v,by:n.by,open:l,multiple:o,required:i,onOpenChange:e=>{l.value=e},dir:m,triggerPointerDownPosRef:f,disabled:a,isEmptyModelValue:p,optionsSet:g,onOptionAdd:e=>{let t=y(e.value);t&&g.value.delete(t),g.value.add(e)},onOptionRemove:e=>{let t=y(e.value);t&&g.value.delete(t)}}),(e,t)=>(L(),z(A(B_),null,{default:j(()=>[F(e.$slots,`default`,{modelValue:A(c),open:A(l)}),A(h)&&e.name?(L(),z(Lx,{key:_.value,"aria-hidden":`true`,tabindex:`-1`,multiple:A(o),required:A(i),name:e.name,autocomplete:e.autocomplete,disabled:A(a),value:A(c)},{default:j(()=>[A(Um)(A(c))?(L(),R(`option`,{key:0,value:e.nullableValue},null,8,Nx)):U(`v-if`,!0),(L(!0),R(I,null,P(Array.from(g.value),e=>(L(),R(`option`,W({key:e.value??``},{ref_for:!0},e),null,16))),128))]),_:1},8,[`multiple`,`required`,`name`,`autocomplete`,`disabled`,`value`])):U(`v-if`,!0)]),_:3}))}}),Lx=N({__name:`BubbleSelect`,props:{autocomplete:{type:String,required:!1},autofocus:{type:Boolean,required:!1},disabled:{type:Boolean,required:!1},form:{type:String,required:!1},multiple:{type:Boolean,required:!1},name:{type:String,required:!1},required:{type:Boolean,required:!1},size:{type:Number,required:!1},value:{type:null,required:!1}},setup(e){let t=e,n=k(),r=Px();M(()=>t.value,(e,t)=>{let r=window.HTMLSelectElement.prototype,i=Object.getOwnPropertyDescrLine truncated
|
||||
`),r=[],i=null,a=null,o=()=>{r.length&&(t.push({kind:`p`,inline:nT(r.join(` `))}),r=[])},s=()=>{i&&=(t.push({kind:i.tag,items:i.items.map(e=>nT(e))}),null)};for(let e=0;e<n.length;e++){let c=n[e];if(c.startsWith("```")){o(),s(),a?(t.push({kind:`pre`,code:a.join(`
|
||||
`)}),a=null):a=[];continue}if(a){a.push(c);continue}let l=iT(c),u=e+1<n.length?iT(n[e+1]):null;if(l&&u&&aT(u)&&l.length===u.length){o(),s();let r=[];for(e+=2;e<n.length;e++){let t=iT(n[e]);if(!t||t.length!==l.length){e--;break}r.push(t)}t.push({kind:`table`,head:l.map(e=>nT(e)),rows:r.map(e=>e.map(e=>nT(e)))});continue}if(!c.trim()){o(),s();continue}let d=c.match(/^(#{1,3})\s+(.+)$/);if(d){o(),s(),t.push({kind:`h${d[1].length}`,inline:nT(d[2])});continue}let f=c.match(/^\s*[-*]\s+(.+)$/),p=c.match(/^\s*\d+[.)]\s+(.+)$/);if(f||p){o();let e=p?`ol`:`ul`;(!i||i.tag!==e)&&(s(),i={tag:e,items:[]}),i.items.push((f||p)[1]);continue}if(c.startsWith(`>`)){o(),s(),t.push({kind:`blockquote`,inline:nT(c.replace(/^>\s?/,``))});continue}r.push(c)}return o(),s(),a&&t.push({kind:`pre`,code:a.join(`
|
||||
`)}),t}function iT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function aT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oT={class:`[overflow-wrap:anywhere]`},sT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},cT={class:`font-mono text-[0.85em]`},lT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},uT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},dT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},fT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},pT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},mT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},hT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},gT={key:8,class:`mb-2.5 last:mb-0`},_T=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>rT(t.text));return(e,t)=>(L(),R(`div`,oT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,sT,[B(`code`,cT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,lT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(eT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(eT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,uT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,dT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,fT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,pT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,mT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,gT,[V(eT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),vT={class:`truncate`},yT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,vT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),bT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},xT={class:`font-semibold text-foreground`},ST={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},CT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(yT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,bT,[V(A(Kd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,xT,O(n.value),1),r.value?(L(),R(`code`,ST,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),wT={key:0,class:`mb-2 grid gap-0.5 text-xs`},TT={key:2,class:`whitespace-pre-wrap`},ET=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,wT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(CT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(_T,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,TT,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),DT={class:`w-full self-center justify-self-center py-6 text-center`},OT={class:`grid gap-2`},kT=[`onClick`],AT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,DT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>cA?`${n.slice(0,cA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var uA=[`title`],dA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Dk(n.event)),a=G(()=>lA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?vO(n.event.at):`—`);return(e,t)=>(L(),z(A(aA),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,uA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function fA(e,t){return`${e}:${t??0}`}function pA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=fA(lA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var mA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},hA=[`aria-expanded`,`aria-label`,`onClick`],gA=[`title`],_A=N({__name:`LiveActivityCard`,setup(e){let t=$T(),{activity:n,streamKind:r,streamState:i}=ad(ek()),a=nn(new Set),o=G(()=>pA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return lA(e.representative)}function u(e){return e.representative.at?vO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(uO),null,{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(pO),null,{default:j(()=>[...t[1]||=[H(`Last 50, newest first`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[V(A(XD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[B(`div`,mA,[V(A(rA),null,{default:j(()=>[V(A(sA),null,{default:j(()=>[V(A(aA),null,{default:j(()=>[V(A(oA),null,{default:j(()=>[...t[2]||=[H(`Event`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[3]||=[H(`Task`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[4]||=[H(`Detail`,-1)]]),_:1}),V(A(oA),null,{default:j(()=>[...t[5]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(iA),null,{default:j(()=>[A(n).length?U(``,!0):(L(),z(A(aA),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(HD),null,{default:j(()=>[V(A(GD),null,{default:j(()=>[V(A(JD),null,{default:j(()=>[...t[6]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),A(n).length?(L(!0),R(I,{key:1},P(o.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(dA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(L(),R(I,{key:1},[V(A(aA),{class:D(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[B(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:lu(t=>s(e.key),[`stop`])},[c(e)?(L(),z(A(xd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(A(Cd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+O(e.label)+` `,1),V(A(XD),{variant:`idle`},{default:j(()=>[H(`×`+O(e.count),1)]),_:2},1024)],8,hA)]),_:2},1024),V(A($),{class:`font-mono`},{default:j(()=>[H(O(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},O(l(e).text),9,gA)]),_:2},1024),V(A($),null,{default:j(()=>[H(O(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(dA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):U(``,!0)],64))],64))),128)):U(``,!0)]),_:1})]),_:1})])]),_:1})]),_:1}))}}),vA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=QS(t,`class`);return(e,r)=>(L(),z(A(Ex),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Dx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`transform:Line truncated
|
||||
`)}),t}function iT(e){let t=String(e||``).trim();if(!t.includes(`|`))return null;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`).map(e=>e.trim());return n.length>1&&n.every(e=>e!==``)?n:null}function aT(e){return e.every(e=>/^:?-{3,}:?$/.test(e))}var oT={class:`[overflow-wrap:anywhere]`},sT={key:0,class:`my-2 overflow-auto rounded-md border border-border bg-background/60 p-3`},cT={class:`font-mono text-[0.85em]`},lT={key:1,class:`my-3 w-full border-collapse text-[0.92em]`},uT={key:2,class:`my-2 border-l-[3px] border-primary pl-3 text-fg-muted`},dT={key:3,class:`mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]`},fT={key:4,class:`mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]`},pT={key:5,class:`mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]`},mT={key:6,class:`my-2.5 flex list-disc flex-col gap-1 pl-5`},hT={key:7,class:`my-2.5 flex list-decimal flex-col gap-1 pl-5`},gT={key:8,class:`mb-2.5 last:mb-0`},_T=N({__name:`ChatMarkdown`,props:{text:{}},setup(e){let t=e,n=G(()=>rT(t.text));return(e,t)=>(L(),R(`div`,oT,[(L(!0),R(I,null,P(n.value,(e,t)=>(L(),R(I,{key:t},[e.kind===`pre`?(L(),R(`pre`,sT,[B(`code`,cT,O(e.code),1)])):e.kind===`table`?(L(),R(`table`,lT,[B(`thead`,null,[B(`tr`,null,[(L(!0),R(I,null,P(e.head,(e,t)=>(L(),R(`th`,{key:t,class:`border border-border bg-muted px-2 py-1.5 text-left font-semibold`},[V(eT,{inline:e},null,8,[`inline`])]))),128))])]),B(`tbody`,null,[(L(!0),R(I,null,P(e.rows,(e,t)=>(L(),R(`tr`,{key:t},[(L(!0),R(I,null,P(e,(e,t)=>(L(),R(`td`,{key:t,class:`border border-border px-2 py-1.5 text-left`},[V(eT,{inline:e},null,8,[`inline`])]))),128))]))),128))])])):e.kind===`blockquote`?(L(),R(`blockquote`,uT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h1`?(L(),R(`h1`,dT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h2`?(L(),R(`h2`,fT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`h3`?(L(),R(`h3`,pT,[V(eT,{inline:e.inline},null,8,[`inline`])])):e.kind===`ul`?(L(),R(`ul`,mT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`ol`?(L(),R(`ol`,hT,[(L(!0),R(I,null,P(e.items,(e,t)=>(L(),R(`li`,{key:t},[V(eT,{inline:e},null,8,[`inline`])]))),128))])):e.kind===`p`?(L(),R(`p`,gT,[V(eT,{inline:e.inline},null,8,[`inline`])])):U(``,!0)],64))),128))]))}}),vT={class:`truncate`},yT=N({__name:`ChatNavChip`,props:{path:{},label:{}},setup(e){return(t,n)=>{let r=ma(`RouterLink`);return L(),z(r,{to:e.path,title:`Go to ${e.label||e.path}`,class:`inline-flex max-w-full items-center gap-1.5 rounded-full border border-primary/45 bg-primary-soft px-2.5 py-1 text-xs font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary`},{default:j(()=>[V(A(yd),{"aria-hidden":`true`,class:`size-3.5 shrink-0`}),B(`span`,vT,O(e.label||e.path),1)]),_:1},8,[`to`,`title`])}}}),bT={key:1,class:`flex items-baseline gap-1.5 [overflow-wrap:anywhere]`},xT={class:`font-semibold text-foreground`},ST={key:0,class:`font-mono text-[0.95em] text-fg-subtle`},CT=N({__name:`ChatToolCall`,props:{tool:{},streaming:{type:Boolean}},setup(e){let t=e,n=G(()=>t.tool.name||t.tool.Name||t.tool.tool||`tool`),r=G(()=>t.tool.parameters||t.tool.Parameters||``),i=G(()=>!!(t.tool.err||t.tool.Err||t.tool.failed)),a=G(()=>t.tool.summary||t.tool.Summary||t.tool.text||t.tool.err||t.tool.Err||(t.streaming?i.value?`failed`:`running…`:`done`));return(t,o)=>e.tool.path?(L(),z(yT,{key:0,path:e.tool.path,label:e.tool.label},null,8,[`path`,`label`])):(L(),R(`div`,bT,[V(A(Kd),{"aria-hidden":`true`,class:`size-3.5 shrink-0 self-center text-fg-subtle`}),B(`span`,xT,O(n.value),1),r.value?(L(),R(`code`,ST,O(r.value),1)):U(``,!0),B(`span`,{class:D(A(J)(`text-fg-muted`,i.value&&`text-danger`))},O(a.value),3)]))}}),wT={key:0,class:`mb-2 grid gap-0.5 text-xs`},TT={key:2,class:`whitespace-pre-wrap`},ET=N({__name:`ChatBubble`,props:{text:{},tools:{default:()=>[]},assistant:{type:Boolean,default:!1},streaming:{type:Boolean,default:!1}},setup(e){return(t,n)=>(L(),R(`div`,{class:D([`flex`,e.assistant?`justify-start`:`justify-end`])},[B(`div`,{class:D(A(J)(`max-w-[min(78ch,86%)] rounded-[0.85rem] px-4 py-3 leading-normal [overflow-wrap:anywhere]`,e.assistant?`bg-muted`:`bg-primary/15`))},[e.assistant&&e.tools.length?(L(),R(`div`,wT,[(L(!0),R(I,null,P(e.tools,(t,n)=>(L(),z(CT,{key:n,tool:t,streaming:e.streaming},null,8,[`tool`,`streaming`]))),128))])):U(``,!0),e.assistant?(L(),z(_T,{key:1,text:e.text},null,8,[`text`])):(L(),R(`div`,TT,O(e.text),1)),F(t.$slots,`default`)],2)],2))}}),DT={class:`w-full self-center justify-self-center py-6 text-center`},OT={class:`grid gap-2`},kT=[`onClick`],AT=N({__name:`ChatEmptyState`,emits:[`prompt`],setup(e,{emit:t}){let n=t,r=[`Summarise active tasks`,`Show running agents`,`Check system status`];return(e,t)=>(L(),R(`div`,DT,[t[0]||=B(`span`,{"aria-hidden":`true`,class:`mx-auto mb-3 grid size-9 placLine truncated
|
||||
`).map(e=>e.trim()).find(Boolean)||``,r=n.length>eA?`${n.slice(0,eA).trimEnd()}…`:n;return{text:r,full:t,truncated:r!==t}}var nA=[`title`],rA=N({__name:`ActivityRow`,props:{event:{}},emits:[`open`],setup(e,{emit:t}){let n=e,r=t,i=G(()=>Dk(n.event)),a=G(()=>tA(n.event));function o(){i.value>0&&r(`open`,i.value)}let s=G(()=>n.event.at?vO(n.event.at):`—`);return(e,t)=>(L(),z(A(Zk),{class:D(i.value>0?`cursor-pointer`:``),role:i.value>0?`link`:void 0,tabindex:i.value>0?0:void 0,title:i.value>0?`Open task details`:void 0,onClick:o,onKeydown:[du(lu(o,[`prevent`]),[`enter`]),du(lu(o,[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[H(O(n.event.kind||n.event.type||`event`),1)]),_:1}),V(A($),{class:`font-mono`},{default:j(()=>[H(O(i.value>0?`#${i.value}`:`—`),1)]),_:1}),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:a.value.truncated?a.value.full:void 0},O(a.value.text),9,nA)]),_:1}),V(A($),null,{default:j(()=>[H(O(s.value),1)]),_:1})]),_:1},8,[`class`,`role`,`tabindex`,`title`,`onKeydown`]))}});function iA(e,t){return`${e}:${t??0}`}function aA(e){let t=[];for(let n of e){let e=n.kind||n.type||`event`,r=Number(n.task_id)||0,i=iA(tA(n).text,r),a=t[t.length-1];if(a&&a.key===i){a.count+=1,a.events.push(n);continue}t.push({key:i,label:e,taskID:r,count:1,representative:n,events:[n]})}return t}var oA={role:`region`,"aria-label":`Live activity`,"aria-live":`polite`},sA={class:`max-h-[28rem] overflow-y-auto`},cA=[`aria-expanded`,`aria-label`,`onClick`],lA=[`title`],uA=N({__name:`LiveActivityCard`,setup(e){let t=$T(),{activity:n,streamKind:r,streamState:i}=ad(ek()),a=nn(new Set),o=G(()=>aA(n.value));function s(e){a.has(e)?a.delete(e):a.add(e)}function c(e){return a.has(e.key)}function l(e){return tA(e.representative)}function u(e){return e.representative.at?vO(e.representative.at):`—`}function d(e){t.push(`/tasks?task=${encodeURIComponent(e)}`)}return(e,t)=>(L(),z(A(uO),null,{default:j(()=>[V(A(hO),null,{default:j(()=>[V(A(gO),null,{default:j(()=>[...t[0]||=[H(`Live activity`,-1)]]),_:1}),V(A(dO),null,{default:j(()=>[V(A(XD),{variant:A(r)},{default:j(()=>[H(O(A(i)),1)]),_:1},8,[`variant`])]),_:1})]),_:1}),V(A(fO),null,{default:j(()=>[B(`div`,oA,[B(`div`,sA,[V(A(Yk),null,{default:j(()=>[V(A($k),{class:`sticky top-0 z-10 bg-card`},{default:j(()=>[V(A(Zk),null,{default:j(()=>[V(A(Qk),null,{default:j(()=>[...t[1]||=[H(`Event`,-1)]]),_:1}),V(A(Qk),null,{default:j(()=>[...t[2]||=[H(`Task`,-1)]]),_:1}),V(A(Qk),null,{default:j(()=>[...t[3]||=[H(`Detail`,-1)]]),_:1}),V(A(Qk),null,{default:j(()=>[...t[4]||=[H(`When`,-1)]]),_:1})]),_:1})]),_:1}),V(A(Xk),null,{default:j(()=>[A(n).length?U(``,!0):(L(),z(A(Zk),{key:0},{default:j(()=>[V(A($),{colspan:`4`},{default:j(()=>[V(A(HD),null,{default:j(()=>[V(A(GD),null,{default:j(()=>[V(A(JD),null,{default:j(()=>[...t[5]||=[H(`Waiting for activity`,-1)]]),_:1})]),_:1})]),_:1})]),_:1})]),_:1})),A(n).length?(L(!0),R(I,{key:1},P(o.value,e=>(L(),R(I,{key:e.key},[e.count===1?(L(),z(rA,{key:0,event:e.representative,onOpen:d},null,8,[`event`])):(L(),R(I,{key:1},[V(A(Zk),{class:D(e.taskID>0?`cursor-pointer`:``),role:e.taskID>0?`link`:void 0,tabindex:e.taskID>0?0:void 0,title:e.taskID>0?`Open task details`:void 0,onClick:t=>e.taskID>0&&d(e.taskID),onKeydown:[du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`enter`]),du(lu(t=>e.taskID>0&&d(e.taskID),[`prevent`]),[`space`])]},{default:j(()=>[V(A($),{class:`font-medium`},{default:j(()=>[B(`button`,{type:`button`,class:`inline-flex items-center gap-1 rounded hover:opacity-80`,"aria-expanded":c(e),"aria-label":`${c(e)?`Hide`:`Show`} ${e.count} ${e.label} events`,onClick:lu(t=>s(e.key),[`stop`])},[c(e)?(L(),z(A(xd),{key:0,class:`size-3.5 shrink-0 text-fg-subtle`})):(L(),z(A(Cd),{key:1,class:`size-3.5 shrink-0 text-fg-subtle`})),H(` `+O(e.label)+` `,1),V(A(XD),{variant:`idle`},{default:j(()=>[H(`×`+O(e.count),1)]),_:2},1024)],8,cA)]),_:2},1024),V(A($),{class:`font-mono`},{default:j(()=>[H(O(e.taskID>0?`#${e.taskID}`:`—`),1)]),_:2},1024),V(A($),{class:`w-[55%] max-w-0`},{default:j(()=>[B(`span`,{class:`block truncate`,title:l(e).truncated?l(e).full:void 0},O(l(e).text),9,lA)]),_:2},1024),V(A($),null,{default:j(()=>[H(O(u(e)),1)]),_:2},1024)]),_:2},1032,[`class`,`role`,`tabindex`,`title`,`onClick`,`onKeydown`]),c(e)?(L(!0),R(I,{key:0},P(e.events,(t,n)=>(L(),z(rA,{key:`${e.key}:${n}`,event:t,onOpen:d},null,8,[`event`]))),128)):U(``,!0)],64))],64))),128)):U(``,!0)]),_:1})]),_:1})])])]),_:1})]),_:1}))}}),dA=N({__name:`Progress`,props:{modelValue:{default:0},max:{},getValueLabel:{},getValueText:{},asChild:{type:Boolean},as:{},class:{type:[Boolean,null,String,Object,Array]}},setup(e){let t=e,n=QS(t,`class`);return(e,r)=>(L(),z(A(Ex),W({"data-slot":`progress`},A(n),{class:A(J)(`bg-muted h-1 rounded-full relative flex w-full items-center overflow-x-hidden`,t.class)}),{default:j(()=>[V(A(Dx),{"data-slot":`progress-indicator`,class:`bg-primary size-full flex-1 transition-all`,style:ve(`tLine truncated
|
||||
@@ -1,75 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
/**
|
||||
* Arc gauge for a single headline percentage.
|
||||
*
|
||||
* A percentage that decides whether you need to act deserves more than a line
|
||||
* of text: the arc is readable at a glance from across a room, which a number
|
||||
* is not. Colour follows the value, so "is this bad" is answered before the
|
||||
* digits are read.
|
||||
*/
|
||||
const props = withDefaults(defineProps<{ value: number | string; label: string; size?: number }>(), {
|
||||
size: 168,
|
||||
});
|
||||
|
||||
const pct = computed(() => Math.max(0, Math.min(100, Number(props.value) || 0)));
|
||||
const rounded = computed(() => Math.round(pct.value));
|
||||
const stroke = computed(() => (pct.value >= 90 ? "var(--ok)" : pct.value >= 70 ? "var(--warn)" : "var(--danger)"));
|
||||
|
||||
// 240-degree arc, opening downward, so the value reads left-to-right.
|
||||
const R = 62;
|
||||
const SWEEP = 240;
|
||||
const START = 150;
|
||||
const circumference = 2 * Math.PI * R * (SWEEP / 360);
|
||||
|
||||
function arc(from: number, deg: number): string {
|
||||
const cx = props.size / 2;
|
||||
const cy = props.size / 2;
|
||||
const a0 = (from * Math.PI) / 180;
|
||||
const a1 = ((from + deg) * Math.PI) / 180;
|
||||
const large = deg > 180 ? 1 : 0;
|
||||
return [
|
||||
`M ${cx + R * Math.cos(a0)} ${cy + R * Math.sin(a0)}`,
|
||||
`A ${R} ${R} 0 ${large} 1 ${cx + R * Math.cos(a1)} ${cy + R * Math.sin(a1)}`,
|
||||
].join(" ");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative grid place-items-center">
|
||||
<!--
|
||||
The label announces the rounded value. It used to announce the raw one, so
|
||||
a screen reader read "71.38461538461539%" before the same figure was
|
||||
shown rounded.
|
||||
-->
|
||||
<svg
|
||||
class="block w-full max-w-[200px]"
|
||||
:viewBox="`0 0 ${props.size} ${props.size * 0.78}`"
|
||||
role="img"
|
||||
:aria-label="`${props.label}: ${rounded}%`"
|
||||
>
|
||||
<path
|
||||
:d="arc(START, SWEEP)"
|
||||
fill="none"
|
||||
stroke="var(--border)"
|
||||
stroke-width="12"
|
||||
stroke-linecap="round"
|
||||
/>
|
||||
<path
|
||||
:d="arc(START, SWEEP)"
|
||||
fill="none"
|
||||
:stroke="stroke"
|
||||
stroke-width="12"
|
||||
stroke-linecap="round"
|
||||
:stroke-dasharray="circumference"
|
||||
:stroke-dashoffset="circumference * (1 - pct / 100)"
|
||||
class="transition-[stroke-dashoffset] duration-[600ms] ease-[cubic-bezier(0.4,0,0.2,1)]"
|
||||
/>
|
||||
</svg>
|
||||
<div class="absolute top-[52%] -translate-y-1/2 text-center">
|
||||
<div class="text-2xl font-semibold tracking-[-0.03em]">{{ rounded }}%</div>
|
||||
<div class="text-xs text-fg-muted">{{ props.label }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,23 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* Inline JSON content with syntax highlighting, or the text verbatim when it
|
||||
* is not JSON. Every source character survives either way — highlighting adds
|
||||
* colour spans, never removes or rewrites text. Callers own the surrounding
|
||||
* <pre> and its classes (borders, max height, wrap behaviour differ per
|
||||
* surface); this renders only the content.
|
||||
*/
|
||||
import { computed } from "vue";
|
||||
|
||||
import { tokenClass, tokenizeJson } from "@/lib/json-tokens";
|
||||
|
||||
const props = defineProps<{ text: string }>();
|
||||
|
||||
const tokens = computed(() => tokenizeJson(props.text));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="tokens">
|
||||
<span v-for="(token, i) in tokens" :key="i" :class="tokenClass(token.kind)">{{ token.text }}</span>
|
||||
</template>
|
||||
<template v-else>{{ props.text }}</template>
|
||||
</template>
|
||||
@@ -66,11 +66,6 @@ const secretHint = computed(() =>
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Alert v-if="props.error" variant="destructive">
|
||||
<AlertTitle>Could not save</AlertTitle>
|
||||
<AlertDescription>{{ props.error }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<form @submit.prevent="emit('save', draft)">
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
@@ -139,6 +134,13 @@ const secretHint = computed(() =>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
|
||||
<!-- Beside the buttons, not at the top: the dialog scrolls, and Save is
|
||||
clicked at the bottom, where a refusal must be seen. -->
|
||||
<Alert v-if="props.error" variant="destructive" class="mt-4">
|
||||
<AlertTitle>Could not save</AlertTitle>
|
||||
<AlertDescription>{{ props.error }}</AlertDescription>
|
||||
</Alert>
|
||||
|
||||
<DialogFooter class="mt-4">
|
||||
<Button type="button" variant="outline" @click="open = false">Cancel</Button>
|
||||
<Button type="submit" :disabled="props.saving">
|
||||
|
||||
@@ -28,9 +28,9 @@ const emit = defineEmits<{
|
||||
<Pencil data-icon="inline-start" />
|
||||
Edit
|
||||
</Button>
|
||||
<!-- Only a pending binding can be approved. A draft is not a state you
|
||||
approve from and an armed binding is already firing, so the button
|
||||
would be a no-op -- or worse, a misleading one. -->
|
||||
<!-- Only a pending binding can be approved. An armed binding is
|
||||
already firing, so the button would be a no-op -- or worse, a
|
||||
misleading one. -->
|
||||
<Button v-if="props.binding.status === 'pending_approval'" size="sm" @click="emit('approve', props.binding)">
|
||||
<Check data-icon="inline-start" />
|
||||
Approve
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { statusKind, statusLabel } from "./binding-draft";
|
||||
|
||||
/** A binding's lifecycle state: draft, pending approval, or armed. The
|
||||
/** A binding's lifecycle state: pending approval or armed. The
|
||||
* colour ramp is shared with every other status in the dashboard, so the
|
||||
* same colour means the same thing here as it does on a task. */
|
||||
const props = defineProps<{ status?: string }>();
|
||||
|
||||
@@ -40,13 +40,11 @@ export interface WorkflowOption {
|
||||
export type StatusKind = "ok" | "warn" | "idle";
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
draft: "draft",
|
||||
pending_approval: "pending approval",
|
||||
armed: "armed",
|
||||
};
|
||||
|
||||
const STATUS_KINDS: Record<string, StatusKind> = {
|
||||
draft: "idle",
|
||||
pending_approval: "warn",
|
||||
armed: "ok",
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import HighlightedJson from "@/base/HighlightedJson.vue";
|
||||
import { prettyPrint } from "./capture-payload";
|
||||
|
||||
/**
|
||||
@@ -24,7 +25,7 @@ const text = computed(() => prettyPrint(props.raw));
|
||||
<pre
|
||||
v-else
|
||||
class="rounded-sm border border-border-strong bg-muted p-3 font-mono text-xs whitespace-pre-wrap wrap-break-word"
|
||||
>{{ text }}</pre
|
||||
><HighlightedJson :text="text" /></pre
|
||||
>
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,4 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { ChevronDown } from "@lucide/vue";
|
||||
|
||||
import {
|
||||
@@ -15,17 +16,49 @@ import NavTrigger from "./NavTrigger.vue";
|
||||
const props = defineProps<{ label: string; items: NavEntry[]; activePath: string }>();
|
||||
|
||||
const holds = (path: string) => props.activePath === path;
|
||||
|
||||
/**
|
||||
* Hover-open, click-toggling menu.
|
||||
*
|
||||
* Pointing at the group opens it; leaving it closes it after a short grace
|
||||
* period, so the move from trigger to content cannot close what you are
|
||||
* moving towards (the content carries its own enter/leave handlers, and the
|
||||
* delay covers the gap between two teleported elements). The trigger keeps
|
||||
* its click and keyboard semantics: reka still emits update:open on
|
||||
* activation, this only controls how long the menu stays open.
|
||||
*/
|
||||
const open = ref(false);
|
||||
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
function openMenu() {
|
||||
clearTimeout(closeTimer);
|
||||
open.value = true;
|
||||
}
|
||||
|
||||
function closeMenuSoon() {
|
||||
clearTimeout(closeTimer);
|
||||
closeTimer = setTimeout(() => {
|
||||
open.value = false;
|
||||
}, 140);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger as-child>
|
||||
<NavTrigger :current="items.some((item) => holds(item.path))">
|
||||
{{ label }}
|
||||
<ChevronDown :size="14" class="opacity-60" />
|
||||
</NavTrigger>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="start" class="w-52">
|
||||
<DropdownMenu :open="open" @update:open="open = $event">
|
||||
<div class="flex" @pointerenter="openMenu" @pointerleave="closeMenuSoon">
|
||||
<DropdownMenuTrigger as-child>
|
||||
<NavTrigger :current="items.some((item) => holds(item.path))">
|
||||
{{ props.label }}
|
||||
<ChevronDown :size="14" class="opacity-60" />
|
||||
</NavTrigger>
|
||||
</DropdownMenuTrigger>
|
||||
</div>
|
||||
<DropdownMenuContent
|
||||
align="start"
|
||||
class="w-52"
|
||||
@pointerenter="openMenu"
|
||||
@pointerleave="closeMenuSoon"
|
||||
>
|
||||
<template v-for="item in items" :key="item.path">
|
||||
<DropdownMenuSeparator v-if="item.dividerBefore" />
|
||||
<DropdownMenuLabel v-if="item.dividerBefore">{{ item.dividerBefore }}</DropdownMenuLabel>
|
||||
@@ -33,4 +66,4 @@ const holds = (path: string) => props.activePath === path;
|
||||
</template>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</template>
|
||||
</template>
|
||||
@@ -17,26 +17,21 @@ import TokenOutlookCard from "./TokenOutlookCard.vue";
|
||||
*/
|
||||
useDashboard();
|
||||
|
||||
const omitSetup = computed(() => {
|
||||
const kind = setupPanelState(setup.value).kind;
|
||||
return kind === "omit" || kind === "dismissed";
|
||||
});
|
||||
const setupIncomplete = computed(() => setupPanelState(setup.value).kind === "incomplete");
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<DashboardHero />
|
||||
|
||||
<!--
|
||||
Each health card takes its own content height rather than the row's.
|
||||
Matching them was right while both held a checklist, but once setup is done
|
||||
that card is a title and a line while Gate pulse carries a gauge and four
|
||||
rows, so equalising them left a mostly-empty box taking a quarter of the
|
||||
first screen. No setup panel to show: the pulse spans the row instead.
|
||||
The Health row holds the pulse alone once setup is done: the checklist
|
||||
only renders while there is setup work left, so the grid collapses to a
|
||||
single column instead of pairing a checklist with an empty neighbour.
|
||||
-->
|
||||
<DashboardSection title="Health">
|
||||
<div
|
||||
class="grid items-start gap-4"
|
||||
:class="omitSetup ? 'grid-cols-1' : 'grid-cols-1 min-[1080px]:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]'"
|
||||
:class="setupIncomplete ? 'grid-cols-1 min-[1080px]:grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)]' : 'grid-cols-1'"
|
||||
>
|
||||
<SetupPanel />
|
||||
<GatePulseCard />
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import Gauge from "@/base/Gauge.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { summary, workflows } from "./state";
|
||||
import { workflows } from "./state";
|
||||
|
||||
/** Sharer of runs: how much of the work that finished passed its gates. */
|
||||
const stats = computed(() => workflows.value?.workflows ?? []);
|
||||
@@ -13,15 +12,18 @@ const stats = computed(() => workflows.value?.workflows ?? []);
|
||||
const totals = computed(() => ({
|
||||
runs: stats.value.reduce((a, w) => a + (w.runs || 0), 0),
|
||||
merged: stats.value.reduce((a, w) => a + (w.merged || 0) + (w.pr_open || 0), 0),
|
||||
parked: stats.value.reduce((a, w) => a + (w.parked || 0), 0),
|
||||
}));
|
||||
|
||||
const pct = computed(() => {
|
||||
if (!totals.value.runs) return 0;
|
||||
return Math.round((totals.value.merged / totals.value.runs) * 100);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card v-if="summary">
|
||||
<Card v-if="workflows">
|
||||
<CardHeader>
|
||||
<CardTitle>Gate pulse</CardTitle>
|
||||
<CardDescription v-if="totals.runs">Work that passed its quality gates</CardDescription>
|
||||
<CardTitle>Quality gates</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Empty v-if="!totals.runs">
|
||||
@@ -30,27 +32,31 @@ const totals = computed(() => ({
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
<template v-else>
|
||||
<Gauge :value="(totals.merged / totals.runs) * 100" label="pass rate" />
|
||||
<ul class="mt-4 flex flex-col gap-2">
|
||||
<li
|
||||
v-for="(w, i) in stats.slice(0, 3)"
|
||||
:key="i"
|
||||
class="flex items-center justify-between gap-3 rounded-sm bg-muted px-3 py-2 text-sm"
|
||||
>
|
||||
<span class="truncate text-fg-muted">{{ w.workflow || "workflow" }}</span>
|
||||
<Badge :variant="(w.merged || 0) === (w.runs || 0) ? 'ok' : (w.parked || 0) > 0 ? 'warn' : 'info'">
|
||||
{{ w.merged || 0 }}/{{ w.runs || 0 }}
|
||||
</Badge>
|
||||
</li>
|
||||
<li
|
||||
v-if="totals.parked > 0"
|
||||
class="flex items-center justify-between gap-3 rounded-sm bg-muted px-3 py-2 text-sm"
|
||||
>
|
||||
<span class="truncate text-fg-muted">Parked, awaiting you</span>
|
||||
<Badge variant="warn">{{ totals.parked }}</Badge>
|
||||
</li>
|
||||
</ul>
|
||||
<!--
|
||||
Two sections, read left to right: the rate on its own, and the
|
||||
per-workflow counts that explain it. Parked tasks are not listed
|
||||
here -- Throughput's Needs-you tile already speaks for them, from
|
||||
the statuses themselves.
|
||||
-->
|
||||
<div class="grid grid-cols-1 gap-6 min-[720px]:grid-cols-[auto_minmax(0,1fr)]">
|
||||
<div class="flex flex-col justify-center">
|
||||
<span class="text-3xl font-semibold">{{ pct }}%</span>
|
||||
<span class="text-xs text-fg-muted">pass rate · {{ totals.runs }} runs</span>
|
||||
</div>
|
||||
<ul class="flex flex-col">
|
||||
<li
|
||||
v-for="(w, i) in stats.slice(0, 3)"
|
||||
:key="i"
|
||||
class="flex items-center justify-between gap-3 border-b border-hairline py-1.5 text-sm last:border-b-0"
|
||||
>
|
||||
<span class="truncate text-fg-muted">{{ w.workflow || "workflow" }}</span>
|
||||
<Badge :variant="(w.merged || 0) === (w.runs || 0) ? 'ok' : (w.parked || 0) > 0 ? 'warn' : 'info'">
|
||||
{{ w.merged || 0 }}/{{ w.runs || 0 }}
|
||||
</Badge>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
</template>
|
||||
@@ -5,7 +5,7 @@ import { useRouter } from "vue-router";
|
||||
|
||||
import { ChevronDown, ChevronRight } from "@lucide/vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardAction, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { ago } from "@/lib/format";
|
||||
@@ -58,7 +58,6 @@ function openTask(taskID: number) {
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Live activity</CardTitle>
|
||||
<CardDescription>Last 50, newest first</CardDescription>
|
||||
<CardAction>
|
||||
<Badge :variant="streamKind">{{ streamState }}</Badge>
|
||||
</CardAction>
|
||||
@@ -72,15 +71,24 @@ function openTask(taskID: number) {
|
||||
appear without a second hidden summary to keep in sync.
|
||||
-->
|
||||
<div role="region" aria-label="Live activity" aria-live="polite">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Event</TableHead>
|
||||
<TableHead>Task</TableHead>
|
||||
<TableHead>Detail</TableHead>
|
||||
<TableHead>When</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<!--
|
||||
The feed's height is bounded to the card, not the page: group rows
|
||||
multiply with the number of interleaved tasks, and an unbounded
|
||||
table made the dashboard ~4,700px tall on a live instance. The
|
||||
newest events stay visible at the top; the rest scroll inside the
|
||||
card. The header stays put via sticky so the columns keep their
|
||||
labels while scrolling.
|
||||
-->
|
||||
<div class="max-h-[28rem] overflow-y-auto">
|
||||
<Table>
|
||||
<TableHeader class="sticky top-0 z-10 bg-card">
|
||||
<TableRow>
|
||||
<TableHead>Event</TableHead>
|
||||
<TableHead>Task</TableHead>
|
||||
<TableHead>Detail</TableHead>
|
||||
<TableHead>When</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-if="!activity.length">
|
||||
<TableCell colspan="4">
|
||||
@@ -139,7 +147,8 @@ function openTask(taskID: number) {
|
||||
</template>
|
||||
</template>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import { Check, X } from "@lucide/vue";
|
||||
import { Check } from "@lucide/vue";
|
||||
import { computed, ref, watch } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardAction, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { dismissSetupComplete, setupPanelState, type SetupPanelState } from "./setup-preference";
|
||||
import { setupPanelState, type SetupPanelState } from "./setup-preference";
|
||||
import { setup } from "./state";
|
||||
|
||||
/**
|
||||
* The setup checklist, or its completion note.
|
||||
* The setup checklist, rendered only while there is setup work left.
|
||||
*
|
||||
* Which of the two this shows comes from the state machine rather than from
|
||||
* "is setup present at all": guarding on presence showed a 100% checklist with
|
||||
* every step struck through where the complete state belongs.
|
||||
* A fully configured daemon renders nothing: the old completion card ("Setup
|
||||
* complete", with a check and a dismiss button) celebrated the absence of a
|
||||
* problem and occupied a grid cell until dismissed. Setup regressing to
|
||||
* incomplete brings the checklist back on its own.
|
||||
*/
|
||||
const panel = ref<SetupPanelState>(setupPanelState(setup.value));
|
||||
|
||||
@@ -27,18 +27,12 @@ const pct = computed(() => {
|
||||
if (!total) return 0;
|
||||
return Math.round(((total - panel.value.remaining.length) / total) * 100);
|
||||
});
|
||||
|
||||
function dismiss() {
|
||||
dismissSetupComplete();
|
||||
panel.value = setupPanelState(setup.value);
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Card v-if="panel.kind === 'incomplete'">
|
||||
<CardHeader>
|
||||
<CardTitle>Finish setting up</CardTitle>
|
||||
<CardDescription>Archie needs these before it can work on its own.</CardDescription>
|
||||
<CardAction>
|
||||
<span class="text-lg font-semibold text-link">{{ pct }}%</span>
|
||||
</CardAction>
|
||||
@@ -61,17 +55,4 @@ function dismiss() {
|
||||
</ul>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card v-else-if="panel.kind === 'complete'">
|
||||
<CardHeader>
|
||||
<CardTitle>Setup complete</CardTitle>
|
||||
<CardDescription>Archie is configured and ready to work.</CardDescription>
|
||||
<CardAction class="flex items-center gap-2">
|
||||
<Check class="size-4 text-ok" />
|
||||
<Button variant="ghost" size="icon-sm" aria-label="Dismiss setup complete" @click="dismiss">
|
||||
<X />
|
||||
</Button>
|
||||
</CardAction>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
</template>
|
||||
</template>
|
||||
@@ -2,7 +2,7 @@
|
||||
import { computed } from "vue";
|
||||
|
||||
import SegmentBar from "@/base/SegmentBar.vue";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { compact } from "@/lib/format";
|
||||
import { summary } from "./state";
|
||||
@@ -20,7 +20,6 @@ const projected = computed(() => Math.round(perDay.value * 30));
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Token outlook</CardTitle>
|
||||
<CardDescription v-if="days.length">Next 30 days at the current rate</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Empty v-if="!days.length">
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
export const SETUP_DISMISSAL_KEY = "archie.setup-complete.dismissed.v1";
|
||||
|
||||
/** One setup step as the daemon reports it. */
|
||||
export interface SetupStep {
|
||||
title: string;
|
||||
@@ -12,33 +10,19 @@ export interface Setup {
|
||||
operator?: string;
|
||||
}
|
||||
|
||||
/** The storage surface this needs, so it is testable without a browser. */
|
||||
export type SetupStorage = Pick<Storage, "getItem" | "removeItem" | "setItem">;
|
||||
|
||||
export interface SetupPanelState {
|
||||
kind: "omit" | "incomplete" | "complete" | "dismissed";
|
||||
/** omit: nothing to show — no setup data, or setup fully done. */
|
||||
kind: "omit" | "incomplete";
|
||||
remaining: SetupStep[];
|
||||
}
|
||||
|
||||
// setupPanelState reconciles persisted presentation state with current setup
|
||||
// truth. If setup later becomes incomplete, an old dismissal is cleared so the
|
||||
// operator cannot miss the new work.
|
||||
export function setupPanelState(
|
||||
setup: Setup | null | undefined,
|
||||
storage: SetupStorage | undefined = globalThis.localStorage,
|
||||
): SetupPanelState {
|
||||
if (!setup?.steps?.length) return { kind: "omit", remaining: [] };
|
||||
const remaining = setup.steps.filter((step) => !step.done);
|
||||
if (remaining.length) {
|
||||
storage?.removeItem?.(SETUP_DISMISSAL_KEY);
|
||||
return { kind: "incomplete", remaining };
|
||||
// setupPanelState distinguishes the only two states worth rendering: there is
|
||||
// setup work left (the checklist), or there is not (nothing — a configured
|
||||
// daemon is the absence of a problem, not a card announcing it).
|
||||
export function setupPanelState(setup: Setup | null | undefined): SetupPanelState {
|
||||
const remaining = (setup?.steps ?? []).filter((step) => !step.done);
|
||||
if (!setup?.steps?.length || !remaining.length) {
|
||||
return { kind: "omit", remaining: [] };
|
||||
}
|
||||
if (storage?.getItem?.(SETUP_DISMISSAL_KEY) === "1") {
|
||||
return { kind: "dismissed", remaining: [] };
|
||||
}
|
||||
return { kind: "complete", remaining: [] };
|
||||
}
|
||||
|
||||
export function dismissSetupComplete(storage: SetupStorage | undefined = globalThis.localStorage): void {
|
||||
storage?.setItem?.(SETUP_DISMISSAL_KEY, "1");
|
||||
}
|
||||
return { kind: "incomplete", remaining };
|
||||
}
|
||||
+8
-1
@@ -149,6 +149,13 @@ export const api = {
|
||||
// log-row keeps it beside the panel that uses it.
|
||||
taskLogDownloadURL: (id: string, attempt?: number | null) =>
|
||||
`/api/tasks/${encodeURIComponent(id)}/logs/download` + (attempt == null ? "" : `?attempt=${attempt}`),
|
||||
// Versions + updates. The install's synchronous phase (clone + build +
|
||||
// install) legitimately runs for minutes; its timeout is therefore minutes,
|
||||
// not the 15s default, and the watchdog owns everything after the restart.
|
||||
version: <T = unknown>() => request<T>("/api/version"),
|
||||
updateSnapshot: <T = unknown>() => request<T>("/api/chat/update"),
|
||||
updateInstall: <T = unknown>(snapshot: unknown) =>
|
||||
request<T>("/api/chat/update/install", { method: "POST", body: { snapshot }, timeoutMs: 15 * 60_000 }),
|
||||
captures: <T = unknown>(limit?: number) => request<T>("/api/captures" + qs({ limit })),
|
||||
mappings: <T = unknown>() => request<T>("/api/mappings"),
|
||||
mappingCreate: <T = unknown>(mapping: Payload) => request<T>("/api/mappings", { method: "POST", body: mapping }),
|
||||
@@ -210,7 +217,7 @@ export function subscribeEvents(
|
||||
onEvent: (event: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
): () => void {
|
||||
const src = new EventSource("/events");
|
||||
const src = new EventSource("/api/stream");
|
||||
src.onopen = () => onStateChange?.("live");
|
||||
src.onerror = () => onStateChange?.("reconnecting");
|
||||
src.onmessage = (e) => {
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* JSON syntax highlighting, tokenised.
|
||||
*
|
||||
* Capture bodies and stored config documents are strings that are "valid JSON
|
||||
* or not" — the reader's rule is: valid JSON renders with typed colour, and
|
||||
* anything else renders plain, exactly as stored. There is no projection and
|
||||
* no library: one pass with a JSON-aware scanner, every character of the
|
||||
* source preserved verbatim in the output tokens.
|
||||
*
|
||||
* Keys and values are distinguished by what follows the string (a colon makes
|
||||
* it a key), which is exactly how JSON itself decides.
|
||||
*/
|
||||
|
||||
export type JsonTokenKind = "key" | "string" | "number" | "keyword" | "punct";
|
||||
|
||||
export interface JsonToken {
|
||||
text: string;
|
||||
kind: JsonTokenKind;
|
||||
}
|
||||
|
||||
/** Matches one JSON token: a string (which may be a key), a number, a keyword. */
|
||||
const SCANNER =
|
||||
/("(?:\\.|[^"\\])*")(\s*:)?|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|(\btrue\b|\bfalse\b|\bnull\b)/g;
|
||||
|
||||
export function tokenizeJson(text: string): JsonToken[] | null {
|
||||
if (!text.trim()) return null;
|
||||
try {
|
||||
JSON.parse(text);
|
||||
} catch {
|
||||
return null; // not JSON: the caller renders it plain
|
||||
}
|
||||
|
||||
const tokens: JsonToken[] = [];
|
||||
let last = 0;
|
||||
for (const match of text.matchAll(SCANNER)) {
|
||||
const [full, str, colon, num, keyword] = match;
|
||||
const at = match.index ?? 0;
|
||||
if (at > last) tokens.push({ text: text.slice(last, at), kind: "punct" });
|
||||
if (str !== undefined) {
|
||||
tokens.push({ text: str, kind: colon ? "key" : "string" });
|
||||
if (colon) tokens.push({ text: colon, kind: "punct" });
|
||||
last = at + full.length;
|
||||
continue;
|
||||
}
|
||||
if (num !== undefined) {
|
||||
tokens.push({ text: num, kind: "number" });
|
||||
} else if (keyword !== undefined) {
|
||||
tokens.push({ text: keyword, kind: "keyword" });
|
||||
}
|
||||
last = at + full.length;
|
||||
}
|
||||
if (last < text.length) tokens.push({ text: text.slice(last), kind: "punct" });
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** The token's colour class, from the design tokens only. */
|
||||
export function tokenClass(kind: JsonTokenKind): string {
|
||||
switch (kind) {
|
||||
case "key":
|
||||
return "text-primary";
|
||||
case "string":
|
||||
return "text-ok";
|
||||
case "number":
|
||||
return "text-warn";
|
||||
case "keyword":
|
||||
return "text-info";
|
||||
default:
|
||||
return "text-foreground";
|
||||
}
|
||||
}
|
||||
@@ -40,8 +40,6 @@ function onOpenChange(open: boolean) {
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<MappingActionError v-if="actionError" :failure="actionError" />
|
||||
|
||||
<Card>
|
||||
<CardContent>
|
||||
<MappingForm />
|
||||
@@ -73,6 +71,10 @@ function onOpenChange(open: boolean) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- Beside the buttons, not at the top: the dialog scrolls, and Save is
|
||||
clicked at the bottom, where a refusal must be seen. -->
|
||||
<MappingActionError v-if="actionError" :failure="actionError" />
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" @click="closeEditor">Cancel</Button>
|
||||
<Button :disabled="saving" @click="saveMapping">
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import HealthStatusCard from "./HealthStatusCard.vue";
|
||||
import VersionsCard from "./VersionsCard.vue";
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -8,5 +9,6 @@ import HealthStatusCard from "./HealthStatusCard.vue";
|
||||
<PageHeader title="Status" />
|
||||
|
||||
<HealthStatusCard />
|
||||
<VersionsCard class="mt-4" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,188 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import { ApiError, api } from "@/lib/api";
|
||||
|
||||
/**
|
||||
* Per-component versions and the update that applies them.
|
||||
*
|
||||
* Everything behind this card already exists: /api/version reports what is
|
||||
* running, what the check command claims, what is available, and the honest
|
||||
* status between those (ok, update_available, drift, unknown); the install
|
||||
* endpoint re-validates freshness and refuses a stale snapshot. This card
|
||||
* only surfaces them.
|
||||
*/
|
||||
|
||||
interface ComponentVersion {
|
||||
id: string;
|
||||
label: string;
|
||||
install_type?: string;
|
||||
reference?: string;
|
||||
running_version?: string;
|
||||
installed_claim?: string;
|
||||
latest_available?: string;
|
||||
status: "ok" | "update_available" | "drift" | "unknown";
|
||||
}
|
||||
|
||||
interface ComponentSnapshot {
|
||||
id?: string;
|
||||
label?: string;
|
||||
installed?: string;
|
||||
available?: string;
|
||||
}
|
||||
|
||||
interface UpdateSnapshot {
|
||||
components?: ComponentSnapshot[];
|
||||
deferred?: boolean;
|
||||
}
|
||||
|
||||
const components = ref<ComponentVersion[]>([]);
|
||||
const snapshot = ref<UpdateSnapshot | null>(null);
|
||||
const canInstall = ref(false);
|
||||
const notConfigured = ref(false);
|
||||
const loading = ref(true);
|
||||
const loadError = ref<string | null>(null);
|
||||
const installing = ref(false);
|
||||
const installProgress = ref<string[]>([]);
|
||||
const installResult = ref<string | null>(null);
|
||||
const installError = ref<string | null>(null);
|
||||
|
||||
const updateable = computed(() => components.value.filter((c) => c.status === "update_available"));
|
||||
|
||||
const statusKind: Record<ComponentVersion["status"], "ok" | "warn" | "danger" | "idle"> = {
|
||||
ok: "ok",
|
||||
update_available: "warn",
|
||||
drift: "danger",
|
||||
unknown: "idle",
|
||||
};
|
||||
|
||||
const statusLabel: Record<ComponentVersion["status"], string> = {
|
||||
ok: "Up to date",
|
||||
update_available: "Update available",
|
||||
drift: "Version drift",
|
||||
unknown: "Unknown",
|
||||
};
|
||||
|
||||
async function load(): Promise<void> {
|
||||
loading.value = true;
|
||||
loadError.value = null;
|
||||
try {
|
||||
const [report, update] = await Promise.all([
|
||||
api.version<{ components: ComponentVersion[] }>(),
|
||||
api.updateSnapshot<{ snapshot: UpdateSnapshot; can_install: boolean }>().catch((err) => {
|
||||
if (err instanceof ApiError && err.status === 501) {
|
||||
notConfigured.value = true;
|
||||
return null;
|
||||
}
|
||||
throw err;
|
||||
}),
|
||||
]);
|
||||
components.value = report.components;
|
||||
if (update) {
|
||||
snapshot.value = update.snapshot;
|
||||
canInstall.value = update.can_install;
|
||||
}
|
||||
} catch (err) {
|
||||
loadError.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
// The snapshot the install endpoint demands is the one the operator saw —
|
||||
// the endpoint re-checks freshness and answers 409 when releases moved.
|
||||
function installableSnapshot(): UpdateSnapshot | null {
|
||||
if (!snapshot.value) return null;
|
||||
if (snapshot.value.components?.some((c) => c.available && c.available !== c.installed)) {
|
||||
return snapshot.value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function install(): Promise<void> {
|
||||
const snap = installableSnapshot();
|
||||
if (!snap || installing.value) return;
|
||||
installing.value = true;
|
||||
installError.value = null;
|
||||
installProgress.value = [];
|
||||
installResult.value = null;
|
||||
try {
|
||||
const result = await api.updateInstall<{ progress?: string[]; result?: { installed?: Record<string, string> } }>(snap);
|
||||
installProgress.value = result.progress ?? [];
|
||||
const installed = result.result?.installed;
|
||||
installResult.value = installed
|
||||
? Object.entries(installed)
|
||||
.map(([id, version]) => `${id} → ${version}`)
|
||||
.join(", ")
|
||||
: "update finished";
|
||||
await load();
|
||||
} catch (err) {
|
||||
installError.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
installing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="notConfigured" class="text-sm text-fg-muted">Update checks not configured.</p>
|
||||
<Card v-else>
|
||||
<CardHeader>
|
||||
<CardTitle>Versions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p v-if="loadError" class="text-sm text-danger">{{ loadError }}</p>
|
||||
<p v-else-if="loading" class="text-sm text-fg-muted">Checking…</p>
|
||||
<template v-else>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Component</TableHead>
|
||||
<TableHead>Running</TableHead>
|
||||
<TableHead>Available</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="component in components" :key="component.id">
|
||||
<TableCell class="font-medium">{{ component.label || component.id }}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">{{ component.running_version || component.installed_claim || "—" }}</TableCell>
|
||||
<TableCell class="font-mono text-fg-muted">{{ component.latest_available || "—" }}</TableCell>
|
||||
<TableCell>
|
||||
<Badge :variant="statusKind[component.status]">{{ statusLabel[component.status] }}</Badge>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
|
||||
<div v-if="canInstall && updateable.length" class="mt-4 flex flex-col gap-2">
|
||||
<Button :disabled="installing" @click="install">
|
||||
{{ installing ? "Installing…" : `Install ${updateable.map((c) => c.label || c.id).join(", ")}` }}
|
||||
</Button>
|
||||
<p v-if="installing" class="text-xs text-fg-muted">
|
||||
The build runs on this host and the restart is verified out of band; the page can be left.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-if="installProgress.length" class="mt-3 rounded-sm border border-border bg-muted p-3 font-mono text-xs">
|
||||
<p v-for="(line, i) in installProgress" :key="i">{{ line }}</p>
|
||||
</div>
|
||||
<p v-if="installResult" class="mt-2 text-sm text-ok">{{ installResult }}</p>
|
||||
<p v-if="installError" class="mt-2 text-sm text-danger">{{ installError }}</p>
|
||||
</template>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</template>
|
||||
@@ -4,6 +4,8 @@
|
||||
* and the debug view), and both must show exactly what the daemon stored --
|
||||
* no projection, no prettifying beyond indentation.
|
||||
*/
|
||||
import HighlightedJson from "@/base/HighlightedJson.vue";
|
||||
|
||||
defineProps<{ value: unknown }>();
|
||||
</script>
|
||||
|
||||
@@ -14,5 +16,5 @@ defineProps<{ value: unknown }>();
|
||||
-->
|
||||
<pre
|
||||
class="max-h-[60vh] overflow-auto rounded-sm border border-border bg-muted p-3 font-mono text-xs leading-normal whitespace-pre-wrap break-words"
|
||||
>{{ JSON.stringify(value ?? {}, null, 2) }}</pre>
|
||||
><HighlightedJson :text="JSON.stringify(value ?? {}, null, 2)" /></pre>
|
||||
</template>
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { tokenizeJson, tokenClass } = await import("../src/lib/json-tokens.ts");
|
||||
|
||||
test("a valid JSON document tokenizes into typed spans", () => {
|
||||
const tokens = tokenizeJson('{"name":"archie","count":3}');
|
||||
assert.ok(tokens, "valid JSON must tokenize");
|
||||
const kinds = tokens.map((t) => t.kind);
|
||||
assert.ok(tokens.some((t) => t.kind === "key" && t.text === '"name"'));
|
||||
assert.ok(tokens.some((t) => t.kind === "string" && t.text === '"archie"'));
|
||||
assert.ok(tokens.some((t) => t.kind === "number" && t.text === "3" || t.text.endsWith("3")));
|
||||
assert.ok(tokens.some((t) => t.kind === "punct" && t.text.includes("{")));
|
||||
});
|
||||
|
||||
test("every character of the source survives, verbatim", () => {
|
||||
const source = '{"a":1,"b":[true,null],"c":"x\\u0041"}';
|
||||
const tokens = tokenizeJson(source);
|
||||
assert.ok(tokens);
|
||||
assert.equal(tokens.map((t) => t.text).join(""), source);
|
||||
});
|
||||
|
||||
test("nested structures keep their punctuation", () => {
|
||||
const tokens = tokenizeJson('{"k":{"n":[1,2]}}');
|
||||
assert.ok(tokens);
|
||||
const open = tokens.filter((t) => t.kind === "punct" && t.text.includes("{"));
|
||||
assert.equal(open.length >= 1, true);
|
||||
});
|
||||
|
||||
test("a non-JSON payload yields null, and the caller renders it plain", () => {
|
||||
assert.equal(tokenizeJson("not json at all"), null);
|
||||
assert.equal(tokenizeJson(""), null);
|
||||
assert.equal(tokenizeJson("{broken"), null);
|
||||
});
|
||||
|
||||
test("an empty string is not JSON", () => {
|
||||
assert.equal(tokenizeJson(""), null);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { setupPanelState } = await import("../src/dashboard/setup-preference.ts");
|
||||
|
||||
import type { Setup } from "../src/dashboard/setup-preference.ts";
|
||||
|
||||
function setupWith(...done: boolean[]): Setup {
|
||||
return { steps: done.map((d, i) => ({ title: `step ${i}`, done: d })) };
|
||||
}
|
||||
type Setup = ReturnType<typeof setupWith>;
|
||||
|
||||
// The completed setup renders no panel: a configured daemon is the absence of
|
||||
// a problem, not a card announcing it. The state machine only distinguishes
|
||||
// "nothing to show" from "there is work left".
|
||||
test("no setup steps omits the panel", () => {
|
||||
assert.equal(setupPanelState(null).kind, "omit");
|
||||
assert.equal(setupPanelState(setupWith()).kind, "omit");
|
||||
});
|
||||
|
||||
test("remaining steps render the checklist", () => {
|
||||
const state = setupPanelState(setupWith(true, false, false));
|
||||
assert.equal(state.kind, "incomplete");
|
||||
assert.equal(state.remaining.length, 2);
|
||||
});
|
||||
|
||||
// The old contract celebrated completion with a "Setup complete" card the
|
||||
// operator had to dismiss. The celebration is gone: all steps done is omit.
|
||||
test("a fully completed setup omits the panel", () => {
|
||||
assert.equal(setupPanelState(setupWith(true, true)).kind, "omit");
|
||||
});
|
||||
|
||||
// If setup later becomes incomplete again, the checklist returns regardless
|
||||
// of anything the operator did while it was complete.
|
||||
test("the checklist returns when setup regresses", () => {
|
||||
const state = setupPanelState(setupWith(true, false));
|
||||
assert.equal(state.kind, "incomplete");
|
||||
assert.equal(state.remaining.length, 1);
|
||||
});
|
||||
+4
-3
@@ -24,10 +24,11 @@ export default defineConfig({
|
||||
server: {
|
||||
// Proxies the API to a locally running archie-ui (the process that serves
|
||||
// the dashboard) so the frontend can be developed without rebuilding Go.
|
||||
// changeOrigin stays false: archie-ui refuses a mutation whose Origin
|
||||
// does not match its Host, and the browser's Origin is this dev server.
|
||||
proxy: {
|
||||
"/api": "http://127.0.0.1:8484",
|
||||
"/health": "http://127.0.0.1:8484",
|
||||
"/events": { target: "http://127.0.0.1:8484", ws: true },
|
||||
"/api": { target: "http://127.0.0.1:8484", changeOrigin: false },
|
||||
"/health": { target: "http://127.0.0.1:8484", changeOrigin: false },
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user