Skip to content

Commit 59e87e7

Browse files
Review fixes: workflow checks, spending, hooks, schedules, scaffolding
- A workflow step that calls a declared or MCP tool itself now passes the same checks as a model's call: kill switch, hooks, spending and role rules, approval. - Spending: a payment is counted when it is let through and taken off if its call fails, under a lock, so payments running at once cannot pass the monthly cap together. An amount that cannot be read blocks the payment instead of skipping the rules. - Hooks that fail closed (compliance, fail_open: false) block on output that is not an answer; plain hooks still allow, as in 1.x. - Plan tasks and the reconciling step get the time actually left. - A steps: mapping in a workflow runs in file order. - The audit log records spending and role blocks. - Schedules: a job never runs twice for the same time, and the local offset is read each time round, so daylight-saving changes are followed. - Starting an agent in an existing repository commits only the files it created, never the user's uncommitted work. - The console help no longer lists the removed web page.
1 parent 94b22e8 commit 59e87e7

11 files changed

Lines changed: 492 additions & 83 deletions

File tree

‎crates/cli/src/init_cmd.rs‎

Lines changed: 73 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -124,11 +124,19 @@ pub(crate) fn scaffold(
124124
std::fs::write(&path, text).map_err(|e| format!("{}: {e}", path.display()))?;
125125
created.push(*rel);
126126
}
127-
let mut note = start_git(dir).unwrap_or_default();
128-
if git(dir, &["rev-parse", "--is-inside-work-tree"])
127+
let started = start_git(dir);
128+
let mut note = started.clone().unwrap_or_default();
129+
// A repository started just now gets everything, as in 1.x; in an
130+
// existing one only the files made here are committed, never the
131+
// user's own uncommitted work.
132+
let committed = git(dir, &["rev-parse", "--is-inside-work-tree"])
129133
&& !created.is_empty()
130-
&& commit_all(dir, "Start the agent")
131-
{
134+
&& if started.is_some() {
135+
commit_all(dir, "Start the agent")
136+
} else {
137+
commit_paths(dir, &created, "Start the agent")
138+
};
139+
if committed {
132140
note.push_str("; committed");
133141
}
134142
Ok((created, note))
@@ -161,6 +169,25 @@ fn commit_all(dir: &std::path::Path, message: &str) -> bool {
161169
)
162170
}
163171

172+
/// Commits only `paths`, leaving anything else staged or changed alone.
173+
fn commit_paths(dir: &std::path::Path, paths: &[&str], message: &str) -> bool {
174+
let mut add = vec!["add", "--"];
175+
add.extend_from_slice(paths);
176+
let mut commit = vec![
177+
"-c",
178+
"user.name=gitagent",
179+
"-c",
180+
"user.email=gitagent@localhost",
181+
"commit",
182+
"--quiet",
183+
"-m",
184+
message,
185+
"--",
186+
];
187+
commit.extend_from_slice(paths);
188+
git(dir, &add) && git(dir, &commit)
189+
}
190+
164191
/// Starts a git repository in `dir` if it is not inside one; gives a note
165192
/// for the user when something happened.
166193
fn start_git(dir: &std::path::Path) -> Option<String> {
@@ -184,3 +211,45 @@ pub(crate) fn ensure_repo(dir: &std::path::Path) -> Option<String> {
184211
}
185212
Some(note)
186213
}
214+
215+
#[cfg(test)]
216+
mod tests {
217+
use super::*;
218+
219+
#[test]
220+
fn scaffolding_in_a_repository_commits_only_its_own_files() {
221+
let dir = tempfile::tempdir().unwrap();
222+
let d = dir.path();
223+
assert!(git(d, &["init", "--quiet"]));
224+
std::fs::write(d.join("app.py"), "print(1)\n").unwrap();
225+
assert!(commit_all(d, "init"));
226+
// The user's work in progress: a change and a new file.
227+
std::fs::write(d.join("app.py"), "print(2)\n").unwrap();
228+
std::fs::write(d.join("notes.txt"), "draft\n").unwrap();
229+
230+
let (created, note) = scaffold(d, "app", "anthropic:m", None).unwrap();
231+
assert!(created.contains(&"agent.yaml"), "{created:?}");
232+
assert!(note.contains("committed"), "{note}");
233+
let shown = Command::new("git")
234+
.args(["show", "--name-only", "--format=", "HEAD"])
235+
.current_dir(d)
236+
.output()
237+
.unwrap();
238+
let files = String::from_utf8_lossy(&shown.stdout).to_string();
239+
assert!(files.contains("agent.yaml"), "{files}");
240+
assert!(
241+
!files.contains("app.py") && !files.contains("notes.txt"),
242+
"{files}"
243+
);
244+
let status = Command::new("git")
245+
.args(["status", "--porcelain"])
246+
.current_dir(d)
247+
.output()
248+
.unwrap();
249+
let status = String::from_utf8_lossy(&status.stdout).to_string();
250+
assert!(
251+
status.contains(" M app.py") && status.contains("?? notes.txt"),
252+
"{status}"
253+
);
254+
}
255+
}

