Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/code-navigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ Start with the issue's terms in `GLOSSARY.md`, then use this index to find their
| Session trace calls | `src/session/trace/calls.rs` — `Calls`: the one call lifecycle shared by recording and the Waterfall, with causal keys, span identities, retained identity overrides (`Retained`), parent recovery, first observation, completion, late amendments and closure | `src/session/trace/calls/tests.rs` |
| Session usage | `src/session/usage.rs` — normalized-event and buffered retained-span adapters, one owned summary, partial-total precedence, inclusive cache normalization and addition across Sessions; `src/logs/session_signals.rs` and `src/evals/experiment/usage.rs` — Run metrics and Arm projections | `src/session/usage/tests.rs`, `tests/metrics.rs`, `tests/run_metrics.rs`, `tests/experiments.rs`, `src/evals/experiment/reading/tests.rs` |
| Plan usage observation (subscription Harnesses) | `src/plan_usage/observation.rs` — `SUBSCRIPTION` (the subscription Harnesses Plan usage watches), `claude_rate_limit`, `claude_api_error`, `codex_token_count`, `terminal_failure`; `src/harness/interpretation/stream.rs` (Claude and Grok wire frames) and `src/harness/codex/stream.rs`, `src/harness/muse/stream.rs`, `src/harness/agy/stream.rs` — passive capture as `Evidence::PlanUsage`, saved by `src/session/recording.rs` through `plan_usage::record`; `src/plan_usage/read.rs` — official non-billed reads (`READABLE`, `WINDOWED`, `Probe::read`: `codex app-server`, `muse serve`, `claude auth status --json` and `src/plan_usage/read/slash.rs` for Claude and Agy `/usage`); `src/plan_usage/model_scope.rs` — matches Plan windows to the resolved Model; `src/plan_usage.rs` — `refresh` and `FRESH` (viewing) and `refresh_for_routing` with `router::FRESH_MINUTES`; `src/plan_usage/store.rs` — `~/.thirdshift/plan-usage.json`, `State::exhaust` cooldowns and the revalidation backoff (`FIRST_BACKOFF_MINUTES`, `LAST_BACKOFF_MINUTES`), `Store::clear` | Inline tests; `tests/plan_usage.rs`, `src/harness/interpretation_tests.rs` |
| One-shot Plan usage reads | `src/plan_usage/read.rs` and `src/plan_usage/read/slash.rs` — prepare Claude and Agy `/usage`, Claude `auth status --json` and Codex `login status` and interpret the results; `src/process.rs` — `one_shot` owns spawn, the deadline, stdout collection and interruption; `src/process/tree.rs` — whole-tree cleanup; `src/plan_usage/read.rs` — Codex and Muse JSON-RPC reply collection | `src/process/tests.rs`, `tests/plan_usage.rs` |
| One-shot Plan usage reads | `src/plan_usage/read.rs` and `src/plan_usage/read/slash.rs` — prepare Claude and Agy `/usage`, Claude `auth status --json` and Codex `login status` and interpret the results; `src/process.rs` — `one_shot` owns spawn, the deadline, stdout collection and interruption; `src/process/tree.rs` — whole-tree cleanup | `src/process/tests.rs`, `tests/plan_usage.rs` |
| Reply-driven Plan usage reads | `src/plan_usage/read.rs` — Codex and Muse JSON-RPC framing, reply collection and interpretation; `src/process.rs` — `exchange` owns spawn, the deadline, interruption and reply-driven completion; `src/process/pipe.rs` — cancellable stdin and stdout; `src/process/tree.rs` — whole-tree cleanup | `src/process/tests.rs`, `tests/plan_usage.rs` |
| Route selection, `[harness] routes`, `max_utilization`, `allow_credits`, `[security] routes` | `src/plan_usage/route.rs` — `Route`, `Routing` (`first`, `ceiling`, `allows_credits`), `parse_routes`, `percentage`; `src/config.rs` — `UserConfig::routing` and the `DEFAULTS` lines Setup and `thirdshift config` inventory; `src/asks.rs` — `Flags::harness` and `security_harness` (a command naming no Harness, Model or Effort takes the first route, `ChosenBy::Routes`); `src/plan_usage/router.rs` — `Router::of` (ordinary and Security candidates, pinning), `harnesses` (every route's Factory skills), `pick` and `select` (proactive), `Router::exhaustion`; `src/plan_usage/view.rs` — `Availability`; `src/plan_usage.rs` — `credits_allowed`; `src/harness/agy.rs` — `NO_CREDITS` (`--settings '{"useG1Credits":false}'`); `src/session.rs` — `Sessions::run_step` and `take_route` (reactive reroute), `OnMachine::worktree_at_start` and `reset` (mid-Step clean reset and conflict re-merge); `src/implement.rs` — `continue_with` (Continuation prompt after commits or an open PR); `src/harness/interpretation.rs` — `SessionFailure::plan_usage_exhausted` | Inline tests in `src/plan_usage/route.rs`, `src/plan_usage/router.rs` and `src/session.rs`; `src/asks.rs` (first route); `tests/plan_usage_routing.rs` |
| Plan-usage Paused Command, Pass skip | `src/session.rs` — `pause_if_exhausted` (no route before a Step) and `paused_at_a_limit` (no route after a stop); `src/session/limits.rs` — `PlanUsagePaused`, `NO_ROUTE`, `plan_usage_paused`; `src/plan_usage/exhaustion.rs` — `Exhaustion`, `judge`; `src/run_ending.rs` — `PAUSED_EXIT`; `src/run.rs` — the resume command via `logs::resumable`; `src/child_run.rs` — `Ended::Paused` from a child's exit code; `src/spec_run/ticket_board.rs` and `src/spec_run.rs` — a paused Ticket stops queued Tickets; `src/claim.rs` — `Ending::Paused`, `release_paused` (no `agent-failed`, `ready-for-agent` back, untrusted-edit `needs-triage`); `src/logs.rs` — `paused`, `handed_back_for_pickup`; `src/logs/command_record.rs` — `handed_back_for_pickup`; `src/logs/reading/inbox.rs` — `NeedsYouKind::Paused`, Done when retaken; `src/notification.rs` — saved, not emailed, under `email.unless_merged` when retaken; `src/command_limit.rs` — `Why::PlanUsage` Pass skip; `src/plan_usage.rs` — `pass_exhaustion`, `machine_exhaustion`, `banner` (shown by `src/logs/status.rs` and the Inbox) | Inline Claim tests; `tests/plan_usage_pause.rs`, `tests/console/inbox.rs`, `tests/run_notification.rs`, `tests/pickup_run.rs` |
| Session trace recording and Trace ancestry | `src/session/trace.rs` — recording adapter: streaming records, flushing first completions, closing unfinished calls and rewriting one final span per ID; `src/logs/trace.rs` — deterministic Command, Ticket run and stage identities; `src/logs/trace/ancestry.rs` — `of`: the one record-derived ancestry and Session attachment for a selected record subtree under its owning Command, shared by the Waterfall and whole Trace export (dispatch-parent stage, descendant-first Session claims, first naming stage, Run fallback) | `tests/session_traces.rs`, `src/session/trace/tests.rs`, `src/session/recording/tests.rs`, `src/logs/recording/tests.rs`, `src/logs/trace/ancestry/tests.rs` |
Expand Down
69 changes: 27 additions & 42 deletions src/plan_usage/read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::sync::mpsc;
use std::process::Command;
use std::time::{Duration, Instant};

use anyhow::{Context, Result, bail};
Expand All @@ -18,7 +17,7 @@ use serde_json::{Value, json};
use super::observation::{Exhausted, Window, from_percent, milliseconds, seconds, token};
use super::store::{Credits, ExecutableStamp, State};
use crate::harness::Harness;
use crate::{interrupt, process};
use crate::process;

mod slash;

Expand Down Expand Up @@ -441,57 +440,43 @@ fn rpc(
requests: &[Value],
wanted: &[i64],
) -> Result<BTreeMap<i64, Value>> {
interrupt::check()?;
let mut child = Command::new(cli)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.with_context(|| format!("could not run {cli}"))?;
let stdout = child.stdout.take().expect("piped stdout");
let (sender, receiver) = mpsc::channel();
std::thread::spawn(move || {
for line in BufReader::new(stdout).lines() {
let Ok(line) = line else { break };
if sender.send(line).is_err() {
break;
}
}
});
let mut stdin = child.stdin.take().expect("piped stdin");
let deadline = Instant::now() + TIMEOUT;
let mut input = Vec::new();
for request in requests {
if writeln!(stdin, "{request}").is_err() {
break;
}
writeln!(input, "{request}")?;
}
let _ = stdin.flush();
let deadline = Instant::now() + TIMEOUT;
let wanted = wanted.to_vec();
let responses = process::exchange(
Command::new(cli).args(args),
cli,
&input,
deadline,
move |stdout| collect_replies(BufReader::new(stdout), &wanted),
)?
.unwrap_or_default();
if responses.is_empty() {
bail!("{cli} {} gave no answer", args.join(" "));
}
Ok(responses)
}

fn collect_replies(stdout: impl BufRead, wanted: &[i64]) -> BTreeMap<i64, Value> {
let mut responses = BTreeMap::new();
while !interrupt::requested() && wanted.iter().any(|id| !responses.contains_key(id)) {
let left = deadline.saturating_duration_since(Instant::now());
let line = match receiver.recv_timeout(left.min(Duration::from_millis(100))) {
Ok(line) => line,
Err(mpsc::RecvTimeoutError::Timeout) if !left.is_zero() => continue,
Err(mpsc::RecvTimeoutError::Timeout | mpsc::RecvTimeoutError::Disconnected) => break,
};
for line in stdout.lines() {
let Ok(line) = line else { break };
let Ok(message) = serde_json::from_str::<Value>(&line) else {
continue;
};
if let Some(id) = message["id"].as_i64().filter(|id| wanted.contains(id))
&& (message.get("result").is_some() || message.get("error").is_some())
{
responses.insert(id, message);
if wanted.iter().all(|id| responses.contains_key(id)) {
break;
}
}
}
drop(stdin);
let _ = child.kill();
let _ = child.wait();
interrupt::check()?;
if responses.is_empty() {
bail!("{cli} {} gave no answer", args.join(" "));
}
Ok(responses)
responses
}

#[cfg(test)]
Expand Down
Loading