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
45 changes: 45 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ members = [
"crates/release-cut",
"crates/sbom-gen",
"crates/fuzz-setup",
"crates/anthropic-usage-poll",
"crates/agent-forecast",
"crates/temporal-grounding",
"bin/hook-entry",
]

[workspace.package]
Expand All @@ -32,7 +36,7 @@ serde_json = "1.0"
tokio = { version = "1.39", features = ["rt-multi-thread", "macros", "fs"] }
walkdir = "2.5"
thiserror = "2.0"
reqwest = { version = "0.13", features = ["blocking"] }
reqwest = { version = "0.13", features = ["blocking", "json"] }
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1.11", features = ["v4", "serde"] }
tracing = "0.1"
Expand All @@ -41,4 +45,3 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[profile.release]
lto = "thin"
codegen-units = 1

18 changes: 18 additions & 0 deletions bin/hook-entry/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
[package]
name = "hook-entry"
description = "Shared PreToolUse hook — injects budget+quota line into Claude Code agent context"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
authors.workspace = true
rust-version.workspace = true

[[bin]]
name = "hook-entry"
path = "src/main.rs"

[dependencies]
anyhow = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
95 changes: 95 additions & 0 deletions bin/hook-entry/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//! Claude Code PreToolUse hook.
//! Reads the hook event from stdin, writes a budget+quota annotation to stdout.
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::Read;
use std::path::PathBuf;

#[derive(Deserialize)]
struct UsageSnapshot {
daily_remaining: Option<u64>,
monthly_remaining: Option<u64>,
updated_at: Option<String>,
}

#[derive(Serialize)]
struct HookOutput {
budget_line: String,
}

fn main() -> Result<()> {
let mut input = String::new();
std::io::stdin().read_to_string(&mut input)?;

// Parse but don't fail on bad input — hooks must not block agents
let _event: Value = serde_json::from_str(&input).unwrap_or_default();

let usage = read_usage();
let budget_line = format!(
"[observability] daily_remaining={} monthly_remaining={} | {} | {} | updated={}",
fmt_opt(usage.as_ref().and_then(|u| u.daily_remaining)),
fmt_opt(usage.as_ref().and_then(|u| u.monthly_remaining)),
read_forecast_hint(),
read_elapsed_hint(),
usage
.as_ref()
.and_then(|u| u.updated_at.as_deref())
.unwrap_or("unknown"),
);

println!("{}", serde_json::to_string(&HookOutput { budget_line })?);
Ok(())
}

fn fmt_opt(v: Option<u64>) -> String {
v.map_or_else(|| String::from("?"), |n| n.to_string())
}

fn claude_dir() -> PathBuf {
std::env::var("HOME")
.map(PathBuf::from)
.unwrap_or_else(|_| PathBuf::from("."))
.join(".claude")
}

fn read_usage() -> Option<UsageSnapshot> {
let path = claude_dir().join("usage.json");
let text = std::fs::read_to_string(path).ok()?;
serde_json::from_str(&text).ok()
}

fn read_forecast_hint() -> String {
// TODO: invoke agent-forecast binary for current prompt category
String::from("forecast=p50:? p90:?")
}

fn read_elapsed_hint() -> String {
// TODO: read active-agents.json, compute elapsed for current session
String::from("elapsed=?")
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn fmt_opt_some() {
assert_eq!(fmt_opt(Some(42_000)), "42000");
}

#[test]
fn fmt_opt_none() {
assert_eq!(fmt_opt(None), "?");
}

#[test]
fn hook_output_serializes() {
let o = HookOutput {
budget_line: "test line".to_string(),
};
let json = serde_json::to_string(&o).unwrap();
assert!(json.contains("budget_line"));
assert!(json.contains("test line"));
}
}
20 changes: 20 additions & 0 deletions crates/agent-forecast/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "agent-forecast"
description = "Per-category p50/p90 token budget forecasting from agent history"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
authors.workspace = true
rust-version.workspace = true

[[bin]]
name = "agent-forecast"
path = "src/main.rs"

[dependencies]
clap = { workspace = true }
anyhow = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
17 changes: 17 additions & 0 deletions crates/agent-forecast/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# agent-forecast

Reads `~/.claude/agent-history.jsonl` and computes p50/p90 token priors per category.

Categories: `sweep audit refactor dependabot scaffold extract merge docs test eval fork cleanup`

## Usage

```bash
agent-forecast categorize "refactor the auth module"
# → refactor

agent-forecast budget refactor
# → {"category":"refactor","p50_tokens":0,"p90_tokens":0,"sample_count":0}
```

History JSONL fields: `timestamp`, `prompt_hash_category`, `tool_uses`, `duration_ms`, `total_tokens`, `outcome`.
Loading
Loading