‎crates/cli/src/repl.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -381,7 +381,6 @@ fn help(s: &Setup) {
381381
"gitagent validate dir",
382382
"check the agent's files (--compliance for the rules)",
383383
);
384-
row("gitagent ui -d dir", "a local web page for the agent");
385384
row("gitagent --help", "every flag");
386385
println!();
387386
}

‎crates/cli/src/schedule_cmd.rs‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -386,16 +386,24 @@ impl Runner {
386386

387387
/// Fires schedules as they come due until Ctrl-C (or `max_runs` jobs).
388388
async fn serve(&mut self, max_runs: Option<u32>) -> ExitCode {
389-
let offset = local_offset();
389+
// When each schedule last fired: its next time is always later, even
390+
// when a job ends within the second it was due.
391+
let mut fired: std::collections::HashMap<String, i64> = Default::default();
390392
loop {
393+
// Read every time round, so a change of daylight-saving time
394+
// moves the schedules with the clock.
395+
let offset = local_offset();
391396
let (found, problems) = schedules::discover(&self.dir);
392397
for p in problems {
393398
eprintln!("gitagent schedule: warning: {p}");
394399
}
395400
let now = now_unix();
396401
let mut due: Vec<(i64, Schedule)> = found
397402
.into_iter()
398-
.filter_map(|s| s.next_after(now - 1, offset).map(|t| (t, s)))
403+
.filter_map(|s| {
404+
let from = fired.get(&s.id).map_or(now - 1, |&t| t.max(now - 1));
405+
s.next_after(from, offset).map(|t| (t, s))
406+
})
399407
.collect();
400408
due.sort_by_key(|(t, _)| *t);
401409
if self.runs == 0 {
@@ -433,10 +441,11 @@ impl Runner {
433441
.into_iter()
434442
.find(|s| s.id == next.id);
435443
match still {
436-
Some(s) if s.enabled && s.next_after(at - 1, offset) == Some(at) => {}
444+
Some(s) if s.enabled && s.next_after(at - 1, local_offset()) == Some(at) => {}
437445
_ => continue,
438446
}
439447
}
448+
fired.insert(next.id.clone(), at);
440449
self.job(&next, next.once).await;
441450
if max_runs.is_some_and(|n| self.runs >= n) {
442451
return ExitCode::SUCCESS;

‎crates/core/src/approval.rs‎

Lines changed: 89 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -121,40 +121,63 @@ pub(crate) struct Gate<'a> {
121121
error_seen: bool,
122122
/// Where this month's spending is kept (`.gitagent/state.json`).
123123
state_file: Option<PathBuf>,
124+
/// Payments counted when their call was let through, by call id; a
125+
/// call that then fails is taken off again.
126+
reserved: std::sync::Mutex<std::collections::HashMap<String, u64>>,
124127
}
125128

129+
/// Held while this month's spending is read and rewritten, so payments
130+
/// running at the same time (a plan's tasks) cannot both pass the cap.
131+
static SPENDING: std::sync::Mutex<()> = std::sync::Mutex::new(());
132+
126133
/// A payment a tool call makes: the amount in cents and its category.
127134
pub(crate) struct Payment {
128135
pub cents: u64,
129136
pub category: Option<String>,
130137
}
131138

132139
/// The payment a call makes, read from `amount_cents` (or `amount`, in
133-
/// whole units) and `category` in its arguments.
134-
pub(crate) fn payment_of(call: &ToolCall) -> Option<Payment> {
140+
/// whole units) and `category` in its arguments. `None` when the call names
141+
/// no amount; an error when it names one that cannot be read, which the
142+
/// spending rules treat as a block rather than as no payment.
143+
pub(crate) fn payment_of(call: &ToolCall) -> Option<Result<Payment, String>> {
135144
let args = &call.arguments;
136145
let cents = match (args.get("amount_cents"), args.get("amount")) {
137-
(Some(c), _) => c
138-
.as_u64()
139-
.or_else(|| c.as_str().and_then(|s| s.parse().ok()))?,
140-
(None, Some(a)) => {
141-
let units = a
142-
.as_f64()
143-
.or_else(|| a.as_str().and_then(|s| s.parse().ok()))?;
144-
if units < 0.0 {
145-
return None;
146-
}
147-
(units * 100.0).round() as u64
148-
}
146+
(Some(c), _) => cents_of(c, 1.0),
147+
(None, Some(a)) => cents_of(a, 100.0),
149148
(None, None) => return None,
150149
};
151-
Some(Payment {
152-
cents,
153-
category: args
154-
.get("category")
155-
.and_then(Value::as_str)
156-
.map(str::to_string),
157-
})
150+
Some(
151+
cents
152+
.map(|cents| Payment {
153+
cents,
154+
category: args
155+
.get("category")
156+
.and_then(Value::as_str)
157+
.map(str::to_string),
158+
})
159+
.ok_or_else(|| "the payment's amount could not be read".to_string()),
160+
)
161+
}
162+
163+
/// An amount in cents from a number or a string such as `"1,500.00"` or
164+
/// `"$15"`, scaled by `scale`; `None` when negative, fractional cents or
165+
/// not a number.
166+
fn cents_of(v: &Value, scale: f64) -> Option<u64> {
167+
let n = v.as_f64().or_else(|| {
168+
v.as_str().and_then(|s| {
169+
s.trim()
170+
.trim_start_matches('$')
171+
.replace(',', "")
172+
.parse::<f64>()
173+
.ok()
174+
})
175+
})?;
176+
let cents = n * scale;
177+
if !cents.is_finite() || cents < 0.0 || (scale == 1.0 && cents.fract() != 0.0) {
178+
return None;
179+
}
180+
Some(cents.round() as u64)
158181
}
159182

160183
impl<'a> Gate<'a> {
@@ -182,6 +205,7 @@ impl<'a> Gate<'a> {
182205
kill_file,
183206
error_seen: false,
184207
state_file,
208+
reserved: Default::default(),
185209
}
186210
}
187211

@@ -197,24 +221,33 @@ impl<'a> Gate<'a> {
197221
}
198222

199223
/// Notes a call's result: for the `error_detected` trigger, and a
200-
/// payment that went through counts toward the month's spending.
224+
/// payment counted by [`Gate::block_reason`] whose call failed, was
225+
/// denied or was blocked is taken off the month's spending again.
201226
pub fn observe(&mut self, call: &ToolCall, is_error: bool) {
202227
self.error_seen |= is_error;
203-
if is_error || self.spec.supervision.finance.is_none() {
204-
return;
205-
}
206-
if let Some(p) = payment_of(call) {
228+
let reserved = self
229+
.reserved
230+
.lock()
231+
.unwrap_or_else(|e| e.into_inner())
232+
.remove(&call.id);
233+
if let (Some(cents), true) = (reserved, is_error) {
234+
let _held = SPENDING.lock().unwrap_or_else(|e| e.into_inner());
207235
let month = this_month();
208-
let mut state = self.state();
209-
let spent = state["spending"][&month].as_u64().unwrap_or(0);
210-
state["spending"][&month] = json!(spent + p.cents);
211-
if let Some(path) = &self.state_file {
212-
if let Some(dir) = path.parent() {
213-
let _ = std::fs::create_dir_all(dir);
214-
}
215-
let _ = std::fs::write(path, state.to_string());
216-
}
236+
let spent = self.state()["spending"][&month].as_u64().unwrap_or(0);
237+
self.write_spent(&month, spent.saturating_sub(cents));
238+
}
239+
}
240+
241+
fn write_spent(&self, month: &str, cents: u64) {
242+
let Some(path) = &self.state_file else {
243+
return;
244+
};
245+
let mut state = self.state();
246+
state["spending"][month] = json!(cents);
247+
if let Some(dir) = path.parent() {
248+
let _ = std::fs::create_dir_all(dir);
217249
}
250+
let _ = std::fs::write(path, state.to_string());
218251
}
219252

220253
fn state(&self) -> Value {
@@ -226,7 +259,10 @@ impl<'a> Gate<'a> {
226259
}
227260

228261
/// Why the call may not run at all, if so: a handoff whose roles the
229-
/// agent does not hold, or a payment outside the spending rules.
262+
/// agent does not hold, or a payment outside the spending rules. A
263+
/// payment that passes is counted toward the month at once, so calls
264+
/// running at the same time see it; [`Gate::observe`] takes it off again
265+
/// if the call does not go through.
230266
pub fn block_reason(&self, call: &ToolCall) -> Option<String> {
231267
let sup = &self.spec.supervision;
232268
let agent = self
@@ -255,6 +291,10 @@ impl<'a> Gate<'a> {
255291
let (Some(f), Some(p)) = (&sup.finance, payment_of(call)) else {
256292
return None;
257293
};
294+
let p = match p {
295+
Ok(p) => p,
296+
Err(why) => return Some(format!("{why} (financial governance)")),
297+
};
258298
if let Some(c) = &p.category {
259299
if f.blocked_categories.iter().any(|b| b == c) {
260300
return Some(format!(
@@ -279,8 +319,10 @@ impl<'a> Gate<'a> {
279319
f.max_per_transaction_cents.unwrap_or_default()
280320
));
281321
}
322+
let _held = SPENDING.lock().unwrap_or_else(|e| e.into_inner());
323+
let month = this_month();
324+
let spent = self.state()["spending"][&month].as_u64().unwrap_or(0);
282325
if let Some(cap) = f.max_monthly_cents {
283-
let spent = self.state()["spending"][this_month()].as_u64().unwrap_or(0);
284326
if spent + p.cents > cap {
285327
return Some(format!(
286328
"{} cents would take this month's spending to {} of the {cap} allowed (financial governance)",
@@ -289,13 +331,21 @@ impl<'a> Gate<'a> {
289331
));
290332
}
291333
}
334+
self.write_spent(&month, spent + p.cents);
335+
self.reserved
336+
.lock()
337+
.unwrap_or_else(|e| e.into_inner())
338+
.insert(call.id.clone(), p.cents);
292339
None
293340
}
294341

295342
/// Whether a request that nobody answers in time counts as approved
296343
/// (a payment with `auto_deny_on_timeout: false`).
297344
pub fn approve_on_timeout(&self, call: &ToolCall) -> bool {
298-
match (&self.spec.supervision.finance, payment_of(call)) {
345+
match (
346+
&self.spec.supervision.finance,
347+
payment_of(call).and_then(Result::ok),
348+
) {
299349
(Some(f), Some(_)) => !f.auto_deny_on_timeout,
300350
_ => false,
301351
}
@@ -338,7 +388,7 @@ impl<'a> Gate<'a> {
338388
));
339389
}
340390
}
341-
if let (Some(f), Some(p)) = (&sup.finance, payment_of(call)) {
391+
if let (Some(f), Some(Ok(p))) = (&sup.finance, payment_of(call)) {
342392
if f.require_above_cents.is_some_and(|t| p.cents > t) {
343393
return Some(format!(
344394
"a payment of {} cents is over {} (financial governance)",

‎crates/core/src/audit.rs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,16 @@ impl AuditLog {
126126
"approval",
127127
object(json!({"turn": turn, "id": e["id"], "approved": e["approved"], "reason": e["reason"]})),
128128
),
129-
"guard" if e["kind"] == "hook_block" => {
130-
self.write("blocked", object(json!({"turn": turn, "reason": e["reason"]})));
129+
"guard" if e["kind"] == "hook_block" || e["kind"] == "compliance_block" => {
130+
let by = if e["kind"] == "hook_block" {
131+
"hook"
132+
} else {
133+
"compliance"
134+
};
135+
self.write(
136+
"blocked",
137+
object(json!({"turn": turn, "by": by, "reason": e["reason"]})),
138+
);
131139
}
132140
"run_end" => self.write(
133141
"run_end",

‎crates/core/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -879,6 +879,7 @@ pub async fn run(
879879
approver: opts.approver.clone(),
880880
kill: opts.kill.clone(),
881881
},
882+
started: Instant::now(),
882883
};
883884
let done =
884885
plan::run(spec, provider, &run_call, &children, &events, at_once)

0 commit comments

Comments
 (0)