Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
cov/c3 ▾

Modern-Apps.git / infra / agents / agentd / src / models.rs

models.rs495 lines · 16.2 KiBRaw
1//! Task / event / session row types and small pure helpers.
2//!
3//! The canonical schema lives in [`crate::store`]; this module holds the
4//! Rust-side enums and the pure functions that are unit-tested (slug,
5//! truncation, commit-message validation).
6
7use serde::{Deserialize, Serialize};
8
9/// Task lifecycle.
10///
11/// * `queued` — waiting for a worker (fresh or re-queued after a park).
12/// * `running` — held by a worker.
13/// * `needs_input` — parked; the driver released its slot. The `kind` field of
14/// [`Pending`] (`pending_json`) says what it waits for: `question`, `plan`,
15/// `chat`, `budget`, `error`, `stopped`.
16/// * `review` — parked with finished work awaiting approval.
17/// * `succeeded` — pushed after Approve.
18/// * `discarded` — terminal; operator threw the work away.
19/// * `failed` — unrecoverable only.
20///
21/// `cancelled` is retired: nothing creates it anymore, but old rows still
22/// parse (mapped to the kept `Cancelled` variant) so historic tasks render.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum TaskStatus {
26 Queued,
27 Running,
28 NeedsInput,
29 Review,
30 Succeeded,
31 Discarded,
32 Failed,
33 Cancelled,
34}
35
36impl TaskStatus {
37 pub fn as_str(self) -> &'static str {
38 match self {
39 TaskStatus::Queued => "queued",
40 TaskStatus::Running => "running",
41 TaskStatus::NeedsInput => "needs_input",
42 TaskStatus::Review => "review",
43 TaskStatus::Succeeded => "succeeded",
44 TaskStatus::Discarded => "discarded",
45 TaskStatus::Failed => "failed",
46 TaskStatus::Cancelled => "cancelled",
47 }
48 }
49
50 pub fn parse(s: &str) -> Option<TaskStatus> {
51 match s {
52 "queued" => Some(TaskStatus::Queued),
53 "running" => Some(TaskStatus::Running),
54 "needs_input" => Some(TaskStatus::NeedsInput),
55 "review" => Some(TaskStatus::Review),
56 "succeeded" => Some(TaskStatus::Succeeded),
57 "discarded" => Some(TaskStatus::Discarded),
58 "failed" => Some(TaskStatus::Failed),
59 "cancelled" => Some(TaskStatus::Cancelled),
60 _ => None,
61 }
62 }
63
64 pub fn is_terminal(self) -> bool {
65 matches!(
66 self,
67 TaskStatus::Succeeded
68 | TaskStatus::Failed
69 | TaskStatus::Discarded
70 | TaskStatus::Cancelled
71 )
72 }
73
74 /// Parked-but-resumable: a message in the inbox re-queues the task.
75 pub fn is_parked(self) -> bool {
76 matches!(self, TaskStatus::NeedsInput | TaskStatus::Review)
77 }
78}
79
80/// One task row.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82pub struct Task {
83 pub id: i64,
84 pub title: String,
85 pub prompt: String,
86 pub module_scope: String,
87 pub model: String,
88 /// Task kind: `task` (interactive, default) or `triage` (automatic
89 /// issue triage; read-only tools, ends via `finish_triage`).
90 #[serde(default = "default_task_kind")]
91 pub kind: String,
92 pub status: TaskStatus,
93 pub slot: Option<u32>,
94 pub branch: String,
95 pub base_sha: Option<String>,
96 pub commit_sha: Option<String>,
97 pub pushed: bool,
98 pub created_at: i64,
99 pub updated_at: i64,
100 pub started_at: Option<i64>,
101 pub finished_at: Option<i64>,
102 pub steps: i64,
103 pub prompt_tokens: i64,
104 pub completion_tokens: i64,
105 pub cost_usd: f64,
106 pub budget_steps: i64,
107 pub budget_usd: f64,
108 pub error: Option<String>,
109 pub summary: Option<String>,
110 /// What a parked task waits for (`pending_json`); `None` on fresh tasks
111 /// and after terminal transitions.
112 #[serde(default)]
113 pub pending: Option<Pending>,
114 /// Raw `todos_json` / `rules_json` (managed by later phases; empty now).
115 #[serde(default)]
116 pub todos_json: Option<String>,
117 #[serde(default)]
118 pub rules_json: Option<String>,
119 #[serde(default)]
120 pub require_plan: bool,
121 #[serde(default)]
122 pub plan_approved: bool,
123 /// Mirror commit holding the parked work (`refs/agent-wip/<id>`).
124 #[serde(default)]
125 pub wip_sha: Option<String>,
126 #[serde(default)]
127 pub pushed_sha: Option<String>,
128 #[serde(default)]
129 pub final_diff: Option<String>,
130 #[serde(default)]
131 pub commit_message: Option<String>,
132 #[serde(default)]
133 pub issue_number: Option<i64>,
134 /// Stored `propose_plan` markdown (the approved plan also appears in the
135 /// volatile tail of the system prompt).
136 #[serde(default)]
137 pub plan_md: Option<String>,
138 /// Operator Stop flag observed by a running driver (cleared on park).
139 #[serde(default)]
140 pub stop_requested: bool,
141}
142
143/// What a parked (`needs_input` / `review`) task is waiting for.
144///
145/// Stored as `pending_json`. The shape is deliberately generic:
146///
147/// ```json
148/// {"kind": "question", "tool_call_id": "call_abc",
149/// "payload": {"question": "...", "options": ["a", "b"], "multi_select": false}}
150/// ```
151///
152/// `kind` values: `question`, `plan`, `review`, `chat`, `budget`, `error`,
153/// `stopped`. `tool_call_id` is set when the park answers a specific pending
154/// tool call (`ask_user`, `propose_plan`, `finish`); on resume the driver
155/// appends exactly one tool result for it built from the drained inbox.
156#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct Pending {
158 pub kind: String,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub tool_call_id: Option<String>,
161 #[serde(default)]
162 pub payload: serde_json::Value,
163}
164
165impl Pending {
166 pub fn new(
167 kind: &str,
168 tool_call_id: Option<String>,
169 payload: serde_json::Value,
170 ) -> Pending {
171 Pending {
172 kind: kind.to_string(),
173 tool_call_id,
174 payload,
175 }
176 }
177}
178
179/// `pending.kind` values (park reasons).
180pub const PENDING_QUESTION: &str = "question";
181pub const PENDING_PLAN: &str = "plan";
182pub const PENDING_REVIEW: &str = "review";
183pub const PENDING_CHAT: &str = "chat";
184pub const PENDING_BUDGET: &str = "budget";
185pub const PENDING_ERROR: &str = "error";
186pub const PENDING_STOPPED: &str = "stopped";
187
188/// Event `kind` values for the task timeline.
189pub const EVENT_ASSISTANT: &str = "assistant";
190pub const EVENT_TOOL_CALL: &str = "tool_call";
191pub const EVENT_TOOL_RESULT: &str = "tool_result";
192pub const EVENT_STATUS: &str = "status";
193pub const EVENT_USER_MESSAGE: &str = "user_message";
194pub const EVENT_QUESTION: &str = "question";
195pub const EVENT_PLAN: &str = "plan";
196pub const EVENT_TODOS: &str = "todos";
197pub const EVENT_REVIEW: &str = "review";
198
199/// Default [`Task::kind`] for rows created before the column existed.
200pub fn default_task_kind() -> String {
201 TASK_KIND_TASK.to_string()
202}
203
204/// `kind` for normal interactive tasks.
205pub const TASK_KIND_TASK: &str = "task";
206/// `kind` for automatic issue-triage tasks.
207#[allow(dead_code)] // Read by the driver worker's triage path (later step).
208pub const TASK_KIND_TRIAGE: &str = "triage";
209
210/// Mirror ref holding a task's parked work.
211pub fn wip_ref(task_id: i64) -> String {
212 format!("refs/agent-wip/{task_id}")
213}
214
215/// Single place mapping tool name → "parking tool". Parking tools must be the
216/// sole call in their turn (enforced server-side): `ask_user`, `propose_plan`,
217/// and `finish` (which parks as `review` instead of pushing).
218pub fn is_parking_tool(name: &str) -> bool {
219 matches!(name, "ask_user" | "propose_plan" | "finish")
220}
221
222/// Message returned to the model when a mutating tool is blocked by the plan
223/// gate (`require_plan` set, plan not yet approved).
224pub fn plan_gate_message() -> &'static str {
225 "Propose a plan with propose_plan and wait for approval before editing or building."
226}
227
228/// Cap for stored `propose_plan` markdown (~32 KB) with a truncation note.
229pub const PLAN_MD_CAP_BYTES: usize = 32 * 1024;
230
231/// Cap plan markdown for `plan_md` / event / pending storage.
232pub fn cap_plan_markdown(plan: &str) -> (String, bool) {
233 if plan.len() <= PLAN_MD_CAP_BYTES {
234 return (plan.to_string(), false);
235 }
236 let mut end = PLAN_MD_CAP_BYTES;
237 while end > 0 && !plan.is_char_boundary(end) {
238 end -= 1;
239 }
240 (
241 format!(
242 "{}\n… [plan truncated at {} bytes] …",
243 &plan[..end],
244 plan.len()
245 ),
246 true,
247 )
248}
249
250/// Inbox `kind` tags. The plan-approve / plan-changes / review routes tag
251/// their rows so the resume path can format the pending tool-call answer
252/// differently from the raw text (plain steering rows keep `kind == ""`).
253pub const INBOX_PLAN_APPROVE: &str = "plan_approve";
254pub const INBOX_PLAN_CHANGES: &str = "plan_changes";
255pub const INBOX_REVIEW_CHANGES: &str = "review_changes";
256
257/// One todo item for `update_todos{items}`.
258#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
259pub struct TodoItem {
260 pub text: String,
261 pub status: String,
262}
263
264/// Max todo items per `update_todos` call.
265pub const MAX_TODOS: usize = 30;
266/// Max chars per todo `text`.
267pub const MAX_TODO_CHARS: usize = 200;
268
269/// Validate `update_todos` items. Returns the canonical items on success.
270pub fn validate_todos(items: &[TodoItem]) -> Result<Vec<TodoItem>, String> {
271 if items.len() > MAX_TODOS {
272 return Err(format!(
273 "too many todos: {} (limit {MAX_TODOS})",
274 items.len()
275 ));
276 }
277 for item in items {
278 if !matches!(item.status.as_str(), "pending" | "in_progress" | "done") {
279 return Err(format!(
280 "bad todo status {:?}: must be pending|in_progress|done",
281 item.status
282 ));
283 }
284 if item.text.chars().count() > MAX_TODO_CHARS {
285 return Err(format!(
286 "todo text too long ({} chars, limit {MAX_TODO_CHARS}): {:?}",
287 item.text.chars().count(),
288 item.text.chars().take(60).collect::<String>(),
289 ));
290 }
291 if item.text.trim().is_empty() {
292 return Err("todo text must be non-empty".to_string());
293 }
294 }
295 Ok(items.to_vec())
296}
297
298/// Render stored todos as human-readable text for the system prompt volatile
299/// tail. `todos_json` holds `[{text, status}]`.
300pub fn render_todos(todos_json: Option<&str>) -> String {
301 let Some(raw) = todos_json else {
302 return String::new();
303 };
304 let items: Vec<TodoItem> = match serde_json::from_str(raw) {
305 Ok(v) => v,
306 Err(_) => return String::new(),
307 };
308 if items.is_empty() {
309 return String::new();
310 }
311 items
312 .iter()
313 .map(|t| {
314 let mark = match t.status.as_str() {
315 "done" => "[x]",
316 "in_progress" => "[>]",
317 _ => "[ ]",
318 };
319 format!("{mark} {}", t.text)
320 })
321 .collect::<Vec<_>>()
322 .join("\n")
323}
324
325/// Cap for `final_diff` stored on the task row (~50 KB) plus truncation note.
326pub const FINAL_DIFF_CAP_BYTES: usize = 50 * 1024;
327
328/// Cap a runner diff for `final_diff` storage, appending a truncation note.
329pub fn cap_final_diff(diff: &str) -> (String, bool) {
330 if diff.len() <= FINAL_DIFF_CAP_BYTES {
331 return (diff.to_string(), false);
332 }
333 let mut end = FINAL_DIFF_CAP_BYTES;
334 while end > 0 && !diff.is_char_boundary(end) {
335 end -= 1;
336 }
337 (
338 format!(
339 "{}\n… [diff truncated at {} bytes; full diff in the branch] …",
340 &diff[..end],
341 diff.len()
342 ),
343 true,
344 )
345}
346
347/// One event row (append-only live log for a task).
348#[derive(Debug, Clone, Serialize, Deserialize)]
349pub struct Event {
350 pub id: i64,
351 pub task_id: i64,
352 pub seq: i64,
353 pub ts: i64,
354 pub kind: String,
355 pub body: serde_json::Value,
356}
357
358pub fn now_unix() -> i64 {
359 std::time::SystemTime::now()
360 .duration_since(std::time::UNIX_EPOCH)
361 .map(|d| d.as_secs() as i64)
362 .unwrap_or(0)
363}
364
365/// Build a safe branch name `agent/<id>-<slug>` from the numeric id and a
366/// free-text title. Only `[a-z0-9-]` survive; runs collapse to one `-`;
367/// empty slugs fall back to `task`.
368pub fn branch_name(id: i64, title: &str) -> String {
369 let slug = slugify(title);
370 format!("agent/{id}-{slug}")
371}
372
373pub fn slugify(title: &str) -> String {
374 let mut out = String::new();
375 let mut prev_dash = true; // collapse leading run too
376 for c in title.to_lowercase().chars() {
377 if c.is_ascii_alphanumeric() {
378 out.push(c);
379 prev_dash = false;
380 } else if !prev_dash {
381 out.push('-');
382 prev_dash = true;
383 }
384 }
385 while out.ends_with('-') {
386 out.pop();
387 }
388 if out.is_empty() {
389 out.push_str("task");
390 }
391 if out.len() > 48 {
392 out.truncate(48);
393 while out.ends_with('-') {
394 out.pop();
395 }
396 }
397 out
398}
399
400/// Max bytes kept per tool result before truncation.
401pub const RESULT_TRUNCATE_BYTES: usize = 16 * 1024;
402
403/// Truncate a tool result to ~16 KiB, keeping head + tail with a marker.
404/// Returns `(text, was_truncated)`.
405pub fn truncate_result(s: &str) -> (String, bool) {
406 if s.len() <= RESULT_TRUNCATE_BYTES {
407 return (s.to_string(), false);
408 }
409 let keep_head = RESULT_TRUNCATE_BYTES * 3 / 4;
410 let keep_tail = RESULT_TRUNCATE_BYTES / 4;
411 // Snap to char boundaries.
412 let mut head_end = keep_head.min(s.len());
413 while head_end > 0 && !s.is_char_boundary(head_end) {
414 head_end -= 1;
415 }
416 let mut tail_start = s.len().saturating_sub(keep_tail);
417 while tail_start < s.len() && !s.is_char_boundary(tail_start) {
418 tail_start += 1;
419 }
420 let omitted = s.len().saturating_sub(head_end + (s.len() - tail_start));
421 (
422 format!(
423 "{}\n… [truncated {} bytes] …\n{}",
424 &s[..head_end],
425 omitted,
426 &s[tail_start..]
427 ),
428 true,
429 )
430}
431
432/// Human placeholder swapped in for old tool results once the conversation
433/// exceeds the context budget (keeps the model oriented without the bytes).
434pub fn trim_placeholder(tool_name: &str, bytes: usize) -> String {
435 format!("[earlier {tool_name} result trimmed, was ~{bytes} chars]")
436}
437
438/// Validate the `finish{commit_message}` first line: `<module>: <desc>`
439/// with `module` a plausible Gradle path (`[a-z0-9-/]+`) and the whole line
440/// <= 80 chars, mirroring the repo's `appname: short description` rule.
441///
442/// When `issue` is `Some(n)`, the subject must end with ` (#<n>)` (repo
443/// convention `appname: short description (#iss)`), so issue-linked fixes
444/// always reference their issue.
445pub fn validate_commit_message(msg: &str) -> Result<(), String> {
446 validate_commit_message_for_issue(msg, None)
447}
448
449/// [`validate_commit_message`] plus the ` (#<n>)` suffix requirement when the
450/// task links issue `n`. Used by `finish` for issue-linked tasks.
451pub fn validate_commit_message_for_issue(msg: &str, issue: Option<i64>) -> Result<(), String> {
452 let first = msg.lines().next().unwrap_or("").trim();
453 if first.is_empty() {
454 return Err("commit message is empty".to_string());
455 }
456 if first.chars().count() > 80 {
457 return Err(format!(
458 "commit message first line is {} chars (limit 80): {first:?}",
459 first.chars().count()
460 ));
461 }
462 let Some((scope, desc)) = first.split_once(':') else {
463 return Err(
464 "commit message must start with `<module>: <description>` (e.g. `notes: fix editor crash`)".to_string(),
465 );
466 };
467 let scope = scope.trim();
468 let desc = desc.trim();
469 if scope.is_empty()
470 || !scope
471 .chars()
472 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '/' || c == '-')
473 {
474 return Err(format!(
475 "commit scope {scope:?} must match [a-z0-9/-]+ (e.g. `notes`, `games/logicgate`)"
476 ));
477 }
478 if desc.is_empty() {
479 return Err("commit description after `<module>:` must be non-empty".to_string());
480 }
481 if let Some(n) = issue {
482 let suffix = format!("(#{n})");
483 if !first.trim_end().ends_with(&suffix) {
484 return Err(format!(
485 "this task fixes issue #{n}, so the commit subject must end with ` (#{n})` (e.g. `notes: fix editor crash (#{n})`)"
486 ));
487 }
488 }
489 if !msg.trim().contains('\n') {
490 return Err(
491 "commit message needs a blank line and a prose body after the first line".to_string(),
492 );
493 }
494 Ok(())
495}