diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..9e039756 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,35 @@ +## Summary + + + +## Specification + + + +## Checks + + + +- [ ] + +## Agent review + + + +| Run | Model | Effort | Commit | Result | +| --- | --- | --- | --- | --- | +| `/simplify` | | | | | +| Claude `/code-review` | | | | | +| Codex | | | | | + + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b1b185bd..bdd3d13f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,6 +20,8 @@ jobs: - run: cargo fmt --all -- --check - run: cargo clippy --workspace --all-targets -- -D warnings - run: cargo nextest run --workspace + # The agent review's runner, on fixture output: no reviewer is reached. + - run: python3 -m unittest discover -s scripts/agent-review # The repository's own specification stays canonical and free of errors and warnings. # These runs of `loft` send nothing: `.cargo/config.toml` starts every process Cargo runs # with telemetry off. A runner is new on every run, so its events would count runs as diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fda1c116..5ca3825c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -43,6 +43,7 @@ jobs: - run: scripts/deslop.sh install - run: scripts/deslop.sh - run: cargo nextest run --workspace + - run: python3 -m unittest discover -s scripts/agent-review - run: cargo run -q -p loft-cli -- fmt --check - run: cargo run -q -p loft-cli -- check --fail-on warning - run: cargo run -q -p loft-cli -- reconcile --fail-on warning diff --git a/AGENTS.md b/AGENTS.md index 2e706c9a..e0134928 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -368,6 +368,7 @@ The thinking behind the Software Plant is at . cargo run -q -p loft-cli -- fmt --check cargo run -q -p loft-cli -- check --fail-on warning cargo run -q -p loft-cli -- reconcile --fail-on warning + python3 -m unittest discover -s scripts/agent-review ``` Install the runner with `cargo install cargo-nextest --locked`, and the architecture check with @@ -378,120 +379,25 @@ The thinking behind the Software Plant is at . - For a focused loop, use `cargo nextest run -p `. - Run the workspace suite at most once per commit, and never in a loop: a branch's commits are not re-tested one by one, and no two workspace runs share a machine at once, however many agents - are working. A review reads the diff; it builds and tests nothing and creates no worktree. + are working. A reviewer builds and tests nothing ([Review](#review)). + +## Review + +- **Review before a human is asked.** At the end of a branch or a wave, before a person is asked + to review or merge it, the change passes the agent review of `docs/contributing/review.md`: two + read-only reviewers in parallel, whose findings the author verifies and the person picks from. + Here it takes the place of the wave review the `yard` skill describes. +- **Reviews are read-only.** A reviewer reads and reports: it makes no edit, commit or push, runs + no build or test, no `loft fmt`, `loft publish` or `loft reconcile --accept`, writes nothing to + Yard Log and creates no worktree. Only the author, verifying a finding, writes and runs tests, + and only focused ones. `docs/contributing/review-checklist.md` is what any reviewer of a change + here checks, and how it reports. ## Releasing -A release happens only with the maintainer's approval, and in this order: - -0. Run `.github/workflows/build.yml` on `develop` ("Run workflow" on its page, or - `gh workflow run build.yml --ref develop`) and wait for every platform to build. Ordinary CI - builds only the host platform, so a change that breaks a cross-build, such as a dependency - with C code, shows here first. -1. On a branch from `develop`, set the new version in every crate's `Cargo.toml`, in the workspace - dependencies, in both plugin manifests and in `PLUGIN_VERSION` of the Claude Code plugin's - `hooks/adapter/index.tsx` (`tests/project/plugins/mod.rs` fails until they agree), and run - `scripts/changelog.sh X.Y.Z`, which writes the version's dated entry in `CHANGELOG.md` from the - change files under `changes/`, above the entries of that version's prereleases, which stay as - they are, and removes the files. Read the entry it wrote before you commit it. Merge the branch - into `develop`, then `develop` into `main`. -2. On `main`, run `loft publish` over the committed `spec/`, commit `spec/labels.yaml` and - `loft.lock.json` together as the publish commit, and check that `loft verify` passes. A second - `loft publish` with nothing changed writes nothing; CI checks both on `main` only, since - `develop` carries unpublished candidates. Push `main`. -3. On `main`, run `scripts/release-check.sh vX.Y.Z`; it checks `HEAD` while the tag does not - exist, and refuses it while `changes/` still holds a change file. Then tag `vX.Y.Z` on `main` - and push the tag. -4. The tag starts `.github/workflows/release.yml`. It runs the release check and the gate, builds - `loft` for each supported platform through `build.yml`, packs the npm packages into tarballs, - runs `loft` through the launcher from them (`scripts/npm-smoke.sh`) and checks them with a dry - run, then waits for the maintainer to approve: on the run's page, "Review deployments", tick - `release`, "Approve and deploy". Once approved, the publish job runs the tarballs it downloaded - once more, `scripts/publish-crates.sh` publishes the crates to crates.io in dependency order, - without building them again (the check job's dry run built each from its package on the same - commit), `scripts/publish-npm.sh` publishes the platform packages and then `@ask-loft/loft`, and - the tag gets a GitHub release with the binaries, whose notes are the version's changelog entry. - Both registries trust the workflow through Trusted Publishing; no registry token is stored - anywhere. -5. Merge `main` back into `develop`, so the allocated labels and the release reach it. - -When `develop` holds work that is not ready to go out, a release is cut from `main` instead: -branch from `main`, run step 0 on that branch (`gh workflow run build.yml --ref `), make -the version change of step 1 on it and merge it into `main` alone, then go on from step 2. Step 5 -brings the release into `develop` and removes there the change files the release gathered; those -of the work that was not ready stay under `changes/` for the next release. - -If a step of the publish job fails, fix its cause and choose "Re-run failed jobs" on the run. -Each step skips what its registry or GitHub already holds, so the run publishes only the rest. - -`software-plant` is never published (`publish = false`). CI on `main` runs -`cargo publish --workspace --dry-run`, so a crate that would not package fails before a release. - -### Prerelease from `develop` - -A prerelease, `vX.Y.Z-alpha.N`, `-beta.N` or `-rc.N`, lets people try what `develop` holds before -the release `X.Y.Z`. It too happens only with the maintainer's approval: - -1. Run step 0 on `develop`. -2. On a branch from `develop`, set the version `X.Y.Z-alpha.N` everywhere step 1 sets one, and - add by hand a dated entry `## X.Y.Z-alpha.N (YYYY-MM-DD)` above the newest entry in - `CHANGELOG.md`: one short paragraph that says how to install it and what it lets people try. - The change files stay under `changes/` for the release. Merge it into `develop` and push - `develop`. -3. On `develop`, run `scripts/release-check.sh vX.Y.Z-alpha.N`, then tag `vX.Y.Z-alpha.N` there - and push the tag. There is no `loft publish`: `develop`'s specification is published by the - release that follows, so the workflow skips `loft verify`. -4. Approve the run as in step 4. npm publishes the packages under the dist-tag `alpha` (`beta`, - `rc`), so `npm install @ask-loft/loft@alpha` installs it and `latest` stays the last release; - the GitHub release is marked a prerelease; crates.io serves it only to those who name it. - -### A minor line beside `develop` - -When the next minor version, `X.Y`, needs to be tried for longer while `develop` goes on -releasing the version before it, it lives on its own line, the branch `develop-X.Y`, cut from -`develop` (git refuses `develop/X.Y` beside `develop`). Feature branches for `X.Y` are cut from -the line and merge into it. - -- After each release or prerelease of `develop`, merge `develop` into the line, so the line holds - everything `develop` has released. A command's schema that `develop` moved to a new version - meanwhile and the line changed too takes the next version on the line, since `develop`'s is - released first. -- The line's change files lie under `changes/` as `develop`'s do. A merge carries them as - files in either direction, and a release gathers only the files its branch holds, so a release - of `develop` merged into the line removes only its own. -- A prerelease of the line follows the steps of a prerelease from `develop` on the line instead: - step 0 on the line (`gh workflow run build.yml --ref develop-X.Y`), the version - `X.Y.0-alpha.N` set and its dated entry added above the newest entry in `CHANGELOG.md`, then - `scripts/release-check.sh vX.Y.0-alpha.N` and the tag on the line. The release check accepts a - prerelease on the line of its own major and minor numbers, and npm publishes it under the - dist-tag `next`, so `npm install @ask-loft/loft@next` installs it while `alpha`, `beta` and - `rc` stay with `develop`'s prereleases. -- Once `X.Y` is ready, and `develop`'s last release before it is out, merge the line into - `develop` and delete the line; `X.Y.0` is then released from `develop` and `main` as any - release is. - -### Release setup - -Set up once, and kept as it is: - -- The GitHub environment `release` requires the maintainer's approval, and only tags matching - `v*` may deploy to it. -- On crates.io, each published crate names the trusted publisher `Ask-Loft/loft`, workflow - `release.yml`, environment `release`. -- On npmjs.com, each of `@ask-loft/loft` and its platform packages names the same trusted - publisher, with "Allow npm publish" ticked and "Allow npm dist-tag" left off. - -A registry names a trusted publisher only for a package that already exists, and npm requires -2FA for a publish with a token. So a new crate or npm package, such as one for a new platform, is -published by hand the first time, from what the release run built: - -- A crate: `cargo publish -p ` from a checkout of the tag, logged in with `cargo login`. -- An npm package: `gh run download -n release`, then - `scripts/publish-npm.sh release/npm` logged in with `npm login`; npm asks for 2FA for each - package it publishes and skips those it holds. - -Then register its trusted publisher as above, and choose "Re-run failed jobs" on the run, which -completes the release. +A release happens only with the maintainer's approval, in the order +`docs/contributing/releasing.md` gives: a release, a prerelease from `develop`, a minor line +beside `develop`, and the release setup kept once. ## Public hygiene diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fee42e31..925e6e6f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -112,6 +112,7 @@ cargo nextest run --workspace cargo run -q -p loft-cli -- fmt --check cargo run -q -p loft-cli -- check --fail-on warning cargo run -q -p loft-cli -- reconcile --fail-on warning +python3 -m unittest discover -s scripts/agent-review ``` Building needs Rust 1.97 or newer, `cargo install cargo-nextest --locked` provides the test @@ -121,11 +122,16 @@ On `main`, which carries only published states, CI also runs `loft verify`. Every commit stays green. Open pull requests against `develop`; `main` carries released, published states only. +Before a person is asked to review it, a change passes the agent review that +[`docs/contributing/review.md`](docs/contributing/review.md) describes, two read-only reviewers +run by `scripts/agent-review/review.py`, and the pull request template records the round. Where a +reviewer cannot run for you, say so in the template instead of leaving its row empty. + ## Releases Releases are cut by the maintainer: a tag `vX.Y.Z` on `main` runs the release workflow, which publishes the crates to crates.io and the prebuilt binaries to npm after the maintainer approves -it. `AGENTS.md` lists the steps. +it. `docs/contributing/releasing.md` lists the steps. ## Public by default diff --git a/changes/feat-review-tokens.md b/changes/feat-review-tokens.md new file mode 100644 index 00000000..7c9cc75d --- /dev/null +++ b/changes/feat-review-tokens.md @@ -0,0 +1,9 @@ +--- +kind: added +--- +`loft yard usage` records the tokens of a run that no Loft hook saw, such as a reviewer a script starts. + +It reads the run's host, session, task and requests as JSON, and counts each request toward the +stage of the task assigned to that session, through the page server while one runs or as it would +count them while none does. The run shows on the page as one turn of its session. Each request's +event id keeps a repeated record from counting twice. diff --git a/crates/loft-cli/src/machine/network.rs b/crates/loft-cli/src/machine/network.rs index 05afd223..7b3b57e3 100644 --- a/crates/loft-cli/src/machine/network.rs +++ b/crates/loft-cli/src/machine/network.rs @@ -57,17 +57,61 @@ pub fn post_json(url: &str, body: &[u8], left: Duration) -> Option { Some(response.status().as_u16()) } -/// An adapter's authenticated post to the local Yard page server, with no redirects or Origin. -pub fn post_local_json(port: u16, path: &str, token: &str, body: &[u8]) -> bool { +/// An adapter's authenticated post to the local Yard page server, with no redirects or Origin: +/// the body of its answer, read up to 1 MiB, or none where the post failed or its answer was no +/// success. +pub fn post_local_json(port: u16, path: &str, token: &str, body: &[u8]) -> Option> { + match deliver_local_json(port, path, token, body, LIMIT) { + Delivery::Answered(status, answer) if (200..300).contains(&status) => Some(answer), + _ => None, + } +} + +/// What became of a post to the local Yard page server. +pub enum Delivery { + /// The page server answered, with its status and its body, read up to 1 MiB. + Answered(u16, Vec), + /// The post never reached it: nothing listens on its port, or the post was not made. + Unreached, + /// The post may have reached it, but no answer came within the time: why. + Unanswered(String), +} + +/// [`post_local_json`] within `left`, saying whether a post that brought no answer may have +/// reached the page server, so that a caller posts again only what it never received. +pub fn deliver_local_json( + port: u16, + path: &str, + token: &str, + body: &[u8], + left: Duration, +) -> Delivery { if token.is_empty() || !matches!(path, "/api/events" | "/api/heard" | "/api/register") { - return false; + return Delivery::Unreached; } - agent(LIMIT, "loft-yard") + let sent = agent(left, "loft-yard") .post(format!("http://127.0.0.1:{port}{path}")) .header("Content-Type", "application/json") .header("Authorization", &format!("Bearer {token}")) - .send(body) - .is_ok_and(|response| response.status().is_success()) + .send(body); + let mut response = match sent { + Ok(response) => response, + Err(ureq::Error::ConnectionFailed) => return Delivery::Unreached, + Err(ureq::Error::Io(error)) if error.kind() == std::io::ErrorKind::ConnectionRefused => { + return Delivery::Unreached; + } + Err(error) => return Delivery::Unanswered(error.to_string()), + }; + let status = response.status().as_u16(); + match response + .body_mut() + .with_config() + .limit(1 << 20) + .read_to_vec() + { + Ok(answer) => Delivery::Answered(status, answer), + Err(error) => Delivery::Unanswered(error.to_string()), + } } /// `GET`s `url` within `left`, asking for GitHub's JSON, following no redirect, and gives the @@ -309,168 +353,4 @@ pub fn origin(url: &str) -> Option { } #[cfg(test)] -mod tests { - use super::{allowed, origin, origin_and_path, origin_path_and_query, same_origin}; - - #[test] - fn https_is_allowed_anywhere_and_http_only_on_the_loopback_interface() { - for url in [ - "https://askloft.ai/api/telemetry", - "https://api.github.com", - "http://127.0.0.1:9/api/telemetry", - "http://127.0.0.2:8080", - "http://localhost:3000/x", - "http://[::1]:8080/", - ] { - assert!(allowed(url).is_some(), "{url}"); - } - for url in [ - "http://askloft.ai/api/telemetry", - "http://10.0.0.5:8080", - "http://localhost.example.com/", - "http://[2001:db8::1]:80/", - "ftp://127.0.0.1/", - "127.0.0.1:9", - "http://127.0.0.1:9@askloft.ai/api/telemetry", - "http://localhost@10.0.0.5/", - ] { - assert!(allowed(url).is_none(), "{url}"); - } - } - - #[test] - fn addresses_with_one_scheme_host_and_effective_port_lie_on_one_origin() { - let address = "https://remote.example/documents/one"; - for other in [ - "https://remote.example/.well-known/oauth-protected-resource/documents", - "https://REMOTE.Example/x", - "HTTPS://remote.example/x", - "https://remote.example:443/x", - "https://someone@remote.example/x?y=z", - ] { - assert!(same_origin(address, other), "{other}"); - assert!(same_origin(other, address), "{other}"); - } - assert!(same_origin("http://127.0.0.1/a", "http://127.0.0.1:80/b")); - assert!(same_origin("http://[::1]:8080/a", "http://[::1]:8080/b")); - } - - #[test] - fn an_address_of_another_scheme_host_or_port_lies_on_another_origin() { - let address = "https://remote.example/documents/one"; - for other in [ - "http://remote.example/x", - "https://elsewhere.example/x", - "https://notes.remote.example/x", - "https://remote.example@elsewhere.example/x", - "https://remote.example:8443/x", - "https://remote.example./x", - // An address that is not an absolute `https` or `http` one lies on no origin. - "/.well-known/oauth-protected-resource/documents", - "ftp://remote.example/x", - "not an address", - ] { - assert!(!same_origin(address, other), "{other}"); - assert!(!same_origin(other, address), "{other}"); - } - for (one, other) in [ - ("http://127.0.0.1:8080/a", "http://127.0.0.1:8081/b"), - ("http://127.0.0.1:8080/a", "http://localhost:8080/b"), - // Two spellings of one IPv6 address are two hosts, as RFC 6454 compares them. - ("http://[::1]:8080/a", "http://[0:0:0:0:0:0:0:1]:8080/b"), - ] { - assert!(!same_origin(one, other), "{one} {other}"); - } - assert!(!same_origin("not an address", "not an address")); - } - - #[test] - fn an_address_is_read_as_its_origin_written_whole_and_its_path() { - for (url, written, path) in [ - ( - "HTTPS://Remote.Example:443/Documents/one?a=b#c", - "https://remote.example", - "/Documents/one", - ), - ( - "https://someone@remote.example:8443", - "https://remote.example:8443", - "/", - ), - ("http://[::1]:80/a/", "http://[::1]", "/a/"), - // An address of another scheme is read too, so that a caller can name its origin. - ("ftp://Files.Example/a", "ftp://files.example", "/a"), - ] { - let (origin, read) = origin_and_path(url).unwrap_or_else(|| panic!("{url}")); - assert_eq!( - (origin.to_string().as_str(), read.as_str()), - (written, path) - ); - } - for url in [ - "remote.example/a", - "/documents", - "https://", - "not an address", - "https://exa mple.org", - // A scheme begins with a letter (RFC 3986, section 3.1), and a host is not empty. - "://remote.example/a", - "1https://remote.example/a", - "https://:443/a", - ] { - assert!(origin_and_path(url).is_none(), "{url}"); - } - // Only an `https` or `http` address lies on an origin that is compared. - assert!(origin("ftp://files.example/a").is_none()); - } - - #[test] - fn an_address_is_read_as_its_origin_its_path_and_its_query() { - for (url, written, path, query) in [ - ( - "HTTPS://Remote.Example:443/mail/inbox?view=all#top", - "https://remote.example", - "/mail/inbox", - "?view=all", - ), - ( - "https://remote.example/notes/", - "https://remote.example", - "/notes/", - "", - ), - ( - "http://127.0.0.1:4000?view=all", - "http://127.0.0.1:4000", - "/", - "?view=all", - ), - ] { - let (origin, read, asked) = - origin_path_and_query(url).unwrap_or_else(|| panic!("{url}")); - assert_eq!( - (origin.to_string().as_str(), read.as_str(), asked.as_str()), - (written, path, query), - "{url}" - ); - } - for url in [ - "/notes?view=all", - "not an address", - "://remote.example/a?b=c", - ] { - assert!(origin_path_and_query(url).is_none(), "{url}"); - } - } - - #[test] - fn an_address_with_user_information_lies_on_the_origin_of_its_host_and_port() { - // The user information names one loopback port, and the host and port another. - let resource = "http://127.0.0.1:4000@127.0.0.1:5000/documents"; - assert!(origin(resource).is_some(), "{resource}"); - assert_eq!(origin(resource), origin("http://127.0.0.1:5000/")); - assert_ne!(origin(resource), origin("http://127.0.0.1:4000/")); - assert!(!same_origin(resource, "http://127.0.0.1:4000/documents/a")); - assert!(same_origin(resource, "http://127.0.0.1:5000/documents/a")); - } -} +mod tests; diff --git a/crates/loft-cli/src/machine/network/tests.rs b/crates/loft-cli/src/machine/network/tests.rs new file mode 100644 index 00000000..85ac8daa --- /dev/null +++ b/crates/loft-cli/src/machine/network/tests.rs @@ -0,0 +1,162 @@ +use super::{allowed, origin, origin_and_path, origin_path_and_query, same_origin}; + +#[test] +fn https_is_allowed_anywhere_and_http_only_on_the_loopback_interface() { + for url in [ + "https://askloft.ai/api/telemetry", + "https://api.github.com", + "http://127.0.0.1:9/api/telemetry", + "http://127.0.0.2:8080", + "http://localhost:3000/x", + "http://[::1]:8080/", + ] { + assert!(allowed(url).is_some(), "{url}"); + } + for url in [ + "http://askloft.ai/api/telemetry", + "http://10.0.0.5:8080", + "http://localhost.example.com/", + "http://[2001:db8::1]:80/", + "ftp://127.0.0.1/", + "127.0.0.1:9", + "http://127.0.0.1:9@askloft.ai/api/telemetry", + "http://localhost@10.0.0.5/", + ] { + assert!(allowed(url).is_none(), "{url}"); + } +} + +#[test] +fn addresses_with_one_scheme_host_and_effective_port_lie_on_one_origin() { + let address = "https://remote.example/documents/one"; + for other in [ + "https://remote.example/.well-known/oauth-protected-resource/documents", + "https://REMOTE.Example/x", + "HTTPS://remote.example/x", + "https://remote.example:443/x", + "https://someone@remote.example/x?y=z", + ] { + assert!(same_origin(address, other), "{other}"); + assert!(same_origin(other, address), "{other}"); + } + assert!(same_origin("http://127.0.0.1/a", "http://127.0.0.1:80/b")); + assert!(same_origin("http://[::1]:8080/a", "http://[::1]:8080/b")); +} + +#[test] +fn an_address_of_another_scheme_host_or_port_lies_on_another_origin() { + let address = "https://remote.example/documents/one"; + for other in [ + "http://remote.example/x", + "https://elsewhere.example/x", + "https://notes.remote.example/x", + "https://remote.example@elsewhere.example/x", + "https://remote.example:8443/x", + "https://remote.example./x", + // An address that is not an absolute `https` or `http` one lies on no origin. + "/.well-known/oauth-protected-resource/documents", + "ftp://remote.example/x", + "not an address", + ] { + assert!(!same_origin(address, other), "{other}"); + assert!(!same_origin(other, address), "{other}"); + } + for (one, other) in [ + ("http://127.0.0.1:8080/a", "http://127.0.0.1:8081/b"), + ("http://127.0.0.1:8080/a", "http://localhost:8080/b"), + // Two spellings of one IPv6 address are two hosts, as RFC 6454 compares them. + ("http://[::1]:8080/a", "http://[0:0:0:0:0:0:0:1]:8080/b"), + ] { + assert!(!same_origin(one, other), "{one} {other}"); + } + assert!(!same_origin("not an address", "not an address")); +} + +#[test] +fn an_address_is_read_as_its_origin_written_whole_and_its_path() { + for (url, written, path) in [ + ( + "HTTPS://Remote.Example:443/Documents/one?a=b#c", + "https://remote.example", + "/Documents/one", + ), + ( + "https://someone@remote.example:8443", + "https://remote.example:8443", + "/", + ), + ("http://[::1]:80/a/", "http://[::1]", "/a/"), + // An address of another scheme is read too, so that a caller can name its origin. + ("ftp://Files.Example/a", "ftp://files.example", "/a"), + ] { + let (origin, read) = origin_and_path(url).unwrap_or_else(|| panic!("{url}")); + assert_eq!( + (origin.to_string().as_str(), read.as_str()), + (written, path) + ); + } + for url in [ + "remote.example/a", + "/documents", + "https://", + "not an address", + "https://exa mple.org", + // A scheme begins with a letter (RFC 3986, section 3.1), and a host is not empty. + "://remote.example/a", + "1https://remote.example/a", + "https://:443/a", + ] { + assert!(origin_and_path(url).is_none(), "{url}"); + } + // Only an `https` or `http` address lies on an origin that is compared. + assert!(origin("ftp://files.example/a").is_none()); +} + +#[test] +fn an_address_is_read_as_its_origin_its_path_and_its_query() { + for (url, written, path, query) in [ + ( + "HTTPS://Remote.Example:443/mail/inbox?view=all#top", + "https://remote.example", + "/mail/inbox", + "?view=all", + ), + ( + "https://remote.example/notes/", + "https://remote.example", + "/notes/", + "", + ), + ( + "http://127.0.0.1:4000?view=all", + "http://127.0.0.1:4000", + "/", + "?view=all", + ), + ] { + let (origin, read, asked) = origin_path_and_query(url).unwrap_or_else(|| panic!("{url}")); + assert_eq!( + (origin.to_string().as_str(), read.as_str(), asked.as_str()), + (written, path, query), + "{url}" + ); + } + for url in [ + "/notes?view=all", + "not an address", + "://remote.example/a?b=c", + ] { + assert!(origin_path_and_query(url).is_none(), "{url}"); + } +} + +#[test] +fn an_address_with_user_information_lies_on_the_origin_of_its_host_and_port() { + // The user information names one loopback port, and the host and port another. + let resource = "http://127.0.0.1:4000@127.0.0.1:5000/documents"; + assert!(origin(resource).is_some(), "{resource}"); + assert_eq!(origin(resource), origin("http://127.0.0.1:5000/")); + assert_ne!(origin(resource), origin("http://127.0.0.1:4000/")); + assert!(!same_origin(resource, "http://127.0.0.1:4000/documents/a")); + assert!(same_origin(resource, "http://127.0.0.1:5000/documents/a")); +} diff --git a/crates/loft-cli/src/yard/args.rs b/crates/loft-cli/src/yard/args.rs index 2101e403..bbe0df11 100644 --- a/crates/loft-cli/src/yard/args.rs +++ b/crates/loft-cli/src/yard/args.rs @@ -287,6 +287,21 @@ pub struct UpgradeArgs { pub output: Output, } +#[derive(Args)] +pub struct UsageArgs { + /// The file that holds the outside run and its requests as JSON, or `-` for standard input. + #[arg(long, value_name = "FILE")] + pub input: PathBuf, + /// A directory of the worktree whose Yard Log holds the run's task, in place of the + /// command's own directory. + #[arg(long, value_name = "DIR")] + pub tree: Option, + #[command(flatten)] + pub beyond: Beyond, + #[command(flatten)] + pub output: Output, +} + #[derive(Args)] pub struct ContinueArgs { /// The agent host; omitted by legacy Claude callers. diff --git a/crates/loft-cli/src/yard/failure.rs b/crates/loft-cli/src/yard/failure.rs index cd9547e2..8f9e7acb 100644 --- a/crates/loft-cli/src/yard/failure.rs +++ b/crates/loft-cli/src/yard/failure.rs @@ -24,6 +24,13 @@ pub enum Failure { Stopped(Stop), /// A refusal by Yard Log's rules: the result's fields, and the errors that say why. Refused { fields: Value, errors: Vec }, + /// A result reached only in part: its outcome and fields, and the errors that say what was + /// left undone. It exits 1, as a refusal does. + Partial { + outcome: &'static str, + fields: Value, + errors: Vec, + }, } impl Failure { @@ -49,7 +56,12 @@ impl Failure { Finished::usage() } Self::Stopped(stop) => stop.exit(schema, as_json), - Self::Refused { fields, errors } => refuse(schema, fields, errors, as_json), + Self::Refused { fields, errors } => refuse(schema, "refused", fields, errors, as_json), + Self::Partial { + outcome, + fields, + errors, + } => refuse(schema, outcome, fields, errors, as_json), } } } @@ -75,19 +87,26 @@ pub fn end( } } -/// Prints a refusal's result, or its reasons for a person, and exits 1. -fn refuse(schema: &str, fields: Value, errors: Vec, as_json: bool) -> Finished { - let finished = Finished::with(ExitCode::FAILURE, "refused", &errors); +/// Prints the result of a refusal, or of a result reached in part, with its `outcome`, or its +/// reasons for a person, and exits 1. +fn refuse( + schema: &str, + outcome: &'static str, + fields: Value, + errors: Vec, + as_json: bool, +) -> Finished { + let finished = Finished::with(ExitCode::FAILURE, outcome, &errors); let lines: Vec = errors .iter() .filter_map(|error| error["message"].as_str()) .map(ToOwned::to_owned) .collect(); if as_json { - json::print(&json::result(schema, "refused", fields, errors)); + json::print(&json::result(schema, outcome, fields, errors)); } else { for line in &lines { - outln!("refused: {line}"); + outln!("{outcome}: {line}"); } } for line in lines { diff --git a/crates/loft-cli/src/yard/hosts/codex/mod.rs b/crates/loft-cli/src/yard/hosts/codex/mod.rs index 8c883ed3..3ddcbb93 100644 --- a/crates/loft-cli/src/yard/hosts/codex/mod.rs +++ b/crates/loft-cli/src/yard/hosts/codex/mod.rs @@ -136,7 +136,9 @@ pub(super) fn message(error: Failure) -> String { match error { Failure::Usage(message) => message, Failure::Stopped(stop) => stop.lines.join("; "), - Failure::Refused { errors, .. } => json!(errors).to_string(), + Failure::Refused { errors, .. } | Failure::Partial { errors, .. } => { + json!(errors).to_string() + } } } diff --git a/crates/loft-cli/src/yard/mod.rs b/crates/loft-cli/src/yard/mod.rs index f23e52b7..bb5b8313 100644 --- a/crates/loft-cli/src/yard/mod.rs +++ b/crates/loft-cli/src/yard/mod.rs @@ -58,6 +58,9 @@ pub enum YardAction { /// Change fields of a task as Yard Log holds it, or with `--release` return the calling /// agent's active tasks to `open`. Task(args::TaskArgs), + /// Record the tokens of a run no Loft hook saw, read as JSON from `--input`, toward the stage + /// of the task it is recorded by. + Usage(args::UsageArgs), /// Wait until a submission is answered or withdrawn, or Yard Log is closed, for at most /// `--timeout` seconds. Wait(args::WaitArgs), @@ -97,6 +100,7 @@ pub fn run(root: &Path, action: YardAction) -> Finished { YardAction::Write(args) => write::run(root, args), YardAction::Withdraw(args) => withdraw::run(root, args), YardAction::Task(args) => task::run(root, args), + YardAction::Usage(args) => serve::usage::run(root, &args), YardAction::Wait(args) => wait::run(root, args), YardAction::Close(args) => close::run(root, args), YardAction::Published(args) => published::run(root, args), diff --git a/crates/loft-cli/src/yard/page/post.rs b/crates/loft-cli/src/yard/page/post.rs index d2340977..92b63c9c 100644 --- a/crates/loft-cli/src/yard/page/post.rs +++ b/crates/loft-cli/src/yard/page/post.rs @@ -2,16 +2,37 @@ //! token of `~/.yard/token` and no `Origin`, through the network client, which reaches the //! loopback interface alone. A post that finds no token or no answer is lost, and says so. +use std::time::Duration; + use serde_json::Value; + +pub use crate::machine::network::Delivery; use yardlog_store::home::{Home, HomeFile}; /// Posts `body` to `path` of the page server on `port`; whether it accepted it. pub fn post(home: &Home, port: u16, path: &str, body: &Value) -> bool { + reply(home, port, path, body).is_some() +} + +/// Posts `body` as [`post`] does, waiting up to `left` for the answer, and says what became of +/// the post; one made with no control token never reached the page server. +pub fn deliver(home: &Home, port: u16, path: &str, body: &Value, left: Duration) -> Delivery { + let Ok(Some(token)) = home.read(HomeFile::Token) else { + return Delivery::Unreached; + }; + let token = String::from_utf8_lossy(&token); + let body = body.to_string(); + crate::machine::network::deliver_local_json(port, path, token.trim(), body.as_bytes(), left) +} + +/// The body of the page server's answer to `body`, where it accepted it. +fn reply(home: &Home, port: u16, path: &str, body: &Value) -> Option> { let Ok(Some(token)) = home.read(HomeFile::Token) else { - return false; + return None; }; let token = String::from_utf8_lossy(&token); - crate::machine::network::post_local_json(port, path, token.trim(), body.to_string().as_bytes()) + let body = body.to_string(); + crate::machine::network::post_local_json(port, path, token.trim(), body.as_bytes()) } /// Posts `body`, one event or a batch of them, to the page server `~/.yard/server.json` names diff --git a/crates/loft-cli/src/yard/serve/events/arrival.rs b/crates/loft-cli/src/yard/serve/events/arrival.rs new file mode 100644 index 00000000..4a92965f --- /dev/null +++ b/crates/loft-cli/src/yard/serve/events/arrival.rs @@ -0,0 +1,154 @@ +//! Where each event of a batch is kept: its agent's working tree, that tree's open Yard Log, the +//! stage the event counts toward and the submissions open as it arrives, each worked out once +//! for the batch. + +use std::collections::HashMap; +use std::path::Path; + +use serde_json::Value; +use yardlog::{YardLog, query, stages}; +use yardlog_store::git::YardGit; +use yardlog_store::home::Home; +use yardlog_store::{Held, Place, YardStore}; + +use crate::yard::session::event::{Event, Who, agent_of}; +use crate::yard::working_tree; + +/// Where an event is kept: its agent's tree and branch, the stage it counts toward and the +/// submissions open as it arrives. +pub(super) struct Arrival { + pub(super) store: YardStore, + pub(super) stage: Option, + pub(super) open: Vec, +} + +/// What the stage an event counts toward depends on: its directory's Yard Log, its agent, +/// whether a subagent's run starts, and the task it names, if any, where that is text. A batch +/// works out each one's stage once. +#[derive(PartialEq, Eq, Hash)] +struct StageQuery<'a> { + dir: &'a str, + host: &'a str, + session: &'a str, + who: &'a Who, + starting: bool, + task: Named<'a>, +} + +/// The task an event names. +#[derive(PartialEq, Eq, Hash)] +enum Named<'a> { + None, + Task(&'a str), + /// A `task` that is not text, which names no block. + Unusable, +} + +impl<'a> StageQuery<'a> { + /// The query of `event`, whose agent's working tree is the directory `dir`. + fn of(event: &'a Event, dir: &'a str) -> Self { + Self { + dir, + host: &event.host, + session: &event.session, + who: &event.who, + starting: matches!(event.who, Who::Sub { .. }) && event.kind == "subagent.start", + task: match event.posted.get("task").map(Value::as_str) { + None => Named::None, + Some(Some(id)) => Named::Task(id), + Some(None) => Named::Unusable, + }, + } + } + + /// The stage counted, by its key: the agent's working stage, or, as a subagent's run + /// starts, the stage that run starts in. A posted task that is not text counts toward none. + fn stage(&self, log: &YardLog) -> Option { + let agent = agent_of(self.host, self.session, self.who); + let task = match self.task { + Named::None => None, + Named::Task(id) => Some(id), + Named::Unusable => return None, + }; + let stage = if self.starting { + stages::starting_stage(log, &agent, task) + } else { + stages::working_stage(log, &agent, task) + }; + stage.map(|stage| stage.to_string()) + } +} + +/// The store and open Yard Log of the branch the directory `dir` is on, where it has one. +pub(super) fn open_at(dir: &str) -> Option<(YardStore, YardLog)> { + let place = Place::locate(&YardGit::default(), Path::new(dir)).ok()?; + place.branch.as_ref()?; + let store = YardStore::new(place).ok()?; + let Ok(Held::Log(log)) = store.read() else { + return None; + }; + (!log.is_closed()).then_some((store, *log)) +} + +/// The directory of the working tree of `event`'s agent: the worktree its session wrote in +/// whose Yard Log holds its working stage, else the directory the event names. +pub(super) fn working_dir(home: &Home, event: &Event) -> String { + let agent = event.agent(); + let dir = Path::new(&event.dir); + working_tree::resolve(Some(home), &agent, dir) + .map_or_else(|_| event.dir.clone(), |tree| tree.display().to_string()) +} + +/// A tree's Yard Log, with its open submissions, as a batch opens it. +type Opened = Option<(YardStore, YardLog, Vec)>; + +/// Where each of `events` is kept, where its agent's working tree has its Yard Log open: +/// `working` finds that tree once for each agent and directory the batch names, and `open` +/// finds and reads its Yard Log once for each tree, however many events name it. +pub(super) fn arrivals( + events: &[Event], + mut working: impl FnMut(&Event) -> String, + mut open: impl FnMut(&str) -> Option<(YardStore, YardLog)>, +) -> Vec> { + let mut trees: HashMap<(&str, &str, &str, &Who), String> = HashMap::new(); + let dirs: Vec = events + .iter() + .map(|event| { + let agent = ( + event.dir.as_str(), + event.host.as_str(), + event.session.as_str(), + &event.who, + ); + trees.entry(agent).or_insert_with(|| working(event)).clone() + }) + .collect(); + // Each tree's Yard Log, with its open submissions, worked out once for the batch. + let mut opened: HashMap<&str, Opened> = HashMap::new(); + let mut stages: HashMap> = HashMap::new(); + events + .iter() + .zip(&dirs) + .map(|(event, dir)| { + let (store, log, submissions) = opened + .entry(dir.as_str()) + .or_insert_with(|| { + let (store, log) = open(dir)?; + let submissions = query::open_submissions(&log) + .iter() + .map(ToString::to_string) + .collect(); + Some((store, log, submissions)) + }) + .as_ref()?; + let stage = stages + .entry(StageQuery::of(event, dir)) + .or_insert_with_key(|query| query.stage(log)); + Some(Arrival { + stage: stage.clone(), + open: submissions.clone(), + store: store.clone(), + }) + }) + .collect() +} diff --git a/crates/loft-cli/src/yard/serve/events/mod.rs b/crates/loft-cli/src/yard/serve/events/mod.rs index da0ba51a..56dba600 100644 --- a/crates/loft-cli/src/yard/serve/events/mod.rs +++ b/crates/loft-cli/src/yard/serve/events/mod.rs @@ -12,30 +12,29 @@ //! such a request, which the log never held. pub mod activity; +mod arrival; pub mod consulted; pub mod newest; use std::collections::{BTreeMap, HashMap}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::Mutex; use serde_json::{Value, json}; use yardlog::session::adapter::Descriptor; -use yardlog::{YardLog, query, stages}; -use yardlog_store::git::YardGit; +use yardlog_store::YardStore; use yardlog_store::home::Home; use yardlog_store::session::SessionFile; -use yardlog_store::{Held, Place, YardStore}; use yardlog::session::consult::{Consultation, Live}; use yardlog::session::totals::Totals; use super::http::Response; -use crate::yard::session::event::{Event, Who, agent_of}; +use crate::yard::session::event::Event; use crate::yard::session::event_ids::Receipts; use crate::yard::session::{session_files, totals}; -use crate::yard::working_tree; use activity::Activity; +use arrival::{Arrival, arrivals, open_at, working_dir}; use newest::Newest; /// What one session keeps in one branch's Yard Log. @@ -78,145 +77,6 @@ pub struct Sessions { written: Newest, } -/// Where an event is kept: its agent's tree and branch, the stage it counts toward and the -/// submissions open as it arrives. -struct Arrival { - store: YardStore, - stage: Option, - open: Vec, -} - -/// What the stage an event counts toward depends on: its directory's Yard Log, its agent, -/// whether a subagent's run starts, and the task it names, if any, where that is text. A batch -/// works out each one's stage once. -#[derive(PartialEq, Eq, Hash)] -struct StageQuery<'a> { - dir: &'a str, - host: &'a str, - session: &'a str, - who: &'a Who, - starting: bool, - task: Named<'a>, -} - -/// The task an event names. -#[derive(PartialEq, Eq, Hash)] -enum Named<'a> { - None, - Task(&'a str), - /// A `task` that is not text, which names no block. - Unusable, -} - -impl<'a> StageQuery<'a> { - /// The query of `event`, whose agent's working tree is the directory `dir`. - fn of(event: &'a Event, dir: &'a str) -> Self { - Self { - dir, - host: &event.host, - session: &event.session, - who: &event.who, - starting: matches!(event.who, Who::Sub { .. }) && event.kind == "subagent.start", - task: match event.posted.get("task").map(Value::as_str) { - None => Named::None, - Some(Some(id)) => Named::Task(id), - Some(None) => Named::Unusable, - }, - } - } - - /// The stage counted, by its key: the agent's working stage, or, as a subagent's run - /// starts, the stage that run starts in. A posted task that is not text counts toward none. - fn stage(&self, log: &YardLog) -> Option { - let agent = agent_of(self.host, self.session, self.who); - let task = match self.task { - Named::None => None, - Named::Task(id) => Some(id), - Named::Unusable => return None, - }; - let stage = if self.starting { - stages::starting_stage(log, &agent, task) - } else { - stages::working_stage(log, &agent, task) - }; - stage.map(|stage| stage.to_string()) - } -} - -/// The store and open Yard Log of the branch the directory `dir` is on, where it has one. -fn open_at(dir: &str) -> Option<(YardStore, YardLog)> { - let place = Place::locate(&YardGit::default(), Path::new(dir)).ok()?; - place.branch.as_ref()?; - let store = YardStore::new(place).ok()?; - let Ok(Held::Log(log)) = store.read() else { - return None; - }; - (!log.is_closed()).then_some((store, *log)) -} - -/// The directory of the working tree of `event`'s agent: the worktree its session wrote in -/// whose Yard Log holds its working stage, else the directory the event names. -fn working_dir(home: &Home, event: &Event) -> String { - let agent = event.agent(); - let dir = Path::new(&event.dir); - working_tree::resolve(Some(home), &agent, dir) - .map_or_else(|_| event.dir.clone(), |tree| tree.display().to_string()) -} - -/// A tree's Yard Log, with its open submissions, as a batch opens it. -type Opened = Option<(YardStore, YardLog, Vec)>; - -/// Where each of `events` is kept, where its agent's working tree has its Yard Log open: -/// `working` finds that tree once for each agent and directory the batch names, and `open` -/// finds and reads its Yard Log once for each tree, however many events name it. -fn arrivals( - events: &[Event], - mut working: impl FnMut(&Event) -> String, - mut open: impl FnMut(&str) -> Option<(YardStore, YardLog)>, -) -> Vec> { - let mut trees: HashMap<(&str, &str, &str, &Who), String> = HashMap::new(); - let dirs: Vec = events - .iter() - .map(|event| { - let agent = ( - event.dir.as_str(), - event.host.as_str(), - event.session.as_str(), - &event.who, - ); - trees.entry(agent).or_insert_with(|| working(event)).clone() - }) - .collect(); - // Each tree's Yard Log, with its open submissions, worked out once for the batch. - let mut opened: HashMap<&str, Opened> = HashMap::new(); - let mut stages: HashMap> = HashMap::new(); - events - .iter() - .zip(&dirs) - .map(|(event, dir)| { - let (store, log, submissions) = opened - .entry(dir.as_str()) - .or_insert_with(|| { - let (store, log) = open(dir)?; - let submissions = query::open_submissions(&log) - .iter() - .map(ToString::to_string) - .collect(); - Some((store, log, submissions)) - }) - .as_ref()?; - let stage = stages - .entry(StageQuery::of(event, dir)) - .or_insert_with_key(|query| query.stage(log)); - Some(Arrival { - stage: stage.clone(), - open: submissions.clone(), - store: store.clone(), - }) - }) - .collect() -} - impl Kept { /// Keeps what `event` adds, under its session's last descriptor `adapter` and with its /// session's estimate state `live`; gives the files whose text changed. Their text is left to @@ -310,11 +170,18 @@ impl Sessions { } } - /// Records `posted`, events in the order they happened. + /// Records `posted`, events in the order they happened. The answer gives how many it + /// recorded and skipped, the index of each it rejected and why, the index of each it had + /// recorded before, by its event id, which it counts as recorded and keeps once, the index + /// of each recorded event whose session file it could not write, and why, and the stage each + /// recorded event counted toward, by its key, or none. pub fn record_events(&self, home: &Home, posted: &[Value]) -> Response { let mut recorded = 0; let mut skipped = 0; let mut rejected = Vec::new(); + let mut repeated = Vec::new(); + let mut unwritten = Vec::new(); + let mut stages = Vec::new(); let mut read = Vec::new(); for (index, posted) in posted.iter().enumerate() { match Event::read(posted) { @@ -341,8 +208,14 @@ impl Sessions { continue; }; match keep(home, &mut kept, event, &arrival) { - Ok(files) => { + Ok(Keeping { + before, + stage, + files, + }) => { recorded += 1; + repeated.extend(before.then_some(index)); + stages.push(json!({ "index": index, "stage": stage })); let generation = self.written.generation(); note(&mut changed, (index, generation), event, &arrival, files); } @@ -359,13 +232,21 @@ impl Sessions { let wrote = self.written.write(&path, generation, || { store.write_session(file, &session, text.as_bytes()) }); + // The event is kept in its log all the same, and counts when the file is next written. if let Err(error) = wrote { - rejected.push(json!({ "index": index, "message": error.to_string() })); + unwritten.push(json!({ "index": index, "message": error.to_string() })); } } Response::json( 200, - &json!({ "recorded": recorded, "skipped": skipped, "rejected": rejected }), + &json!({ + "recorded": recorded, + "skipped": skipped, + "rejected": rejected, + "repeated": repeated, + "unwritten": unwritten, + "stages": stages, + }), ) } } @@ -409,14 +290,22 @@ fn skip(kept: &mut HashMap, event: &Event) { /// event log the next time it is heard of. const SESSIONS_KEPT: usize = 256; -/// Appends `event` to its session's log and keeps what it adds; gives the session's files of its -/// Yard Log's folder whose text changed. +/// What keeping an event did: whether its event id was recorded before, the stage it counted +/// toward, by its key, then or now, and the session's files of its Yard Log's folder whose text +/// changed. +struct Keeping { + before: bool, + stage: Option, + files: Vec<(SessionFile, String)>, +} + +/// Appends `event` to its session's log and keeps what it adds. fn keep( home: &Home, kept: &mut HashMap, event: &Event, arrival: &Arrival, -) -> Result, String> { +) -> Result { let tree = arrival.store.tree().display().to_string(); let branch = arrival.store.branch().to_owned(); if !kept.contains_key(&event.session_key()) && kept.len() >= SESSIONS_KEPT { @@ -428,10 +317,16 @@ fn keep( .or_insert_with(|| replay(home, &event.session_key())); let place_key = (tree.clone(), branch.clone()); if session.receipts.contains(event.receipt.as_ref())? { - return Ok(session + let files = session .logs .get(&place_key) - .map_or_else(Vec::new, |kept| kept.texts(SessionFile::ALL))); + .map_or_else(Vec::new, |kept| kept.texts(SessionFile::ALL)); + let stage = session.receipts.stage(event.receipt.as_ref()); + return Ok(Keeping { + before: true, + stage: stage.map(ToOwned::to_owned), + files, + }); } let mut line = event.posted.clone(); if let Some(receipt) = &event.receipt { @@ -444,7 +339,9 @@ fn keep( let text = serde_json::to_vec(&line).map_err(|error| error.to_string())?; home.append_event(&event.session_key(), &text) .map_err(|error| error.to_string())?; - session.receipts.keep(event.receipt.as_ref()); + session + .receipts + .keep(event.receipt.as_ref(), arrival.stage.as_deref()); session.describe(event); let kept = session.logs.entry(place_key).or_default(); let changed = kept.apply( @@ -453,7 +350,11 @@ fn keep( session.adapter.as_ref(), &mut session.live, ); - Ok(kept.texts(changed)) + Ok(Keeping { + before: false, + stage: arrival.stage.clone(), + files: kept.texts(changed), + }) } mod hints; diff --git a/crates/loft-cli/src/yard/serve/logs/mod.rs b/crates/loft-cli/src/yard/serve/logs/mod.rs index a853cd45..0df6b1ca 100644 --- a/crates/loft-cli/src/yard/serve/logs/mod.rs +++ b/crates/loft-cli/src/yard/serve/logs/mod.rs @@ -61,6 +61,11 @@ fn answer_failure(failure: Failure, schema: &str) -> Response { Failure::Refused { fields, errors } => { Response::json(409, &json::result(schema, "refused", fields, errors)) } + Failure::Partial { + outcome, + fields, + errors, + } => Response::json(409, &json::result(schema, outcome, fields, errors)), } } diff --git a/crates/loft-cli/src/yard/serve/mod.rs b/crates/loft-cli/src/yard/serve/mod.rs index d746e0d3..704ff731 100644 --- a/crates/loft-cli/src/yard/serve/mod.rs +++ b/crates/loft-cli/src/yard/serve/mod.rs @@ -21,6 +21,7 @@ mod logs; mod routes; mod stream; pub(super) mod trees; +pub(super) mod usage; mod watch; use std::cmp::Ordering as Compared; @@ -155,6 +156,15 @@ pub struct ServeArgs { pub output: Output, } +/// Records `events` as the page server records a post of them, by a process that holds the page +/// server's lock, so that none runs meanwhile: each appended to its session's event log, with +/// the session's files rebuilt from that log. Gives what the page server would answer: how many +/// it recorded and skipped, and which it rejected. +fn record_held(home: &Home, events: &[Value]) -> Value { + let answer = events::Sessions::default().record_events(home, events); + serde_json::from_slice(&answer.body).unwrap_or(Value::Null) +} + pub fn run(args: &ServeArgs) -> Finished { let as_json = args.output.json(); match start(args) { diff --git a/crates/loft-cli/src/yard/serve/trees/mod.rs b/crates/loft-cli/src/yard/serve/trees/mod.rs index 29d689a5..2df926f9 100644 --- a/crates/loft-cli/src/yard/serve/trees/mod.rs +++ b/crates/loft-cli/src/yard/serve/trees/mod.rs @@ -353,7 +353,7 @@ fn asking(block: &Block) -> Value { pub fn failure_value(failure: Failure) -> Value { match failure { Failure::Stopped(stop) => json!(stop.errors), - Failure::Refused { errors, .. } => json!(errors), + Failure::Refused { errors, .. } | Failure::Partial { errors, .. } => json!(errors), Failure::Usage(message) => json!([crate::json::error("usage", &message, &[])]), } } diff --git a/crates/loft-cli/src/yard/serve/usage/document.rs b/crates/loft-cli/src/yard/serve/usage/document.rs new file mode 100644 index 00000000..8c12cc12 --- /dev/null +++ b/crates/loft-cli/src/yard/serve/usage/document.rs @@ -0,0 +1,171 @@ +//! The document `loft yard usage` reads: the run's host, session and task, its start and end +//! where it names them, and its requests, each with its event id, model, time and counts. A +//! field it does not define is refused, so that a misspelled one is never read as absent. + +use std::collections::BTreeSet; + +use serde_json::{Map, Value}; +use yardlog::session::usage::COUNTERS; +use yardlog::{Handle, Time}; + +use crate::yard::failure; +use crate::yard::session::event; + +/// The fields of the document, and of each of its requests. +const RUN_FIELDS: [&str; 6] = ["host", "session", "task", "started", "ended", "requests"]; +const REQUEST_FIELDS: [&str; 4] = ["eventId", "model", "at", "tokens"]; + +/// An outside run, as the document names it. +pub struct Run { + pub host: String, + pub session: String, + pub task: Handle, + pub started: Option