Merge branch 'feat/tui-implementation'
This commit is contained in:
commit
f1ab948bb4
29 files changed
+11321
-8
No files matched your search
+11
@@ -1,3 +1,14 @@
|
|||||||
target/
|
target/
|
||||||
__pycache__/
|
__pycache__/
|
||||||
*.jsonl
|
*.jsonl
|
||||||
|
|
||||||
|
# Devenv
|
||||||
|
.devenv*
|
||||||
|
devenv.local.nix
|
||||||
|
devenv.local.yaml
|
||||||
|
|
||||||
|
# direnv
|
||||||
|
.direnv
|
||||||
|
|
||||||
|
# pre-commit
|
||||||
|
.pre-commit-config.yaml
|
||||||
Generated
+1693
-2
File diff suppressed because it is too large.
Load diff
+7
-1
@@ -7,7 +7,13 @@ description = "Orchestrator that runs many hx coding agents"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
crossterm = "0.29.0"
|
||||||
|
indexmap = { version = "2.14.2", features = ["serde"] }
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
|
quick-xml = "0.42.0"
|
||||||
|
ratatui = "0.30.2"
|
||||||
|
rusqlite = { version = "0.42.0", features = ["bundled"] }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
toml = "0.8"
|
toml = { version = "0.8", features = ["preserve_order"] }
|
||||||
|
unicode-width = "0.2"
|
||||||
@@ -44,6 +44,37 @@ kind = "cmd"
|
|||||||
command = "python3 /work/adapters/gitea.py"
|
command = "python3 /work/adapters/gitea.py"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## State-machine sessions and the TUI
|
||||||
|
|
||||||
|
`orch` without a subcommand opens the TUI: sessions overview (`enter` on a row opens the session detail, `esc` goes
|
||||||
|
back; `t` full test output, `d` diff, `l` event transcript, `o` open the worktree in hx). It reads `.hx/orch.db` of the
|
||||||
|
current directory. `orch session --repo . --machine task --name NAME [--profile P]` creates a session and runs it.
|
||||||
|
Machines are TOML files in `.hx/machines/` or `~/.hx/machines/` (examples in `examples/machines/`). A `computer` step
|
||||||
|
with `report = "junit"` writes its JUnit XML to `$ORCH_REPORT` (also available as `{{report}}` in `cmd`); orch parses
|
||||||
|
it into counts and failing tests. See ORCHESTRATOR.md for the whole design.
|
||||||
|
|
||||||
|
A running session can be steered from the session screen, also when `orch session` runs in another terminal: `i`
|
||||||
|
interrupt (the agent stops, you reply with a hint), `m` message to the agent, `s` force a state, `k` kill (type
|
||||||
|
`yes`; goes to `on_abort`), and `r` re-plan from the start state while the loop detector box shows (the last test
|
||||||
|
runs failed on the same tests). On the goal screen `j/k` selects a decision and `v` vetoes it: the agent is told and
|
||||||
|
the session goes back to `code`. The commands go through the database (`commands` table) and the runner picks them
|
||||||
|
up within a fraction of a second, even in the middle of a shell command. A machine can set limits:
|
||||||
|
|
||||||
|
[budget]
|
||||||
|
wall_secs = 5400 # time spent working, waiting for you does not count
|
||||||
|
cost = 5.0 # US dollars
|
||||||
|
compact_at = 85 # percent of the context window; hx gets `hx/compact`
|
||||||
|
|
||||||
|
Passing wall time or cost sends the session to `on_budget` (or fails it when the machine has none).
|
||||||
|
|
||||||
|
The goal lives in the same database: `orch goal "sentence"`, `orch check NAME CMD [--owner sN]` (an acceptance
|
||||||
|
check: pass = exit 0), `orch checks [--owner sN | --main]`. `g` in the TUI opens the goal view (task graph, critical
|
||||||
|
path, decisions, checks; `e` edit goal, `+` add check, `R` run all checks on main). `orch session --after s1,s2` makes
|
||||||
|
a session wait until those have merged. Only one session at a time runs the state that ends in `merged` (first come,
|
||||||
|
first served); after each merge all checks run again on main in a clean worktree. Machine steps get `ORCH_DB`,
|
||||||
|
`ORCH_REPO` and `ORCH_SESSION`, and `{{repo}}` in `cmd`; the example machines merge with
|
||||||
|
`git -C {{repo}} merge --ff-only {{branch}}` in `mark-merged`.
|
||||||
|
|
||||||
## More
|
## More
|
||||||
|
|
||||||
- [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema)
|
- [docs/cmd-protocol.md](docs/cmd-protocol.md): task sources and result sinks as external commands (+ JSON schema)
|
||||||
|
|||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"devenv": {
|
||||||
|
"locked": {
|
||||||
|
"dir": "src/modules",
|
||||||
|
"lastModified": 1794562632,
|
||||||
|
"narHash": "sha256-MOb8lrEUUki0Kxe+LNLuhj3DbPsjcurZWq3eG3R0Z9U=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"rev": "6c954cc1c04f1d0b2f6ad689c9dffd835fa4d928",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"dir": "src/modules",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs-src": "nixpkgs-src"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1793043970,
|
||||||
|
"narHash": "sha256-m14odYTdkBUEkJOiEYs2zjGjn8fcjvdCJsm45+k084U=",
|
||||||
|
"owner": "cachix",
|
||||||
|
"repo": "devenv-nixpkgs",
|
||||||
|
"rev": "d97234e58d4e90e3bf77c082fc3b546e51200938",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "cachix",
|
||||||
|
"ref": "rolling",
|
||||||
|
"repo": "devenv-nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs-src": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1792812153,
|
||||||
|
"narHash": "sha256-T2+XBfNbf9pecLUWS4+RtuVNZ3W8K5taG5QdV71mWlk=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "674a2028661e550a97400c1cc992b9cca9a668a1",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixpkgs-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"devenv": "devenv",
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
pkgs,
|
||||||
|
lib,
|
||||||
|
config,
|
||||||
|
inputs,
|
||||||
|
...
|
||||||
|
}:
|
||||||
|
|
||||||
|
{
|
||||||
|
packages = with pkgs; [
|
||||||
|
sqlite
|
||||||
|
];
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
# yaml-language-server: $schema=https://devenv.sh/devenv.schema.json
|
||||||
|
inputs:
|
||||||
|
nixpkgs:
|
||||||
|
url: github:cachix/devenv-nixpkgs/rolling
|
||||||
|
|
||||||
|
# If you're using non-OSS software, you can set allow_unfree to true.
|
||||||
|
# allow_unfree: true
|
||||||
|
|
||||||
|
# If you're not willing to allow unsupported packages:
|
||||||
|
# allow_unsupported_system: false
|
||||||
|
|
||||||
|
# If you're willing to use a package that's vulnerable
|
||||||
|
# permitted_insecure_packages:
|
||||||
|
# - "openssl-1.1.1w"
|
||||||
|
|
||||||
|
# If you have more than one devenv you can merge them
|
||||||
|
#imports:
|
||||||
|
# - ./backend
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
name = "docs"
|
||||||
|
on_abort = "aborted"
|
||||||
|
on_budget = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "plan"
|
||||||
|
kind = "start"
|
||||||
|
steps = [ { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" } ]
|
||||||
|
catch = { PlanInvalid = "plan" }
|
||||||
|
next = "write"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "write"
|
||||||
|
steps = [ { name = "write", run = "agent", sets = "writing", prompt = "implement" } ]
|
||||||
|
catch = { ToolDenied = "review" }
|
||||||
|
next = "lint"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "lint"
|
||||||
|
steps = [ { name = "markdownlint", run = "computer", sets = "linting", cmd = "markdownlint ." } ]
|
||||||
|
catch = { LintFailed = "write" }
|
||||||
|
next = "links"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "links"
|
||||||
|
steps = [ { name = "check links", run = "computer", sets = "checking links", cmd = "lychee --offline ." } ]
|
||||||
|
catch = { LinksBroken = "write" }
|
||||||
|
retry = { LinksBroken = { max = 3, then = "escalated" } }
|
||||||
|
next = "review"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "review"
|
||||||
|
kind = "gate"
|
||||||
|
steps = [
|
||||||
|
{ name = "open-diff", run = "computer" },
|
||||||
|
{ name = "wait-approval", run = "human", sets = "waiting" },
|
||||||
|
]
|
||||||
|
catch = { ChangesRequested = "write" }
|
||||||
|
next = "merge"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "merge"
|
||||||
|
kind = "exit"
|
||||||
|
steps = [
|
||||||
|
{ name = "rebase-main", run = "computer", cmd = "git rebase main" },
|
||||||
|
{ name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" },
|
||||||
|
]
|
||||||
|
catch = { RebaseConflict = "write" }
|
||||||
|
end = "merged"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "escalated"
|
||||||
|
kind = "exit"
|
||||||
|
only_on = ["LinksBroken x3", "budget"]
|
||||||
|
steps = [
|
||||||
|
{ name = "snapshot-worktree", run = "computer" },
|
||||||
|
{ name = "notify", run = "computer", sets = "needs you" },
|
||||||
|
]
|
||||||
|
end = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "aborted"
|
||||||
|
kind = "abort"
|
||||||
|
only_on = ["abort"]
|
||||||
|
steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ]
|
||||||
|
end = "aborted"
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
name = "e2e"
|
||||||
|
on_abort = "aborted"
|
||||||
|
on_budget = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "plan"
|
||||||
|
kind = "start"
|
||||||
|
steps = [ { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" } ]
|
||||||
|
catch = { PlanInvalid = "plan" }
|
||||||
|
next = "code"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "code"
|
||||||
|
steps = [ { name = "edit", run = "agent", sets = "coding", prompt = "implement" } ]
|
||||||
|
catch = { ToolDenied = "review" }
|
||||||
|
next = "stack-up"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "stack-up"
|
||||||
|
steps = [ { name = "compose up", run = "computer", sets = "starting stack", cmd = "docker compose up -d --wait" } ]
|
||||||
|
catch = { StackFailed = "code" }
|
||||||
|
next = "e2e"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "e2e"
|
||||||
|
steps = [ { name = "cargo test e2e", run = "computer", sets = "testing", cmd = "cargo test --test e2e {{scope}}", report = "junit" } ]
|
||||||
|
catch = { TestsFailed = "stack-down" }
|
||||||
|
retry = { TestsFailed = { max = 3, then = "escalated" } }
|
||||||
|
next = "stack-down"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "stack-down"
|
||||||
|
steps = [ { name = "compose down", run = "computer", sets = "stopping stack", cmd = "docker compose down -v" } ]
|
||||||
|
catch = { TeardownFailed = "escalated" }
|
||||||
|
next = "review"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "review"
|
||||||
|
kind = "gate"
|
||||||
|
steps = [
|
||||||
|
{ name = "open-diff", run = "computer" },
|
||||||
|
{ name = "wait-approval", run = "human", sets = "waiting" },
|
||||||
|
]
|
||||||
|
catch = { ChangesRequested = "code" }
|
||||||
|
next = "merge"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "merge"
|
||||||
|
kind = "exit"
|
||||||
|
steps = [
|
||||||
|
{ name = "rebase-main", run = "computer", cmd = "git rebase main" },
|
||||||
|
{ name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" },
|
||||||
|
{ name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" },
|
||||||
|
]
|
||||||
|
catch = { RebaseConflict = "code" }
|
||||||
|
end = "merged"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "escalated"
|
||||||
|
kind = "exit"
|
||||||
|
only_on = ["TestsFailed x3", "budget"]
|
||||||
|
steps = [
|
||||||
|
{ name = "snapshot-worktree", run = "computer" },
|
||||||
|
{ name = "notify", run = "computer", sets = "needs you" },
|
||||||
|
]
|
||||||
|
end = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "aborted"
|
||||||
|
kind = "abort"
|
||||||
|
only_on = ["abort"]
|
||||||
|
steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ]
|
||||||
|
end = "aborted"
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
name = "migration"
|
||||||
|
on_abort = "aborted"
|
||||||
|
on_budget = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "plan"
|
||||||
|
kind = "start"
|
||||||
|
steps = [ { name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" } ]
|
||||||
|
catch = { PlanInvalid = "plan" }
|
||||||
|
next = "code"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "code"
|
||||||
|
steps = [ { name = "edit", run = "agent", sets = "coding", prompt = "implement" } ]
|
||||||
|
catch = { ToolDenied = "review" }
|
||||||
|
next = "up"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "up"
|
||||||
|
steps = [ { name = "migrate up", run = "computer", sets = "migrating", cmd = "sqlx migrate run" } ]
|
||||||
|
catch = { MigrationFailed = "code" }
|
||||||
|
next = "down"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "down"
|
||||||
|
steps = [ { name = "migrate down", run = "computer", sets = "reverting", cmd = "sqlx migrate revert" } ]
|
||||||
|
catch = { RevertFailed = "code" }
|
||||||
|
next = "test"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "test"
|
||||||
|
steps = [
|
||||||
|
{ name = "migrate up again", run = "computer", cmd = "sqlx migrate run" },
|
||||||
|
{ name = "cargo test", run = "computer", sets = "testing", cmd = "cargo test {{scope}}", report = "junit" },
|
||||||
|
]
|
||||||
|
catch = { TestsFailed = "code" }
|
||||||
|
retry = { TestsFailed = { max = 3, then = "escalated" } }
|
||||||
|
next = "review"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "review"
|
||||||
|
kind = "gate"
|
||||||
|
steps = [
|
||||||
|
{ name = "open-diff", run = "computer" },
|
||||||
|
{ name = "wait-approval", run = "human", sets = "waiting" },
|
||||||
|
]
|
||||||
|
catch = { ChangesRequested = "code" }
|
||||||
|
next = "merge"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "merge"
|
||||||
|
kind = "exit"
|
||||||
|
steps = [
|
||||||
|
{ name = "rebase-main", run = "computer", cmd = "git rebase main" },
|
||||||
|
{ name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" },
|
||||||
|
{ name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" },
|
||||||
|
]
|
||||||
|
catch = { RebaseConflict = "code" }
|
||||||
|
end = "merged"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "escalated"
|
||||||
|
kind = "exit"
|
||||||
|
only_on = ["TestsFailed x3", "budget"]
|
||||||
|
steps = [
|
||||||
|
{ name = "snapshot-worktree", run = "computer" },
|
||||||
|
{ name = "notify", run = "computer", sets = "needs you" },
|
||||||
|
]
|
||||||
|
end = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "aborted"
|
||||||
|
kind = "abort"
|
||||||
|
only_on = ["abort"]
|
||||||
|
steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ]
|
||||||
|
end = "aborted"
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
name = "task"
|
||||||
|
on_abort = "aborted"
|
||||||
|
on_budget = "escalated"
|
||||||
|
|
||||||
|
[budget]
|
||||||
|
wall_secs = 5400 # 90 min of work, not counting time spent waiting for you
|
||||||
|
cost = 5.0 # US dollars
|
||||||
|
compact_at = 85 # percent of the context window
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "plan"
|
||||||
|
kind = "start"
|
||||||
|
steps = [
|
||||||
|
{ name = "read-goal", run = "computer", cmd = "orch goal --export" },
|
||||||
|
{ name = "draft-plan", run = "agent", sets = "planning", prompt = "plan" },
|
||||||
|
]
|
||||||
|
catch = { PlanInvalid = "plan" }
|
||||||
|
next = "code"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "code"
|
||||||
|
steps = [ { name = "edit", run = "agent", sets = "coding", prompt = "implement" } ]
|
||||||
|
# ORCHESTRATOR.md maps ToolDenied to a "waiting" state that the file never defines; review is the human gate.
|
||||||
|
catch = { ToolDenied = "review" }
|
||||||
|
next = "build"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "build"
|
||||||
|
steps = [ { name = "cargo build", run = "computer", sets = "building", cmd = "cargo build" } ]
|
||||||
|
catch = { BuildFailed = "code" }
|
||||||
|
next = "test"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "test"
|
||||||
|
steps = [ { name = "cargo test", run = "computer", sets = "testing", cmd = "cargo test {{scope}}", report = "junit" } ]
|
||||||
|
catch = { TestsFailed = "code" }
|
||||||
|
retry = { TestsFailed = { max = 3, then = "escalated" } }
|
||||||
|
next = "review"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "review"
|
||||||
|
kind = "gate"
|
||||||
|
steps = [
|
||||||
|
{ name = "open-diff", run = "computer" },
|
||||||
|
{ name = "wait-approval", run = "human", sets = "waiting" },
|
||||||
|
]
|
||||||
|
catch = { ChangesRequested = "code" }
|
||||||
|
next = "merge"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "merge"
|
||||||
|
kind = "exit"
|
||||||
|
steps = [
|
||||||
|
{ name = "rebase-main", run = "computer", cmd = "git rebase main" },
|
||||||
|
{ name = "run-acceptance", run = "computer", cmd = "orch checks --owner {{session}}" },
|
||||||
|
{ name = "mark-merged", run = "computer", sets = "merged", cmd = "git -C {{repo}} merge --ff-only {{branch}}" },
|
||||||
|
]
|
||||||
|
catch = { RebaseConflict = "code" }
|
||||||
|
end = "merged"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "escalated"
|
||||||
|
kind = "exit"
|
||||||
|
only_on = ["TestsFailed x3", "budget"]
|
||||||
|
steps = [
|
||||||
|
{ name = "snapshot-worktree", run = "computer" },
|
||||||
|
{ name = "notify", run = "computer", sets = "needs you" },
|
||||||
|
]
|
||||||
|
end = "escalated"
|
||||||
|
|
||||||
|
[[state]]
|
||||||
|
name = "aborted"
|
||||||
|
kind = "abort"
|
||||||
|
only_on = ["abort"]
|
||||||
|
steps = [ { name = "remove-worktree", run = "computer", sets = "aborted" } ]
|
||||||
|
end = "aborted"
|
||||||
+257
@@ -0,0 +1,257 @@
|
|||||||
|
//! ACP client (ORCHESTRATOR.md section 5): JSON-RPC 2.0, one JSON object per line, over the stdio of
|
||||||
|
//! `hx serve --acp`. Standard ACP messages (`initialize`, `session/new`, `session/update`,
|
||||||
|
//! `session/request_permission`) plus the custom `hx/*` messages. `hx/step` is acknowledged at once; the
|
||||||
|
//! outcome arrives later as the `hx/step_result` notification.
|
||||||
|
|
||||||
|
use crate::profile::Profile;
|
||||||
|
use crate::run::hx_env;
|
||||||
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use std::io::{BufRead, Write};
|
||||||
|
use std::os::unix::process::CommandExt;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||||
|
use std::sync::mpsc;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
/// Receives what hx reports while a step runs.
|
||||||
|
pub trait Sink {
|
||||||
|
/// Notifications: `hx/intent`, `hx/edit`, `hx/usage`, `hx/decision`, `hx/plan`, `session/update`.
|
||||||
|
fn notify(&mut self, method: &str, params: &Value) -> Result<()>;
|
||||||
|
/// `session/request_permission`: returns the chosen `optionId`, or None to cancel the request.
|
||||||
|
fn permission(&mut self, params: &Value) -> Option<String>;
|
||||||
|
/// Called about every 100 ms while a step runs: what the user or the budgets want hx to be told.
|
||||||
|
fn poll(&mut self) -> Poll {
|
||||||
|
Poll::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What to send to a running step.
|
||||||
|
#[derive(Default, Debug, PartialEq)]
|
||||||
|
pub struct Poll {
|
||||||
|
/// User hints, sent as `hx/message`.
|
||||||
|
pub messages: Vec<String>,
|
||||||
|
/// `hx/interrupt`: finish the current tool call, then stop (the step result still arrives).
|
||||||
|
pub interrupt: bool,
|
||||||
|
/// `hx/compact`: compact the context now.
|
||||||
|
pub compact: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
const POLL_EVERY: Duration = Duration::from_millis(100);
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub struct StepResult {
|
||||||
|
/// done | blocked | needs_input
|
||||||
|
pub status: String,
|
||||||
|
pub catch: Option<String>,
|
||||||
|
/// Why a step is `blocked` without a catch; `"limit"` means hx hit a limit passed in `hx/step`.
|
||||||
|
pub reason: Option<String>,
|
||||||
|
pub question: Option<String>,
|
||||||
|
pub summary: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Acp {
|
||||||
|
child: Child,
|
||||||
|
stdin: ChildStdin,
|
||||||
|
rx: mpsc::Receiver<Value>,
|
||||||
|
next_id: u64,
|
||||||
|
session: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Acp {
|
||||||
|
/// Starts `hx serve --acp --cwd <worktree> --session <id>` and opens an ACP session.
|
||||||
|
pub fn spawn(p: &Profile, worktree: &Path, id: &str) -> Result<Self> {
|
||||||
|
let mut parts = p.hx.split_whitespace();
|
||||||
|
let mut cmd = Command::new(parts.next().context("empty hx command")?);
|
||||||
|
cmd.args(parts)
|
||||||
|
.args(["serve", "--acp", "--cwd"])
|
||||||
|
.arg(worktree)
|
||||||
|
.args(["--session", id]);
|
||||||
|
// same cleared environment as the batch runner: orch's secrets never reach the agent
|
||||||
|
cmd.env_clear().envs(hx_env(std::env::vars(), p));
|
||||||
|
if let Some(h) = &p.home {
|
||||||
|
cmd.env("HOME", h);
|
||||||
|
}
|
||||||
|
let log = std::fs::File::create(format!("{}.agent.log", worktree.display()))?;
|
||||||
|
let mut child = cmd
|
||||||
|
.current_dir(worktree)
|
||||||
|
.stdin(Stdio::piped())
|
||||||
|
.stdout(Stdio::piped())
|
||||||
|
.stderr(Stdio::from(log))
|
||||||
|
.process_group(0) // own group: kill takes hx and its tool children together
|
||||||
|
.spawn()
|
||||||
|
.with_context(|| format!("spawn {}", p.hx))?;
|
||||||
|
let stdin = child.stdin.take().expect("piped");
|
||||||
|
let out = child.stdout.take().expect("piped");
|
||||||
|
let (tx, rx) = mpsc::channel();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
for l in std::io::BufReader::new(out).lines().map_while(Result::ok) {
|
||||||
|
if let Ok(v) = serde_json::from_str::<Value>(&l)
|
||||||
|
&& tx.send(v).is_err()
|
||||||
|
{
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let mut a = Self {
|
||||||
|
child,
|
||||||
|
stdin,
|
||||||
|
rx,
|
||||||
|
next_id: 1,
|
||||||
|
session: String::new(),
|
||||||
|
};
|
||||||
|
a.request(
|
||||||
|
"initialize",
|
||||||
|
json!({"protocolVersion": 1, "clientCapabilities": {}}),
|
||||||
|
)?;
|
||||||
|
let new = a.request("session/new", json!({"cwd": worktree, "mcpServers": []}))?;
|
||||||
|
a.session = new["sessionId"].as_str().unwrap_or(id).to_string();
|
||||||
|
Ok(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&mut self, v: Value) -> Result<()> {
|
||||||
|
let mut line = v.to_string();
|
||||||
|
line.push('\n');
|
||||||
|
self.stdin
|
||||||
|
.write_all(line.as_bytes())
|
||||||
|
.and_then(|()| self.stdin.flush())
|
||||||
|
.context("write to hx (did it exit?)")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends a request and returns its result. Only used for the handshake, before any step runs, so
|
||||||
|
/// nothing hx sends in between has a sink to go to and is dropped.
|
||||||
|
fn request(&mut self, method: &str, params: Value) -> Result<Value> {
|
||||||
|
let id = self.next_id;
|
||||||
|
self.next_id += 1;
|
||||||
|
self.send(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}))?;
|
||||||
|
loop {
|
||||||
|
let m = self.recv()?;
|
||||||
|
if m.get("method").is_none() && m["id"] == json!(id) {
|
||||||
|
if let Some(e) = m.get("error") {
|
||||||
|
bail!("hx {method}: {}", e["message"].as_str().unwrap_or("error"));
|
||||||
|
}
|
||||||
|
return Ok(m["result"].clone());
|
||||||
|
}
|
||||||
|
self.dispatch(&m, None)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn recv(&mut self) -> Result<Value> {
|
||||||
|
self.rx
|
||||||
|
.recv()
|
||||||
|
.map_err(|_| anyhow!("hx closed its output (exited or crashed)"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles one message that is not the response we wait for. Returns a step result if it was one.
|
||||||
|
fn dispatch(&mut self, m: &Value, sink: Option<&mut dyn Sink>) -> Result<Option<StepResult>> {
|
||||||
|
let Some(method) = m["method"].as_str() else {
|
||||||
|
return Ok(None); // a late response (e.g. the ack of hx/step)
|
||||||
|
};
|
||||||
|
// ACP reserves a leading `_` for custom methods: `_hx/intent` is the same as `hx/intent`
|
||||||
|
let method = method
|
||||||
|
.strip_prefix('_')
|
||||||
|
.filter(|r| r.starts_with("hx/"))
|
||||||
|
.unwrap_or(method);
|
||||||
|
let params = &m["params"];
|
||||||
|
if m.get("id").is_some() {
|
||||||
|
// a request from hx
|
||||||
|
let reply = if method == "session/request_permission" {
|
||||||
|
let chosen = sink.and_then(|s| s.permission(params));
|
||||||
|
let outcome = match chosen {
|
||||||
|
Some(o) => json!({"outcome": "selected", "optionId": o}),
|
||||||
|
None => json!({"outcome": "cancelled"}),
|
||||||
|
};
|
||||||
|
json!({"jsonrpc": "2.0", "id": m["id"], "result": {"outcome": outcome}})
|
||||||
|
} else {
|
||||||
|
json!({"jsonrpc": "2.0", "id": m["id"], "error": {"code": -32601, "message": format!("unsupported: {method}")}})
|
||||||
|
};
|
||||||
|
self.send(reply)?;
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
if method == "hx/step_result" {
|
||||||
|
let s = |k: &str| params[k].as_str().map(String::from);
|
||||||
|
return Ok(Some(StepResult {
|
||||||
|
status: s("status").unwrap_or_default(),
|
||||||
|
catch: s("catch"),
|
||||||
|
reason: s("reason"),
|
||||||
|
question: s("question"),
|
||||||
|
summary: s("summary").unwrap_or_default(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
if let Some(s) = sink {
|
||||||
|
s.notify(method, params)?;
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs one agent step and waits for its `hx/step_result`.
|
||||||
|
pub fn step(
|
||||||
|
&mut self,
|
||||||
|
prompt: &str,
|
||||||
|
instruction: &str,
|
||||||
|
context: Value,
|
||||||
|
limits: Value,
|
||||||
|
sink: &mut dyn Sink,
|
||||||
|
) -> Result<StepResult> {
|
||||||
|
let id = self.next_id;
|
||||||
|
self.next_id += 1;
|
||||||
|
self.send(
|
||||||
|
json!({"jsonrpc": "2.0", "id": id, "method": "hx/step", "params": {
|
||||||
|
"sessionId": self.session, "prompt": prompt, "instruction": instruction,
|
||||||
|
"context": context, "limits": limits,
|
||||||
|
}}),
|
||||||
|
)?;
|
||||||
|
let mut last_poll = Instant::now();
|
||||||
|
let mut interrupted = false;
|
||||||
|
loop {
|
||||||
|
// poll on a timer, also while hx streams without a pause (a recv timeout alone would starve it)
|
||||||
|
if last_poll.elapsed() >= POLL_EVERY {
|
||||||
|
last_poll = Instant::now();
|
||||||
|
let p = sink.poll();
|
||||||
|
for text in p.messages {
|
||||||
|
self.notify(
|
||||||
|
"hx/message",
|
||||||
|
json!({"sessionId": self.session, "text": text}),
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
if p.interrupt && !interrupted {
|
||||||
|
interrupted = true;
|
||||||
|
self.notify("hx/interrupt", json!({"sessionId": self.session}))?;
|
||||||
|
}
|
||||||
|
if p.compact {
|
||||||
|
self.notify("hx/compact", json!({"sessionId": self.session}))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let m = match self.rx.recv_timeout(POLL_EVERY) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(mpsc::RecvTimeoutError::Timeout) => continue,
|
||||||
|
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||||
|
bail!("hx closed its output (exited or crashed)")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if m.get("method").is_none() && m["id"] == json!(id) {
|
||||||
|
if let Some(e) = m.get("error") {
|
||||||
|
bail!(
|
||||||
|
"hx/step rejected: {}",
|
||||||
|
e["message"].as_str().unwrap_or("error")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
continue; // the ack
|
||||||
|
}
|
||||||
|
if let Some(r) = self.dispatch(&m, Some(&mut *sink))? {
|
||||||
|
return Ok(r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn notify(&mut self, method: &str, params: Value) -> Result<()> {
|
||||||
|
self.send(json!({"jsonrpc": "2.0", "method": method, "params": params}))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Acp {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
crate::state::kill_group(self.child.id());
|
||||||
|
let _ = self.child.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
+292
@@ -0,0 +1,292 @@
|
|||||||
|
//! Budgets and the loop detector (ORCHESTRATOR.md section 4), as pure functions over a session's events.
|
||||||
|
//! The runner uses them to stop a session; the session screen uses them to show how close it is.
|
||||||
|
|
||||||
|
use crate::db::Event;
|
||||||
|
use crate::machine::BudgetCfg;
|
||||||
|
use std::collections::{BTreeSet, HashMap};
|
||||||
|
|
||||||
|
/// Seconds the session spent working: from its first event to its end (or now), minus the time it sat in the
|
||||||
|
/// Needs-you queue. Waiting for you must not eat the wall-time budget.
|
||||||
|
pub fn active_secs(evs: &[&Event], now_ms: u64) -> u64 {
|
||||||
|
// work starts with the first state; time blocked on dependencies before that is not work
|
||||||
|
let Some(first) = evs.iter().find(|e| e.kind == "state") else {
|
||||||
|
return 0;
|
||||||
|
};
|
||||||
|
let end = match evs.last() {
|
||||||
|
Some(e) if e.kind == "end" => e.at,
|
||||||
|
_ => now_ms,
|
||||||
|
};
|
||||||
|
let mut open: HashMap<i64, u64> = HashMap::new(); // need id -> when it was put in the queue
|
||||||
|
let mut waited = 0;
|
||||||
|
for e in evs {
|
||||||
|
let id = e.payload["id"].as_i64().unwrap_or(-1);
|
||||||
|
match e.kind.as_str() {
|
||||||
|
"need" => {
|
||||||
|
open.insert(id, e.at);
|
||||||
|
}
|
||||||
|
"answer" => {
|
||||||
|
if let Some(at) = open.remove(&id) {
|
||||||
|
waited += e.at.saturating_sub(at);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
waited += open.values().map(|at| end.saturating_sub(*at)).sum::<u64>();
|
||||||
|
end.saturating_sub(first.at).saturating_sub(waited) / 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cost so far: the last `usage` event carries the running total.
|
||||||
|
pub fn cost(evs: &[&Event]) -> f64 {
|
||||||
|
evs.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|e| e.kind == "usage")
|
||||||
|
.and_then(|e| e.payload["cost"].as_f64())
|
||||||
|
.unwrap_or(0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Context window use in percent, from the last `usage` event.
|
||||||
|
pub fn ctx_pct(evs: &[&Event]) -> Option<u8> {
|
||||||
|
let e = evs.iter().rev().find(|e| e.kind == "usage")?;
|
||||||
|
let (used, limit) = (
|
||||||
|
e.payload["ctx_used"].as_u64()?,
|
||||||
|
e.payload["ctx_limit"].as_u64()?,
|
||||||
|
);
|
||||||
|
Some((used * 100).checked_div(limit)?.min(100) as u8)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub struct Exceeded {
|
||||||
|
pub what: &'static str,
|
||||||
|
pub used: String,
|
||||||
|
pub limit: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn exceeded(evs: &[&Event], cfg: &BudgetCfg, now_ms: u64) -> Option<Exceeded> {
|
||||||
|
if let Some(limit) = cfg.wall_secs {
|
||||||
|
let used = active_secs(evs, now_ms);
|
||||||
|
if used > limit {
|
||||||
|
return Some(Exceeded {
|
||||||
|
what: "wall time",
|
||||||
|
used: format!("{}m", used / 60),
|
||||||
|
limit: format!("{}m", limit / 60),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(limit) = cfg.cost {
|
||||||
|
let used = cost(evs);
|
||||||
|
if used > limit {
|
||||||
|
return Some(Exceeded {
|
||||||
|
what: "cost",
|
||||||
|
used: format!("${used:.2}"),
|
||||||
|
limit: format!("${limit:.2}"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub struct LoopInfo {
|
||||||
|
/// Test runs in a row that failed on exactly the same tests.
|
||||||
|
pub runs: usize,
|
||||||
|
/// How many tests that is.
|
||||||
|
pub tests: usize,
|
||||||
|
/// The file the agent edited most since the loop began.
|
||||||
|
pub file: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failing(e: &Event) -> BTreeSet<String> {
|
||||||
|
e.payload["failures"]
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.filter_map(|f| f["name"].as_str().map(String::from))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After a failed test run: do the last runs fail on the same set of tests? Two in a row is a loop (the agent
|
||||||
|
/// tried a fix and got the same failures), a run that passes or fails differently ends it.
|
||||||
|
pub fn looping(evs: &[&Event]) -> Option<LoopInfo> {
|
||||||
|
let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect();
|
||||||
|
let last = failing(runs.last()?);
|
||||||
|
if last.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let n = runs.iter().rev().take_while(|r| failing(r) == last).count();
|
||||||
|
if n < 2 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let since = runs[runs.len() - n].id;
|
||||||
|
let mut edits: HashMap<&str, u64> = HashMap::new();
|
||||||
|
for e in evs.iter().filter(|e| e.kind == "edit" && e.id > since) {
|
||||||
|
let touched =
|
||||||
|
e.payload["added"].as_u64().unwrap_or(0) + e.payload["removed"].as_u64().unwrap_or(0);
|
||||||
|
*edits
|
||||||
|
.entry(e.payload["path"].as_str().unwrap_or_default())
|
||||||
|
.or_default() += touched.max(1);
|
||||||
|
}
|
||||||
|
let file = edits
|
||||||
|
.into_iter()
|
||||||
|
.max_by(|a, b| a.1.cmp(&b.1).then(b.0.cmp(a.0)))
|
||||||
|
.map(|(p, _)| p.to_string());
|
||||||
|
Some(LoopInfo {
|
||||||
|
runs: n,
|
||||||
|
tests: last.len(),
|
||||||
|
file,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn ev(id: i64, at: u64, kind: &str, payload: serde_json::Value) -> Event {
|
||||||
|
Event {
|
||||||
|
id,
|
||||||
|
session: "s1".into(),
|
||||||
|
at,
|
||||||
|
kind: kind.into(),
|
||||||
|
payload,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refs(v: &[Event]) -> Vec<&Event> {
|
||||||
|
v.iter().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_run(id: i64, names: &[&str]) -> Event {
|
||||||
|
let f: Vec<_> = names.iter().map(|n| json!({"name": n})).collect();
|
||||||
|
ev(
|
||||||
|
id,
|
||||||
|
id as u64 * 1000,
|
||||||
|
"test",
|
||||||
|
json!({"passed": 3, "failed": names.len(), "failures": f}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn time_in_the_queue_does_not_count_as_work() {
|
||||||
|
let evs = [
|
||||||
|
ev(1, 0, "state", json!({})),
|
||||||
|
ev(2, 60_000, "need", json!({"id": 5})),
|
||||||
|
ev(3, 660_000, "answer", json!({"id": 5})), // waited ten minutes
|
||||||
|
ev(4, 720_000, "step", json!({})),
|
||||||
|
];
|
||||||
|
assert_eq!(active_secs(&refs(&evs), 720_000), 120);
|
||||||
|
// still waiting: the open item counts as waiting until now
|
||||||
|
assert_eq!(active_secs(&refs(&evs[..2]), 3_600_000), 60);
|
||||||
|
// a finished session stops at its end, not at now
|
||||||
|
let done = [
|
||||||
|
ev(1, 0, "state", json!({})),
|
||||||
|
ev(2, 30_000, "end", json!({})),
|
||||||
|
];
|
||||||
|
assert_eq!(active_secs(&refs(&done), 9_999_999), 30);
|
||||||
|
assert_eq!(active_secs(&[], 5), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn limits_trip_on_time_and_cost() {
|
||||||
|
let evs = [
|
||||||
|
ev(1, 0, "state", json!({})),
|
||||||
|
ev(
|
||||||
|
2,
|
||||||
|
10_000,
|
||||||
|
"usage",
|
||||||
|
json!({"cost": 5.25, "ctx_used": 142, "ctx_limit": 200}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let r = refs(&evs);
|
||||||
|
assert_eq!(cost(&r), 5.25);
|
||||||
|
assert_eq!(ctx_pct(&r), Some(71));
|
||||||
|
let none = BudgetCfg::default();
|
||||||
|
assert_eq!(
|
||||||
|
exceeded(&r, &none, 999_999_999),
|
||||||
|
None,
|
||||||
|
"no limits, no budget stop"
|
||||||
|
);
|
||||||
|
let cost_cap = BudgetCfg {
|
||||||
|
cost: Some(5.0),
|
||||||
|
..none.clone()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
exceeded(&r, &cost_cap, 0),
|
||||||
|
Some(Exceeded {
|
||||||
|
what: "cost",
|
||||||
|
used: "$5.25".into(),
|
||||||
|
limit: "$5.00".into()
|
||||||
|
})
|
||||||
|
);
|
||||||
|
let wall = BudgetCfg {
|
||||||
|
wall_secs: Some(60),
|
||||||
|
..none
|
||||||
|
};
|
||||||
|
assert_eq!(exceeded(&r, &wall, 30_000), None);
|
||||||
|
let e = exceeded(&r, &wall, 600_000).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(e.what, e.used.as_str(), e.limit.as_str()),
|
||||||
|
("wall time", "10m", "1m")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn same_failing_tests_twice_is_a_loop() {
|
||||||
|
let evs = [
|
||||||
|
ev(
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/old.rs", "added": 50, "removed": 0}),
|
||||||
|
), // before the first of the identical runs: not part of the loop
|
||||||
|
test_run(1, &["a::x", "a::y"]),
|
||||||
|
test_run(3, &["a::y", "a::x"]),
|
||||||
|
ev(
|
||||||
|
4,
|
||||||
|
4000,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/token.rs", "added": 6, "removed": 2}),
|
||||||
|
),
|
||||||
|
ev(
|
||||||
|
5,
|
||||||
|
5000,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/token.rs", "added": 1, "removed": 1}),
|
||||||
|
),
|
||||||
|
ev(
|
||||||
|
6,
|
||||||
|
6000,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/mod.rs", "added": 1, "removed": 0}),
|
||||||
|
),
|
||||||
|
test_run(7, &["a::x", "a::y"]),
|
||||||
|
];
|
||||||
|
let l = looping(&refs(&evs)).expect("loop");
|
||||||
|
assert_eq!((l.runs, l.tests), (3, 2));
|
||||||
|
assert_eq!(
|
||||||
|
l.file.as_deref(),
|
||||||
|
Some("src/token.rs"),
|
||||||
|
"edits before the loop do not count"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn different_or_fixed_failures_are_no_loop() {
|
||||||
|
// fix 1 changed which tests fail: progress, not a loop
|
||||||
|
let evs = [test_run(1, &["a::x", "a::y"]), test_run(2, &["a::x"])];
|
||||||
|
assert_eq!(looping(&refs(&evs)), None);
|
||||||
|
// the last run passed
|
||||||
|
let evs = [
|
||||||
|
test_run(1, &["a::x"]),
|
||||||
|
test_run(2, &["a::x"]),
|
||||||
|
test_run(3, &[]),
|
||||||
|
];
|
||||||
|
assert_eq!(looping(&refs(&evs)), None);
|
||||||
|
// only one run so far
|
||||||
|
assert_eq!(looping(&refs(&[test_run(1, &["a::x"])])), None);
|
||||||
|
assert_eq!(looping(&[]), None);
|
||||||
|
// a loop without edits has no file to blame
|
||||||
|
let evs = [test_run(1, &["a::x"]), test_run(2, &["a::x"])];
|
||||||
|
assert_eq!(looping(&refs(&evs)).unwrap().file, None);
|
||||||
|
}
|
||||||
|
}
|
||||||
+159
@@ -0,0 +1,159 @@
|
|||||||
|
//! Acceptance checks (ORCHESTRATOR.md section 2): shell commands, pass = exit 0. A goal is done when every
|
||||||
|
//! check is green on main, so results on main are what the goal view shows; a session can also run its own
|
||||||
|
//! checks on its branch before merging (`run-acceptance` step) without touching the recorded result.
|
||||||
|
|
||||||
|
use crate::db::{CheckRow, Db};
|
||||||
|
use crate::run::{git, tail};
|
||||||
|
use anyhow::Result;
|
||||||
|
use serde_json::json;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::process::Command;
|
||||||
|
|
||||||
|
/// Pseudo session id for goal-level events (check results on main).
|
||||||
|
pub const GOAL: &str = "goal";
|
||||||
|
|
||||||
|
pub struct Outcome {
|
||||||
|
pub check: CheckRow,
|
||||||
|
pub pass: bool,
|
||||||
|
pub exit: Option<i32>,
|
||||||
|
pub output: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the checks in `dir`. `owner` limits to one session's checks. `record` stores the result as the check's
|
||||||
|
/// status on main; it is only for runs that really are on main.
|
||||||
|
pub fn run(db: &Db, dir: &Path, owner: Option<&str>, record: bool) -> Result<Vec<Outcome>> {
|
||||||
|
let mut out = vec![];
|
||||||
|
for c in db.checks()? {
|
||||||
|
if owner.is_some() && c.owner.as_deref() != owner {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let o = Command::new("sh")
|
||||||
|
.args(["-c", &format!("({}) 2>&1", c.cmd)])
|
||||||
|
.current_dir(dir)
|
||||||
|
.output()?;
|
||||||
|
let (pass, exit) = (o.status.success(), o.status.code());
|
||||||
|
let output = tail(&o.stdout, 2000);
|
||||||
|
if record {
|
||||||
|
db.set_check_result(c.id, pass)?;
|
||||||
|
}
|
||||||
|
let session = owner.unwrap_or(GOAL);
|
||||||
|
db.emit(
|
||||||
|
session,
|
||||||
|
"check",
|
||||||
|
json!({
|
||||||
|
"name": c.name, "pass": pass, "exit": exit,
|
||||||
|
"where": if record { "main" } else { "branch" },
|
||||||
|
"output": if pass { String::new() } else { output.clone() },
|
||||||
|
}),
|
||||||
|
)?;
|
||||||
|
out.push(Outcome {
|
||||||
|
check: c,
|
||||||
|
pass,
|
||||||
|
exit,
|
||||||
|
output,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All checks, recorded, in a clean detached worktree of the repo's HEAD (main after a merge). The
|
||||||
|
/// user's own checkout is never touched.
|
||||||
|
pub fn run_on_main(db: &Db, repo: &Path) -> Result<Vec<Outcome>> {
|
||||||
|
if db.checks()?.is_empty() {
|
||||||
|
return Ok(vec![]);
|
||||||
|
}
|
||||||
|
let tmp = repo.join(format!(".hx/main-check-{}", crate::state::now_ms()));
|
||||||
|
let lock_path = repo.join(".git/orch-worktree.lock");
|
||||||
|
{
|
||||||
|
let _l = crate::lock::lock(&lock_path)?; // git races on its own locks
|
||||||
|
git(
|
||||||
|
repo,
|
||||||
|
&[
|
||||||
|
"worktree",
|
||||||
|
"add",
|
||||||
|
"--detach",
|
||||||
|
&tmp.to_string_lossy(),
|
||||||
|
"HEAD",
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
let res = run(db, &tmp, None, true);
|
||||||
|
let _l = crate::lock::lock(&lock_path)?;
|
||||||
|
let _ = git(
|
||||||
|
repo,
|
||||||
|
&["worktree", "remove", "--force", &tmp.to_string_lossy()],
|
||||||
|
);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn repo(tag: &str) -> (std::path::PathBuf, Db) {
|
||||||
|
let dir = std::env::temp_dir().join(format!("orch-checks-{tag}-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
git(&dir, &["init", "-q", "-b", "main"]).unwrap();
|
||||||
|
std::fs::write(dir.join("present.txt"), "x").unwrap();
|
||||||
|
git(&dir, &["add", "-A"]).unwrap();
|
||||||
|
git(&dir, &["commit", "-qm", "init"]).unwrap();
|
||||||
|
let db = Db::open(&dir.join(".hx/orch.db")).unwrap();
|
||||||
|
(dir, db)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn main_run_records_in_a_clean_worktree_and_leaves_the_checkout_alone() {
|
||||||
|
let (dir, db) = repo("main");
|
||||||
|
db.add_check("file present", "test -f present.txt", None)
|
||||||
|
.unwrap();
|
||||||
|
db.add_check("untracked junk absent", "test ! -f junk.txt", Some("s1"))
|
||||||
|
.unwrap();
|
||||||
|
db.add_check("always red", "echo nope; exit 3", None)
|
||||||
|
.unwrap();
|
||||||
|
// junk in the user's checkout must not be visible to the checks: they run in a clean worktree
|
||||||
|
std::fs::write(dir.join("junk.txt"), "dirty").unwrap();
|
||||||
|
let r = run_on_main(&db, &dir).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
r.iter().map(|o| o.pass).collect::<Vec<_>>(),
|
||||||
|
[true, true, false]
|
||||||
|
);
|
||||||
|
assert_eq!(r[2].exit, Some(3));
|
||||||
|
let rows = db.checks().unwrap();
|
||||||
|
let st: Vec<_> = rows
|
||||||
|
.iter()
|
||||||
|
.map(|c| c.last_status.as_deref().unwrap())
|
||||||
|
.collect();
|
||||||
|
assert_eq!(st, ["pass", "pass", "fail"]);
|
||||||
|
assert!(rows[0].last_run_at.is_some());
|
||||||
|
assert!(dir.join("junk.txt").exists(), "checkout untouched");
|
||||||
|
let leftovers: Vec<_> = std::fs::read_dir(dir.join(".hx"))
|
||||||
|
.unwrap()
|
||||||
|
.flatten()
|
||||||
|
.filter(|e| e.file_name().to_string_lossy().starts_with("main-check"))
|
||||||
|
.collect();
|
||||||
|
assert!(leftovers.is_empty(), "temporary worktree removed");
|
||||||
|
let ev = db.events(Some(GOAL), 0).unwrap();
|
||||||
|
assert_eq!(ev.len(), 3);
|
||||||
|
assert_eq!(ev[2].payload["output"], "nope\n");
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn branch_run_filters_by_owner_and_does_not_record() {
|
||||||
|
let (dir, db) = repo("branch");
|
||||||
|
db.add_check("mine", "true", Some("s1")).unwrap();
|
||||||
|
db.add_check("theirs", "false", Some("s2")).unwrap();
|
||||||
|
db.add_check("unowned", "false", None).unwrap();
|
||||||
|
let r = run(&db, &dir, Some("s1"), false).unwrap();
|
||||||
|
assert_eq!(r.len(), 1);
|
||||||
|
assert!(r[0].pass);
|
||||||
|
assert!(db.checks().unwrap().iter().all(|c| c.last_status.is_none()));
|
||||||
|
assert_eq!(
|
||||||
|
db.events(Some("s1"), 0).unwrap()[0].payload["where"],
|
||||||
|
"branch"
|
||||||
|
);
|
||||||
|
assert_eq!(db.events(Some(GOAL), 0).unwrap().len(), 0);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,632 @@
|
|||||||
|
//! Per-goal SQLite file (`.hx/orch.db`, ORCHESTRATOR.md section 6). The `events` table is append-only; every
|
||||||
|
//! view is rebuilt from it plus the machine files. Each thread opens its own connection (WAL + busy timeout).
|
||||||
|
// shortcut: checks/decisions tables exist but have no accessors yet; milestones 7 and 8 add them.
|
||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use rusqlite::{Connection, OptionalExtension, params};
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
const SCHEMA: &str = "
|
||||||
|
create table if not exists goal(text text not null, created_at integer not null);
|
||||||
|
create table if not exists checks(
|
||||||
|
id integer primary key, name text not null, cmd text not null, owner_session text,
|
||||||
|
last_status text, last_run_at integer);
|
||||||
|
create table if not exists tasks(
|
||||||
|
id text primary key, name text not null, subtitle text not null default '',
|
||||||
|
machine text not null, depends_on text not null default '[]');
|
||||||
|
create table if not exists sessions(
|
||||||
|
id text primary key, task_id text not null, branch text not null, worktree text not null,
|
||||||
|
pid integer, current_state text not null default '', status text not null default 'queued');
|
||||||
|
create table if not exists events(
|
||||||
|
id integer primary key autoincrement, session_id text not null, at integer not null,
|
||||||
|
kind text not null, payload text not null default '{}');
|
||||||
|
create index if not exists events_session on events(session_id, id);
|
||||||
|
create table if not exists decisions(
|
||||||
|
session_id text not null, text text not null, state text not null, at integer not null,
|
||||||
|
vetoed integer not null default 0);
|
||||||
|
create table if not exists commands(
|
||||||
|
id integer primary key autoincrement, session_id text not null, kind text not null,
|
||||||
|
payload text not null default '{}', at integer not null, done integer not null default 0);
|
||||||
|
create table if not exists merge_queue(
|
||||||
|
ticket integer primary key autoincrement, session_id text not null unique);
|
||||||
|
create table if not exists needs(
|
||||||
|
id integer primary key autoincrement, session_id text not null, kind text not null,
|
||||||
|
payload text not null default '{}', created_at integer not null, answer text,
|
||||||
|
done integer not null default 0);
|
||||||
|
";
|
||||||
|
|
||||||
|
pub struct Db {
|
||||||
|
conn: Connection,
|
||||||
|
path: std::path::PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An acceptance check: a shell command, pass = exit 0. `last_status` is the result on main.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct CheckRow {
|
||||||
|
pub id: i64,
|
||||||
|
pub name: String,
|
||||||
|
pub cmd: String,
|
||||||
|
pub owner: Option<String>,
|
||||||
|
/// pass | fail, None until the first run
|
||||||
|
pub last_status: Option<String>,
|
||||||
|
pub last_run_at: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A choice an agent reported with `hx/decision`.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct DecisionRow {
|
||||||
|
pub id: i64,
|
||||||
|
pub session: String,
|
||||||
|
pub text: String,
|
||||||
|
pub state: String,
|
||||||
|
pub at: u64,
|
||||||
|
pub vetoed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Event {
|
||||||
|
pub id: i64,
|
||||||
|
pub session: String,
|
||||||
|
/// Milliseconds since the epoch.
|
||||||
|
pub at: u64,
|
||||||
|
pub kind: String,
|
||||||
|
pub payload: Value,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One item of the Needs-you queue: a `human` step, a permission request or an agent question. The runner
|
||||||
|
/// writes it and waits; the TUI (or anything else with the database) writes the answer.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct NeedRow {
|
||||||
|
pub id: i64,
|
||||||
|
pub session: String,
|
||||||
|
/// review | permission | input
|
||||||
|
pub kind: String,
|
||||||
|
pub payload: Value,
|
||||||
|
/// Milliseconds since the epoch.
|
||||||
|
pub at: u64,
|
||||||
|
pub answer: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Task {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub subtitle: String,
|
||||||
|
pub machine: String,
|
||||||
|
pub depends_on: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Session {
|
||||||
|
pub id: String,
|
||||||
|
pub task_id: String,
|
||||||
|
pub branch: String,
|
||||||
|
pub worktree: String,
|
||||||
|
pub pid: Option<u32>,
|
||||||
|
pub state: String,
|
||||||
|
/// queued, running, or the machine's `end` value (merged, escalated, aborted) or `failed`.
|
||||||
|
pub status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Db {
|
||||||
|
pub fn open(path: &Path) -> Result<Self> {
|
||||||
|
if let Some(d) = path.parent() {
|
||||||
|
std::fs::create_dir_all(d)?;
|
||||||
|
}
|
||||||
|
let conn = Connection::open(path).with_context(|| path.display().to_string())?;
|
||||||
|
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||||
|
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||||
|
conn.execute_batch(SCHEMA)?;
|
||||||
|
Ok(Self {
|
||||||
|
conn,
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where this database lives; exported to machine steps as `ORCH_DB`.
|
||||||
|
pub fn path(&self) -> &Path {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_check(&self, name: &str, cmd: &str, owner: Option<&str>) -> Result<i64> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into checks(name, cmd, owner_session) values (?1, ?2, ?3)",
|
||||||
|
params![name, cmd, owner],
|
||||||
|
)?;
|
||||||
|
Ok(self.conn.last_insert_rowid())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn checks(&self) -> Result<Vec<CheckRow>> {
|
||||||
|
let mut q = self.conn.prepare(
|
||||||
|
"select id, name, cmd, owner_session, last_status, last_run_at from checks order by id",
|
||||||
|
)?;
|
||||||
|
let rows = q.query_map([], |r| {
|
||||||
|
Ok(CheckRow {
|
||||||
|
id: r.get(0)?,
|
||||||
|
name: r.get(1)?,
|
||||||
|
cmd: r.get(2)?,
|
||||||
|
owner: r.get(3)?,
|
||||||
|
last_status: r.get(4)?,
|
||||||
|
last_run_at: r.get::<_, Option<i64>>(5)?.map(|v| v as u64),
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_check_result(&self, id: i64, pass: bool) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"update checks set last_status = ?2, last_run_at = ?3 where id = ?1",
|
||||||
|
params![
|
||||||
|
id,
|
||||||
|
if pass { "pass" } else { "fail" },
|
||||||
|
crate::state::now_ms() as i64
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decisions(&self) -> Result<Vec<DecisionRow>> {
|
||||||
|
let mut q = self.conn.prepare(
|
||||||
|
"select rowid, session_id, text, state, at, vetoed from decisions order by rowid",
|
||||||
|
)?;
|
||||||
|
let rows = q.query_map([], |r| {
|
||||||
|
Ok(DecisionRow {
|
||||||
|
id: r.get(0)?,
|
||||||
|
session: r.get(1)?,
|
||||||
|
text: r.get(2)?,
|
||||||
|
state: r.get(3)?,
|
||||||
|
at: r.get::<_, i64>(4)? as u64,
|
||||||
|
vetoed: r.get::<_, i64>(5)? != 0,
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Joins the merge queue (once) and returns the ticket; lower tickets merge first.
|
||||||
|
pub fn queue_join(&self, session: &str) -> Result<i64> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert or ignore into merge_queue(session_id) values (?1)",
|
||||||
|
[session],
|
||||||
|
)?;
|
||||||
|
Ok(self.conn.query_row(
|
||||||
|
"select ticket from merge_queue where session_id = ?1",
|
||||||
|
[session],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session at the head of the merge queue.
|
||||||
|
pub fn queue_head(&self) -> Result<Option<String>> {
|
||||||
|
Ok(self
|
||||||
|
.conn
|
||||||
|
.query_row(
|
||||||
|
"select session_id from merge_queue order by ticket limit 1",
|
||||||
|
[],
|
||||||
|
|r| r.get(0),
|
||||||
|
)
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1 = head of the queue.
|
||||||
|
pub fn queue_position(&self, session: &str) -> Result<usize> {
|
||||||
|
let n: i64 = self.conn.query_row(
|
||||||
|
"select count(*) from merge_queue where ticket <=
|
||||||
|
(select ticket from merge_queue where session_id = ?1)",
|
||||||
|
[session],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
Ok(n as usize)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn queue_leave(&self, session: &str) -> Result<()> {
|
||||||
|
self.conn
|
||||||
|
.execute("delete from merge_queue where session_id = ?1", [session])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A command for a running session (`message`, `interrupt`, `goto`, `abort`, `veto`). The runner, which may be
|
||||||
|
/// another process, picks it up the next time it polls.
|
||||||
|
pub fn add_command(&self, session: &str, kind: &str, payload: &Value) -> Result<i64> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into commands(session_id, kind, payload, at) values (?1, ?2, ?3, ?4)",
|
||||||
|
params![
|
||||||
|
session,
|
||||||
|
kind,
|
||||||
|
payload.to_string(),
|
||||||
|
crate::state::now_ms() as i64
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(self.conn.last_insert_rowid())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes the session's unprocessed commands, oldest first, and marks them processed.
|
||||||
|
pub fn take_commands(&self, session: &str) -> Result<Vec<(String, Value)>> {
|
||||||
|
let mut q = self.conn.prepare(
|
||||||
|
"select id, kind, payload from commands where session_id = ?1 and done = 0 order by id",
|
||||||
|
)?;
|
||||||
|
let rows: Vec<(i64, String, String)> = q
|
||||||
|
.query_map([session], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
|
||||||
|
.collect::<rusqlite::Result<_>>()?;
|
||||||
|
for (id, ..) in &rows {
|
||||||
|
self.conn
|
||||||
|
.execute("update commands set done = 1 where id = ?1", [id])?;
|
||||||
|
}
|
||||||
|
Ok(rows
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, k, p)| (k, serde_json::from_str(&p).unwrap_or(Value::Null)))
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks a decision as vetoed; false if it does not exist or was already vetoed.
|
||||||
|
pub fn veto_decision(&self, id: i64) -> Result<bool> {
|
||||||
|
let n = self.conn.execute(
|
||||||
|
"update decisions set vetoed = 1 where rowid = ?1 and vetoed = 0",
|
||||||
|
[id],
|
||||||
|
)?;
|
||||||
|
Ok(n == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_goal(&self, text: &str) -> Result<()> {
|
||||||
|
self.conn.execute("delete from goal", [])?;
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into goal(text, created_at) values (?1, ?2)",
|
||||||
|
params![text, crate::state::now() as i64],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn goal(&self) -> Result<Option<String>> {
|
||||||
|
Ok(self
|
||||||
|
.conn
|
||||||
|
.query_row("select text from goal limit 1", [], |r| r.get(0))
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Next free session id: s1, s2, ...
|
||||||
|
pub fn next_session_id(&self) -> Result<String> {
|
||||||
|
let n: i64 = self.conn.query_row(
|
||||||
|
"select coalesce(max(cast(substr(id, 2) as integer)), 0) from sessions",
|
||||||
|
[],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
Ok(format!("s{}", n + 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_task(&self, t: &Task) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into tasks(id, name, subtitle, machine, depends_on) values (?1, ?2, ?3, ?4, ?5)",
|
||||||
|
params![
|
||||||
|
t.id,
|
||||||
|
t.name,
|
||||||
|
t.subtitle,
|
||||||
|
t.machine,
|
||||||
|
serde_json::to_string(&t.depends_on)?
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tasks(&self) -> Result<Vec<Task>> {
|
||||||
|
let mut q = self.conn.prepare(
|
||||||
|
"select id, name, subtitle, machine, depends_on from tasks order by cast(substr(id, 2) as integer), id",
|
||||||
|
)?;
|
||||||
|
let rows = q.query_map([], |r| {
|
||||||
|
let deps: String = r.get(4)?;
|
||||||
|
Ok(Task {
|
||||||
|
id: r.get(0)?,
|
||||||
|
name: r.get(1)?,
|
||||||
|
subtitle: r.get(2)?,
|
||||||
|
machine: r.get(3)?,
|
||||||
|
depends_on: serde_json::from_str(&deps).unwrap_or_default(),
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_session(&self, s: &Session) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into sessions(id, task_id, branch, worktree, pid, current_state, status) values (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
|
||||||
|
params![s.id, s.task_id, s.branch, s.worktree, s.pid, s.state, s.status],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn session(&self, id: &str) -> Result<Option<Session>> {
|
||||||
|
Ok(self
|
||||||
|
.conn
|
||||||
|
.query_row(
|
||||||
|
"select id, task_id, branch, worktree, pid, current_state, status from sessions where id = ?1",
|
||||||
|
[id],
|
||||||
|
session_row,
|
||||||
|
)
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn sessions(&self) -> Result<Vec<Session>> {
|
||||||
|
let mut q = self.conn.prepare(
|
||||||
|
"select id, task_id, branch, worktree, pid, current_state, status from sessions order by cast(substr(id, 2) as integer), id",
|
||||||
|
)?;
|
||||||
|
Ok(q.query_map([], session_row)?
|
||||||
|
.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_session(&self, id: &str, state: &str, status: &str) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"update sessions set current_state = ?2, status = ?3 where id = ?1",
|
||||||
|
params![id, state, status],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_pid(&self, id: &str, pid: Option<u32>) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"update sessions set pid = ?2 where id = ?1",
|
||||||
|
params![id, pid],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append one event; returns its id.
|
||||||
|
pub fn emit(&self, session: &str, kind: &str, payload: Value) -> Result<i64> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into events(session_id, at, kind, payload) values (?1, ?2, ?3, ?4)",
|
||||||
|
params![
|
||||||
|
session,
|
||||||
|
crate::state::now_ms() as i64,
|
||||||
|
kind,
|
||||||
|
payload.to_string()
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(self.conn.last_insert_rowid())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_need(&self, session: &str, kind: &str, payload: &Value) -> Result<i64> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into needs(session_id, kind, payload, created_at) values (?1, ?2, ?3, ?4)",
|
||||||
|
params![
|
||||||
|
session,
|
||||||
|
kind,
|
||||||
|
payload.to_string(),
|
||||||
|
crate::state::now_ms() as i64
|
||||||
|
],
|
||||||
|
)?;
|
||||||
|
Ok(self.conn.last_insert_rowid())
|
||||||
|
}
|
||||||
|
|
||||||
|
const NEED_COLS: &'static str = "id, session_id, kind, payload, created_at, answer";
|
||||||
|
|
||||||
|
/// Items still waiting for an answer, oldest first.
|
||||||
|
pub fn pending_needs(&self) -> Result<Vec<NeedRow>> {
|
||||||
|
let mut q = self.conn.prepare(&format!(
|
||||||
|
"select {} from needs where done = 0 and answer is null order by id",
|
||||||
|
Self::NEED_COLS
|
||||||
|
))?;
|
||||||
|
Ok(q.query_map([], need_row)?
|
||||||
|
.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An unfinished item of this session with this `payload.key`: after an orchestrator restart the same
|
||||||
|
/// question must not be asked twice.
|
||||||
|
pub fn open_need(&self, session: &str, kind: &str, key: &str) -> Result<Option<NeedRow>> {
|
||||||
|
Ok(self
|
||||||
|
.conn
|
||||||
|
.query_row(
|
||||||
|
&format!(
|
||||||
|
"select {} from needs where session_id = ?1 and kind = ?2 and done = 0
|
||||||
|
and json_extract(payload, '$.key') = ?3 order by id desc limit 1",
|
||||||
|
Self::NEED_COLS
|
||||||
|
),
|
||||||
|
params![session, kind, key],
|
||||||
|
need_row,
|
||||||
|
)
|
||||||
|
.optional()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn need_answer(&self, id: i64) -> Result<Option<String>> {
|
||||||
|
Ok(self
|
||||||
|
.conn
|
||||||
|
.query_row("select answer from needs where id = ?1", [id], |r| r.get(0))?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers an item (first answer wins) and returns false if it was already answered.
|
||||||
|
pub fn answer_need(&self, id: i64, answer: &str) -> Result<bool> {
|
||||||
|
let n = self.conn.execute(
|
||||||
|
"update needs set answer = ?2 where id = ?1 and answer is null",
|
||||||
|
params![id, answer],
|
||||||
|
)?;
|
||||||
|
Ok(n == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The runner took the answer; the item is history now.
|
||||||
|
pub fn finish_need(&self, id: i64) -> Result<()> {
|
||||||
|
self.conn
|
||||||
|
.execute("update needs set done = 1 where id = ?1", [id])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A choice an agent reported with `hx/decision`; the goal view lists them for veto.
|
||||||
|
pub fn add_decision(&self, session: &str, text: &str, state: &str) -> Result<()> {
|
||||||
|
self.conn.execute(
|
||||||
|
"insert into decisions(session_id, text, state, at) values (?1, ?2, ?3, ?4)",
|
||||||
|
params![session, text, state, crate::state::now_ms() as i64],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn decision_count(&self, session: &str) -> Result<usize> {
|
||||||
|
let n: i64 = self.conn.query_row(
|
||||||
|
"select count(*) from decisions where session_id = ?1",
|
||||||
|
[session],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
Ok(n as usize)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Events oldest first, optionally one session, only those after `after` (event id).
|
||||||
|
pub fn events(&self, session: Option<&str>, after: i64) -> Result<Vec<Event>> {
|
||||||
|
let mut q = self.conn.prepare(
|
||||||
|
"select id, session_id, at, kind, payload from events
|
||||||
|
where id > ?1 and (?2 is null or session_id = ?2) order by id",
|
||||||
|
)?;
|
||||||
|
let rows = q.query_map(params![after, session], |r| {
|
||||||
|
let p: String = r.get(4)?;
|
||||||
|
Ok(Event {
|
||||||
|
id: r.get(0)?,
|
||||||
|
session: r.get(1)?,
|
||||||
|
at: r.get::<_, i64>(2)? as u64,
|
||||||
|
kind: r.get(3)?,
|
||||||
|
payload: serde_json::from_str(&p).unwrap_or(Value::Null),
|
||||||
|
})
|
||||||
|
})?;
|
||||||
|
Ok(rows.collect::<rusqlite::Result<_>>()?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How often `catch` fired in `state` of this session (rebuilt from events, so it survives restarts).
|
||||||
|
pub fn catch_count(&self, session: &str, state: &str, catch: &str) -> Result<u32> {
|
||||||
|
let n: i64 = self.conn.query_row(
|
||||||
|
"select count(*) from events where session_id = ?1 and kind = 'catch'
|
||||||
|
and json_extract(payload, '$.state') = ?2 and json_extract(payload, '$.catch') = ?3",
|
||||||
|
params![session, state, catch],
|
||||||
|
|r| r.get(0),
|
||||||
|
)?;
|
||||||
|
Ok(n as u32)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn need_row(r: &rusqlite::Row) -> rusqlite::Result<NeedRow> {
|
||||||
|
let p: String = r.get(3)?;
|
||||||
|
Ok(NeedRow {
|
||||||
|
id: r.get(0)?,
|
||||||
|
session: r.get(1)?,
|
||||||
|
kind: r.get(2)?,
|
||||||
|
payload: serde_json::from_str(&p).unwrap_or(Value::Null),
|
||||||
|
at: r.get::<_, i64>(4)? as u64,
|
||||||
|
answer: r.get(5)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_row(r: &rusqlite::Row) -> rusqlite::Result<Session> {
|
||||||
|
Ok(Session {
|
||||||
|
id: r.get(0)?,
|
||||||
|
task_id: r.get(1)?,
|
||||||
|
branch: r.get(2)?,
|
||||||
|
worktree: r.get(3)?,
|
||||||
|
pid: r.get(4)?,
|
||||||
|
state: r.get(5)?,
|
||||||
|
status: r.get(6)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
pub fn temp_db(tag: &str) -> (Db, std::path::PathBuf) {
|
||||||
|
let d = std::env::temp_dir().join(format!("orch-db-{tag}-{}", std::process::id()));
|
||||||
|
let _ = std::fs::remove_dir_all(&d);
|
||||||
|
(Db::open(&d.join("orch.db")).unwrap(), d)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn roundtrip() {
|
||||||
|
let (db, dir) = temp_db("rt");
|
||||||
|
assert_eq!(db.goal().unwrap(), None);
|
||||||
|
db.set_goal("ship it").unwrap();
|
||||||
|
assert_eq!(db.goal().unwrap().as_deref(), Some("ship it"));
|
||||||
|
assert_eq!(db.next_session_id().unwrap(), "s1");
|
||||||
|
let s = Session {
|
||||||
|
id: "s1".into(),
|
||||||
|
task_id: "s1".into(),
|
||||||
|
branch: "hx/s1-x".into(),
|
||||||
|
worktree: "/w".into(),
|
||||||
|
pid: None,
|
||||||
|
state: String::new(),
|
||||||
|
status: "queued".into(),
|
||||||
|
};
|
||||||
|
db.add_session(&s).unwrap();
|
||||||
|
assert_eq!(db.next_session_id().unwrap(), "s2");
|
||||||
|
db.set_session("s1", "plan", "running").unwrap();
|
||||||
|
assert_eq!(db.session("s1").unwrap().unwrap().state, "plan");
|
||||||
|
db.emit("s1", "catch", json!({"state": "test", "catch": "T"}))
|
||||||
|
.unwrap();
|
||||||
|
let last = db.emit("s1", "state", json!({"to": "code"})).unwrap();
|
||||||
|
assert_eq!(db.catch_count("s1", "test", "T").unwrap(), 1);
|
||||||
|
assert_eq!(db.catch_count("s1", "test", "U").unwrap(), 0);
|
||||||
|
assert_eq!(db.events(Some("s1"), 0).unwrap().len(), 2);
|
||||||
|
assert_eq!(db.events(None, last - 1).unwrap().len(), 1);
|
||||||
|
assert!(db.events(Some("s9"), 0).unwrap().is_empty());
|
||||||
|
// checks keep their last result; decisions list in insertion order
|
||||||
|
let c = db.add_check("build", "true", Some("s1")).unwrap();
|
||||||
|
assert_eq!(db.checks().unwrap()[0].last_status, None);
|
||||||
|
db.set_check_result(c, true).unwrap();
|
||||||
|
let ch = &db.checks().unwrap()[0];
|
||||||
|
assert_eq!(
|
||||||
|
(ch.last_status.as_deref(), ch.owner.as_deref()),
|
||||||
|
(Some("pass"), Some("s1"))
|
||||||
|
);
|
||||||
|
db.add_decision("s1", "use a bucket", "plan").unwrap();
|
||||||
|
assert_eq!(db.decisions().unwrap()[0].text, "use a bucket");
|
||||||
|
// merge queue is first come, first served, and joining twice keeps the place
|
||||||
|
assert_eq!(db.queue_head().unwrap(), None);
|
||||||
|
let (t1, t2) = (db.queue_join("s1").unwrap(), db.queue_join("s2").unwrap());
|
||||||
|
assert!(t1 < t2);
|
||||||
|
assert_eq!(db.queue_join("s1").unwrap(), t1);
|
||||||
|
assert_eq!(db.queue_head().unwrap().as_deref(), Some("s1"));
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
db.queue_position("s1").unwrap(),
|
||||||
|
db.queue_position("s2").unwrap()
|
||||||
|
),
|
||||||
|
(1, 2)
|
||||||
|
);
|
||||||
|
db.queue_leave("s1").unwrap();
|
||||||
|
assert_eq!(db.queue_head().unwrap().as_deref(), Some("s2"));
|
||||||
|
db.queue_leave("s2").unwrap();
|
||||||
|
// commands: taken once, in order, per session
|
||||||
|
db.add_command("s1", "message", &json!({"text": "hi"}))
|
||||||
|
.unwrap();
|
||||||
|
db.add_command("s1", "interrupt", &json!({})).unwrap();
|
||||||
|
db.add_command("s2", "abort", &json!({})).unwrap();
|
||||||
|
let cmds = db.take_commands("s1").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
cmds.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(),
|
||||||
|
["message", "interrupt"]
|
||||||
|
);
|
||||||
|
assert_eq!(cmds[0].1["text"], "hi");
|
||||||
|
assert!(db.take_commands("s1").unwrap().is_empty());
|
||||||
|
assert_eq!(db.take_commands("s2").unwrap().len(), 1);
|
||||||
|
// a decision can be vetoed once
|
||||||
|
let d = db.decisions().unwrap()[0].id;
|
||||||
|
assert!(db.veto_decision(d).unwrap());
|
||||||
|
assert!(!db.veto_decision(d).unwrap());
|
||||||
|
assert!(db.decisions().unwrap()[0].vetoed);
|
||||||
|
// needs queue: pending until answered, the first answer wins, finished items disappear
|
||||||
|
let n = db
|
||||||
|
.add_need("s1", "review", &json!({"key": "review/ok", "title": "t"}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(db.pending_needs().unwrap().len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
db.open_need("s1", "review", "review/ok")
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.id,
|
||||||
|
n
|
||||||
|
);
|
||||||
|
assert!(db.open_need("s1", "review", "other").unwrap().is_none());
|
||||||
|
assert_eq!(db.need_answer(n).unwrap(), None);
|
||||||
|
assert!(db.answer_need(n, "approve").unwrap());
|
||||||
|
assert!(!db.answer_need(n, "changes: x").unwrap());
|
||||||
|
assert_eq!(db.need_answer(n).unwrap().as_deref(), Some("approve"));
|
||||||
|
assert!(db.pending_needs().unwrap().is_empty());
|
||||||
|
db.finish_need(n).unwrap();
|
||||||
|
assert!(db.open_need("s1", "review", "review/ok").unwrap().is_none());
|
||||||
|
// reopening sees the same data: restart restores views
|
||||||
|
drop(db);
|
||||||
|
let db = Db::open(&dir.join("orch.db")).unwrap();
|
||||||
|
assert_eq!(db.sessions().unwrap().len(), 1);
|
||||||
|
let _ = std::fs::remove_dir_all(&dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
+780
@@ -0,0 +1,780 @@
|
|||||||
|
//! View model of the session detail screen (ORCHESTRATOR.md 7.2, `Session.dc.html`): the machine rendered as
|
||||||
|
//! text with a live column, the path taken, the last test run, what the agent does now, changed files, budgets.
|
||||||
|
//! Pure, like `view.rs`: events and the machine file in, lines out.
|
||||||
|
|
||||||
|
use crate::budget;
|
||||||
|
use crate::db::Event;
|
||||||
|
use crate::machine::{Kind, RunOn};
|
||||||
|
use crate::view::{Input, Status};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum LineKind {
|
||||||
|
Header,
|
||||||
|
Step,
|
||||||
|
Catch,
|
||||||
|
End,
|
||||||
|
Only,
|
||||||
|
Blank,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which block color a line gets: the current state is highlighted, failed ones are red.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum Block {
|
||||||
|
Done,
|
||||||
|
Cur,
|
||||||
|
Fail,
|
||||||
|
Todo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct MLine {
|
||||||
|
pub kind: LineKind,
|
||||||
|
pub text: String,
|
||||||
|
/// ` → target` of a catch line, drawn in the state color.
|
||||||
|
pub to: String,
|
||||||
|
pub exec: Option<RunOn>,
|
||||||
|
pub sets: String,
|
||||||
|
pub live: String,
|
||||||
|
pub block: Block,
|
||||||
|
/// A catch that fired: its live text is drawn bold red.
|
||||||
|
pub hit: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct PathStep {
|
||||||
|
pub name: String,
|
||||||
|
pub failed: bool,
|
||||||
|
pub current: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct FailView {
|
||||||
|
pub name: String,
|
||||||
|
pub message: String,
|
||||||
|
pub location: String,
|
||||||
|
/// `failed in fix 1 too`, or empty.
|
||||||
|
pub repeats: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct TestRun {
|
||||||
|
pub step: String,
|
||||||
|
pub at_ms: u64,
|
||||||
|
pub passed: u32,
|
||||||
|
pub failed: u32,
|
||||||
|
pub skipped: u32,
|
||||||
|
pub secs: f64,
|
||||||
|
pub failures: Vec<FailView>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug, Default)]
|
||||||
|
pub struct Now {
|
||||||
|
/// `agent`, `computer` or empty.
|
||||||
|
pub who: String,
|
||||||
|
pub line: String,
|
||||||
|
pub intent: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct FileChange {
|
||||||
|
pub path: String,
|
||||||
|
pub added: u32,
|
||||||
|
pub removed: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug, Default)]
|
||||||
|
pub struct Budget {
|
||||||
|
/// (used, limit) context tokens.
|
||||||
|
pub ctx: Option<(u64, u64)>,
|
||||||
|
/// (fix count, max) of the busiest retry loop.
|
||||||
|
pub retries: Option<(u32, u32)>,
|
||||||
|
/// Time spent working, not counting time waiting for the user.
|
||||||
|
pub wall_secs: u64,
|
||||||
|
pub cost: f64,
|
||||||
|
/// Limits from the machine's `[budget]`; None = no cap.
|
||||||
|
pub wall_cap: Option<u64>,
|
||||||
|
pub cost_cap: Option<f64>,
|
||||||
|
pub compact_at: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The loop detector fired: the last test runs failed on the same tests.
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct LoopView {
|
||||||
|
pub runs: usize,
|
||||||
|
pub tests: usize,
|
||||||
|
/// The file the agent keeps editing.
|
||||||
|
pub file: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct Detail {
|
||||||
|
pub id: String,
|
||||||
|
pub task: String,
|
||||||
|
pub status: Status,
|
||||||
|
pub branch: String,
|
||||||
|
pub worktree: String,
|
||||||
|
pub pid: Option<u32>,
|
||||||
|
pub machine_file: String,
|
||||||
|
pub on_abort: Option<String>,
|
||||||
|
pub on_budget: Option<String>,
|
||||||
|
pub lines: Vec<MLine>,
|
||||||
|
pub path: Vec<PathStep>,
|
||||||
|
pub test: Option<TestRun>,
|
||||||
|
pub now: Now,
|
||||||
|
pub files: Vec<FileChange>,
|
||||||
|
pub budget: Budget,
|
||||||
|
pub looping: Option<LoopView>,
|
||||||
|
/// Every state of the machine, for the force-state key.
|
||||||
|
pub states: Vec<String>,
|
||||||
|
/// The start state, where `re-plan` goes.
|
||||||
|
pub start: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `6.2s`, `0m59s`, `4m10s`.
|
||||||
|
pub fn dur(ms: u64) -> String {
|
||||||
|
if ms < 10_000 {
|
||||||
|
format!("{:.1}s", ms as f64 / 1000.0)
|
||||||
|
} else {
|
||||||
|
let s = ms / 1000;
|
||||||
|
format!("{}m{:02}s", s / 60, s % 60)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One stay in a state: from the `state` event to the next one.
|
||||||
|
struct Visit<'a> {
|
||||||
|
state: &'a str,
|
||||||
|
/// (step, ms, ok)
|
||||||
|
steps: Vec<(&'a str, u64, bool)>,
|
||||||
|
caught: Option<&'a str>,
|
||||||
|
test: Option<(u64, u64)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn s<'a>(v: &'a serde_json::Value, k: &str) -> &'a str {
|
||||||
|
v[k].as_str().unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build(i: &Input, id: &str) -> Option<Detail> {
|
||||||
|
let sess = i.sessions.iter().find(|x| x.id == id)?;
|
||||||
|
let task = i.tasks.iter().find(|t| t.id == sess.task_id)?;
|
||||||
|
let machine = i.machines.get(&task.machine)?;
|
||||||
|
let overview = crate::view::build(i);
|
||||||
|
let status = overview.rows.iter().find(|r| r.id == id)?.status;
|
||||||
|
let evs: Vec<&Event> = i.events.iter().filter(|e| e.session == id).collect();
|
||||||
|
|
||||||
|
let mut visits: Vec<Visit> = vec![];
|
||||||
|
for e in &evs {
|
||||||
|
let p = &e.payload;
|
||||||
|
match e.kind.as_str() {
|
||||||
|
"state" => visits.push(Visit {
|
||||||
|
state: s(p, "to"),
|
||||||
|
steps: vec![],
|
||||||
|
caught: None,
|
||||||
|
test: None,
|
||||||
|
}),
|
||||||
|
"step" => {
|
||||||
|
if let Some(v) = visits.last_mut() {
|
||||||
|
v.steps
|
||||||
|
.push((s(p, "step"), p["ms"].as_u64().unwrap_or(0), p["ok"] == true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"catch" => {
|
||||||
|
if let Some(v) = visits.last_mut() {
|
||||||
|
v.caught = Some(s(p, "catch"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"test" => {
|
||||||
|
if let Some(v) = visits.last_mut() {
|
||||||
|
v.test = Some((
|
||||||
|
p["passed"].as_u64().unwrap_or(0),
|
||||||
|
p["failed"].as_u64().unwrap_or(0),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let active = matches!(sess.status.as_str(), "running" | "waiting");
|
||||||
|
let cur_state = if active {
|
||||||
|
visits.last().map(|v| v.state)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let last_at = evs.last().map_or(0, |e| e.at);
|
||||||
|
let hits = |state: &str, catch: &str| {
|
||||||
|
evs.iter()
|
||||||
|
.filter(|e| {
|
||||||
|
e.kind == "catch"
|
||||||
|
&& s(&e.payload, "state") == state
|
||||||
|
&& s(&e.payload, "catch") == catch
|
||||||
|
})
|
||||||
|
.count() as u32
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut lines: Vec<MLine> = vec![];
|
||||||
|
let mut running_step: Option<(&str, RunOn, Option<&str>)> = None;
|
||||||
|
let line = |kind, text: String| MLine {
|
||||||
|
kind,
|
||||||
|
text,
|
||||||
|
to: String::new(),
|
||||||
|
exec: None,
|
||||||
|
sets: String::new(),
|
||||||
|
live: String::new(),
|
||||||
|
block: Block::Todo,
|
||||||
|
hit: false,
|
||||||
|
};
|
||||||
|
// main flow first, then the only_on states, like the machine file reads
|
||||||
|
let ordered = machine
|
||||||
|
.states
|
||||||
|
.iter()
|
||||||
|
.filter(|st| st.only_on.is_empty())
|
||||||
|
.chain(machine.states.iter().filter(|st| !st.only_on.is_empty()));
|
||||||
|
for st in ordered {
|
||||||
|
let mine: Vec<&Visit> = visits.iter().filter(|v| v.state == st.name).collect();
|
||||||
|
let last = mine.last();
|
||||||
|
let is_cur = cur_state == Some(st.name.as_str());
|
||||||
|
let block = if is_cur {
|
||||||
|
Block::Cur
|
||||||
|
} else if let Some(v) = last {
|
||||||
|
let died_here =
|
||||||
|
sess.status == "failed" && visits.last().is_some_and(|l| l.state == st.name);
|
||||||
|
if v.caught.is_some() || died_here {
|
||||||
|
Block::Fail
|
||||||
|
} else {
|
||||||
|
Block::Done
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Block::Todo
|
||||||
|
};
|
||||||
|
let only = !st.only_on.is_empty();
|
||||||
|
let bar = if only { "│ " } else { "" };
|
||||||
|
if !lines.is_empty() {
|
||||||
|
lines.push(line(LineKind::Blank, String::new()));
|
||||||
|
}
|
||||||
|
if only {
|
||||||
|
let when = st.only_on.join(", ").replace(" x", " ×");
|
||||||
|
lines.push(line(LineKind::Only, format!("│ only on {when}")));
|
||||||
|
}
|
||||||
|
let tag = match st.kind {
|
||||||
|
Kind::Start => " · start",
|
||||||
|
Kind::Gate => " · gate",
|
||||||
|
Kind::Exit => " · exit",
|
||||||
|
Kind::Abort => " · abort",
|
||||||
|
Kind::Normal => "",
|
||||||
|
};
|
||||||
|
let mut h = line(LineKind::Header, format!("{bar}{}{tag}", st.name));
|
||||||
|
h.block = block;
|
||||||
|
h.live = match (block, last) {
|
||||||
|
(Block::Cur, _) if mine.len() > 1 => format!("▶ fix {}", mine.len() - 1),
|
||||||
|
(Block::Cur, _) => "▶".into(),
|
||||||
|
(Block::Fail, Some(v)) => match v.test {
|
||||||
|
Some((p, f)) => format!("✗ {p}/{}", p + f),
|
||||||
|
None => "✗".into(),
|
||||||
|
},
|
||||||
|
(Block::Done, Some(v)) => {
|
||||||
|
let total: u64 = v.steps.iter().map(|x| x.1).sum();
|
||||||
|
let times = if mine.len() > 1 {
|
||||||
|
format!(" ×{}", mine.len())
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
format!("✓ {}{times}", dur(total))
|
||||||
|
}
|
||||||
|
_ => String::new(),
|
||||||
|
};
|
||||||
|
lines.push(h);
|
||||||
|
// the step that runs right now: the first one of the current visit without a result
|
||||||
|
let done_in_visit = if is_cur {
|
||||||
|
last.map_or(0, |v| v.steps.len())
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
for (n, step) in st.steps.iter().enumerate() {
|
||||||
|
let mut l = line(LineKind::Step, format!("{bar} {}", step.name));
|
||||||
|
l.exec = Some(step.run);
|
||||||
|
l.sets = step
|
||||||
|
.sets
|
||||||
|
.as_ref()
|
||||||
|
.map(|x| format!("■ {x}"))
|
||||||
|
.unwrap_or_default();
|
||||||
|
l.block = block;
|
||||||
|
let rec = last.and_then(|v| v.steps.iter().find(|x| x.0 == step.name));
|
||||||
|
l.live = match rec {
|
||||||
|
Some(&(_, ms, true)) if !is_cur || n < done_in_visit => format!("✓ {}", dur(ms)),
|
||||||
|
Some(&(_, ms, false)) if !is_cur || n < done_in_visit => format!("✗ {}", dur(ms)),
|
||||||
|
_ if is_cur && n == done_in_visit => {
|
||||||
|
running_step = Some((&step.name, step.run, step.cmd.as_deref()));
|
||||||
|
format!("▶ {}", dur(i.now_ms.saturating_sub(last_at)))
|
||||||
|
}
|
||||||
|
_ => String::new(),
|
||||||
|
};
|
||||||
|
lines.push(l);
|
||||||
|
}
|
||||||
|
for (c, target) in &st.catch {
|
||||||
|
let n = hits(&st.name, c);
|
||||||
|
let mut l = line(LineKind::Catch, format!("{bar} catch {c}"));
|
||||||
|
l.to = format!(" → {target}");
|
||||||
|
l.block = block;
|
||||||
|
if n > 0 {
|
||||||
|
l.live = format!("hit {n}×");
|
||||||
|
l.hit = true;
|
||||||
|
}
|
||||||
|
lines.push(l);
|
||||||
|
if let Some(r) = st.retry.get(c) {
|
||||||
|
let mut l = line(LineKind::Catch, format!("{bar} catch {c} ×{}", r.max));
|
||||||
|
l.to = format!(" → {}", r.then);
|
||||||
|
l.block = if n + 1 >= r.max { Block::Fail } else { block };
|
||||||
|
if n + 1 == r.max {
|
||||||
|
l.live = "next".into();
|
||||||
|
}
|
||||||
|
lines.push(l);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let (true, Some(end)) = (matches!(st.kind, Kind::Exit | Kind::Abort), &st.end) {
|
||||||
|
let mut l = line(LineKind::End, format!("{bar} end: {end}"));
|
||||||
|
l.block = block;
|
||||||
|
lines.push(l);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut path: Vec<PathStep> = visits
|
||||||
|
.iter()
|
||||||
|
.map(|v| PathStep {
|
||||||
|
name: v.state.to_string(),
|
||||||
|
failed: v.caught.is_some(),
|
||||||
|
current: false,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if let Some(l) = path.last_mut() {
|
||||||
|
if cur_state.is_some() {
|
||||||
|
l.current = true;
|
||||||
|
} else if sess.status == "failed" {
|
||||||
|
l.failed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// test runs, oldest first; failures remember in which earlier runs they failed too
|
||||||
|
let runs: Vec<&&Event> = evs.iter().filter(|e| e.kind == "test").collect();
|
||||||
|
let test = runs.last().map(|e| {
|
||||||
|
let p = &e.payload;
|
||||||
|
let mut earlier: HashMap<&str, Vec<usize>> = HashMap::new();
|
||||||
|
for (n, r) in runs[..runs.len() - 1].iter().enumerate() {
|
||||||
|
for f in r.payload["failures"].as_array().into_iter().flatten() {
|
||||||
|
earlier.entry(s(f, "name")).or_default().push(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let failures = p["failures"]
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|f| {
|
||||||
|
let name = s(f, "name");
|
||||||
|
let repeats = match earlier.get(name) {
|
||||||
|
Some(v) if !v.is_empty() => {
|
||||||
|
let which: Vec<String> = v
|
||||||
|
.iter()
|
||||||
|
.map(|&n| {
|
||||||
|
if n == 0 {
|
||||||
|
"the first run".into()
|
||||||
|
} else {
|
||||||
|
format!("fix {n}")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
format!("failed in {} too", which.join(", "))
|
||||||
|
}
|
||||||
|
_ => String::new(),
|
||||||
|
};
|
||||||
|
FailView {
|
||||||
|
name: name.into(),
|
||||||
|
message: s(f, "message").into(),
|
||||||
|
location: s(f, "location").into(),
|
||||||
|
repeats,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
TestRun {
|
||||||
|
step: s(p, "step").into(),
|
||||||
|
at_ms: e.at,
|
||||||
|
passed: p["passed"].as_u64().unwrap_or(0) as u32,
|
||||||
|
failed: p["failed"].as_u64().unwrap_or(0) as u32,
|
||||||
|
skipped: p["skipped"].as_u64().unwrap_or(0) as u32,
|
||||||
|
secs: p["secs"].as_f64().unwrap_or(0.0),
|
||||||
|
failures,
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut now = Now::default();
|
||||||
|
if let Some((name, run, cmd)) = running_step {
|
||||||
|
match run {
|
||||||
|
RunOn::Agent => {
|
||||||
|
now.who = "agent".into();
|
||||||
|
now.line = evs
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find_map(|e| match e.kind.as_str() {
|
||||||
|
"tool" => Some(s(&e.payload, "title").to_string()),
|
||||||
|
"edit" => Some(format!(
|
||||||
|
"edit {} +{} −{}",
|
||||||
|
s(&e.payload, "path"),
|
||||||
|
e.payload["added"],
|
||||||
|
e.payload["removed"]
|
||||||
|
)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| name.to_string());
|
||||||
|
}
|
||||||
|
RunOn::Computer => {
|
||||||
|
now.who = "computer".into();
|
||||||
|
now.line = cmd.unwrap_or(name).to_string();
|
||||||
|
}
|
||||||
|
RunOn::Human => {
|
||||||
|
now.who = "human".into();
|
||||||
|
now.line = name.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
now.intent = evs
|
||||||
|
.iter()
|
||||||
|
.rev()
|
||||||
|
.find(|e| e.kind == "intent")
|
||||||
|
.map(|e| s(&e.payload, "text").to_string())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
let mut files: Vec<FileChange> = vec![];
|
||||||
|
for e in evs.iter().filter(|e| e.kind == "edit") {
|
||||||
|
let (path, a, r) = (
|
||||||
|
s(&e.payload, "path"),
|
||||||
|
e.payload["added"].as_u64().unwrap_or(0) as u32,
|
||||||
|
e.payload["removed"].as_u64().unwrap_or(0) as u32,
|
||||||
|
);
|
||||||
|
match files.iter_mut().find(|f| f.path == path) {
|
||||||
|
Some(f) => {
|
||||||
|
f.added += a;
|
||||||
|
f.removed += r;
|
||||||
|
}
|
||||||
|
None => files.push(FileChange {
|
||||||
|
path: path.into(),
|
||||||
|
added: a,
|
||||||
|
removed: r,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let usage = evs.iter().rev().find(|e| e.kind == "usage");
|
||||||
|
let retries = machine
|
||||||
|
.states
|
||||||
|
.iter()
|
||||||
|
.flat_map(|st| {
|
||||||
|
st.retry
|
||||||
|
.iter()
|
||||||
|
.map(move |(c, r)| (st.name.as_str(), c.as_str(), r.max))
|
||||||
|
})
|
||||||
|
.map(|(st, c, max)| (hits(st, c), max))
|
||||||
|
.filter(|&(n, _)| n > 0)
|
||||||
|
.max_by_key(|&(n, _)| n);
|
||||||
|
let budget = Budget {
|
||||||
|
ctx: usage.map(|e| {
|
||||||
|
(
|
||||||
|
e.payload["ctx_used"].as_u64().unwrap_or(0),
|
||||||
|
e.payload["ctx_limit"].as_u64().unwrap_or(0),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
retries,
|
||||||
|
wall_secs: budget::active_secs(&evs, i.now_ms),
|
||||||
|
cost: budget::cost(&evs),
|
||||||
|
wall_cap: machine.budget.wall_secs,
|
||||||
|
cost_cap: machine.budget.cost,
|
||||||
|
compact_at: machine.budget.compact_at,
|
||||||
|
};
|
||||||
|
// a loop only matters while the session still runs
|
||||||
|
let looping = if active {
|
||||||
|
budget::looping(&evs).map(|l| LoopView {
|
||||||
|
runs: l.runs,
|
||||||
|
tests: l.tests,
|
||||||
|
file: l.file,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
|
Some(Detail {
|
||||||
|
id: id.into(),
|
||||||
|
task: task.name.clone(),
|
||||||
|
status,
|
||||||
|
branch: sess.branch.clone(),
|
||||||
|
worktree: sess.worktree.clone(),
|
||||||
|
pid: sess.pid,
|
||||||
|
machine_file: format!("{}.toml", machine.name),
|
||||||
|
on_abort: machine.on_abort.clone(),
|
||||||
|
on_budget: machine.on_budget.clone(),
|
||||||
|
lines,
|
||||||
|
path,
|
||||||
|
test,
|
||||||
|
now,
|
||||||
|
files,
|
||||||
|
budget,
|
||||||
|
looping,
|
||||||
|
states: machine.states.iter().map(|s| s.name.clone()).collect(),
|
||||||
|
start: machine.start().name.clone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::db::{Session, Task};
|
||||||
|
use crate::machine::Machine;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn ev(id: i64, kind: &str, payload: serde_json::Value) -> Event {
|
||||||
|
Event {
|
||||||
|
id,
|
||||||
|
session: "s2".into(),
|
||||||
|
at: 1000 * id as u64,
|
||||||
|
kind: kind.into(),
|
||||||
|
payload,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn state(id: i64, from: &str, to: &str) -> Event {
|
||||||
|
ev(id, "state", json!({"from": from, "to": to}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(id: i64, st: &str, name: &str, ms: u64, ok: bool) -> Event {
|
||||||
|
ev(
|
||||||
|
id,
|
||||||
|
"step",
|
||||||
|
json!({"state": st, "step": name, "ms": ms, "ok": ok}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_run(id: i64, names: &[&str]) -> Event {
|
||||||
|
let failures: Vec<_> = names
|
||||||
|
.iter()
|
||||||
|
.map(|n| json!({"name": n, "message": format!("{n} broke"), "location": "src/a.rs:1"}))
|
||||||
|
.collect();
|
||||||
|
ev(
|
||||||
|
id,
|
||||||
|
"test",
|
||||||
|
json!({"state": "test", "step": "cargo test", "passed": 39, "failed": names.len(), "skipped": 0, "secs": 6.2, "failures": failures}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn catch(id: i64) -> Event {
|
||||||
|
ev(
|
||||||
|
id,
|
||||||
|
"catch",
|
||||||
|
json!({"state": "test", "catch": "TestsFailed"}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// plan, code, build, test (2 failing) -> code; again; now in code for the third time.
|
||||||
|
fn scenario() -> Vec<Event> {
|
||||||
|
vec![
|
||||||
|
state(1, "", "plan"),
|
||||||
|
step(2, "plan", "read-goal", 200, true),
|
||||||
|
step(3, "plan", "draft-plan", 250_000, true),
|
||||||
|
state(4, "plan", "code"),
|
||||||
|
step(5, "code", "edit", 59_000, true),
|
||||||
|
state(6, "code", "build"),
|
||||||
|
step(7, "build", "cargo build", 38_000, true),
|
||||||
|
state(8, "build", "test"),
|
||||||
|
test_run(9, &["a::one", "a::two"]),
|
||||||
|
step(10, "test", "cargo test", 6_200, false),
|
||||||
|
catch(11),
|
||||||
|
state(12, "test", "code"),
|
||||||
|
step(13, "code", "edit", 59_000, true),
|
||||||
|
state(14, "code", "build"),
|
||||||
|
step(15, "build", "cargo build", 38_000, true),
|
||||||
|
state(16, "build", "test"),
|
||||||
|
test_run(17, &["a::one", "a::two"]),
|
||||||
|
step(18, "test", "cargo test", 6_200, false),
|
||||||
|
catch(19),
|
||||||
|
state(20, "test", "code"),
|
||||||
|
ev(21, "intent", json!({"text": "rotate the key"})),
|
||||||
|
ev(
|
||||||
|
22,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/auth/token.rs", "added": 6, "removed": 2}),
|
||||||
|
),
|
||||||
|
ev(
|
||||||
|
23,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/auth/token.rs", "added": 4, "removed": 0}),
|
||||||
|
),
|
||||||
|
ev(
|
||||||
|
24,
|
||||||
|
"edit",
|
||||||
|
json!({"path": "src/auth/mod.rs", "added": 1, "removed": 1}),
|
||||||
|
),
|
||||||
|
ev(25, "tool", json!({"title": "edit src/auth/token.rs"})),
|
||||||
|
ev(
|
||||||
|
26,
|
||||||
|
"usage",
|
||||||
|
json!({"ctx_used": 142_000, "ctx_limit": 200_000, "cost": 1.12}),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn detail(events: &[Event], status: &str, state: &str) -> Detail {
|
||||||
|
let m = HashMap::from([(
|
||||||
|
"task".to_string(),
|
||||||
|
Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(),
|
||||||
|
)]);
|
||||||
|
let tasks = [Task {
|
||||||
|
id: "s2".into(),
|
||||||
|
name: "oauth".into(),
|
||||||
|
subtitle: String::new(),
|
||||||
|
machine: "task".into(),
|
||||||
|
depends_on: vec![],
|
||||||
|
}];
|
||||||
|
let sessions = [Session {
|
||||||
|
id: "s2".into(),
|
||||||
|
task_id: "s2".into(),
|
||||||
|
branch: "hx/s2-oauth".into(),
|
||||||
|
worktree: "/wt/s2".into(),
|
||||||
|
pid: Some(7),
|
||||||
|
state: state.into(),
|
||||||
|
status: status.into(),
|
||||||
|
}];
|
||||||
|
build(
|
||||||
|
&Input {
|
||||||
|
goal: None,
|
||||||
|
tasks: &tasks,
|
||||||
|
sessions: &sessions,
|
||||||
|
events,
|
||||||
|
machines: &m,
|
||||||
|
needs: &[],
|
||||||
|
checks: &[],
|
||||||
|
decisions: &[],
|
||||||
|
now_ms: 36_000,
|
||||||
|
},
|
||||||
|
"s2",
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find<'a>(d: &'a Detail, text: &str) -> &'a MLine {
|
||||||
|
d.lines
|
||||||
|
.iter()
|
||||||
|
.find(|l| l.text.trim_end() == text)
|
||||||
|
.unwrap_or_else(|| panic!("no line {text:?}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn machine_lines_follow_the_mockup() {
|
||||||
|
let d = detail(&scenario(), "running", "code");
|
||||||
|
let plan = find(&d, "plan · start");
|
||||||
|
assert_eq!((plan.block, plan.live.as_str()), (Block::Done, "✓ 4m10s"));
|
||||||
|
let draft = find(&d, " draft-plan");
|
||||||
|
assert_eq!(
|
||||||
|
(draft.exec, draft.sets.as_str(), draft.live.as_str()),
|
||||||
|
(Some(RunOn::Agent), "■ planning", "✓ 4m10s")
|
||||||
|
);
|
||||||
|
let code = find(&d, "code");
|
||||||
|
assert_eq!((code.block, code.live.as_str()), (Block::Cur, "▶ fix 2"));
|
||||||
|
// the running step shows the time since the last event (36s now, last event at 26s)
|
||||||
|
assert_eq!(find(&d, " edit").live, "▶ 0m10s");
|
||||||
|
let build = find(&d, "build");
|
||||||
|
assert_eq!(build.live, "✓ 0m38s ×2");
|
||||||
|
let test = find(&d, "test");
|
||||||
|
assert_eq!((test.block, test.live.as_str()), (Block::Fail, "✗ 39/41"));
|
||||||
|
let hit = find(&d, " catch TestsFailed");
|
||||||
|
assert_eq!(
|
||||||
|
(hit.live.as_str(), hit.hit, hit.to.as_str()),
|
||||||
|
("hit 2×", true, " → code")
|
||||||
|
);
|
||||||
|
let next = find(&d, " catch TestsFailed ×3");
|
||||||
|
assert_eq!(
|
||||||
|
(next.live.as_str(), next.to.as_str()),
|
||||||
|
("next", " → escalated")
|
||||||
|
);
|
||||||
|
assert_eq!(find(&d, "review · gate").block, Block::Todo);
|
||||||
|
assert_eq!(find(&d, "merge · exit").live, "");
|
||||||
|
assert_eq!(find(&d, " end: merged").kind, LineKind::End);
|
||||||
|
// only_on states come last, marked
|
||||||
|
assert!(
|
||||||
|
d.lines
|
||||||
|
.iter()
|
||||||
|
.any(|l| l.text == "│ only on TestsFailed ×3, budget")
|
||||||
|
);
|
||||||
|
assert!(d.lines.iter().any(|l| l.text == "│ escalated · exit"));
|
||||||
|
assert!(d.lines.iter().any(|l| l.text == "│ snapshot-worktree"));
|
||||||
|
// untouched machine order: escalated after merge
|
||||||
|
let pos = |t: &str| d.lines.iter().position(|l| l.text == t).unwrap();
|
||||||
|
assert!(pos("merge · exit") < pos("│ escalated · exit"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn path_test_run_now_files_budget() {
|
||||||
|
let d = detail(&scenario(), "running", "code");
|
||||||
|
let names: Vec<String> = d
|
||||||
|
.path
|
||||||
|
.iter()
|
||||||
|
.map(|p| format!("{}{}", p.name, if p.failed { " ✗" } else { "" }))
|
||||||
|
.collect();
|
||||||
|
assert_eq!(
|
||||||
|
names,
|
||||||
|
[
|
||||||
|
"plan", "code", "build", "test ✗", "code", "build", "test ✗", "code"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(d.path.last().unwrap().current);
|
||||||
|
|
||||||
|
let t = d.test.as_ref().unwrap();
|
||||||
|
assert_eq!((t.passed, t.failed, t.step.as_str()), (39, 2, "cargo test"));
|
||||||
|
assert_eq!(t.failures[0].repeats, "failed in the first run too");
|
||||||
|
assert_eq!(t.failures[1].location, "src/a.rs:1");
|
||||||
|
|
||||||
|
assert_eq!(d.now.who, "agent");
|
||||||
|
assert_eq!(d.now.line, "edit src/auth/token.rs");
|
||||||
|
assert_eq!(d.now.intent, "rotate the key");
|
||||||
|
|
||||||
|
assert_eq!(d.files.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
(
|
||||||
|
d.files[0].path.as_str(),
|
||||||
|
d.files[0].added,
|
||||||
|
d.files[0].removed
|
||||||
|
),
|
||||||
|
("src/auth/token.rs", 10, 2)
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(d.budget.ctx, Some((142_000, 200_000)));
|
||||||
|
assert_eq!(d.budget.retries, Some((2, 3)));
|
||||||
|
assert_eq!(d.budget.wall_secs, 35);
|
||||||
|
assert!((d.budget.cost - 1.12).abs() < 1e-9);
|
||||||
|
assert_eq!(
|
||||||
|
(d.status, d.branch.as_str(), d.pid),
|
||||||
|
(Status::Fix, "hx/s2-oauth", Some(7))
|
||||||
|
);
|
||||||
|
assert_eq!(d.on_budget.as_deref(), Some("escalated"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn third_failure_lists_both_earlier_runs() {
|
||||||
|
let mut evs = scenario();
|
||||||
|
evs.push(test_run(30, &["a::one"]));
|
||||||
|
let d = detail(&evs, "running", "code");
|
||||||
|
assert_eq!(
|
||||||
|
d.test.unwrap().failures[0].repeats,
|
||||||
|
"failed in the first run, fix 1 too"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn finished_session_has_no_current_state() {
|
||||||
|
let evs = vec![
|
||||||
|
state(1, "", "plan"),
|
||||||
|
step(2, "plan", "read-goal", 100, true),
|
||||||
|
ev(3, "end", json!({"status": "failed", "reason": "boom"})),
|
||||||
|
];
|
||||||
|
let d = detail(&evs, "failed", "plan");
|
||||||
|
assert_eq!(find(&d, "plan · start").block, Block::Fail);
|
||||||
|
assert!(d.path[0].failed && !d.path[0].current);
|
||||||
|
assert_eq!(d.now, Now::default());
|
||||||
|
assert_eq!(dur(500), "0.5s");
|
||||||
|
assert_eq!(dur(65_000), "1m05s");
|
||||||
|
}
|
||||||
|
}
|
||||||
+351
@@ -0,0 +1,351 @@
|
|||||||
|
//! View model of the goal screen (ORCHESTRATOR.md 7.3, `Goal.dc.html`): the goal and its definition of done,
|
||||||
|
//! the task graph in columns by dependency depth, the critical path, the decisions agents made, the checks.
|
||||||
|
|
||||||
|
use crate::view::{Input, Status, hms};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct TaskBox {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub status: Status,
|
||||||
|
/// `merged`, `queued`, or the state the session is in.
|
||||||
|
pub detail: String,
|
||||||
|
pub after: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct Column {
|
||||||
|
pub label: String,
|
||||||
|
pub tasks: Vec<TaskBox>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct DecisionView {
|
||||||
|
pub id: i64,
|
||||||
|
pub session: String,
|
||||||
|
pub text: String,
|
||||||
|
/// The state the decision was made in.
|
||||||
|
pub state: String,
|
||||||
|
/// `plan · 13:22`
|
||||||
|
pub whence: String,
|
||||||
|
pub vetoed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum CheckState {
|
||||||
|
Pass,
|
||||||
|
Fail,
|
||||||
|
/// Never ran on main.
|
||||||
|
Unknown,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct CheckView {
|
||||||
|
pub name: String,
|
||||||
|
pub owner: String,
|
||||||
|
pub state: CheckState,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug, Default)]
|
||||||
|
pub struct GoalView {
|
||||||
|
pub goal: String,
|
||||||
|
pub done_when: String,
|
||||||
|
pub columns: Vec<Column>,
|
||||||
|
/// `s2 oauth-provider`, in order; the longest chain of unfinished tasks.
|
||||||
|
pub critical: Vec<String>,
|
||||||
|
pub decisions: Vec<DecisionView>,
|
||||||
|
pub checks: Vec<CheckView>,
|
||||||
|
pub green: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Length of the dependency chain below a task (0 = no dependencies). Cycles count as 0 instead of looping.
|
||||||
|
fn depth(id: &str, deps: &HashMap<&str, &Vec<String>>, seen: &mut Vec<String>) -> usize {
|
||||||
|
if seen.iter().any(|s| s == id) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
seen.push(id.to_string());
|
||||||
|
let d = deps.get(id).map_or(0, |ds| {
|
||||||
|
ds.iter()
|
||||||
|
.map(|d| 1 + depth(d, deps, seen))
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0)
|
||||||
|
});
|
||||||
|
seen.pop();
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build(i: &Input) -> GoalView {
|
||||||
|
let overview = crate::view::build(i);
|
||||||
|
let deps: HashMap<&str, &Vec<String>> = i
|
||||||
|
.tasks
|
||||||
|
.iter()
|
||||||
|
.map(|t| (t.id.as_str(), &t.depends_on))
|
||||||
|
.collect();
|
||||||
|
let mut boxes: Vec<(usize, TaskBox)> = vec![];
|
||||||
|
for t in i.tasks {
|
||||||
|
let row = overview.rows.iter().find(|r| r.id == t.id);
|
||||||
|
let session = i.sessions.iter().find(|s| s.id == t.id);
|
||||||
|
let status = row.map_or(Status::Blocked, |r| r.status);
|
||||||
|
let detail = match (status, session) {
|
||||||
|
(Status::Done, _) => "merged".to_string(),
|
||||||
|
(_, Some(s)) if !s.state.is_empty() => match row {
|
||||||
|
Some(r) if !r.retry.is_empty() => format!("{} {}", s.state, r.retry),
|
||||||
|
_ => s.state.clone(),
|
||||||
|
},
|
||||||
|
_ => "queued".to_string(),
|
||||||
|
};
|
||||||
|
boxes.push((
|
||||||
|
depth(&t.id, &deps, &mut vec![]),
|
||||||
|
TaskBox {
|
||||||
|
id: t.id.clone(),
|
||||||
|
name: t.name.clone(),
|
||||||
|
status,
|
||||||
|
detail,
|
||||||
|
after: t.depends_on.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let levels = boxes.iter().map(|b| b.0).max().map_or(0, |m| m + 1);
|
||||||
|
let columns = (0..levels)
|
||||||
|
.map(|l| Column {
|
||||||
|
label: format!("level {l}"),
|
||||||
|
tasks: boxes
|
||||||
|
.iter()
|
||||||
|
.filter(|b| b.0 == l)
|
||||||
|
.map(|b| b.1.clone())
|
||||||
|
.collect(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// critical path: longest chain over unfinished tasks only
|
||||||
|
let open: Vec<&TaskBox> = boxes
|
||||||
|
.iter()
|
||||||
|
.map(|b| &b.1)
|
||||||
|
.filter(|t| t.status != Status::Done)
|
||||||
|
.collect();
|
||||||
|
let mut best: HashMap<&str, (usize, Option<&str>)> = HashMap::new();
|
||||||
|
let mut order: Vec<&TaskBox> = open.clone();
|
||||||
|
order.sort_by_key(|t| depth(&t.id, &deps, &mut vec![])); // dependencies first
|
||||||
|
for t in &order {
|
||||||
|
let prev = t
|
||||||
|
.after
|
||||||
|
.iter()
|
||||||
|
.filter_map(|d| best.get(d.as_str()).map(|(n, _)| (*n, d.as_str())))
|
||||||
|
.max_by(|a, b| a.0.cmp(&b.0).then(b.1.cmp(a.1))); // longest, then lowest id
|
||||||
|
best.insert(&t.id, (prev.map_or(1, |p| p.0 + 1), prev.map(|p| p.1)));
|
||||||
|
}
|
||||||
|
let end = open
|
||||||
|
.iter()
|
||||||
|
.map(|t| t.id.as_str())
|
||||||
|
.max_by(|a, b| best[a].0.cmp(&best[b].0).then(b.cmp(a)));
|
||||||
|
let mut critical = vec![];
|
||||||
|
let mut cur = end;
|
||||||
|
while let Some(id) = cur {
|
||||||
|
let name = boxes
|
||||||
|
.iter()
|
||||||
|
.find(|b| b.1.id == id)
|
||||||
|
.map_or("", |b| b.1.name.as_str());
|
||||||
|
critical.push(format!("{id} {name}"));
|
||||||
|
cur = best[id].1;
|
||||||
|
}
|
||||||
|
critical.reverse();
|
||||||
|
|
||||||
|
let decisions = i
|
||||||
|
.decisions
|
||||||
|
.iter()
|
||||||
|
.map(|d| DecisionView {
|
||||||
|
id: d.id,
|
||||||
|
session: d.session.clone(),
|
||||||
|
text: d.text.clone(),
|
||||||
|
state: d.state.clone(),
|
||||||
|
whence: format!("{} · {}", d.state, &hms(d.at)[..5]),
|
||||||
|
vetoed: d.vetoed,
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let checks: Vec<CheckView> = i
|
||||||
|
.checks
|
||||||
|
.iter()
|
||||||
|
.map(|c| CheckView {
|
||||||
|
name: c.name.clone(),
|
||||||
|
owner: c.owner.clone().unwrap_or_else(|| "-".into()),
|
||||||
|
state: match c.last_status.as_deref() {
|
||||||
|
Some("pass") => CheckState::Pass,
|
||||||
|
Some(_) => CheckState::Fail,
|
||||||
|
None => CheckState::Unknown,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let green = checks
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.state == CheckState::Pass)
|
||||||
|
.count();
|
||||||
|
let done_when = if checks.is_empty() {
|
||||||
|
"Done = all acceptance checks green on main. None defined yet: orch check NAME CMD."
|
||||||
|
.to_string()
|
||||||
|
} else {
|
||||||
|
format!(
|
||||||
|
"Done = all {} acceptance checks green on main. The orchestrator re-runs them after every merge.",
|
||||||
|
checks.len()
|
||||||
|
)
|
||||||
|
};
|
||||||
|
GoalView {
|
||||||
|
goal: i.goal.unwrap_or("no goal set: orch goal \"…\"").to_string(),
|
||||||
|
done_when,
|
||||||
|
columns,
|
||||||
|
critical,
|
||||||
|
decisions,
|
||||||
|
checks,
|
||||||
|
green,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::db::{CheckRow, DecisionRow, Session, Task};
|
||||||
|
use crate::machine::Machine;
|
||||||
|
|
||||||
|
fn task(id: &str, name: &str, after: &[&str]) -> Task {
|
||||||
|
Task {
|
||||||
|
id: id.into(),
|
||||||
|
name: name.into(),
|
||||||
|
subtitle: String::new(),
|
||||||
|
machine: "task".into(),
|
||||||
|
depends_on: after.iter().map(|a| a.to_string()).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session(id: &str, state: &str, status: &str) -> Session {
|
||||||
|
Session {
|
||||||
|
id: id.into(),
|
||||||
|
task_id: id.into(),
|
||||||
|
branch: "b".into(),
|
||||||
|
worktree: "/w".into(),
|
||||||
|
pid: None,
|
||||||
|
state: state.into(),
|
||||||
|
status: status.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view(
|
||||||
|
tasks: &[Task],
|
||||||
|
sessions: &[Session],
|
||||||
|
checks: &[CheckRow],
|
||||||
|
decisions: &[DecisionRow],
|
||||||
|
) -> GoalView {
|
||||||
|
let m = HashMap::from([(
|
||||||
|
"task".to_string(),
|
||||||
|
Machine::parse(include_str!("../examples/machines/task.toml")).unwrap(),
|
||||||
|
)]);
|
||||||
|
build(&Input {
|
||||||
|
goal: Some("Move login to OAuth2"),
|
||||||
|
tasks,
|
||||||
|
sessions,
|
||||||
|
events: &[],
|
||||||
|
machines: &m,
|
||||||
|
needs: &[],
|
||||||
|
checks,
|
||||||
|
decisions,
|
||||||
|
now_ms: 0,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(name: &str, owner: Option<&str>, st: Option<&str>) -> CheckRow {
|
||||||
|
CheckRow {
|
||||||
|
id: 1,
|
||||||
|
name: name.into(),
|
||||||
|
cmd: "true".into(),
|
||||||
|
owner: owner.map(Into::into),
|
||||||
|
last_status: st.map(Into::into),
|
||||||
|
last_run_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn graph_columns_critical_path_and_checks() {
|
||||||
|
let tasks = [
|
||||||
|
task("s1", "schema-migrate", &[]),
|
||||||
|
task("s2", "oauth-provider", &["s1"]),
|
||||||
|
task("s3", "auth-middleware", &["s1"]),
|
||||||
|
task("s4", "rate-limiter", &["s1"]),
|
||||||
|
task("s5", "docs-update", &["s2", "s3"]),
|
||||||
|
task("s6", "e2e-tests", &["s3", "s4"]),
|
||||||
|
];
|
||||||
|
let sessions = [
|
||||||
|
session("s1", "merge", "merged"),
|
||||||
|
session("s2", "test", "running"),
|
||||||
|
session("s3", "review", "waiting"),
|
||||||
|
session("s4", "build", "running"),
|
||||||
|
session("s5", "", "queued"),
|
||||||
|
session("s6", "plan", "running"),
|
||||||
|
];
|
||||||
|
let checks = [
|
||||||
|
check("build", None, Some("pass")),
|
||||||
|
check("unit", Some("s2"), Some("fail")),
|
||||||
|
check("e2e", Some("s6"), None),
|
||||||
|
];
|
||||||
|
let decisions = [DecisionRow {
|
||||||
|
id: 1,
|
||||||
|
session: "s4".into(),
|
||||||
|
text: "token bucket".into(),
|
||||||
|
state: "plan".into(),
|
||||||
|
at: 0,
|
||||||
|
vetoed: false,
|
||||||
|
}];
|
||||||
|
let v = view(&tasks, &sessions, &checks, &decisions);
|
||||||
|
|
||||||
|
fn ids(c: &Column) -> Vec<&str> {
|
||||||
|
c.tasks.iter().map(|t| t.id.as_str()).collect()
|
||||||
|
}
|
||||||
|
assert_eq!(v.columns.len(), 3);
|
||||||
|
assert_eq!(ids(&v.columns[0]), ["s1"]);
|
||||||
|
assert_eq!(ids(&v.columns[1]), ["s2", "s3", "s4"]);
|
||||||
|
assert_eq!(ids(&v.columns[2]), ["s5", "s6"]);
|
||||||
|
assert_eq!(v.columns[0].label, "level 0");
|
||||||
|
let s1 = &v.columns[0].tasks[0];
|
||||||
|
assert_eq!((s1.status, s1.detail.as_str()), (Status::Done, "merged"));
|
||||||
|
let s3 = &v.columns[1].tasks[1];
|
||||||
|
assert_eq!(
|
||||||
|
(s3.status, s3.detail.as_str(), s3.after.clone()),
|
||||||
|
(Status::Wait, "review", vec!["s1".to_string()])
|
||||||
|
);
|
||||||
|
let s5 = &v.columns[2].tasks[0];
|
||||||
|
assert_eq!((s5.status, s5.detail.as_str()), (Status::Blocked, "queued"));
|
||||||
|
|
||||||
|
// longest chain of unfinished tasks; s1 is merged and not part of it
|
||||||
|
assert_eq!(v.critical, ["s2 oauth-provider", "s5 docs-update"]);
|
||||||
|
|
||||||
|
assert_eq!((v.green, v.checks.len()), (1, 3));
|
||||||
|
assert_eq!(
|
||||||
|
v.checks.iter().map(|c| c.state).collect::<Vec<_>>(),
|
||||||
|
[CheckState::Pass, CheckState::Fail, CheckState::Unknown]
|
||||||
|
);
|
||||||
|
assert_eq!(v.checks[0].owner, "-");
|
||||||
|
assert!(
|
||||||
|
v.done_when
|
||||||
|
.starts_with("Done = all 3 acceptance checks green on main")
|
||||||
|
);
|
||||||
|
assert_eq!(v.decisions[0].session, "s4");
|
||||||
|
assert!(v.decisions[0].whence.starts_with("plan · "));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_and_cyclic_goals_do_not_break() {
|
||||||
|
let v = view(&[], &[], &[], &[]);
|
||||||
|
assert!(v.columns.is_empty() && v.critical.is_empty());
|
||||||
|
assert!(v.done_when.contains("None defined yet"));
|
||||||
|
// a cycle is a user error, not a hang
|
||||||
|
let tasks = [task("s1", "a", &["s2"]), task("s2", "b", &["s1"])];
|
||||||
|
let sessions = [session("s1", "", "queued"), session("s2", "", "queued")];
|
||||||
|
let v = view(&tasks, &sessions, &[], &[]);
|
||||||
|
assert_eq!(v.columns.iter().map(|c| c.tasks.len()).sum::<usize>(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_done_has_no_critical_path() {
|
||||||
|
let tasks = [task("s1", "a", &[])];
|
||||||
|
let sessions = [session("s1", "merge", "merged")];
|
||||||
|
assert!(view(&tasks, &sessions, &[], &[]).critical.is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
+253
@@ -0,0 +1,253 @@
|
|||||||
|
//! JUnit XML test reports (`report = "junit"` steps): counts and the failing tests with message and location.
|
||||||
|
//! Works with `cargo nextest --message-format junit`, `cargo2junit`, pytest, JUnit itself: it only needs
|
||||||
|
//! `<testcase name classname time file line>` with `<failure>`/`<error>`/`<skipped>` children.
|
||||||
|
|
||||||
|
use anyhow::{Result, anyhow};
|
||||||
|
use quick_xml::Reader;
|
||||||
|
use quick_xml::escape::resolve_predefined_entity;
|
||||||
|
use quick_xml::events::{BytesStart, Event};
|
||||||
|
use serde::Serialize;
|
||||||
|
|
||||||
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
||||||
|
pub struct Failure {
|
||||||
|
pub name: String,
|
||||||
|
/// The assertion text: the `message` attribute, else the first line of the failure body.
|
||||||
|
pub message: String,
|
||||||
|
/// `file:line` when the report has it, else the first `path.ext:NN` in the failure body.
|
||||||
|
pub location: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize, Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct Report {
|
||||||
|
pub passed: u32,
|
||||||
|
pub failed: u32,
|
||||||
|
pub skipped: u32,
|
||||||
|
/// Sum of the test times.
|
||||||
|
pub secs: f64,
|
||||||
|
pub failures: Vec<Failure>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attr(e: &BytesStart, key: &str) -> String {
|
||||||
|
e.attributes()
|
||||||
|
.flatten()
|
||||||
|
.find(|a| a.key.as_ref() == key)
|
||||||
|
.and_then(|a| {
|
||||||
|
a.normalized_value(quick_xml::XmlVersion::Implicit1_0)
|
||||||
|
.ok()
|
||||||
|
.map(|v| v.into_owned())
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// First `something/with.ext:123` word of a text.
|
||||||
|
fn find_location(text: &str) -> String {
|
||||||
|
text.split(|c: char| c.is_whitespace() || matches!(c, '(' | ')' | ',' | '\'' | '"' | '`'))
|
||||||
|
.map(|w| w.trim_end_matches(':'))
|
||||||
|
.find(|w| {
|
||||||
|
let mut it = w.rsplitn(2, ':');
|
||||||
|
let (line, file) = (it.next(), it.next());
|
||||||
|
// rsplitn on `a.rs:12:5` leaves `a.rs:12` as the file part; accept both shapes
|
||||||
|
let file = file.unwrap_or("").split(':').next().unwrap_or("");
|
||||||
|
line.is_some_and(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
|
||||||
|
&& file.contains('.')
|
||||||
|
&& !file.starts_with('.')
|
||||||
|
})
|
||||||
|
.map(|w| {
|
||||||
|
// keep file:line, drop a trailing :column
|
||||||
|
let parts: Vec<&str> = w.split(':').collect();
|
||||||
|
if parts.len() >= 3 {
|
||||||
|
format!("{}:{}", parts[0], parts[1])
|
||||||
|
} else {
|
||||||
|
w.to_string()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Case {
|
||||||
|
name: String,
|
||||||
|
file: String,
|
||||||
|
line: String,
|
||||||
|
failure: Option<(String, String)>, // (message attr, body)
|
||||||
|
skipped: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parse(xml: &str) -> Result<Report> {
|
||||||
|
let mut r = Reader::from_str(xml);
|
||||||
|
let mut rep = Report::default();
|
||||||
|
let mut case: Option<Case> = None;
|
||||||
|
// inside <failure>/<error>: collecting the body text
|
||||||
|
let mut in_failure = false;
|
||||||
|
loop {
|
||||||
|
let ev = r
|
||||||
|
.read_event()
|
||||||
|
.map_err(|e| anyhow!("bad junit xml at byte {}: {e}", r.buffer_position()))?;
|
||||||
|
match &ev {
|
||||||
|
Event::Eof => break,
|
||||||
|
Event::Start(e) | Event::Empty(e) => {
|
||||||
|
let empty = matches!(ev, Event::Empty(_));
|
||||||
|
match e.local_name().as_ref() {
|
||||||
|
"testcase" => {
|
||||||
|
let (class, name) = (attr(e, "classname"), attr(e, "name"));
|
||||||
|
let name = if class.is_empty() || name.contains("::") {
|
||||||
|
name
|
||||||
|
} else {
|
||||||
|
format!("{class}::{name}")
|
||||||
|
};
|
||||||
|
rep.secs += attr(e, "time").parse::<f64>().unwrap_or(0.0);
|
||||||
|
let c = Case {
|
||||||
|
name,
|
||||||
|
file: attr(e, "file"),
|
||||||
|
line: attr(e, "line"),
|
||||||
|
failure: None,
|
||||||
|
skipped: false,
|
||||||
|
};
|
||||||
|
if empty {
|
||||||
|
rep.passed += 1;
|
||||||
|
} else {
|
||||||
|
case = Some(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"failure" | "error" => {
|
||||||
|
if let Some(c) = &mut case {
|
||||||
|
c.failure = Some((attr(e, "message"), String::new()));
|
||||||
|
in_failure = !empty;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"skipped" => {
|
||||||
|
if let Some(c) = &mut case {
|
||||||
|
c.skipped = true;
|
||||||
|
rep.skipped += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Event::Text(t) if in_failure => push_body(&mut case, &t.xml10_content()),
|
||||||
|
Event::CData(t) if in_failure => push_body(&mut case, &t.xml10_content()),
|
||||||
|
Event::GeneralRef(g) if in_failure => {
|
||||||
|
let s = if g.is_char_ref() {
|
||||||
|
g.resolve_char_ref().ok().flatten().map(String::from)
|
||||||
|
} else {
|
||||||
|
resolve_predefined_entity(&g.xml10_content()).map(String::from)
|
||||||
|
};
|
||||||
|
push_body(&mut case, &s.unwrap_or_default());
|
||||||
|
}
|
||||||
|
Event::End(e) => match e.local_name().as_ref() {
|
||||||
|
"failure" | "error" => in_failure = false,
|
||||||
|
"testcase" => {
|
||||||
|
if let Some(c) = case.take() {
|
||||||
|
match c.failure {
|
||||||
|
Some((msg, body)) => {
|
||||||
|
rep.failed += 1;
|
||||||
|
let message = if msg.trim().is_empty() {
|
||||||
|
body.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.find(|l| !l.is_empty())
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_string()
|
||||||
|
} else {
|
||||||
|
msg
|
||||||
|
};
|
||||||
|
let location = if !c.file.is_empty() && !c.line.is_empty() {
|
||||||
|
format!("{}:{}", c.file, c.line)
|
||||||
|
} else {
|
||||||
|
find_location(&format!("{message} {body}"))
|
||||||
|
};
|
||||||
|
rep.failures.push(Failure {
|
||||||
|
name: c.name,
|
||||||
|
message,
|
||||||
|
location,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
None if c.skipped => {}
|
||||||
|
None => rep.passed += 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
},
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(rep)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push_body(case: &mut Option<Case>, s: &str) {
|
||||||
|
if let Some(Case {
|
||||||
|
failure: Some((_, body)),
|
||||||
|
..
|
||||||
|
}) = case
|
||||||
|
{
|
||||||
|
body.push_str(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const XML: &str = r#"<?xml version="1.0"?>
|
||||||
|
<testsuites>
|
||||||
|
<testsuite name="auth" tests="5" failures="2" skipped="1">
|
||||||
|
<testcase classname="auth::token" name="issues_pair" time="0.5"/>
|
||||||
|
<testcase classname="auth::token" name="skipped_one" time="0"><skipped/></testcase>
|
||||||
|
<testcase classname="auth::token" name="refresh_rotates_secret" time="1.5">
|
||||||
|
<failure message="assertion `left != right` failed: key id unchanged after refresh" type="assert">
|
||||||
|
thread 'main' panicked at src/auth/token.rs:142:9:
|
||||||
|
assertion failed
|
||||||
|
</failure>
|
||||||
|
</testcase>
|
||||||
|
<testcase classname="x" name="auth::token::expired_token_rejected" time="2.25">
|
||||||
|
<failure type="assert">expected Err(Expired), got Ok(Claims { sub: "u_17" })
|
||||||
|
at src/auth/token.rs:188:5</failure>
|
||||||
|
</testcase>
|
||||||
|
<testcase classname="auth::token" name="passes_with_body" time="0.25"><system-out><![CDATA[noise]]></system-out></testcase>
|
||||||
|
</testsuite>
|
||||||
|
</testsuites>"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn counts_failures_and_locations() {
|
||||||
|
let r = parse(XML).unwrap();
|
||||||
|
assert_eq!((r.passed, r.failed, r.skipped), (2, 2, 1));
|
||||||
|
assert!((r.secs - 4.5).abs() < 1e-9);
|
||||||
|
assert_eq!(
|
||||||
|
r.failures[0],
|
||||||
|
Failure {
|
||||||
|
name: "auth::token::refresh_rotates_secret".into(),
|
||||||
|
message: "assertion `left != right` failed: key id unchanged after refresh".into(),
|
||||||
|
location: "src/auth/token.rs:142".into(),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
// message from the body (entities resolved), classname dropped when the name has a path already
|
||||||
|
assert_eq!(r.failures[1].name, "auth::token::expired_token_rejected");
|
||||||
|
assert_eq!(
|
||||||
|
r.failures[1].message,
|
||||||
|
"expected Err(Expired), got Ok(Claims { sub: \"u_17\" })"
|
||||||
|
);
|
||||||
|
assert_eq!(r.failures[1].location, "src/auth/token.rs:188");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn file_and_line_attributes_win() {
|
||||||
|
let r = parse(
|
||||||
|
r#"<testsuite><testcase name="t" file="a/b.rs" line="7"><error message="boom"/></testcase></testsuite>"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(r.failures[0].location, "a/b.rs:7");
|
||||||
|
assert_eq!((r.passed, r.failed), (0, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_and_broken_input() {
|
||||||
|
assert_eq!(parse("<testsuite/>").unwrap(), Report::default());
|
||||||
|
assert!(parse("<testsuite><testcase></testsuite>").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn locations() {
|
||||||
|
assert_eq!(find_location("panicked at src/a.rs:12:5:"), "src/a.rs:12");
|
||||||
|
assert_eq!(find_location("see lib.rs:3"), "lib.rs:3");
|
||||||
|
assert_eq!(find_location("no location 12:30 here"), "");
|
||||||
|
}
|
||||||
|
}
|
||||||
+365
@@ -0,0 +1,365 @@
|
|||||||
|
//! Machine files: TOML state machines that drive one session (see ORCHESTRATOR.md section 3).
|
||||||
|
// shortcut: nothing calls this yet; the session runner (milestone 2) does. Remove then.
|
||||||
|
#![allow(dead_code)]
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, bail, ensure};
|
||||||
|
use indexmap::IndexMap;
|
||||||
|
use serde::Deserialize;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone, Copy, PartialEq, Eq, Debug, Default)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Kind {
|
||||||
|
Start,
|
||||||
|
#[default]
|
||||||
|
Normal,
|
||||||
|
Gate,
|
||||||
|
Exit,
|
||||||
|
Abort,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum RunOn {
|
||||||
|
Computer,
|
||||||
|
Agent,
|
||||||
|
Human,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone, Debug)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Step {
|
||||||
|
pub name: String,
|
||||||
|
pub run: RunOn,
|
||||||
|
/// Shell command (`computer`); supports {{session}} {{scope}} {{worktree}} {{branch}}.
|
||||||
|
pub cmd: Option<String>,
|
||||||
|
/// Status label shown as `■ <label>`.
|
||||||
|
pub sets: Option<String>,
|
||||||
|
/// Prompt kind for `agent` steps.
|
||||||
|
pub prompt: Option<String>,
|
||||||
|
/// Test report format the orchestrator parses after the step (`junit`).
|
||||||
|
pub report: Option<String>,
|
||||||
|
/// Catch to raise when the step fails; default is the first catch of the state.
|
||||||
|
pub fail_as: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone, Debug)]
|
||||||
|
pub struct Retry {
|
||||||
|
pub max: u32,
|
||||||
|
pub then: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone, Debug)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct State {
|
||||||
|
pub name: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub kind: Kind,
|
||||||
|
#[serde(default)]
|
||||||
|
pub steps: Vec<Step>,
|
||||||
|
/// Catch name -> target state. Order matters: the first key is the default catch.
|
||||||
|
#[serde(default)]
|
||||||
|
pub catch: IndexMap<String, String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub retry: IndexMap<String, Retry>,
|
||||||
|
pub next: Option<String>,
|
||||||
|
/// Final session status for `exit` and `abort` states.
|
||||||
|
pub end: Option<String>,
|
||||||
|
/// Never entered by `next`; only by these catches or events.
|
||||||
|
#[serde(default)]
|
||||||
|
pub only_on: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Per-session limits. Exceeding `wall_secs` (time spent working, not waiting for the user) or `cost` emits a
|
||||||
|
/// `budget` event and sends the session to `on_budget`. Past `compact_at` percent of the context window hx is
|
||||||
|
/// told to compact. The retry limit is the `retry` table of the state that loops.
|
||||||
|
#[derive(Deserialize, Clone, Debug, Default, PartialEq)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct BudgetCfg {
|
||||||
|
pub wall_secs: Option<u64>,
|
||||||
|
/// US dollars.
|
||||||
|
pub cost: Option<f64>,
|
||||||
|
pub compact_at: Option<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Clone, Debug)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct Machine {
|
||||||
|
pub name: String,
|
||||||
|
pub on_abort: Option<String>,
|
||||||
|
pub on_budget: Option<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub budget: BudgetCfg,
|
||||||
|
#[serde(rename = "state")]
|
||||||
|
pub states: Vec<State>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Machine {
|
||||||
|
pub fn parse(text: &str) -> Result<Self> {
|
||||||
|
let m: Machine = toml::from_str(text)?;
|
||||||
|
m.validate()?;
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load(path: &Path) -> Result<Self> {
|
||||||
|
let text = std::fs::read_to_string(path).with_context(|| path.display().to_string())?;
|
||||||
|
Self::parse(&text).with_context(|| format!("machine {}", path.display()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<name>.toml` in `<repo>/.hx/machines/`, then `~/.hx/machines/`.
|
||||||
|
pub fn find(name: &str, repo: &Path) -> Result<Self> {
|
||||||
|
let file = format!("{name}.toml");
|
||||||
|
let mut dirs = vec![repo.join(".hx/machines")];
|
||||||
|
if let Some(h) = std::env::var_os("HOME") {
|
||||||
|
dirs.push(PathBuf::from(h).join(".hx/machines"));
|
||||||
|
}
|
||||||
|
for d in &dirs {
|
||||||
|
if d.join(&file).is_file() {
|
||||||
|
return Self::load(&d.join(&file));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bail!("machine {name:?} not found in {dirs:?}")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn state(&self, name: &str) -> Option<&State> {
|
||||||
|
self.states.iter().find(|s| s.name == name)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn start(&self) -> &State {
|
||||||
|
// validate() guarantees exactly one
|
||||||
|
self.states
|
||||||
|
.iter()
|
||||||
|
.find(|s| s.kind == Kind::Start)
|
||||||
|
.expect("validated machine has a start state")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// States shown in the overview strip: everything except `only_on` states.
|
||||||
|
pub fn strip(&self) -> impl Iterator<Item = &State> {
|
||||||
|
self.states.iter().filter(|s| s.only_on.is_empty())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn validate(&self) -> Result<()> {
|
||||||
|
let starts = self.states.iter().filter(|s| s.kind == Kind::Start).count();
|
||||||
|
ensure!(starts == 1, "need exactly one start state, found {starts}");
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
for s in &self.states {
|
||||||
|
ensure!(seen.insert(&s.name), "duplicate state {:?}", s.name);
|
||||||
|
}
|
||||||
|
let target = |from: &str, what: &str, to: &str| -> Result<()> {
|
||||||
|
ensure!(
|
||||||
|
self.state(to).is_some(),
|
||||||
|
"state {from:?}: {what} points at unknown state {to:?}"
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
if let Some(c) = self.budget.compact_at {
|
||||||
|
ensure!(
|
||||||
|
(1..=100).contains(&c),
|
||||||
|
"budget.compact_at is a percent, 1 to 100"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (what, to) in [("on_abort", &self.on_abort), ("on_budget", &self.on_budget)] {
|
||||||
|
if let Some(to) = to {
|
||||||
|
target("<machine>", what, to)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for s in &self.states {
|
||||||
|
let n = &s.name;
|
||||||
|
let ends = matches!(s.kind, Kind::Exit | Kind::Abort);
|
||||||
|
if ends {
|
||||||
|
ensure!(
|
||||||
|
s.end.is_some(),
|
||||||
|
"state {n:?}: {:?} state needs `end`",
|
||||||
|
s.kind
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
ensure!(s.next.is_some(), "state {n:?} needs `next`");
|
||||||
|
}
|
||||||
|
if let Some(t) = &s.next {
|
||||||
|
target(n, "next", t)?;
|
||||||
|
let dest = self.state(t).expect("checked above");
|
||||||
|
ensure!(
|
||||||
|
dest.only_on.is_empty(),
|
||||||
|
"state {n:?}: next points at {t:?}, which has only_on"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (c, t) in &s.catch {
|
||||||
|
target(n, &format!("catch {c}"), t)?;
|
||||||
|
}
|
||||||
|
for (c, r) in &s.retry {
|
||||||
|
target(n, &format!("retry {c}"), &r.then)?;
|
||||||
|
ensure!(r.max > 0, "state {n:?}: retry {c} needs max > 0");
|
||||||
|
ensure!(
|
||||||
|
s.catch.contains_key(c),
|
||||||
|
"state {n:?}: retry {c} has no matching catch"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for st in &s.steps {
|
||||||
|
match st.run {
|
||||||
|
RunOn::Agent => ensure!(
|
||||||
|
st.prompt.is_some(),
|
||||||
|
"state {n:?} step {:?}: agent step needs `prompt`",
|
||||||
|
st.name
|
||||||
|
),
|
||||||
|
RunOn::Computer | RunOn::Human => {}
|
||||||
|
}
|
||||||
|
if let Some(r) = &st.report {
|
||||||
|
ensure!(
|
||||||
|
r == "junit",
|
||||||
|
"state {n:?} step {:?}: unknown report format {r:?} (only junit)",
|
||||||
|
st.name
|
||||||
|
);
|
||||||
|
ensure!(
|
||||||
|
st.run == RunOn::Computer,
|
||||||
|
"state {n:?} step {:?}: only computer steps can have a report",
|
||||||
|
st.name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(f) = &st.fail_as {
|
||||||
|
ensure!(
|
||||||
|
s.catch.contains_key(f),
|
||||||
|
"state {n:?} step {:?}: fail_as {f:?} is not a catch of the state",
|
||||||
|
st.name
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const EXAMPLES: &[&str] = &["task", "migration", "docs", "e2e"];
|
||||||
|
|
||||||
|
fn example(name: &str) -> Machine {
|
||||||
|
let p = Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||||
|
.join("examples/machines")
|
||||||
|
.join(format!("{name}.toml"));
|
||||||
|
Machine::load(&p).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn examples_load_and_validate() {
|
||||||
|
for n in EXAMPLES {
|
||||||
|
assert_eq!(example(n).name, *n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strip_matches_the_mockup() {
|
||||||
|
let names =
|
||||||
|
|n: &str| -> Vec<String> { example(n).strip().map(|s| s.name.clone()).collect() };
|
||||||
|
assert_eq!(
|
||||||
|
names("task"),
|
||||||
|
["plan", "code", "build", "test", "review", "merge"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
names("migration"),
|
||||||
|
["plan", "code", "up", "down", "test", "review", "merge"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
names("docs"),
|
||||||
|
["plan", "write", "lint", "links", "review", "merge"]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
names("e2e"),
|
||||||
|
[
|
||||||
|
"plan",
|
||||||
|
"code",
|
||||||
|
"stack-up",
|
||||||
|
"e2e",
|
||||||
|
"stack-down",
|
||||||
|
"review",
|
||||||
|
"merge"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn task_machine_details() {
|
||||||
|
let m = example("task");
|
||||||
|
assert_eq!(m.start().name, "plan");
|
||||||
|
assert_eq!(
|
||||||
|
m.budget,
|
||||||
|
BudgetCfg {
|
||||||
|
wall_secs: Some(5400),
|
||||||
|
cost: Some(5.0),
|
||||||
|
compact_at: Some(85)
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(example("docs").budget, BudgetCfg::default());
|
||||||
|
let t = m.state("test").unwrap();
|
||||||
|
assert_eq!(t.catch.keys().next().unwrap(), "TestsFailed");
|
||||||
|
assert_eq!(t.retry["TestsFailed"].max, 3);
|
||||||
|
assert_eq!(t.retry["TestsFailed"].then, "escalated");
|
||||||
|
assert_eq!(t.steps[0].report.as_deref(), Some("junit"));
|
||||||
|
assert_eq!(m.state("review").unwrap().kind, Kind::Gate);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn err(text: &str) -> String {
|
||||||
|
format!("{:#}", Machine::parse(text).unwrap_err())
|
||||||
|
}
|
||||||
|
|
||||||
|
const OK: &str = r#"
|
||||||
|
name = "m"
|
||||||
|
[[state]]
|
||||||
|
name = "a"
|
||||||
|
kind = "start"
|
||||||
|
next = "b"
|
||||||
|
[[state]]
|
||||||
|
name = "b"
|
||||||
|
kind = "exit"
|
||||||
|
end = "done"
|
||||||
|
"#;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn minimal_machine_is_valid() {
|
||||||
|
Machine::parse(OK).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_bad_machines() {
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace("name = \"m\"", "name = \"m\"\n[budget]\ncompact_at = 0"))
|
||||||
|
.contains("percent")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace("name = \"m\"", "name = \"m\"\n[budget]\nbogus = 1"))
|
||||||
|
.contains("unknown field")
|
||||||
|
);
|
||||||
|
assert!(err(&OK.replace("kind = \"start\"", "")).contains("exactly one start"));
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace("kind = \"exit\"", "kind = \"start\"")).contains("exactly one start")
|
||||||
|
);
|
||||||
|
assert!(err(&OK.replace("next = \"b\"", "next = \"zzz\"")).contains("unknown state"));
|
||||||
|
assert!(err(&OK.replace("next = \"b\"", "")).contains("needs `next`"));
|
||||||
|
assert!(err(&OK.replace("end = \"done\"", "")).contains("needs `end`"));
|
||||||
|
assert!(err(&format!("{OK}\n[[state]]\nname = \"a\"\nnext = \"b\"")).contains("duplicate"));
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace("next = \"b\"", "next = \"b\"\ncatch = { X = \"nope\" }"))
|
||||||
|
.contains("catch X")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace(
|
||||||
|
"next = \"b\"",
|
||||||
|
"next = \"b\"\nretry = { X = { max = 2, then = \"b\" } }"
|
||||||
|
))
|
||||||
|
.contains("no matching catch")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace("end = \"done\"", "end = \"done\"\nonly_on = [\"x\"]"))
|
||||||
|
.contains("only_on")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
err(&OK.replace(
|
||||||
|
"next = \"b\"",
|
||||||
|
"next = \"b\"\nsteps = [{ name = \"s\", run = \"agent\" }]"
|
||||||
|
))
|
||||||
|
.contains("needs `prompt`")
|
||||||
|
);
|
||||||
|
assert!(err(&format!("{OK}\nbogus = 1")).contains("unknown field"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+181
-3
@@ -1,10 +1,21 @@
|
|||||||
|
mod acp;
|
||||||
mod adapter;
|
mod adapter;
|
||||||
|
mod budget;
|
||||||
|
mod checks;
|
||||||
|
mod db;
|
||||||
|
mod detail;
|
||||||
|
mod goal;
|
||||||
|
mod junit;
|
||||||
mod lock;
|
mod lock;
|
||||||
|
mod machine;
|
||||||
mod policy;
|
mod policy;
|
||||||
mod profile;
|
mod profile;
|
||||||
mod report;
|
mod report;
|
||||||
mod run;
|
mod run;
|
||||||
|
mod runner;
|
||||||
mod state;
|
mod state;
|
||||||
|
mod tui;
|
||||||
|
mod view;
|
||||||
|
|
||||||
use anyhow::{Context, Result, bail};
|
use anyhow::{Context, Result, bail};
|
||||||
use clap::{Parser, Subcommand};
|
use clap::{Parser, Subcommand};
|
||||||
@@ -14,10 +25,13 @@ use std::sync::Mutex;
|
|||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
|
||||||
#[derive(Parser)]
|
#[derive(Parser)]
|
||||||
#[command(version, about = "Run hx coding agents on tasks")]
|
#[command(
|
||||||
|
version,
|
||||||
|
about = "Run hx coding agents on tasks; without a subcommand, opens the TUI"
|
||||||
|
)]
|
||||||
struct Cli {
|
struct Cli {
|
||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
cmd: Cmd,
|
cmd: Option<Cmd>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
@@ -62,6 +76,59 @@ enum Cmd {
|
|||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
check: bool,
|
check: bool,
|
||||||
},
|
},
|
||||||
|
/// Show or set the goal sentence; `--export` also prints the acceptance checks (for machine steps).
|
||||||
|
Goal {
|
||||||
|
/// New goal text.
|
||||||
|
text: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
export: bool,
|
||||||
|
/// Repo with the goal (default: ORCH_DB of a machine step, else the current directory).
|
||||||
|
#[arg(long)]
|
||||||
|
repo: Option<PathBuf>,
|
||||||
|
},
|
||||||
|
/// Add an acceptance check: a shell command, pass = exit 0.
|
||||||
|
Check {
|
||||||
|
name: String,
|
||||||
|
cmd: String,
|
||||||
|
/// Session that is responsible for it (its `run-acceptance` step runs it before merging).
|
||||||
|
#[arg(long)]
|
||||||
|
owner: Option<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
repo: Option<PathBuf>,
|
||||||
|
},
|
||||||
|
/// Run acceptance checks in the current directory (a worktree), or with --main in a clean copy of main.
|
||||||
|
Checks {
|
||||||
|
/// Only the checks this session owns.
|
||||||
|
#[arg(long)]
|
||||||
|
owner: Option<String>,
|
||||||
|
/// All checks on main; the results are recorded for the goal view.
|
||||||
|
#[arg(long)]
|
||||||
|
main: bool,
|
||||||
|
#[arg(long)]
|
||||||
|
repo: Option<PathBuf>,
|
||||||
|
},
|
||||||
|
/// Create a state-machine session in REPO and run it to the end. Waits for `--after` sessions to merge.
|
||||||
|
Session {
|
||||||
|
/// Sessions that must be merged before this one starts, comma separated.
|
||||||
|
#[arg(long, value_delimiter = ',')]
|
||||||
|
after: Vec<String>,
|
||||||
|
#[arg(long)]
|
||||||
|
repo: PathBuf,
|
||||||
|
/// Machine file name, without .toml (looked up in REPO/.hx/machines, then ~/.hx/machines).
|
||||||
|
#[arg(long, required_unless_present = "resume")]
|
||||||
|
machine: Option<String>,
|
||||||
|
#[arg(long, required_unless_present = "resume")]
|
||||||
|
name: Option<String>,
|
||||||
|
/// Continue this unfinished session (e.g. s1) from its saved state instead of creating one.
|
||||||
|
#[arg(long, conflicts_with_all = ["machine", "name", "after"])]
|
||||||
|
resume: Option<String>,
|
||||||
|
/// Value for {{scope}} in machine commands.
|
||||||
|
#[arg(long, default_value = "")]
|
||||||
|
scope: String,
|
||||||
|
/// Profile that says how to start hx for agent steps.
|
||||||
|
#[arg(long, default_value = "default")]
|
||||||
|
profile: String,
|
||||||
|
},
|
||||||
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
|
/// hx extension that enforces a run's tool allowlist (started by hx, not by hand).
|
||||||
#[command(hide = true)]
|
#[command(hide = true)]
|
||||||
Guard { policy: PathBuf },
|
Guard { policy: PathBuf },
|
||||||
@@ -93,12 +160,123 @@ pub fn state_dir() -> PathBuf {
|
|||||||
env_dir("ORCH_STATE_DIR", "XDG_STATE_HOME", ".local/state")
|
env_dir("ORCH_STATE_DIR", "XDG_STATE_HOME", ".local/state")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The goal database: `--repo`, else `ORCH_DB` (set by the runner for machine steps), else `./.hx/orch.db`.
|
||||||
|
fn open_db(repo: Option<&Path>) -> Result<db::Db> {
|
||||||
|
if repo.is_none()
|
||||||
|
&& let Some(p) = std::env::var_os("ORCH_DB")
|
||||||
|
{
|
||||||
|
return db::Db::open(Path::new(&p));
|
||||||
|
}
|
||||||
|
let dir = match repo {
|
||||||
|
Some(r) => r.to_path_buf(),
|
||||||
|
None => std::env::current_dir()?,
|
||||||
|
};
|
||||||
|
db::Db::open(&dir.join(".hx/orch.db"))
|
||||||
|
}
|
||||||
|
|
||||||
fn code(ok: bool) -> std::process::ExitCode {
|
fn code(ok: bool) -> std::process::ExitCode {
|
||||||
u8::from(!ok).into()
|
u8::from(!ok).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> Result<std::process::ExitCode> {
|
fn main() -> Result<std::process::ExitCode> {
|
||||||
match Cli::parse().cmd {
|
let Some(cmd) = Cli::parse().cmd else {
|
||||||
|
tui::run()?;
|
||||||
|
return Ok(code(true));
|
||||||
|
};
|
||||||
|
match cmd {
|
||||||
|
Cmd::Goal { text, export, repo } => {
|
||||||
|
let db = open_db(repo.as_deref())?;
|
||||||
|
if let Some(t) = text {
|
||||||
|
db.set_goal(&t)?;
|
||||||
|
}
|
||||||
|
println!("{}", db.goal()?.unwrap_or_else(|| "no goal set".into()));
|
||||||
|
if export {
|
||||||
|
println!("\nAcceptance checks (all must pass on main):");
|
||||||
|
for c in db.checks()? {
|
||||||
|
let owner = c.owner.map_or(String::new(), |o| format!(" [{o}]"));
|
||||||
|
println!("- {}{owner}: {}", c.name, c.cmd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(code(true))
|
||||||
|
}
|
||||||
|
Cmd::Check {
|
||||||
|
name,
|
||||||
|
cmd,
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
} => {
|
||||||
|
let id = open_db(repo.as_deref())?.add_check(&name, &cmd, owner.as_deref())?;
|
||||||
|
println!("check {id}: {name}");
|
||||||
|
Ok(code(true))
|
||||||
|
}
|
||||||
|
Cmd::Checks { owner, main, repo } => {
|
||||||
|
let db = open_db(repo.as_deref())?;
|
||||||
|
let results = if main {
|
||||||
|
let repo = match (repo, std::env::var_os("ORCH_REPO")) {
|
||||||
|
(Some(r), _) => r,
|
||||||
|
(None, Some(r)) => r.into(),
|
||||||
|
(None, None) => std::env::current_dir()?,
|
||||||
|
};
|
||||||
|
checks::run_on_main(&db, &repo)?
|
||||||
|
} else {
|
||||||
|
checks::run(&db, &std::env::current_dir()?, owner.as_deref(), false)?
|
||||||
|
};
|
||||||
|
for r in &results {
|
||||||
|
if r.pass {
|
||||||
|
println!("✓ {}", r.check.name);
|
||||||
|
} else {
|
||||||
|
println!("✗ {} (exit {})", r.check.name, r.exit.unwrap_or(-1));
|
||||||
|
print!("{}", r.output);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(code(results.iter().all(|r| r.pass)))
|
||||||
|
}
|
||||||
|
Cmd::Session {
|
||||||
|
after,
|
||||||
|
repo,
|
||||||
|
machine,
|
||||||
|
name,
|
||||||
|
resume,
|
||||||
|
scope,
|
||||||
|
profile,
|
||||||
|
} => {
|
||||||
|
let profile = profile::Profile::load(&profile)?;
|
||||||
|
let repo = repo.canonicalize()?;
|
||||||
|
let db = db::Db::open(&repo.join(".hx/orch.db"))?;
|
||||||
|
let s = if let Some(id) = resume {
|
||||||
|
let s = db
|
||||||
|
.session(&id)?
|
||||||
|
.with_context(|| format!("no session {id}"))?;
|
||||||
|
anyhow::ensure!(
|
||||||
|
!db.events(Some(&id), 0)?.iter().any(|e| e.kind == "end"),
|
||||||
|
"session {id} already ended; start a new one"
|
||||||
|
);
|
||||||
|
anyhow::ensure!(
|
||||||
|
s.pid
|
||||||
|
.is_none_or(|p| !Path::new(&format!("/proc/{p}")).exists()
|
||||||
|
|| p == std::process::id()),
|
||||||
|
"session {id} is still running (pid {})",
|
||||||
|
s.pid.unwrap_or(0)
|
||||||
|
);
|
||||||
|
s
|
||||||
|
} else {
|
||||||
|
// shortcut: worktrees are grouped by repo directory name; two repos with one name would share ids
|
||||||
|
let base = repo.file_name().unwrap_or_default();
|
||||||
|
let wts = state_dir().join("worktrees").join(base);
|
||||||
|
let (machine, name) = (machine.unwrap_or_default(), name.unwrap_or_default());
|
||||||
|
machine::Machine::find(&machine, &repo)?;
|
||||||
|
runner::create_after(&db, &wts, &name, "", &machine, &after)?
|
||||||
|
};
|
||||||
|
let task = db
|
||||||
|
.tasks()?
|
||||||
|
.into_iter()
|
||||||
|
.find(|t| t.id == s.task_id)
|
||||||
|
.with_context(|| format!("no task {}", s.task_id))?;
|
||||||
|
let m = machine::Machine::find(&task.machine, &repo)?;
|
||||||
|
let status = runner::run_session(&db, &m, &s.id, &repo, &scope, &profile)?;
|
||||||
|
println!("{} {} -> {status}", s.id, s.branch);
|
||||||
|
Ok(code(status == "merged"))
|
||||||
|
}
|
||||||
Cmd::Run {
|
Cmd::Run {
|
||||||
task,
|
task,
|
||||||
repo,
|
repo,
|
||||||
|
|||||||
+2
-2
@@ -14,7 +14,7 @@ use std::process::{Command, Stdio};
|
|||||||
use std::sync::mpsc;
|
use std::sync::mpsc;
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
fn git(dir: &Path, args: &[&str]) -> Result<String> {
|
pub(crate) fn git(dir: &Path, args: &[&str]) -> Result<String> {
|
||||||
let o = Command::new("git")
|
let o = Command::new("git")
|
||||||
.args(["-c", "user.name=orch", "-c", "user.email=orch@localhost"])
|
.args(["-c", "user.name=orch", "-c", "user.email=orch@localhost"])
|
||||||
.args(args)
|
.args(args)
|
||||||
@@ -129,7 +129,7 @@ fn is_rate_limit(reason: &str) -> bool {
|
|||||||
/// Max bytes of gate output fed back to hx (the tail: errors are at the end).
|
/// Max bytes of gate output fed back to hx (the tail: errors are at the end).
|
||||||
const GATE_LOG_LIMIT: usize = 8000;
|
const GATE_LOG_LIMIT: usize = 8000;
|
||||||
|
|
||||||
fn tail(b: &[u8], limit: usize) -> String {
|
pub(crate) fn tail(b: &[u8], limit: usize) -> String {
|
||||||
let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned();
|
let s = String::from_utf8_lossy(&b[b.len().saturating_sub(limit)..]).into_owned();
|
||||||
s.trim_start_matches('\u{FFFD}').to_string()
|
s.trim_start_matches('\u{FFFD}').to_string()
|
||||||
}
|
}
|
||||||
|
|||||||
+2156
File diff suppressed because it is too large.
Load diff
+308
@@ -0,0 +1,308 @@
|
|||||||
|
//! Screen 3: goal view (ORCHESTRATOR.md 7.3, `Goal.dc.html`).
|
||||||
|
|
||||||
|
use super::overview::Header;
|
||||||
|
use super::theme::{self, bold, fg, inverted};
|
||||||
|
use crate::goal::{CheckState, GoalView, TaskBox};
|
||||||
|
use crate::view::{Status, hms};
|
||||||
|
use ratatui::Frame;
|
||||||
|
use ratatui::layout::{Constraint, Layout, Rect};
|
||||||
|
use ratatui::style::{Color, Modifier, Style};
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
use ratatui::widgets::{Block, Paragraph};
|
||||||
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
|
const BOX_W: u16 = 26;
|
||||||
|
const GAP_W: u16 = 5;
|
||||||
|
const BOX_H: u16 = 5;
|
||||||
|
|
||||||
|
pub fn draw(f: &mut Frame, g: &GoalView, h: &Header, checks_running: bool, dec_sel: usize) {
|
||||||
|
let area = f.area();
|
||||||
|
f.render_widget(
|
||||||
|
Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
let [head, goal, body, keys] = Layout::vertical([
|
||||||
|
Constraint::Length(1),
|
||||||
|
Constraint::Length(4),
|
||||||
|
Constraint::Fill(1),
|
||||||
|
Constraint::Length(1),
|
||||||
|
])
|
||||||
|
.areas(area);
|
||||||
|
f.render_widget(header(h, head.width as usize), head);
|
||||||
|
goal_box(f, goal, g);
|
||||||
|
let [left, right] =
|
||||||
|
Layout::horizontal([Constraint::Fill(1), Constraint::Length(56)]).areas(body);
|
||||||
|
left_box(f, left, g, dec_sel);
|
||||||
|
acceptance_box(f, right, g, checks_running);
|
||||||
|
f.render_widget(key_bar(), keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header(h: &Header, width: usize) -> Line<'static> {
|
||||||
|
let clock = hms(h.now_ms);
|
||||||
|
let used = " hx·orch ".width() + " ‹ sessions / goal".width() + clock.width();
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(" hx·orch ", inverted(theme::RUN)),
|
||||||
|
Span::styled(" ‹ sessions / ", fg(theme::DIM)),
|
||||||
|
Span::styled("goal", bold(theme::TEXT)),
|
||||||
|
Span::raw(" ".repeat(width.saturating_sub(used))),
|
||||||
|
Span::raw(clock),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fit(s: &str, w: usize) -> String {
|
||||||
|
if s.width() <= w {
|
||||||
|
return s.to_string();
|
||||||
|
}
|
||||||
|
let mut out = String::new();
|
||||||
|
for c in s.chars() {
|
||||||
|
if out.width() + 1 >= w {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
out.push('…');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn titled<'a>(title: Vec<Span<'a>>, border: Color) -> Block<'a> {
|
||||||
|
let mut t = vec![Span::raw(" ")];
|
||||||
|
t.extend(title);
|
||||||
|
t.push(Span::raw(" "));
|
||||||
|
Block::bordered()
|
||||||
|
.border_style(fg(border))
|
||||||
|
.title(Line::from(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn goal_box(f: &mut Frame, area: Rect, g: &GoalView) {
|
||||||
|
let b = Block::bordered().border_style(fg(theme::BORDER));
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let w = inner.width as usize;
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(vec![
|
||||||
|
Line::from(Span::styled(
|
||||||
|
format!(" {}", fit(&g.goal, w - 1)),
|
||||||
|
bold(theme::TEXT),
|
||||||
|
)),
|
||||||
|
Line::from(Span::styled(
|
||||||
|
format!(" {}", fit(&g.done_when, w - 1)),
|
||||||
|
fg(theme::DIM),
|
||||||
|
)),
|
||||||
|
]),
|
||||||
|
inner,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_color(s: Status) -> Color {
|
||||||
|
match s {
|
||||||
|
Status::Done => theme::OK,
|
||||||
|
Status::Fix | Status::Fail => theme::ERR,
|
||||||
|
Status::Wait => theme::WAIT,
|
||||||
|
Status::Run => theme::RUN,
|
||||||
|
Status::Blocked => theme::AGENT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn task_box(f: &mut Frame, area: Rect, t: &TaskBox) {
|
||||||
|
let border = if t.status == Status::Done {
|
||||||
|
theme::BORDER
|
||||||
|
} else {
|
||||||
|
status_color(t.status)
|
||||||
|
};
|
||||||
|
let b = Block::bordered().border_style(fg(border));
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let w = inner.width as usize;
|
||||||
|
let after = if t.after.is_empty() {
|
||||||
|
"after: —".to_string()
|
||||||
|
} else {
|
||||||
|
format!("after: {}", t.after.join(", "))
|
||||||
|
};
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(vec![
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(format!("{} ", t.id), fg(theme::DIM)),
|
||||||
|
Span::styled(fit(&t.name, w.saturating_sub(4)), bold(theme::TEXT)),
|
||||||
|
]),
|
||||||
|
Line::from(Span::styled(
|
||||||
|
fit(&format!("{} · {}", t.status.label(), t.detail), w),
|
||||||
|
bold(status_color(t.status)),
|
||||||
|
)),
|
||||||
|
Line::from(Span::styled(fit(&after, w), fg(theme::DIM))),
|
||||||
|
]),
|
||||||
|
inner,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn left_box(f: &mut Frame, area: Rect, g: &GoalView, dec_sel: usize) {
|
||||||
|
let title = vec![
|
||||||
|
Span::styled("Task graph", bold(theme::TEXT)),
|
||||||
|
Span::styled(" left to right = dependency order", fg(theme::DIM)),
|
||||||
|
];
|
||||||
|
let b = titled(title, theme::BORDER);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let tallest = g.columns.iter().map(|c| c.tasks.len()).max().unwrap_or(0) as u16;
|
||||||
|
let graph_h = (1 + tallest * (BOX_H + 1)).max(3);
|
||||||
|
let [graph, crit, decisions] = Layout::vertical([
|
||||||
|
Constraint::Length(graph_h.min(inner.height.saturating_sub(8))),
|
||||||
|
Constraint::Length(3),
|
||||||
|
Constraint::Fill(1),
|
||||||
|
])
|
||||||
|
.areas(inner);
|
||||||
|
|
||||||
|
let step = BOX_W + GAP_W;
|
||||||
|
for (c, col) in g.columns.iter().enumerate() {
|
||||||
|
let x = graph.x + 1 + c as u16 * step;
|
||||||
|
if x + BOX_W > graph.right() {
|
||||||
|
break; // does not fit on this terminal
|
||||||
|
}
|
||||||
|
f.render_widget(
|
||||||
|
Span::styled(col.label.clone(), fg(theme::DIM)),
|
||||||
|
Rect::new(x, graph.y, BOX_W, 1),
|
||||||
|
);
|
||||||
|
for (i, t) in col.tasks.iter().enumerate() {
|
||||||
|
let y = graph.y + 1 + i as u16 * (BOX_H + 1);
|
||||||
|
if y + BOX_H > graph.bottom() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
task_box(f, Rect::new(x, y, BOX_W, BOX_H), t);
|
||||||
|
if c + 1 < g.columns.len() {
|
||||||
|
f.render_widget(
|
||||||
|
Span::styled("──▶", fg(theme::SEP)),
|
||||||
|
Rect::new(x + BOX_W + 1, y + 2, 3, 1),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let crit_line = if g.critical.is_empty() {
|
||||||
|
Line::from(Span::styled(
|
||||||
|
" critical path nothing left to do",
|
||||||
|
fg(theme::DIM),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(" critical path ", bold(theme::WAIT)),
|
||||||
|
Span::raw(g.critical.join(" → ")),
|
||||||
|
])
|
||||||
|
};
|
||||||
|
let sep = Block::new()
|
||||||
|
.borders(ratatui::widgets::Borders::TOP)
|
||||||
|
.border_style(fg(theme::BORDER));
|
||||||
|
f.render_widget(Paragraph::new(crit_line).block(sep), crit);
|
||||||
|
|
||||||
|
let db = titled(
|
||||||
|
vec![Span::styled("Decisions agents made", bold(theme::TEXT))],
|
||||||
|
theme::BORDER,
|
||||||
|
);
|
||||||
|
let di = db.inner(decisions);
|
||||||
|
f.render_widget(db, decisions);
|
||||||
|
let w = di.width as usize;
|
||||||
|
// scroll so the selected decision stays in view
|
||||||
|
let skip = dec_sel.saturating_sub((di.height as usize).saturating_sub(1));
|
||||||
|
let lines: Vec<Line> = g
|
||||||
|
.decisions
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.skip(skip)
|
||||||
|
.take(di.height as usize)
|
||||||
|
.map(|(i, d)| {
|
||||||
|
let text_style = if d.vetoed {
|
||||||
|
fg(theme::DIM).add_modifier(Modifier::CROSSED_OUT)
|
||||||
|
} else {
|
||||||
|
Style::new()
|
||||||
|
};
|
||||||
|
let cursor = if i == dec_sel {
|
||||||
|
Span::styled("▶", fg(theme::RUN))
|
||||||
|
} else {
|
||||||
|
Span::raw(" ")
|
||||||
|
};
|
||||||
|
let tag = if d.vetoed { " vetoed" } else { "" };
|
||||||
|
Line::from(vec![
|
||||||
|
cursor,
|
||||||
|
Span::styled(format!("{:<4}", d.session), fg(theme::RUN)),
|
||||||
|
Span::styled(fit(&d.text, w.saturating_sub(30)), text_style),
|
||||||
|
Span::styled(format!(" {:<14}", d.whence), fg(theme::DIM)),
|
||||||
|
Span::styled(tag, fg(theme::ERR)),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if lines.is_empty() {
|
||||||
|
f.render_widget(Span::styled(" none reported yet", fg(theme::DIM)), di);
|
||||||
|
} else {
|
||||||
|
f.render_widget(Paragraph::new(lines), di);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acceptance_box(f: &mut Frame, area: Rect, g: &GoalView, running: bool) {
|
||||||
|
let mut title = vec![
|
||||||
|
Span::styled("Acceptance ", bold(theme::TEXT)),
|
||||||
|
Span::styled(g.green.to_string(), fg(theme::OK)),
|
||||||
|
Span::styled(format!("/{}", g.checks.len()), fg(theme::DIM)),
|
||||||
|
];
|
||||||
|
if running {
|
||||||
|
title.push(Span::styled(" running…", fg(theme::WAIT)));
|
||||||
|
}
|
||||||
|
let b = titled(title, theme::BORDER);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let w = inner.width.saturating_sub(2) as usize;
|
||||||
|
let total = g.checks.len();
|
||||||
|
let on = (g.green * w).checked_div(total).unwrap_or(0);
|
||||||
|
let mut lines = vec![
|
||||||
|
Line::from(vec![
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled("█".repeat(on), fg(theme::OK)),
|
||||||
|
Span::styled("█".repeat(w - on), fg(theme::BORDER)),
|
||||||
|
]),
|
||||||
|
Line::raw(""),
|
||||||
|
];
|
||||||
|
if g.checks.is_empty() {
|
||||||
|
lines.push(Line::from(Span::styled(
|
||||||
|
" no checks yet · press +",
|
||||||
|
fg(theme::DIM),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
for c in &g.checks {
|
||||||
|
let (mark, style, name_style) = match c.state {
|
||||||
|
CheckState::Pass => ("✓", fg(theme::OK), Style::new()),
|
||||||
|
CheckState::Fail => (
|
||||||
|
"✗",
|
||||||
|
fg(theme::ERR),
|
||||||
|
Style::new().add_modifier(Modifier::BOLD),
|
||||||
|
),
|
||||||
|
CheckState::Unknown => ("·", fg(theme::TODO), fg(theme::DIM)),
|
||||||
|
};
|
||||||
|
let owner_w = 4; // `s12`, `ci`, `-`: right-aligned in a fixed column
|
||||||
|
let name_w = w.saturating_sub(owner_w + 4);
|
||||||
|
lines.push(Line::from(vec![
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(mark, style),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(format!("{:<name_w$}", fit(&c.name, name_w)), name_style),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(format!("{:>owner_w$}", c.owner), fg(theme::DIM)),
|
||||||
|
]));
|
||||||
|
}
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_bar() -> Line<'static> {
|
||||||
|
let mut v = vec![Span::raw(" ")];
|
||||||
|
for (k, what) in [
|
||||||
|
("esc", "back"),
|
||||||
|
("e", "edit goal"),
|
||||||
|
("+", "add check"),
|
||||||
|
("R", "run all checks"),
|
||||||
|
("j/k", "select decision"),
|
||||||
|
("v", "veto decision"),
|
||||||
|
] {
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!(" {k} "),
|
||||||
|
Style::new().fg(theme::BG).bg(theme::DIM),
|
||||||
|
));
|
||||||
|
v.push(Span::styled(format!(" {what} "), fg(theme::DIM)));
|
||||||
|
}
|
||||||
|
Line::from(v)
|
||||||
|
}
|
||||||
+1641
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,400 @@
|
|||||||
|
//! Screen 1: sessions overview (ORCHESTRATOR.md 7.1, `Main.dc.html`).
|
||||||
|
|
||||||
|
use super::theme::{self, bold, fg, inverted};
|
||||||
|
use crate::view::{Chip, EventLine, Mark, Need, Overview, Row, Status, hms};
|
||||||
|
use ratatui::Frame;
|
||||||
|
use ratatui::layout::{Constraint, Layout, Rect};
|
||||||
|
use ratatui::style::{Color, Style};
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
use ratatui::widgets::{Block, Paragraph};
|
||||||
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
|
/// What the header shows that is not derived from events.
|
||||||
|
pub struct Header {
|
||||||
|
pub repo: String,
|
||||||
|
pub rev: String,
|
||||||
|
pub now_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
const W_ID: usize = 5;
|
||||||
|
const W_STATUS: usize = 7;
|
||||||
|
const W_TASK: usize = 24;
|
||||||
|
const W_TESTS: usize = 10;
|
||||||
|
const W_DIFF: usize = 10;
|
||||||
|
const W_CTX: usize = 10;
|
||||||
|
|
||||||
|
pub fn draw(f: &mut Frame, o: &Overview, h: &Header, sel: usize, need_sel: usize) {
|
||||||
|
let area = f.area();
|
||||||
|
f.render_widget(
|
||||||
|
Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
let rows_h = (o.rows.len().max(1) * 2 + 3) as u16;
|
||||||
|
let sessions_h = rows_h.clamp(5, area.height.saturating_sub(14).max(5));
|
||||||
|
let [head, stats, sessions, lower, keys] = Layout::vertical([
|
||||||
|
Constraint::Length(1),
|
||||||
|
Constraint::Length(1),
|
||||||
|
Constraint::Length(sessions_h),
|
||||||
|
Constraint::Fill(1),
|
||||||
|
Constraint::Length(1),
|
||||||
|
])
|
||||||
|
.areas(area);
|
||||||
|
let [needs, events] =
|
||||||
|
Layout::horizontal([Constraint::Length(62), Constraint::Fill(1)]).areas(lower);
|
||||||
|
f.render_widget(header_line(o, h, head.width as usize), head);
|
||||||
|
f.render_widget(stats_line(o), stats);
|
||||||
|
sessions_box(f, sessions, o, sel);
|
||||||
|
needs_box(f, needs, &o.needs, need_sel);
|
||||||
|
events_box(f, events, &o.events);
|
||||||
|
f.render_widget(key_bar(), keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cuts `s` to `w` display columns, ending in `…` when it was too long.
|
||||||
|
fn fit(s: &str, w: usize) -> String {
|
||||||
|
if s.width() <= w {
|
||||||
|
return s.to_string();
|
||||||
|
}
|
||||||
|
let mut out = String::new();
|
||||||
|
for c in s.chars() {
|
||||||
|
if out.width() + 1 >= w {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
out.push('…');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends `parts` and pads the cell to `w` columns plus one gap column.
|
||||||
|
fn cell<'a>(line: &mut Vec<Span<'a>>, parts: Vec<Span<'a>>, w: usize) {
|
||||||
|
let used: usize = parts.iter().map(|s| s.width()).sum();
|
||||||
|
line.extend(parts);
|
||||||
|
line.push(Span::raw(" ".repeat((w + 1).saturating_sub(used))));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bar(done: usize, total: usize) -> Vec<Span<'static>> {
|
||||||
|
let n = total.min(24);
|
||||||
|
let d = (done * n).checked_div(total).unwrap_or(0);
|
||||||
|
vec![
|
||||||
|
Span::styled("█".repeat(d), fg(theme::OK)),
|
||||||
|
Span::styled("█".repeat(n - d), fg(theme::BORDER)),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header_line(o: &Overview, h: &Header, width: usize) -> Line<'static> {
|
||||||
|
let goal = if o.goal.is_empty() {
|
||||||
|
"no goal set"
|
||||||
|
} else {
|
||||||
|
&o.goal
|
||||||
|
};
|
||||||
|
let right = format!("{} · {} {}", h.repo, h.rev, hms(h.now_ms));
|
||||||
|
let left_fixed = " hx·orch ".width() + " goal ".width();
|
||||||
|
let goal_w = width.saturating_sub(left_fixed + right.width() + 2);
|
||||||
|
let goal = fit(goal, goal_w);
|
||||||
|
let gap = goal_w.saturating_sub(goal.width()) + 2;
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(" hx·orch ", inverted(theme::RUN)),
|
||||||
|
Span::styled(" goal ", fg(theme::DIM)),
|
||||||
|
Span::styled(
|
||||||
|
goal,
|
||||||
|
Style::new().add_modifier(ratatui::style::Modifier::BOLD),
|
||||||
|
),
|
||||||
|
Span::raw(" ".repeat(gap)),
|
||||||
|
Span::styled(right, fg(theme::DIM)),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stats_line(o: &Overview) -> Line<'static> {
|
||||||
|
let mut v = vec![Span::styled(" tasks ", fg(theme::DIM))];
|
||||||
|
if o.total == 0 {
|
||||||
|
v.push(Span::raw("—"));
|
||||||
|
} else {
|
||||||
|
v.extend(bar(o.merged, o.total));
|
||||||
|
v.push(Span::raw(format!(" {}/{} merged", o.merged, o.total)));
|
||||||
|
}
|
||||||
|
v.push(Span::styled(" acceptance ", fg(theme::DIM)));
|
||||||
|
match o.checks {
|
||||||
|
Some((ok, total)) => {
|
||||||
|
v.extend(bar(ok, total));
|
||||||
|
v.push(Span::raw(format!(" {ok}/{total} checks")));
|
||||||
|
}
|
||||||
|
None => v.push(Span::raw("—")),
|
||||||
|
}
|
||||||
|
v.push(Span::raw(" "));
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!("{} running", o.running),
|
||||||
|
fg(theme::RUN),
|
||||||
|
));
|
||||||
|
v.push(Span::raw(" · "));
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!("{} waiting on you", o.waiting),
|
||||||
|
fg(theme::WAIT),
|
||||||
|
));
|
||||||
|
v.push(Span::raw(" · "));
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!("{} blocked", o.blocked),
|
||||||
|
fg(theme::AGENT),
|
||||||
|
));
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!(
|
||||||
|
" spent ${:.2} · {} elapsed",
|
||||||
|
o.cost,
|
||||||
|
crate::view::ago(o.elapsed_secs)
|
||||||
|
),
|
||||||
|
fg(theme::DIM),
|
||||||
|
));
|
||||||
|
Line::from(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A box with its title set into the top border, like `┌ Sessions 6 ──`.
|
||||||
|
fn boxed<'a>(title: &str, count: Option<usize>, color: Color, border: Color) -> Block<'a> {
|
||||||
|
let mut t = vec![Span::styled(format!(" {title}"), bold(color))];
|
||||||
|
if let Some(n) = count {
|
||||||
|
t.push(Span::styled(format!(" {n}"), fg(theme::DIM)));
|
||||||
|
}
|
||||||
|
t.push(Span::raw(" "));
|
||||||
|
Block::bordered()
|
||||||
|
.border_style(fg(border))
|
||||||
|
.title(Line::from(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_color(s: Status) -> Color {
|
||||||
|
match s {
|
||||||
|
Status::Done => theme::OK,
|
||||||
|
Status::Fix | Status::Fail => theme::ERR,
|
||||||
|
Status::Wait => theme::WAIT,
|
||||||
|
Status::Run => theme::RUN,
|
||||||
|
Status::Blocked => theme::AGENT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chip_span(c: &Chip) -> Span<'static> {
|
||||||
|
match c.mark {
|
||||||
|
Mark::Done => Span::styled(format!("✓{}", c.name), fg(theme::OK)),
|
||||||
|
Mark::Active => Span::styled(format!("●{}", c.name), inverted(theme::RUN)),
|
||||||
|
Mark::Failed => Span::styled(format!("✗{}", c.name), fg(theme::ERR)),
|
||||||
|
Mark::Waiting => Span::styled(format!("◆{}", c.name), inverted(theme::WAIT)),
|
||||||
|
Mark::Todo => Span::styled(format!("·{}", c.name), fg(theme::TODO)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn machine_spans(r: &Row) -> Vec<Span<'static>> {
|
||||||
|
let mut v = vec![];
|
||||||
|
for (i, c) in r.chips.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
v.push(Span::styled(" › ", fg(theme::SEP)));
|
||||||
|
}
|
||||||
|
v.push(chip_span(c));
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ctx_bar(pct: u8) -> Span<'static> {
|
||||||
|
let n = (pct as usize + 5) / 10;
|
||||||
|
let color = if pct > 65 { theme::WAIT } else { theme::DIM };
|
||||||
|
Span::styled(
|
||||||
|
format!("{}{}", "▰".repeat(n), "▱".repeat(10 - n)),
|
||||||
|
fg(color),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sessions_box(f: &mut Frame, area: Rect, o: &Overview, sel: usize) {
|
||||||
|
let block = boxed("Sessions", Some(o.rows.len()), theme::TEXT, theme::BORDER);
|
||||||
|
let inner = block.inner(area);
|
||||||
|
f.render_widget(block, area);
|
||||||
|
if o.rows.is_empty() {
|
||||||
|
let hint = " no sessions yet · orch session --repo . --machine task --name NAME";
|
||||||
|
f.render_widget(Paragraph::new(Span::styled(hint, fg(theme::DIM))), inner);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let w_machine = o
|
||||||
|
.rows
|
||||||
|
.iter()
|
||||||
|
.map(|r| machine_spans(r).iter().map(|s| s.width()).sum::<usize>())
|
||||||
|
.max()
|
||||||
|
.unwrap_or(0)
|
||||||
|
.clamp(12, 72);
|
||||||
|
let mut head = vec![];
|
||||||
|
cell(&mut head, vec![Span::raw(" id")], W_ID);
|
||||||
|
cell(&mut head, vec![Span::raw("status")], W_STATUS);
|
||||||
|
cell(&mut head, vec![Span::raw("task")], W_TASK);
|
||||||
|
cell(&mut head, vec![Span::raw("machine")], w_machine);
|
||||||
|
cell(&mut head, vec![Span::raw("tests")], W_TESTS);
|
||||||
|
cell(&mut head, vec![Span::raw("diff")], W_DIFF);
|
||||||
|
cell(&mut head, vec![Span::raw("context")], W_CTX);
|
||||||
|
head.push(Span::raw("last activity"));
|
||||||
|
let mut lines = vec![Line::from(head).style(fg(theme::DIM))];
|
||||||
|
for (i, r) in o.rows.iter().enumerate() {
|
||||||
|
let on = i == sel;
|
||||||
|
let cursor = if on {
|
||||||
|
Span::styled("▶ ", fg(theme::RUN))
|
||||||
|
} else {
|
||||||
|
Span::raw(" ")
|
||||||
|
};
|
||||||
|
let mut l1 = vec![];
|
||||||
|
cell(&mut l1, vec![cursor, Span::raw(r.id.clone())], W_ID);
|
||||||
|
cell(
|
||||||
|
&mut l1,
|
||||||
|
vec![Span::styled(r.status.label(), bold(status_color(r.status)))],
|
||||||
|
W_STATUS,
|
||||||
|
);
|
||||||
|
cell(
|
||||||
|
&mut l1,
|
||||||
|
vec![Span::styled(fit(&r.task, W_TASK), bold(theme::TEXT))],
|
||||||
|
W_TASK,
|
||||||
|
);
|
||||||
|
cell(&mut l1, machine_spans(r), w_machine);
|
||||||
|
let tests_color = match r.tests_ok {
|
||||||
|
Some(true) => theme::OK,
|
||||||
|
Some(false) => theme::ERR,
|
||||||
|
None => theme::TODO,
|
||||||
|
};
|
||||||
|
cell(
|
||||||
|
&mut l1,
|
||||||
|
vec![Span::styled(r.tests.clone(), fg(tests_color))],
|
||||||
|
W_TESTS,
|
||||||
|
);
|
||||||
|
let diff = if r.added + r.removed == 0 {
|
||||||
|
vec![]
|
||||||
|
} else {
|
||||||
|
vec![
|
||||||
|
Span::styled(format!("+{}", r.added), fg(theme::OK)),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(format!("−{}", r.removed), fg(theme::ERR)),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
cell(&mut l1, diff, W_DIFF);
|
||||||
|
let ctx = r
|
||||||
|
.ctx
|
||||||
|
.map_or_else(|| Span::styled("—", fg(theme::TODO)), ctx_bar);
|
||||||
|
cell(&mut l1, vec![ctx], W_CTX);
|
||||||
|
let rest = (inner.width as usize)
|
||||||
|
.saturating_sub(W_ID + W_STATUS + W_TASK + w_machine + W_TESTS + W_DIFF + W_CTX + 8);
|
||||||
|
l1.push(Span::styled(fit(&r.last, rest), fg(theme::DIM)));
|
||||||
|
let mut l2 = vec![];
|
||||||
|
cell(&mut l2, vec![], W_ID + W_STATUS + 1);
|
||||||
|
cell(
|
||||||
|
&mut l2,
|
||||||
|
vec![Span::styled(fit(&r.sub, W_TASK), fg(theme::DIM))],
|
||||||
|
W_TASK,
|
||||||
|
);
|
||||||
|
// the retry counter sits next to the machine file name: on the chip line it would push every column right
|
||||||
|
let mut m2 = vec![Span::styled(r.machine.clone(), fg(theme::DIM))];
|
||||||
|
if !r.retry.is_empty() {
|
||||||
|
m2.push(Span::styled(format!(" {}", r.retry), fg(theme::ERR)));
|
||||||
|
}
|
||||||
|
if r.looping {
|
||||||
|
m2.push(Span::styled(" · looping", bold(theme::WAIT)));
|
||||||
|
}
|
||||||
|
cell(&mut l2, m2, w_machine);
|
||||||
|
let bg = if on {
|
||||||
|
Style::new().bg(theme::SEL)
|
||||||
|
} else {
|
||||||
|
Style::new()
|
||||||
|
};
|
||||||
|
lines.push(Line::from(l1).style(bg));
|
||||||
|
lines.push(Line::from(l2).style(bg));
|
||||||
|
}
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn needs_box(f: &mut Frame, area: Rect, needs: &[Need], focus: usize) {
|
||||||
|
let border = if needs.is_empty() {
|
||||||
|
theme::BORDER
|
||||||
|
} else {
|
||||||
|
theme::WAIT
|
||||||
|
};
|
||||||
|
let block = boxed("◆ Needs you", Some(needs.len()), theme::WAIT, border);
|
||||||
|
let inner = block.inner(area);
|
||||||
|
f.render_widget(block, area);
|
||||||
|
let mut lines = vec![];
|
||||||
|
for (i, n) in needs.iter().enumerate() {
|
||||||
|
// several items: the keys act on the focused one, tab moves the focus
|
||||||
|
let mark = if i == focus && needs.len() > 1 {
|
||||||
|
Span::styled("▶", fg(theme::WAIT))
|
||||||
|
} else {
|
||||||
|
Span::raw(" ")
|
||||||
|
};
|
||||||
|
let age = if n.age_secs > 0 {
|
||||||
|
format!(" · {}", crate::view::ago(n.age_secs))
|
||||||
|
} else {
|
||||||
|
String::new()
|
||||||
|
};
|
||||||
|
lines.push(Line::from(vec![
|
||||||
|
mark,
|
||||||
|
Span::styled(n.session.clone(), fg(theme::WAIT)),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(n.task.clone(), bold(theme::TEXT)),
|
||||||
|
Span::styled(format!(" · {}{age}", n.what), fg(theme::DIM)),
|
||||||
|
]));
|
||||||
|
let w = (inner.width as usize).saturating_sub(1);
|
||||||
|
if !n.detail.is_empty() {
|
||||||
|
lines.push(Line::from(Span::raw(format!(" {}", fit(&n.detail, w)))));
|
||||||
|
}
|
||||||
|
let keys = n.keys();
|
||||||
|
if !keys.is_empty() {
|
||||||
|
lines.push(Line::from(Span::styled(format!(" {keys}"), fg(theme::DIM))));
|
||||||
|
}
|
||||||
|
lines.push(Line::raw(""));
|
||||||
|
}
|
||||||
|
if needs.is_empty() {
|
||||||
|
lines.push(Line::from(Span::styled(
|
||||||
|
" nothing waits on you",
|
||||||
|
fg(theme::DIM),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind_color(kind: &str) -> Color {
|
||||||
|
match kind {
|
||||||
|
"test" | "catch" => theme::ERR,
|
||||||
|
"state" | "resume" => theme::RUN,
|
||||||
|
"tool" => theme::AGENT,
|
||||||
|
"edit" => theme::OK,
|
||||||
|
"notify" | "end" => theme::WAIT,
|
||||||
|
_ => theme::DIM,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events_box(f: &mut Frame, area: Rect, events: &[EventLine]) {
|
||||||
|
let mut title = vec![Span::styled(" Events", bold(theme::TEXT))];
|
||||||
|
title.push(Span::styled(" all sessions · f filter ", fg(theme::DIM)));
|
||||||
|
let block = Block::bordered()
|
||||||
|
.border_style(fg(theme::BORDER))
|
||||||
|
.title(Line::from(title));
|
||||||
|
let inner = block.inner(area);
|
||||||
|
f.render_widget(block, area);
|
||||||
|
let take = inner.height as usize;
|
||||||
|
let skip = events.len().saturating_sub(take);
|
||||||
|
let lines: Vec<Line> = events[skip..]
|
||||||
|
.iter()
|
||||||
|
.map(|e| {
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(format!("{} ", hms(e.at_ms)), fg(theme::DIM)),
|
||||||
|
Span::styled(format!("{:<4}", e.session), fg(theme::RUN)),
|
||||||
|
Span::styled(format!("{:<7}", fit(&e.kind, 7)), fg(kind_color(&e.kind))),
|
||||||
|
Span::raw(fit(&e.text, (inner.width as usize).saturating_sub(21))),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_bar() -> Line<'static> {
|
||||||
|
let mut v = vec![Span::raw(" ")];
|
||||||
|
for (k, what) in [
|
||||||
|
("j/k", "move"),
|
||||||
|
("enter", "open"),
|
||||||
|
("g", "goal"),
|
||||||
|
("tab", "next item"),
|
||||||
|
("q", "quit"),
|
||||||
|
] {
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!(" {k} "),
|
||||||
|
Style::new().fg(theme::BG).bg(theme::DIM),
|
||||||
|
));
|
||||||
|
v.push(Span::styled(format!(" {what} "), fg(theme::DIM)));
|
||||||
|
}
|
||||||
|
Line::from(v)
|
||||||
|
}
|
||||||
@@ -0,0 +1,542 @@
|
|||||||
|
//! Screen 2: session detail (ORCHESTRATOR.md 7.2, `Session.dc.html`).
|
||||||
|
|
||||||
|
use super::overview::Header;
|
||||||
|
use super::theme::{self, bold, fg, inverted};
|
||||||
|
use crate::detail::{Block as Blk, Detail, LineKind, MLine, TestRun};
|
||||||
|
use crate::machine::RunOn;
|
||||||
|
use crate::view::{Status, ago, hms};
|
||||||
|
use ratatui::Frame;
|
||||||
|
use ratatui::layout::{Constraint, Layout, Rect};
|
||||||
|
use ratatui::style::{Color, Modifier, Style};
|
||||||
|
use ratatui::text::{Line, Span};
|
||||||
|
use ratatui::widgets::{Block, Paragraph};
|
||||||
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
|
const W_TEXT: usize = 31;
|
||||||
|
const W_EXEC: usize = 9;
|
||||||
|
const W_SETS: usize = 14;
|
||||||
|
|
||||||
|
pub fn draw(f: &mut Frame, d: &Detail, h: &Header) {
|
||||||
|
let area = f.area();
|
||||||
|
f.render_widget(
|
||||||
|
Block::new().style(Style::new().bg(theme::BG).fg(theme::TEXT)),
|
||||||
|
area,
|
||||||
|
);
|
||||||
|
let [head, body, keys] = Layout::vertical([
|
||||||
|
Constraint::Length(1),
|
||||||
|
Constraint::Fill(1),
|
||||||
|
Constraint::Length(1),
|
||||||
|
])
|
||||||
|
.areas(area);
|
||||||
|
let [left, right] =
|
||||||
|
Layout::horizontal([Constraint::Length(90), Constraint::Fill(1)]).areas(body);
|
||||||
|
f.render_widget(header(d, h, head.width as usize), head);
|
||||||
|
machine_box(f, left, d);
|
||||||
|
|
||||||
|
let test_h = match &d.test {
|
||||||
|
Some(t) => (3 + t.failures.len() * 3).clamp(4, 16) as u16,
|
||||||
|
None => 3,
|
||||||
|
};
|
||||||
|
let files_h = (d.files.len().clamp(1, 6) + 2) as u16;
|
||||||
|
// the loop detector box only exists while the session loops
|
||||||
|
let loop_h = if d.looping.is_some() { 7 } else { 0 };
|
||||||
|
let [loop_area, test, now, files, budget] = Layout::vertical([
|
||||||
|
Constraint::Length(loop_h),
|
||||||
|
Constraint::Length(test_h),
|
||||||
|
Constraint::Length(4),
|
||||||
|
Constraint::Length(files_h),
|
||||||
|
Constraint::Min(6),
|
||||||
|
])
|
||||||
|
.areas(right);
|
||||||
|
if let Some(l) = &d.looping {
|
||||||
|
loop_box(f, loop_area, d, l);
|
||||||
|
}
|
||||||
|
test_box(f, test, d.test.as_ref());
|
||||||
|
now_box(f, now, d);
|
||||||
|
files_box(f, files, d);
|
||||||
|
budget_box(f, budget, d);
|
||||||
|
f.render_widget(key_bar(d.looping.is_some()), keys);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn loop_box(f: &mut Frame, area: Rect, d: &Detail, l: &crate::detail::LoopView) {
|
||||||
|
let b = Block::bordered().border_style(fg(theme::WAIT));
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let mut what = format!(
|
||||||
|
"The last {} test runs failed on the same {} tests.",
|
||||||
|
l.runs, l.tests
|
||||||
|
);
|
||||||
|
if let Some(file) = &l.file {
|
||||||
|
what.push_str(&format!(" The agent keeps editing {file}."));
|
||||||
|
}
|
||||||
|
// the sentence wraps (two lines fit); the keys get a line each so none is cut
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(vec![
|
||||||
|
Line::from(Span::styled(" ◆ Loop detector", bold(theme::WAIT))),
|
||||||
|
Line::from(Span::raw(format!(" {what}"))),
|
||||||
|
Line::from(Span::styled(
|
||||||
|
format!(
|
||||||
|
" [r] re-plan from {} [m] send hint to agent",
|
||||||
|
d.start.to_uppercase()
|
||||||
|
),
|
||||||
|
fg(theme::DIM),
|
||||||
|
)),
|
||||||
|
Line::from(Span::styled(" [k] kill and hand over", fg(theme::DIM))),
|
||||||
|
])
|
||||||
|
.wrap(ratatui::widgets::Wrap { trim: false }),
|
||||||
|
inner,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn status_color(s: Status) -> Color {
|
||||||
|
match s {
|
||||||
|
Status::Done => theme::OK,
|
||||||
|
Status::Fix | Status::Fail => theme::ERR,
|
||||||
|
Status::Wait => theme::WAIT,
|
||||||
|
Status::Run => theme::RUN,
|
||||||
|
Status::Blocked => theme::AGENT,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn header(d: &Detail, h: &Header, width: usize) -> Line<'static> {
|
||||||
|
let pid = d.pid.map_or(String::new(), |p| format!(" · pid {p}"));
|
||||||
|
let info = format!("branch {} · worktree {}{pid}", d.branch, d.worktree);
|
||||||
|
let clock = hms(h.now_ms);
|
||||||
|
let fixed = " hx·orch ".width()
|
||||||
|
+ " ‹ sessions / ".width()
|
||||||
|
+ format!("{} {}", d.id, d.task).width()
|
||||||
|
+ 2
|
||||||
|
+ d.status.label().width()
|
||||||
|
+ 2
|
||||||
|
+ clock.width()
|
||||||
|
+ 2;
|
||||||
|
let info = fit(&info, width.saturating_sub(fixed));
|
||||||
|
let gap = width.saturating_sub(fixed - 2 + info.width()).max(1);
|
||||||
|
Line::from(vec![
|
||||||
|
Span::styled(" hx·orch ", inverted(theme::RUN)),
|
||||||
|
Span::styled(" ‹ sessions / ", fg(theme::DIM)),
|
||||||
|
Span::styled(format!("{} {}", d.id, d.task), bold(theme::TEXT)),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(d.status.label(), bold(status_color(d.status))),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(info, fg(theme::DIM)),
|
||||||
|
Span::raw(" ".repeat(gap)),
|
||||||
|
Span::raw(clock),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fit(s: &str, w: usize) -> String {
|
||||||
|
if s.width() <= w {
|
||||||
|
return s.to_string();
|
||||||
|
}
|
||||||
|
let mut out = String::new();
|
||||||
|
for c in s.chars() {
|
||||||
|
if out.width() + 1 >= w {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
out.push('…');
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn titled<'a>(title: &str, sub: &str, border: Color) -> Block<'a> {
|
||||||
|
let mut t = vec![Span::styled(format!(" {title}"), bold(theme::TEXT))];
|
||||||
|
if !sub.is_empty() {
|
||||||
|
t.push(Span::styled(format!(" {sub}"), fg(theme::DIM)));
|
||||||
|
}
|
||||||
|
t.push(Span::raw(" "));
|
||||||
|
Block::bordered()
|
||||||
|
.border_style(fg(border))
|
||||||
|
.title(Line::from(t))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pad(spans: &mut Vec<Span<'static>>, parts: Vec<Span<'static>>, w: usize) {
|
||||||
|
let used: usize = parts.iter().map(|s| s.width()).sum();
|
||||||
|
spans.extend(parts);
|
||||||
|
spans.push(Span::raw(" ".repeat((w + 1).saturating_sub(used))));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn machine_line(l: &MLine) -> Line<'static> {
|
||||||
|
if l.kind == LineKind::Blank {
|
||||||
|
return Line::raw("");
|
||||||
|
}
|
||||||
|
let todo = l.block == Blk::Todo;
|
||||||
|
let text_style = match l.kind {
|
||||||
|
LineKind::Header => bold(theme::RUN),
|
||||||
|
LineKind::Only => fg(theme::WAIT),
|
||||||
|
LineKind::End => fg(theme::DIM),
|
||||||
|
_ if todo => fg(theme::DIM),
|
||||||
|
_ => fg(theme::TEXT),
|
||||||
|
};
|
||||||
|
let bar = if l.block == Blk::Cur {
|
||||||
|
Span::styled("▌", fg(theme::RUN))
|
||||||
|
} else {
|
||||||
|
Span::raw(" ")
|
||||||
|
};
|
||||||
|
let mut v = vec![bar];
|
||||||
|
let mut text = vec![Span::styled(l.text.clone(), text_style)];
|
||||||
|
if !l.to.is_empty() {
|
||||||
|
text.push(Span::styled(l.to.clone(), fg(theme::RUN)));
|
||||||
|
}
|
||||||
|
pad(&mut v, text, W_TEXT);
|
||||||
|
let exec = l.exec.map_or_else(
|
||||||
|
|| Span::raw(""),
|
||||||
|
|e| {
|
||||||
|
let (name, c) = match e {
|
||||||
|
RunOn::Computer => ("computer", theme::TEXT),
|
||||||
|
RunOn::Agent => ("agent", theme::AGENT),
|
||||||
|
RunOn::Human => ("human", theme::WAIT),
|
||||||
|
};
|
||||||
|
Span::styled(name, fg(c))
|
||||||
|
},
|
||||||
|
);
|
||||||
|
pad(&mut v, vec![exec], W_EXEC);
|
||||||
|
let sets_color = if todo { theme::DIM } else { theme::RUN };
|
||||||
|
pad(
|
||||||
|
&mut v,
|
||||||
|
vec![Span::styled(l.sets.clone(), fg(sets_color))],
|
||||||
|
W_SETS,
|
||||||
|
);
|
||||||
|
let live_color = if l.hit || l.block == Blk::Fail {
|
||||||
|
theme::ERR
|
||||||
|
} else if l.block == Blk::Cur {
|
||||||
|
theme::RUN
|
||||||
|
} else {
|
||||||
|
theme::OK
|
||||||
|
};
|
||||||
|
let live_style = if l.hit {
|
||||||
|
bold(live_color)
|
||||||
|
} else {
|
||||||
|
fg(live_color)
|
||||||
|
};
|
||||||
|
v.push(Span::styled(l.live.clone(), live_style));
|
||||||
|
let line = Line::from(v);
|
||||||
|
if l.block == Blk::Cur {
|
||||||
|
line.style(Style::new().bg(theme::SEL))
|
||||||
|
} else {
|
||||||
|
line
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn machine_box(f: &mut Frame, area: Rect, d: &Detail) {
|
||||||
|
let mut sub = d.machine_file.clone();
|
||||||
|
if let Some(a) = &d.on_abort {
|
||||||
|
sub.push_str(&format!(" · on abort → {a}"));
|
||||||
|
}
|
||||||
|
if let Some(b) = &d.on_budget {
|
||||||
|
sub.push_str(&format!(" · on budget → {b}"));
|
||||||
|
}
|
||||||
|
let block = titled("Machine", &sub, theme::BORDER);
|
||||||
|
let inner = block.inner(area);
|
||||||
|
f.render_widget(block, area);
|
||||||
|
let [head, lines, path] = Layout::vertical([
|
||||||
|
Constraint::Length(1),
|
||||||
|
Constraint::Fill(1),
|
||||||
|
Constraint::Length(3),
|
||||||
|
])
|
||||||
|
.areas(inner);
|
||||||
|
|
||||||
|
let mut hv = vec![Span::raw(" ")];
|
||||||
|
pad(&mut hv, vec![Span::raw("state / step")], W_TEXT);
|
||||||
|
pad(&mut hv, vec![Span::raw("runs on")], W_EXEC);
|
||||||
|
pad(&mut hv, vec![Span::raw("sets")], W_SETS);
|
||||||
|
hv.push(Span::raw("live"));
|
||||||
|
f.render_widget(Line::from(hv).style(fg(theme::DIM)), head);
|
||||||
|
|
||||||
|
// keep the current state in view when the machine is longer than the box
|
||||||
|
let all: Vec<Line> = d.lines.iter().map(machine_line).collect();
|
||||||
|
let h = lines.height as usize;
|
||||||
|
let cur = d
|
||||||
|
.lines
|
||||||
|
.iter()
|
||||||
|
.position(|l| l.block == Blk::Cur && l.kind == LineKind::Header)
|
||||||
|
.unwrap_or(0);
|
||||||
|
let start = if all.len() > h {
|
||||||
|
cur.saturating_sub(h / 3).min(all.len() - h)
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
f.render_widget(Paragraph::new(all[start..].to_vec()), lines);
|
||||||
|
|
||||||
|
let mut p = vec![Span::styled(" path ", fg(theme::DIM))];
|
||||||
|
for (i, s) in d.path.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
p.push(Span::raw(" → "));
|
||||||
|
}
|
||||||
|
let label = if s.failed {
|
||||||
|
format!("{} ✗", s.name)
|
||||||
|
} else {
|
||||||
|
s.name.clone()
|
||||||
|
};
|
||||||
|
p.push(if s.current {
|
||||||
|
Span::styled(format!(" {label} "), inverted(theme::RUN))
|
||||||
|
} else if s.failed {
|
||||||
|
Span::styled(label, fg(theme::ERR))
|
||||||
|
} else {
|
||||||
|
Span::styled(label, fg(theme::OK))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let sep = Block::new()
|
||||||
|
.borders(ratatui::widgets::Borders::TOP)
|
||||||
|
.border_style(fg(theme::BORDER));
|
||||||
|
f.render_widget(
|
||||||
|
Paragraph::new(Line::from(p))
|
||||||
|
.block(sep)
|
||||||
|
.wrap(ratatui::widgets::Wrap { trim: false }),
|
||||||
|
path,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_box(f: &mut Frame, area: Rect, t: Option<&TestRun>) {
|
||||||
|
let Some(t) = t else {
|
||||||
|
let b = titled("Last test run", "", theme::BORDER);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
f.render_widget(Span::styled(" no test report yet", fg(theme::DIM)), inner);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let border = if t.failed > 0 { theme::ERR } else { theme::OK };
|
||||||
|
let b = titled(
|
||||||
|
"Last test run",
|
||||||
|
&format!("{} · {}", t.step, hms(t.at_ms)),
|
||||||
|
border,
|
||||||
|
);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let total = (t.passed + t.failed).max(1) as usize;
|
||||||
|
let width = 40usize;
|
||||||
|
let red = ((t.failed as usize * width).div_ceil(total)).min(width);
|
||||||
|
let red = if t.failed > 0 { red.max(1) } else { 0 };
|
||||||
|
let mut lines = vec![Line::from(vec![
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(format!("{} passed", t.passed), fg(theme::OK)),
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(
|
||||||
|
format!("{} failed", t.failed),
|
||||||
|
if t.failed > 0 {
|
||||||
|
bold(theme::ERR)
|
||||||
|
} else {
|
||||||
|
fg(theme::DIM)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
Span::styled(
|
||||||
|
format!(" {} skipped · {:.1}s ", t.skipped, t.secs),
|
||||||
|
fg(theme::DIM),
|
||||||
|
),
|
||||||
|
Span::styled("█".repeat(width - red), fg(theme::OK)),
|
||||||
|
Span::styled("█".repeat(red), fg(theme::ERR)),
|
||||||
|
])];
|
||||||
|
for fl in &t.failures {
|
||||||
|
lines.push(Line::from(Span::styled(
|
||||||
|
format!(" ✗ {}", fl.name),
|
||||||
|
fg(theme::ERR),
|
||||||
|
)));
|
||||||
|
lines.push(Line::from(Span::styled(
|
||||||
|
format!(
|
||||||
|
" {}",
|
||||||
|
fit(&fl.message, (inner.width as usize).saturating_sub(6))
|
||||||
|
),
|
||||||
|
fg(theme::DIM),
|
||||||
|
)));
|
||||||
|
let mut where_ = fl.location.clone();
|
||||||
|
if !fl.repeats.is_empty() {
|
||||||
|
if !where_.is_empty() {
|
||||||
|
where_.push_str(" · ");
|
||||||
|
}
|
||||||
|
where_.push_str(&fl.repeats);
|
||||||
|
}
|
||||||
|
lines.push(Line::from(Span::styled(
|
||||||
|
format!(" {where_}"),
|
||||||
|
fg(theme::DIM),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn now_box(f: &mut Frame, area: Rect, d: &Detail) {
|
||||||
|
let b = titled("Now", "", theme::BORDER);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let who_color = if d.now.who == "agent" {
|
||||||
|
theme::AGENT
|
||||||
|
} else {
|
||||||
|
theme::TEXT
|
||||||
|
};
|
||||||
|
let first = if d.now.who.is_empty() {
|
||||||
|
Line::from(Span::styled(" idle", fg(theme::DIM)))
|
||||||
|
} else {
|
||||||
|
Line::from(vec![
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled(format!("{:<9}", d.now.who), fg(who_color)),
|
||||||
|
Span::raw(fit(&d.now.line, (inner.width as usize).saturating_sub(11))),
|
||||||
|
])
|
||||||
|
};
|
||||||
|
let second = Line::from(vec![
|
||||||
|
Span::raw(" "),
|
||||||
|
Span::styled("intent ", fg(theme::DIM)),
|
||||||
|
Span::raw(fit(
|
||||||
|
&d.now.intent,
|
||||||
|
(inner.width as usize).saturating_sub(11),
|
||||||
|
)),
|
||||||
|
]);
|
||||||
|
f.render_widget(Paragraph::new(vec![first, second]), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn files_box(f: &mut Frame, area: Rect, d: &Detail) {
|
||||||
|
let (a, r): (u32, u32) = d
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.fold((0, 0), |(a, r), x| (a + x.added, r + x.removed));
|
||||||
|
let b = titled(
|
||||||
|
"Changed files",
|
||||||
|
&format!("{} · +{a} −{r}", d.files.len()),
|
||||||
|
theme::BORDER,
|
||||||
|
);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let lines: Vec<Line> = d
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.take(inner.height as usize)
|
||||||
|
.map(|x| {
|
||||||
|
Line::from(vec![
|
||||||
|
Span::raw(format!(" {:<30}", fit(&x.path, 29))),
|
||||||
|
Span::styled(format!("{:<6}", format!("+{}", x.added)), fg(theme::OK)),
|
||||||
|
Span::styled(format!("{:<6}", format!("−{}", x.removed)), fg(theme::ERR)),
|
||||||
|
Span::styled(
|
||||||
|
"■".repeat((x.added as usize).div_ceil(6).min(12)),
|
||||||
|
fg(theme::OK),
|
||||||
|
),
|
||||||
|
Span::styled(
|
||||||
|
"■".repeat((x.removed as usize).div_ceil(6).min(12)),
|
||||||
|
fg(theme::ERR),
|
||||||
|
),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if lines.is_empty() {
|
||||||
|
f.render_widget(Span::styled(" no edits yet", fg(theme::DIM)), inner);
|
||||||
|
} else {
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bar(used: usize, total: usize, n: usize, color: Color) -> Span<'static> {
|
||||||
|
let on = (used * n).checked_div(total).unwrap_or(0).min(n);
|
||||||
|
Span::styled(
|
||||||
|
format!("{}{}", "▰".repeat(on), "▱".repeat(n - on)),
|
||||||
|
fg(color),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn k(n: u64) -> String {
|
||||||
|
if n >= 1000 {
|
||||||
|
format!("{}k", n / 1000)
|
||||||
|
} else {
|
||||||
|
n.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn budget_box(f: &mut Frame, area: Rect, d: &Detail) {
|
||||||
|
let b = titled("Budget", "", theme::BORDER);
|
||||||
|
let inner = b.inner(area);
|
||||||
|
f.render_widget(b, area);
|
||||||
|
let label = |s: &str| Span::styled(format!(" {s:<10}"), fg(theme::DIM));
|
||||||
|
let mut lines = vec![];
|
||||||
|
lines.push(match d.budget.ctx {
|
||||||
|
Some((u, l)) => {
|
||||||
|
let pct = (u * 100).checked_div(l).unwrap_or(0);
|
||||||
|
let c = if pct > 65 { theme::WAIT } else { theme::DIM };
|
||||||
|
Line::from(vec![
|
||||||
|
label("context"),
|
||||||
|
bar(u as usize, l as usize, 10, c),
|
||||||
|
Span::raw(format!(" {} / {}", k(u), k(l))),
|
||||||
|
Span::styled(
|
||||||
|
d.budget
|
||||||
|
.compact_at
|
||||||
|
.map_or(String::new(), |c| format!(" compact at {c}%")),
|
||||||
|
fg(theme::DIM),
|
||||||
|
),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
None => Line::from(vec![label("context"), Span::styled("—", fg(theme::DIM))]),
|
||||||
|
});
|
||||||
|
lines.push(match d.budget.retries {
|
||||||
|
Some((n, max)) => Line::from(vec![
|
||||||
|
label("retries"),
|
||||||
|
bar(n as usize, max as usize, max as usize, theme::ERR),
|
||||||
|
Span::raw(format!(" {n} / {max}")),
|
||||||
|
]),
|
||||||
|
None => Line::from(vec![
|
||||||
|
label("retries"),
|
||||||
|
Span::styled("none yet", fg(theme::DIM)),
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
// a cap turns the plain number into a bar; red once it is passed
|
||||||
|
let over = |used: f64, cap: f64| if used > cap { theme::ERR } else { theme::RUN };
|
||||||
|
lines.push(match d.budget.wall_cap {
|
||||||
|
Some(cap) => {
|
||||||
|
let c = over(d.budget.wall_secs as f64, cap as f64);
|
||||||
|
Line::from(vec![
|
||||||
|
label("wall time"),
|
||||||
|
bar(d.budget.wall_secs as usize, cap as usize, 10, c),
|
||||||
|
Span::raw(format!(" {} / {} cap", ago(d.budget.wall_secs), ago(cap))),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
None => Line::from(vec![
|
||||||
|
label("wall time"),
|
||||||
|
Span::styled(ago(d.budget.wall_secs), fg(theme::RUN)),
|
||||||
|
Span::styled(" no cap set", fg(theme::DIM)),
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
lines.push(match d.budget.cost_cap {
|
||||||
|
Some(cap) => {
|
||||||
|
let c = over(d.budget.cost, cap);
|
||||||
|
Line::from(vec![
|
||||||
|
label("cost"),
|
||||||
|
bar(
|
||||||
|
(d.budget.cost * 100.0) as usize,
|
||||||
|
(cap * 100.0) as usize,
|
||||||
|
10,
|
||||||
|
c,
|
||||||
|
),
|
||||||
|
Span::raw(format!(" ${:.2} / ${cap:.2}", d.budget.cost)),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
None => Line::from(vec![
|
||||||
|
label("cost"),
|
||||||
|
Span::styled(format!("${:.2}", d.budget.cost), fg(theme::RUN)),
|
||||||
|
Span::styled(" no cap set", fg(theme::DIM)),
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
f.render_widget(Paragraph::new(lines), inner);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key_bar(looping: bool) -> Line<'static> {
|
||||||
|
let mut v = vec![Span::raw(" ")];
|
||||||
|
for (key, what) in [
|
||||||
|
("esc", "back"),
|
||||||
|
("t", "full test output"),
|
||||||
|
("d", "diff"),
|
||||||
|
("l", "transcript"),
|
||||||
|
("i", "interrupt"),
|
||||||
|
("m", "message"),
|
||||||
|
("s", "state"),
|
||||||
|
("k", "kill"),
|
||||||
|
("o", "open in hx"),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.chain(looping.then_some(("r", "re-plan")))
|
||||||
|
{
|
||||||
|
v.push(Span::styled(
|
||||||
|
format!(" {key} "),
|
||||||
|
Style::new()
|
||||||
|
.fg(theme::BG)
|
||||||
|
.bg(theme::DIM)
|
||||||
|
.add_modifier(Modifier::empty()),
|
||||||
|
));
|
||||||
|
v.push(Span::styled(format!(" {what} "), fg(theme::DIM)));
|
||||||
|
}
|
||||||
|
Line::from(v)
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
//! Colors from ORCHESTRATOR.md section 8. Truecolor; ratatui maps to the nearest color on 256-color terminals
|
||||||
|
//! only through the terminal itself, so `COLORTERM` without truecolor looks approximate.
|
||||||
|
// shortcut: no explicit 256-color table; add one if a target terminal needs it.
|
||||||
|
|
||||||
|
use ratatui::style::{Color, Modifier, Style};
|
||||||
|
|
||||||
|
const fn rgb(hex: u32) -> Color {
|
||||||
|
Color::Rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const BG: Color = rgb(0x0b0e14);
|
||||||
|
pub const TEXT: Color = rgb(0xc9d1d9);
|
||||||
|
pub const DIM: Color = rgb(0x8b949e);
|
||||||
|
pub const TODO: Color = rgb(0x7d8590);
|
||||||
|
pub const BORDER: Color = rgb(0x30363d);
|
||||||
|
pub const SEL: Color = rgb(0x161b22);
|
||||||
|
pub const SEP: Color = rgb(0x484f58);
|
||||||
|
pub const RUN: Color = rgb(0x79c0ff);
|
||||||
|
pub const OK: Color = rgb(0x7ee787);
|
||||||
|
pub const ERR: Color = rgb(0xff7b72);
|
||||||
|
pub const WAIT: Color = rgb(0xe3b341);
|
||||||
|
pub const AGENT: Color = rgb(0xd2a8ff);
|
||||||
|
|
||||||
|
pub fn fg(c: Color) -> Style {
|
||||||
|
Style::new().fg(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bold(c: Color) -> Style {
|
||||||
|
Style::new().fg(c).add_modifier(Modifier::BOLD)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inverted block: dark text on a colored ground (active and waiting marks, key caps).
|
||||||
|
pub fn inverted(c: Color) -> Style {
|
||||||
|
Style::new().fg(BG).bg(c).add_modifier(Modifier::BOLD)
|
||||||
|
}
|
||||||
+714
@@ -0,0 +1,714 @@
|
|||||||
|
//! Pure view models: sessions, tasks, events and machine files in, what a screen shows out (ORCHESTRATOR.md
|
||||||
|
//! principle 3: no panel computes state on its own). No terminal and no database in here, so it is easy to test.
|
||||||
|
|
||||||
|
use crate::db::{Event, Session, Task};
|
||||||
|
use crate::machine::Machine;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Overview status column. `Fail` is not in the spec's list; a failed or aborted session needs some label.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum Status {
|
||||||
|
Run,
|
||||||
|
Fix,
|
||||||
|
Wait,
|
||||||
|
Blocked,
|
||||||
|
Done,
|
||||||
|
Fail,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Status {
|
||||||
|
pub fn label(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Status::Run => "RUN",
|
||||||
|
Status::Fix => "FIX",
|
||||||
|
Status::Wait => "WAIT",
|
||||||
|
Status::Blocked => "BLOCKED",
|
||||||
|
Status::Done => "DONE",
|
||||||
|
Status::Fail => "FAIL",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum Mark {
|
||||||
|
Done,
|
||||||
|
Active,
|
||||||
|
Failed,
|
||||||
|
Waiting,
|
||||||
|
Todo,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct Chip {
|
||||||
|
pub name: String,
|
||||||
|
pub mark: Mark,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct Row {
|
||||||
|
pub id: String,
|
||||||
|
pub status: Status,
|
||||||
|
pub task: String,
|
||||||
|
pub sub: String,
|
||||||
|
pub machine: String,
|
||||||
|
pub chips: Vec<Chip>,
|
||||||
|
/// `↻ fix 2/3` while the session recovers from a catch, else empty.
|
||||||
|
pub retry: String,
|
||||||
|
/// The loop detector fired: the last test runs failed on the same tests.
|
||||||
|
pub looping: bool,
|
||||||
|
/// `39/41 ✗2`, `18/18 ✓` or `—`.
|
||||||
|
pub tests: String,
|
||||||
|
pub tests_ok: Option<bool>,
|
||||||
|
pub added: u32,
|
||||||
|
pub removed: u32,
|
||||||
|
/// Context used, percent.
|
||||||
|
pub ctx: Option<u8>,
|
||||||
|
pub last: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum NeedKind {
|
||||||
|
/// A `human` step (review gate): approve or send back with a comment.
|
||||||
|
Review,
|
||||||
|
/// hx asks to run a tool: allow once, always, or deny.
|
||||||
|
Permission,
|
||||||
|
/// hx asks a question: reply with text.
|
||||||
|
Input,
|
||||||
|
/// The session ended in `escalated`. Derived from the session, nothing to answer in the queue.
|
||||||
|
Escalated,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One item of the Needs-you box.
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct Need {
|
||||||
|
/// Row id in the `needs` table; 0 for derived items.
|
||||||
|
pub id: i64,
|
||||||
|
pub kind: NeedKind,
|
||||||
|
pub session: String,
|
||||||
|
pub task: String,
|
||||||
|
/// `review ready`, `permission`, `question`, `escalated`.
|
||||||
|
pub what: String,
|
||||||
|
pub detail: String,
|
||||||
|
pub age_secs: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Need {
|
||||||
|
/// The key line under the item, like `[y] allow once [Y] always for s4 [n] deny`.
|
||||||
|
pub fn keys(&self) -> String {
|
||||||
|
match self.kind {
|
||||||
|
NeedKind::Review => "[a] approve [d] open diff [c] comment back".into(),
|
||||||
|
NeedKind::Permission => format!(
|
||||||
|
"[y] allow once [Y] always for {} [n] deny",
|
||||||
|
self.session
|
||||||
|
),
|
||||||
|
NeedKind::Input => "[r] reply".into(),
|
||||||
|
NeedKind::Escalated => String::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, PartialEq, Debug)]
|
||||||
|
pub struct EventLine {
|
||||||
|
pub id: i64,
|
||||||
|
pub at_ms: u64,
|
||||||
|
pub session: String,
|
||||||
|
pub kind: String,
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, PartialEq, Debug)]
|
||||||
|
pub struct Overview {
|
||||||
|
pub goal: String,
|
||||||
|
pub rows: Vec<Row>,
|
||||||
|
pub needs: Vec<Need>,
|
||||||
|
pub events: Vec<EventLine>,
|
||||||
|
pub merged: usize,
|
||||||
|
pub total: usize,
|
||||||
|
/// (passing, total) acceptance checks; None until checks exist (milestone 7).
|
||||||
|
pub checks: Option<(usize, usize)>,
|
||||||
|
pub running: usize,
|
||||||
|
pub waiting: usize,
|
||||||
|
pub blocked: usize,
|
||||||
|
pub cost: f64,
|
||||||
|
pub elapsed_secs: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Input<'a> {
|
||||||
|
pub goal: Option<&'a str>,
|
||||||
|
pub tasks: &'a [Task],
|
||||||
|
pub sessions: &'a [Session],
|
||||||
|
/// All events, oldest first.
|
||||||
|
pub events: &'a [Event],
|
||||||
|
/// Loaded machine files by name; a missing one only costs the strip.
|
||||||
|
pub machines: &'a HashMap<String, Machine>,
|
||||||
|
/// Unanswered items of the Needs-you queue, oldest first.
|
||||||
|
pub needs: &'a [crate::db::NeedRow],
|
||||||
|
/// Acceptance checks with their last result on main.
|
||||||
|
pub checks: &'a [crate::db::CheckRow],
|
||||||
|
pub decisions: &'a [crate::db::DecisionRow],
|
||||||
|
pub now_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build(i: &Input) -> Overview {
|
||||||
|
let mut by_session: HashMap<&str, Vec<&Event>> = HashMap::new();
|
||||||
|
for e in i.events {
|
||||||
|
by_session.entry(e.session.as_str()).or_default().push(e);
|
||||||
|
}
|
||||||
|
let none = vec![];
|
||||||
|
let mut o = Overview {
|
||||||
|
goal: i.goal.unwrap_or_default().to_string(),
|
||||||
|
total: i.tasks.len(),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let name_of = |sid: &str| {
|
||||||
|
i.tasks
|
||||||
|
.iter()
|
||||||
|
.find(|t| t.id == sid)
|
||||||
|
.map_or_else(String::new, |t| t.name.clone())
|
||||||
|
};
|
||||||
|
let mut escalated = vec![];
|
||||||
|
for n in i.needs {
|
||||||
|
let Some(task) = i
|
||||||
|
.sessions
|
||||||
|
.iter()
|
||||||
|
.find(|s| s.id == n.session)
|
||||||
|
.and_then(|s| i.tasks.iter().find(|t| t.id == s.task_id))
|
||||||
|
else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let text = |k: &str| n.payload[k].as_str().unwrap_or_default().to_string();
|
||||||
|
o.needs.push(Need {
|
||||||
|
id: n.id,
|
||||||
|
kind: match n.kind.as_str() {
|
||||||
|
"permission" => NeedKind::Permission,
|
||||||
|
"input" => NeedKind::Input,
|
||||||
|
_ => NeedKind::Review,
|
||||||
|
},
|
||||||
|
session: n.session.clone(),
|
||||||
|
task: task.name.clone(),
|
||||||
|
what: text("title"),
|
||||||
|
detail: text("detail"),
|
||||||
|
age_secs: i.now_ms.saturating_sub(n.at) / 1000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for s in i.sessions {
|
||||||
|
let Some(task) = i.tasks.iter().find(|t| t.id == s.task_id) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let evs = by_session.get(s.id.as_str()).unwrap_or(&none);
|
||||||
|
let machine = i.machines.get(&task.machine);
|
||||||
|
let scan = scan(evs, s, machine);
|
||||||
|
let unmet = task.depends_on.iter().find(|d| {
|
||||||
|
i.sessions
|
||||||
|
.iter()
|
||||||
|
.find(|x| &x.id == *d)
|
||||||
|
.is_none_or(|x| x.status != "merged")
|
||||||
|
});
|
||||||
|
let status = match s.status.as_str() {
|
||||||
|
"merged" => Status::Done,
|
||||||
|
"failed" | "aborted" => Status::Fail,
|
||||||
|
"waiting" | "escalated" => Status::Wait,
|
||||||
|
"queued" if unmet.is_some() => Status::Blocked,
|
||||||
|
_ if !scan.retry.is_empty() => Status::Fix,
|
||||||
|
_ => Status::Run,
|
||||||
|
};
|
||||||
|
let last = match (status, unmet) {
|
||||||
|
(Status::Blocked, Some(d)) => format!("waits on {d} {}", name_of(d)),
|
||||||
|
(Status::Done, _) => {
|
||||||
|
let at = evs.last().map_or(0, |e| e.at);
|
||||||
|
format!("merged · {} ago", ago(i.now_ms.saturating_sub(at) / 1000))
|
||||||
|
}
|
||||||
|
_ => evs.last().map_or_else(String::new, |e| describe(e)),
|
||||||
|
};
|
||||||
|
if s.status == "escalated" {
|
||||||
|
let end = evs.iter().rev().find(|e| e.kind == "end");
|
||||||
|
escalated.push(Need {
|
||||||
|
id: 0,
|
||||||
|
kind: NeedKind::Escalated,
|
||||||
|
session: s.id.clone(),
|
||||||
|
task: task.name.clone(),
|
||||||
|
what: "escalated".into(),
|
||||||
|
detail: end
|
||||||
|
.and_then(|e| e.payload["reason"].as_str().map(String::from))
|
||||||
|
.unwrap_or_default(),
|
||||||
|
age_secs: end.map_or(0, |e| i.now_ms.saturating_sub(e.at) / 1000),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
match status {
|
||||||
|
Status::Run | Status::Fix => o.running += 1,
|
||||||
|
Status::Wait => o.waiting += 1,
|
||||||
|
Status::Blocked => o.blocked += 1,
|
||||||
|
Status::Done => o.merged += 1,
|
||||||
|
Status::Fail => {}
|
||||||
|
}
|
||||||
|
o.cost += scan.cost;
|
||||||
|
o.rows.push(Row {
|
||||||
|
id: s.id.clone(),
|
||||||
|
status,
|
||||||
|
task: task.name.clone(),
|
||||||
|
sub: task.subtitle.clone(),
|
||||||
|
machine: machine.map_or_else(|| task.machine.clone(), |m| format!("{}.toml", m.name)),
|
||||||
|
chips: scan.chips,
|
||||||
|
retry: scan.retry,
|
||||||
|
looping: scan.looping,
|
||||||
|
tests: scan.tests.0,
|
||||||
|
tests_ok: scan.tests.1,
|
||||||
|
added: scan.added,
|
||||||
|
removed: scan.removed,
|
||||||
|
ctx: scan.ctx,
|
||||||
|
last,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
o.needs.extend(escalated);
|
||||||
|
if !i.checks.is_empty() {
|
||||||
|
let green = i
|
||||||
|
.checks
|
||||||
|
.iter()
|
||||||
|
.filter(|c| c.last_status.as_deref() == Some("pass"))
|
||||||
|
.count();
|
||||||
|
o.checks = Some((green, i.checks.len()));
|
||||||
|
}
|
||||||
|
o.events = i
|
||||||
|
.events
|
||||||
|
.iter()
|
||||||
|
.map(|e| EventLine {
|
||||||
|
id: e.id,
|
||||||
|
at_ms: e.at,
|
||||||
|
session: e.session.clone(),
|
||||||
|
kind: e.kind.clone(),
|
||||||
|
text: line_text(e),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
o.elapsed_secs = i
|
||||||
|
.events
|
||||||
|
.first()
|
||||||
|
.map_or(0, |e| i.now_ms.saturating_sub(e.at) / 1000);
|
||||||
|
o
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Scan {
|
||||||
|
chips: Vec<Chip>,
|
||||||
|
retry: String,
|
||||||
|
looping: bool,
|
||||||
|
tests: (String, Option<bool>),
|
||||||
|
added: u32,
|
||||||
|
removed: u32,
|
||||||
|
ctx: Option<u8>,
|
||||||
|
cost: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pass over a session's events. Strip marks: a state that was left through a catch is failed, one left
|
||||||
|
/// normally is done, the state the session is in is active.
|
||||||
|
fn scan(evs: &[&Event], s: &Session, machine: Option<&Machine>) -> Scan {
|
||||||
|
let mut marks: HashMap<String, Mark> = HashMap::new();
|
||||||
|
let mut cur = String::new();
|
||||||
|
let mut pending_fail: Option<String> = None;
|
||||||
|
// (state, catch) the session is recovering from; cleared once that state passes again
|
||||||
|
let mut recovering: Option<(String, String)> = None;
|
||||||
|
let mut sc = Scan {
|
||||||
|
chips: vec![],
|
||||||
|
retry: String::new(),
|
||||||
|
looping: false,
|
||||||
|
tests: ("—".into(), None),
|
||||||
|
added: 0,
|
||||||
|
removed: 0,
|
||||||
|
ctx: None,
|
||||||
|
cost: 0.0,
|
||||||
|
};
|
||||||
|
for e in evs {
|
||||||
|
let p = &e.payload;
|
||||||
|
match e.kind.as_str() {
|
||||||
|
"catch" => {
|
||||||
|
let (st, c) = (str_of(p, "state"), str_of(p, "catch"));
|
||||||
|
pending_fail = Some(st.clone());
|
||||||
|
recovering = Some((st, c));
|
||||||
|
}
|
||||||
|
"state" => {
|
||||||
|
let (from, to) = (str_of(p, "from"), str_of(p, "to"));
|
||||||
|
if !from.is_empty() {
|
||||||
|
let failed = pending_fail.as_deref() == Some(from.as_str());
|
||||||
|
marks.insert(from.clone(), if failed { Mark::Failed } else { Mark::Done });
|
||||||
|
if !failed && recovering.as_ref().is_some_and(|(r, _)| *r == from) {
|
||||||
|
recovering = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pending_fail = None;
|
||||||
|
marks.insert(to.clone(), Mark::Active);
|
||||||
|
cur = to;
|
||||||
|
}
|
||||||
|
"end" => {
|
||||||
|
let ok = p["status"].as_str().is_some_and(|x| x != "failed");
|
||||||
|
marks.insert(cur.clone(), if ok { Mark::Done } else { Mark::Failed });
|
||||||
|
}
|
||||||
|
"test" => {
|
||||||
|
let (pass, fail) = (
|
||||||
|
p["passed"].as_u64().unwrap_or(0),
|
||||||
|
p["failed"].as_u64().unwrap_or(0),
|
||||||
|
);
|
||||||
|
let total = pass + fail;
|
||||||
|
sc.tests = if fail > 0 {
|
||||||
|
(format!("{pass}/{total} ✗{fail}"), Some(false))
|
||||||
|
} else {
|
||||||
|
(format!("{pass}/{total} ✓"), Some(true))
|
||||||
|
};
|
||||||
|
}
|
||||||
|
"edit" => {
|
||||||
|
sc.added += p["added"].as_u64().unwrap_or(0) as u32;
|
||||||
|
sc.removed += p["removed"].as_u64().unwrap_or(0) as u32;
|
||||||
|
}
|
||||||
|
"usage" => {
|
||||||
|
let (used, limit) = (
|
||||||
|
p["ctx_used"].as_u64().unwrap_or(0),
|
||||||
|
p["ctx_limit"].as_u64().unwrap_or(0),
|
||||||
|
);
|
||||||
|
if let Some(pct) = (used * 100).checked_div(limit) {
|
||||||
|
sc.ctx = Some(pct.min(100) as u8);
|
||||||
|
}
|
||||||
|
sc.cost = p["cost"].as_f64().unwrap_or(sc.cost);
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.status == "waiting"
|
||||||
|
&& let Some(m) = marks.get_mut(&cur)
|
||||||
|
{
|
||||||
|
*m = Mark::Waiting;
|
||||||
|
}
|
||||||
|
if let Some(m) = machine {
|
||||||
|
sc.chips = m
|
||||||
|
.strip()
|
||||||
|
.map(|st| Chip {
|
||||||
|
name: st.name.clone(),
|
||||||
|
mark: marks.get(&st.name).copied().unwrap_or(Mark::Todo),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if s.status == "running"
|
||||||
|
&& let Some((st, c)) = &recovering
|
||||||
|
{
|
||||||
|
let n = evs
|
||||||
|
.iter()
|
||||||
|
.filter(|e| {
|
||||||
|
e.kind == "catch"
|
||||||
|
&& str_of(&e.payload, "state") == *st
|
||||||
|
&& str_of(&e.payload, "catch") == *c
|
||||||
|
})
|
||||||
|
.count();
|
||||||
|
sc.retry = match m.state(st).and_then(|x| x.retry.get(c)) {
|
||||||
|
Some(r) => format!("↻ fix {n}/{}", r.max),
|
||||||
|
None => format!("↻ fix {n}"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sc.looping =
|
||||||
|
matches!(s.status.as_str(), "running" | "waiting") && crate::budget::looping(evs).is_some();
|
||||||
|
sc
|
||||||
|
}
|
||||||
|
|
||||||
|
fn str_of(p: &serde_json::Value, k: &str) -> String {
|
||||||
|
p[k].as_str().unwrap_or_default().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Short text for the "last activity" column.
|
||||||
|
fn describe(e: &Event) -> String {
|
||||||
|
let p = &e.payload;
|
||||||
|
match e.kind.as_str() {
|
||||||
|
"state" => format!("entered {}", str_of(p, "to")),
|
||||||
|
"step" if p["ok"] == true => format!(
|
||||||
|
"{} · {}",
|
||||||
|
str_of(p, "step"),
|
||||||
|
secs(p["ms"].as_u64().unwrap_or(0))
|
||||||
|
),
|
||||||
|
"step" => format!("{} failed", str_of(p, "step")),
|
||||||
|
"catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
|
||||||
|
"end" => format!("ended: {}", str_of(p, "status")),
|
||||||
|
"resume" => "resumed".into(),
|
||||||
|
"status" => str_of(p, "label"),
|
||||||
|
"intent" => str_of(p, "text"),
|
||||||
|
"tool" => str_of(p, "title"),
|
||||||
|
k => k.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text of one line in the events box.
|
||||||
|
fn line_text(e: &Event) -> String {
|
||||||
|
let p = &e.payload;
|
||||||
|
match e.kind.as_str() {
|
||||||
|
"state" if str_of(p, "from").is_empty() => format!("start {}", str_of(p, "to")),
|
||||||
|
"state" => format!("{} → {}", str_of(p, "from"), str_of(p, "to")),
|
||||||
|
"step" => {
|
||||||
|
let res = if p["ok"] == true {
|
||||||
|
"ok".to_string()
|
||||||
|
} else {
|
||||||
|
format!("exit {}", p["exit"])
|
||||||
|
};
|
||||||
|
format!(
|
||||||
|
"{}/{} → {res} ({})",
|
||||||
|
str_of(p, "state"),
|
||||||
|
str_of(p, "step"),
|
||||||
|
secs(p["ms"].as_u64().unwrap_or(0))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
"catch" => format!("{} ✗ {}", str_of(p, "state"), str_of(p, "catch")),
|
||||||
|
"end" => match p["reason"].as_str() {
|
||||||
|
Some(r) => format!("ended: {} ({r})", str_of(p, "status")),
|
||||||
|
None => format!("ended: {}", str_of(p, "status")),
|
||||||
|
},
|
||||||
|
"status" => format!("■ {}", str_of(p, "label")),
|
||||||
|
"resume" => format!("resumed in {}", str_of(p, "state")),
|
||||||
|
"edit" => format!("{} +{} −{}", str_of(p, "path"), p["added"], p["removed"]),
|
||||||
|
"tool" => str_of(p, "title"),
|
||||||
|
"permission" => format!(
|
||||||
|
"permission {}: {}",
|
||||||
|
str_of(p, "decision"),
|
||||||
|
str_of(p, "tool")
|
||||||
|
),
|
||||||
|
"plan" => {
|
||||||
|
let steps = p["steps"].as_array().map_or(0, Vec::len);
|
||||||
|
format!(
|
||||||
|
"{steps} steps, {} files",
|
||||||
|
p["files"].as_array().map_or(0, Vec::len)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
_ => p["text"]
|
||||||
|
.as_str()
|
||||||
|
.map_or_else(|| e.kind.clone(), String::from),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secs(ms: u64) -> String {
|
||||||
|
if ms < 10_000 {
|
||||||
|
format!("{:.1}s", ms as f64 / 1000.0)
|
||||||
|
} else {
|
||||||
|
format!("{}s", ms / 1000)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ago(secs: u64) -> String {
|
||||||
|
match secs {
|
||||||
|
0..60 => format!("{secs}s"),
|
||||||
|
60..3600 => format!("{}m", secs / 60),
|
||||||
|
_ => format!("{}h", secs / 3600),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Local wall-clock time `HH:MM:SS` of a millisecond timestamp.
|
||||||
|
pub fn hms(ms: u64) -> String {
|
||||||
|
let t = (ms / 1000) as libc::time_t;
|
||||||
|
// SAFETY: localtime_r writes into our zeroed tm and reads t; no shared state.
|
||||||
|
let tm = unsafe {
|
||||||
|
let mut tm: libc::tm = std::mem::zeroed();
|
||||||
|
libc::localtime_r(&t, &mut tm);
|
||||||
|
tm
|
||||||
|
};
|
||||||
|
format!("{:02}:{:02}:{:02}", tm.tm_hour, tm.tm_min, tm.tm_sec)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn session(id: &str, task: &str, state: &str, status: &str) -> Session {
|
||||||
|
Session {
|
||||||
|
id: id.into(),
|
||||||
|
task_id: task.into(),
|
||||||
|
branch: "b".into(),
|
||||||
|
worktree: "/w".into(),
|
||||||
|
pid: None,
|
||||||
|
state: state.into(),
|
||||||
|
status: status.into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn task(id: &str, name: &str, deps: &[&str]) -> Task {
|
||||||
|
Task {
|
||||||
|
id: id.into(),
|
||||||
|
name: name.into(),
|
||||||
|
subtitle: "sub".into(),
|
||||||
|
machine: "task".into(),
|
||||||
|
depends_on: deps.iter().map(|d| d.to_string()).collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ev(id: i64, s: &str, kind: &str, payload: serde_json::Value) -> Event {
|
||||||
|
Event {
|
||||||
|
id,
|
||||||
|
session: s.into(),
|
||||||
|
at: 1_000 * id as u64,
|
||||||
|
kind: kind.into(),
|
||||||
|
payload,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn machines() -> HashMap<String, Machine> {
|
||||||
|
let text = include_str!("../examples/machines/task.toml");
|
||||||
|
HashMap::from([("task".into(), Machine::parse(text).unwrap())])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn marks(r: &Row) -> String {
|
||||||
|
r.chips
|
||||||
|
.iter()
|
||||||
|
.map(|c| match c.mark {
|
||||||
|
Mark::Done => 'd',
|
||||||
|
Mark::Active => 'a',
|
||||||
|
Mark::Failed => 'f',
|
||||||
|
Mark::Waiting => 'w',
|
||||||
|
Mark::Todo => 't',
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn st(id: i64, from: &str, to: &str) -> Event {
|
||||||
|
ev(id, "s2", "state", json!({"from": from, "to": to}))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fix_loop_marks_and_label() {
|
||||||
|
// plan -> code -> build -> test fails -> code (fix 1 of 3)
|
||||||
|
let events = vec![
|
||||||
|
st(1, "", "plan"),
|
||||||
|
st(2, "plan", "code"),
|
||||||
|
st(3, "code", "build"),
|
||||||
|
st(4, "build", "test"),
|
||||||
|
ev(5, "s2", "test", json!({"passed": 39, "failed": 2})),
|
||||||
|
ev(
|
||||||
|
6,
|
||||||
|
"s2",
|
||||||
|
"catch",
|
||||||
|
json!({"state": "test", "catch": "TestsFailed"}),
|
||||||
|
),
|
||||||
|
st(7, "test", "code"),
|
||||||
|
ev(
|
||||||
|
8,
|
||||||
|
"s2",
|
||||||
|
"edit",
|
||||||
|
json!({"path": "a.rs", "added": 6, "removed": 2}),
|
||||||
|
),
|
||||||
|
ev(
|
||||||
|
9,
|
||||||
|
"s2",
|
||||||
|
"usage",
|
||||||
|
json!({"ctx_used": 71, "ctx_limit": 100, "cost": 1.5}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let m = machines();
|
||||||
|
let (tasks, sessions) = (
|
||||||
|
[task("s2", "oauth", &[])],
|
||||||
|
[session("s2", "s2", "code", "running")],
|
||||||
|
);
|
||||||
|
let o = build(&Input {
|
||||||
|
goal: Some("g"),
|
||||||
|
tasks: &tasks,
|
||||||
|
sessions: &sessions,
|
||||||
|
events: &events,
|
||||||
|
machines: &m,
|
||||||
|
needs: &[],
|
||||||
|
checks: &[],
|
||||||
|
decisions: &[],
|
||||||
|
now_ms: 20_000,
|
||||||
|
});
|
||||||
|
let r = &o.rows[0];
|
||||||
|
// plan done, code active again, build done, test failed, review and merge not reached
|
||||||
|
assert_eq!(marks(r), "dadftt");
|
||||||
|
assert_eq!(r.status, Status::Fix);
|
||||||
|
assert_eq!(r.retry, "↻ fix 1/3");
|
||||||
|
assert_eq!((r.tests.as_str(), r.tests_ok), ("39/41 ✗2", Some(false)));
|
||||||
|
assert_eq!((r.added, r.removed, r.ctx), (6, 2, Some(71)));
|
||||||
|
assert_eq!(o.running, 1);
|
||||||
|
assert!((o.cost - 1.5).abs() < 1e-9);
|
||||||
|
assert_eq!(o.elapsed_secs, 19);
|
||||||
|
assert_eq!(o.events.len(), 9);
|
||||||
|
assert_eq!(o.events[5].text, "test ✗ TestsFailed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn retry_label_clears_when_the_state_passes() {
|
||||||
|
let events = vec![
|
||||||
|
st(1, "", "test"),
|
||||||
|
ev(
|
||||||
|
2,
|
||||||
|
"s2",
|
||||||
|
"catch",
|
||||||
|
json!({"state": "test", "catch": "TestsFailed"}),
|
||||||
|
),
|
||||||
|
st(3, "test", "code"),
|
||||||
|
st(4, "code", "build"),
|
||||||
|
st(5, "build", "test"),
|
||||||
|
st(6, "test", "review"),
|
||||||
|
];
|
||||||
|
let m = machines();
|
||||||
|
let (tasks, sessions) = (
|
||||||
|
[task("s2", "t", &[])],
|
||||||
|
[session("s2", "s2", "review", "running")],
|
||||||
|
);
|
||||||
|
let o = build(&Input {
|
||||||
|
goal: None,
|
||||||
|
tasks: &tasks,
|
||||||
|
sessions: &sessions,
|
||||||
|
events: &events,
|
||||||
|
machines: &m,
|
||||||
|
needs: &[],
|
||||||
|
checks: &[],
|
||||||
|
decisions: &[],
|
||||||
|
now_ms: 0,
|
||||||
|
});
|
||||||
|
assert_eq!(o.rows[0].retry, "");
|
||||||
|
assert_eq!(o.rows[0].status, Status::Run);
|
||||||
|
assert_eq!(marks(&o.rows[0]), "tdddat");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn blocked_done_and_wait() {
|
||||||
|
let events = vec![
|
||||||
|
ev(1, "s1", "end", json!({"status": "merged", "reason": null})),
|
||||||
|
ev(
|
||||||
|
2,
|
||||||
|
"s3",
|
||||||
|
"end",
|
||||||
|
json!({"status": "escalated", "reason": "budget"}),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
let m = machines();
|
||||||
|
let tasks = [
|
||||||
|
task("s1", "one", &[]),
|
||||||
|
task("s2", "two", &["s1", "s3"]),
|
||||||
|
task("s3", "three", &[]),
|
||||||
|
];
|
||||||
|
let sessions = [
|
||||||
|
session("s1", "s1", "merge", "merged"),
|
||||||
|
session("s2", "s2", "", "queued"),
|
||||||
|
session("s3", "s3", "escalated", "escalated"),
|
||||||
|
];
|
||||||
|
let o = build(&Input {
|
||||||
|
goal: None,
|
||||||
|
tasks: &tasks,
|
||||||
|
sessions: &sessions,
|
||||||
|
events: &events,
|
||||||
|
machines: &m,
|
||||||
|
needs: &[],
|
||||||
|
checks: &[],
|
||||||
|
decisions: &[],
|
||||||
|
now_ms: 61_000,
|
||||||
|
});
|
||||||
|
let s: Vec<_> = o.rows.iter().map(|r| r.status).collect();
|
||||||
|
assert_eq!(s, [Status::Done, Status::Blocked, Status::Wait]);
|
||||||
|
assert_eq!(o.rows[1].last, "waits on s3 three");
|
||||||
|
assert_eq!(o.rows[0].last, "merged · 1m ago");
|
||||||
|
assert_eq!((o.merged, o.total, o.blocked, o.waiting), (1, 3, 1, 1));
|
||||||
|
assert_eq!(o.needs.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
(o.needs[0].session.as_str(), o.needs[0].detail.as_str()),
|
||||||
|
("s3", "budget")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn helpers() {
|
||||||
|
assert_eq!(ago(5), "5s");
|
||||||
|
assert_eq!(ago(130), "2m");
|
||||||
|
assert_eq!(ago(7300), "2h");
|
||||||
|
assert_eq!(secs(1500), "1.5s");
|
||||||
|
assert_eq!(secs(38_000), "38s");
|
||||||
|
assert_eq!(hms(0).len(), 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
"""Fake `hx serve --acp --cwd DIR --session ID`: newline-delimited JSON-RPC 2.0 on stdio.
|
||||||
|
|
||||||
|
Behaviour per `hx/step`, chosen with FAKE_MODE (orch passes FAKE_* through the profile's `env`):
|
||||||
|
ok intent, tool call, edit, usage, decision, plan, then step_result done (default)
|
||||||
|
blocked step_result blocked, catch FAKE_CATCH (default PlanInvalid)
|
||||||
|
block_once blocked the first time (marker file .fake_blocked in cwd), done afterwards
|
||||||
|
needs_input step_result needs_input with a question; finishes when the retried step has a context.hint
|
||||||
|
permission asks session/request_permission first and records the answer in permission.txt
|
||||||
|
slow works until hx/interrupt (records hx/message and hx/compact in messages.txt / compact.txt), then
|
||||||
|
answers done; a retried step with context.hint finishes at once
|
||||||
|
limit step_result blocked, no catch, reason "limit" (hx hit a limit from hx/step)
|
||||||
|
error step_result blocked, no catch, reason "error"
|
||||||
|
crash exits without a step_result
|
||||||
|
FAKE_UNDERSCORE=1 sends every custom method as `_hx/...`.
|
||||||
|
FAKE_USAGE="ctx_used,ctx_limit,cost" makes every step report that usage first.
|
||||||
|
Every received message is appended to FAKE_LOG when set. Each step also appends its prompt kind to steps.txt.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
args = sys.argv[1:]
|
||||||
|
cwd = args[args.index("--cwd") + 1] if "--cwd" in args else os.getcwd()
|
||||||
|
session = args[args.index("--session") + 1] if "--session" in args else "sess-1"
|
||||||
|
mode = os.environ.get("FAKE_MODE", "ok")
|
||||||
|
log = os.environ.get("FAKE_LOG")
|
||||||
|
|
||||||
|
|
||||||
|
def send(o):
|
||||||
|
sys.stdout.write(json.dumps({"jsonrpc": "2.0", **o}) + "\n")
|
||||||
|
sys.stdout.flush()
|
||||||
|
|
||||||
|
|
||||||
|
def note(method, params):
|
||||||
|
if os.environ.get("FAKE_UNDERSCORE") and method.startswith("hx/"):
|
||||||
|
method = "_" + method
|
||||||
|
send({"method": method, "params": params})
|
||||||
|
|
||||||
|
|
||||||
|
def recv():
|
||||||
|
line = sys.stdin.readline()
|
||||||
|
if not line:
|
||||||
|
sys.exit(0)
|
||||||
|
m = json.loads(line)
|
||||||
|
if log:
|
||||||
|
with open(log, "a") as f:
|
||||||
|
f.write(json.dumps(m) + "\n")
|
||||||
|
return m
|
||||||
|
|
||||||
|
|
||||||
|
def step(params):
|
||||||
|
kind = params["prompt"]
|
||||||
|
with open(os.path.join(cwd, "steps.txt"), "a") as f:
|
||||||
|
f.write(kind + "\n")
|
||||||
|
if mode == "crash":
|
||||||
|
sys.exit(3)
|
||||||
|
note("hx/intent", {"text": f"working on {kind}"})
|
||||||
|
usage = os.environ.get("FAKE_USAGE") # "ctx_used,ctx_limit,cost"
|
||||||
|
if usage:
|
||||||
|
used, limit, cost = usage.split(",")
|
||||||
|
note("hx/usage", {"ctx_used": int(used), "ctx_limit": int(limit), "cost": float(cost)})
|
||||||
|
note("session/update", {"sessionId": session, "update": {"sessionUpdate": "tool_call", "toolCallId": "t1", "title": "edit src/lib.rs", "kind": "edit", "status": "in_progress"}})
|
||||||
|
if mode == "permission":
|
||||||
|
send({"id": 900, "method": "session/request_permission", "params": {
|
||||||
|
"sessionId": session,
|
||||||
|
"toolCall": {"toolCallId": "t2", "title": "docker compose up -d redis"},
|
||||||
|
"options": [{"optionId": "allow", "name": "Allow once", "kind": "allow_once"}, {"optionId": "deny", "name": "Deny", "kind": "reject_once"}]}})
|
||||||
|
while True:
|
||||||
|
m = recv()
|
||||||
|
if m.get("id") == 900:
|
||||||
|
with open(os.path.join(cwd, "permission.txt"), "w") as f:
|
||||||
|
f.write(json.dumps(m["result"]))
|
||||||
|
break
|
||||||
|
# slow keeps working until the orchestrator interrupts it; it records what it is told meanwhile.
|
||||||
|
# A retried step (context.hint set, e.g. the user's reply after an interrupt) finishes at once.
|
||||||
|
if mode == "slow" and not params.get("context", {}).get("hint"):
|
||||||
|
while True:
|
||||||
|
m = recv()
|
||||||
|
md = m.get("method")
|
||||||
|
if md == "hx/message":
|
||||||
|
with open(os.path.join(cwd, "messages.txt"), "a") as f:
|
||||||
|
f.write(m["params"]["text"] + "\n")
|
||||||
|
elif md == "hx/compact":
|
||||||
|
with open(os.path.join(cwd, "compact.txt"), "a") as f:
|
||||||
|
f.write("compact\n")
|
||||||
|
elif md == "hx/interrupt":
|
||||||
|
note("hx/step_result", {"status": "done", "summary": "interrupted"})
|
||||||
|
return
|
||||||
|
# needs_input asks once; with the user's answer in context.hint the same step finishes
|
||||||
|
if mode == "needs_input" and not params.get("context", {}).get("hint"):
|
||||||
|
note("hx/step_result", {"status": "needs_input", "question": "Which provider?"})
|
||||||
|
return
|
||||||
|
if mode in ("limit", "error"): # blocked without a catch, only the reason differs
|
||||||
|
note("hx/step_result", {"status": "blocked", "reason": mode, "summary": f"hit the {mode}"})
|
||||||
|
return
|
||||||
|
blocked = mode == "blocked"
|
||||||
|
if mode == "block_once" and not os.path.exists(os.path.join(cwd, ".fake_blocked")):
|
||||||
|
open(os.path.join(cwd, ".fake_blocked"), "w").close()
|
||||||
|
blocked = True
|
||||||
|
if blocked:
|
||||||
|
note("hx/step_result", {"status": "blocked", "catch": os.environ.get("FAKE_CATCH", "PlanInvalid"), "summary": "cannot continue"})
|
||||||
|
return
|
||||||
|
with open(os.path.join(cwd, f"agent_{kind}.txt"), "a") as f:
|
||||||
|
f.write("work\n")
|
||||||
|
note("hx/edit", {"path": f"agent_{kind}.txt", "added": 4, "removed": 1})
|
||||||
|
note("hx/usage", {"ctx_used": 40000, "ctx_limit": 200000, "cost": 0.25})
|
||||||
|
note("hx/decision", {"text": "token bucket over sliding window", "state": kind, "at": 1})
|
||||||
|
if kind == "plan":
|
||||||
|
note("hx/plan", {"steps": ["write the limiter", "add tests"], "files": ["src/limiter.rs"]})
|
||||||
|
note("hx/step_result", {"status": "done", "summary": f"{kind} finished"})
|
||||||
|
|
||||||
|
|
||||||
|
while True:
|
||||||
|
m = recv()
|
||||||
|
method, mid = m.get("method"), m.get("id")
|
||||||
|
if method == "initialize":
|
||||||
|
send({"id": mid, "result": {"protocolVersion": 1, "agentCapabilities": {}}})
|
||||||
|
elif method == "session/new":
|
||||||
|
send({"id": mid, "result": {"sessionId": session}})
|
||||||
|
elif method == "hx/step":
|
||||||
|
send({"id": mid, "result": {}}) # ack; the outcome comes as hx/step_result
|
||||||
|
step(m["params"])
|
||||||
|
elif mid is not None:
|
||||||
|
send({"id": mid, "error": {"code": -32601, "message": "unknown method"}})
|
||||||
Reference in new issue
Block a user