graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: session_recap wire event + harness-side recaps (#419)
Rach Pradhan18e3f31e8d01
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex ec330625..bf9464bb 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -39,3 +39,7 @@{"id": "budget-exhausted-past-the-landing-dies-fatal", "why": "#368 exhaustedFatal, the harness's own last words - and the FIRST case that can exist at all, since the runner auto-failed every nonzero exit until expected_exit landed. The #390 landing reserve buys the run ONE tools-free final call; it cannot stop a model that answers that call with a tool call anyway, and executing that tool demands a call the pool cannot admit. A one-shot (-p) run must then die LOUDLY: exit 1 with the harness naming what ran out, that the work is PARTIAL and was NOT rolled back, and where the trace is - never the bare 'turn failed: RunBudgetExhausted' that #368 replaced, and never a silent exit 0. The asserts pin the whole ordering: request 1 carries the full toolset, request 2 IS the landing call (note present, tools gone), and only PAST it does the run die. NOTE (-p): one-shot sets root.out = null, so the --json event stream is empty and no event/final_text assert is expressible here; the same exhaustion inside the stdin/mainloop shape is non-fatal by design (an error event, exit 0), which is why this case must be one-shot. GRAFF_FLEET=on plus the workflow call makes the run carry a real orchestration decision, so exhaustedFatal's other half fires too - it files the score-0 exhausted:true orch_outcome row before dying (verified by hand in the workspace: kind:\"orch_outcome\" ... \"exhausted\":true,\"landed\":false). That row is NOT asserted: it is written as the process dies, after every scripted bash step could run, and the runner keeps no post-mortem surface - it becomes assertable when the trajectory_row extension lands.", "args": ["--max-model-calls", "2", "-p", "fix the failing checks in parser.py"], "env": {"GRAFF_FLEET": "on"}, "expected_exit": 1, "timeout_s": 90, "prompt": "fix the failing checks in parser.py", "script": [{"tool": "workflow", "arguments": {"phases": [{"title": "find the defect", "tasks": [{"description": "find", "prompt": "read parser.py and locate the failing check"}]}]}}, {"tool": "todo_read", "arguments": {}}, {"tool": "todo_read", "arguments": {}}, {"text": "never reached: the pool was dry two calls ago"}], "assert": [{"request_contains": {"index": 0, "text": "\"todo_write\""}}, {"request_lacks": {"index": 0, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_lacks": {"index": -1, "text": "\"todo_write\""}}, {"stderr_contains": "model-call budget exhausted"}, {"stderr_contains": "(--max-model-calls 2)"}, {"stderr_contains": "Work done so far is PARTIAL and was NOT rolled back"}, {"stderr_contains": "raise --max-model-calls or re-run to continue"}]}{"id": "new-ask-retires-finished-checklist", "why": "#394: completed items from PRIOR asks piled up. The omitted-completed preserve rule (2896b32) is per-ASK, but the parking never expired: five unrelated goals in one session came back from todo_read as one 13-item [x] pile, and every new prompt inherited it. A checklist that is FULLY completed retires at the next user ask, so the second ask's list holds the second ask's work only - while an unfinished list still crosses the turn untouched (compaction-keeps-completed) and an omission inside one ask still preserves (todo-preserves-completed).", "args": [], "prompt": "rename the config flag", "second_prompt": "unrelated: draft the release notes", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "rename the flag in config.zig", "status": "completed"}]}}, {"text": "the flag is renamed"}, {"tool": "todo_write", "arguments": {"todos": [{"content": "draft the release notes", "status": "in_progress"}]}}, {"tool": "todo_read", "arguments": {}}, {"text": "the release notes are drafted"}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "todo_read"}, "count": 1}}, {"request_contains": {"index": -1, "text": "[~] draft the release notes"}}, {"request_lacks": {"index": -1, "text": "[x] rename the flag in config.zig\\n[~] draft the release notes"}}, {"final_text_contains": "the release notes are drafted"}]}{"id": "btw-side-question-leaves-no-trace", "why": "#415: /btw must be answered from the LIVE context with NO tools and then vanish. The next turn's request is where the regression would show: a side question that reaches it has reached root.messages, which is the only way it could also reach the session file OR the append-only transcript (#441) - both are written from that same array.", "prompt": "build it", "controls_after_turn": [{"type": "btw", "text": "what did that linker error actually mean?"}], "second_prompt": "ok, carry on", "script": [{"text": "the link step failed with an undefined symbol"}, {"text": "SIDE-ONLY it means the entry point was renamed"}, {"text": "moving on"}], "assert": [{"event": {"type": "btw", "ok": true, "persisted": false}}, {"request_contains": {"index": 1, "text": "what did that linker error actually mean?"}}, {"request_contains": {"index": 1, "text": "the link step failed with an undefined symbol"}}, {"request_lacks": {"index": 1, "text": "\"tools\""}}, {"request_lacks": {"index": -1, "text": "what did that linker error actually mean?"}}, {"request_lacks": {"index": -1, "text": "SIDE-ONLY"}}, {"request_contains": {"index": -1, "text": "the link step failed with an undefined symbol"}}]}+{"id": "peer-checkpoint-blocks-shared-tree-git", "why": "#469: with a live co-resident session in the same worktree, the FIRST index/tree-mutating git command must come back un-executed as a checkpoint naming the peer, and the identical re-issue must run. The regression is two graffs silently mutating one git index again.", "live_peer": true, "args": [], "prompt": "init a repo and stage everything", "script": [{"tool": "bash", "arguments": {"command": "git init -q"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"tool": "bash", "arguments": {"command": "git add -A"}}, {"text": "staged, once the checkpoint told me about the peer session"}], "assert": [{"event": {"type": "tool_call_finished", "name": "bash", "is_error": false}}, {"events_at_least": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"events_at_most": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 1}}, {"request_contains": {"index": 2, "text": "shared-tree checkpoint (#469)"}}, {"request_contains": {"index": 2, "text": "another graff session already owns this worktree"}}]}+{"id": "session-recap-precedes-turn", "why": "#419: every cleanly completed turn must emit a heuristic session_recap before the terminal turn event, so stream-until-turn clients (the GUI agent overview) always learn the session's one-line state and status.", "prompt": "say hi", "script": [{"text": "hello there"}], "assert": [{"event": {"type": "session_recap", "status": "completed", "source": "heuristic", "text": "hello there"}}, {"event": {"type": "turn", "complete": true}}]}+{"id": "session-recap-needs-input-heuristic", "why": "#419: a turn that ends on a question reads as needs_input without any model call - the heuristic degrade path the issue asks for when no cheap model is available.", "prompt": "what do you need", "script": [{"text": "Which file should I change?"}], "assert": [{"event": {"type": "session_recap", "status": "needs_input", "source": "heuristic"}}]}+{"id": "session-recap-model-silent-without-cheap-rung", "why": "#419: the cheap-model recap is silently disabled when the provider has no ladder rung (lmstudio in the mock rig) - no event, no error, the heuristic recap still lands.", "prompt": "say hi", "script": [{"text": "hi"}], "controls_after_turn": [{"type": "set_mode", "mode": "normal"}], "assert": [{"event": {"type": "session_recap", "source": "heuristic"}}, {"no_event": {"type": "session_recap", "source": "model"}}]}diff --git a/gui/src-tauri/examples/generate_desktop_contracts.rs b/gui/src-tauri/examples/generate_desktop_contracts.rsindex d6a7f723..efe2f1b6 100644--- a/gui/src-tauri/examples/generate_desktop_contracts.rs+++ b/gui/src-tauri/examples/generate_desktop_contracts.rs@@ -17,7 +17,8 @@ use codegraff_gui_lib::dto::{ProviderSummaryDto, ProviderUrlParamDto, ProviderUrlParamValueDto, QuickStartProjectInput,QuickStartVisibility, RemoveProviderInput, RuntimeStatusDto, SaveConversationLayoutInput,SavedWorkspaceDetailDto, SavedWorkspaceSummaryDto, SendPromptInput, SessionMessageDto,- SessionSnapshotDto, SessionTodoDto, SessionTodoStatusDto, StartProviderAuthInput,+ SessionRecapDto, SessionRecapSourceDto, SessionRecapStatusDto, SessionSnapshotDto,+ SessionTodoDto, SessionTodoStatusDto, StartProviderAuthInput,StatusCategoryDto, TerminalCloseInput, TerminalErrorEventDto, TerminalExitEventDto,TerminalOpenInput, TerminalOutputEventDto, TerminalResizeInput, TerminalSessionDto,TerminalWriteInput, ToolCallDetailDto, ToolResultDetailDto, UpdatePromptSettingsInput,@@ -46,6 +47,9 @@ fn main() -> anyhow::Result<()> {export_decl::<SessionMessageDto>(&config),export_decl::<SessionTodoStatusDto>(&config),export_decl::<SessionTodoDto>(&config),+ export_decl::<SessionRecapStatusDto>(&config),+ export_decl::<SessionRecapSourceDto>(&config),+ export_decl::<SessionRecapDto>(&config),export_decl::<ConversationSessionSummaryDto>(&config),export_decl::<ChatBindingDto>(&config),export_decl::<ConversationViewSnapshotDto>(&config),diff --git a/gui/src-tauri/src/dto/mod.rs b/gui/src-tauri/src/dto/mod.rsindex 1427b85d..17a5e762 100644--- a/gui/src-tauri/src/dto/mod.rs+++ b/gui/src-tauri/src/dto/mod.rs@@ -33,8 +33,9 @@ pub use runtime::{};pub use session::{ChatBindingDto, ConversationSessionSummaryDto, ConversationViewSnapshotDto,- SavedWorkspaceDetailDto, SavedWorkspaceSummaryDto, SessionMessageDto, SessionSnapshotDto,- SessionTodoDto, SessionTodoStatusDto, WorkspaceKindDto, WorkspaceSessionDto,+ SavedWorkspaceDetailDto, SavedWorkspaceSummaryDto, SessionMessageDto, SessionRecapDto,+ SessionRecapSourceDto, SessionRecapStatusDto, SessionSnapshotDto, SessionTodoDto,+ SessionTodoStatusDto, WorkspaceKindDto, WorkspaceSessionDto,};pub use terminal::{TerminalCloseInput, TerminalErrorEventDto, TerminalExitEventDto, TerminalOpenInput,diff --git a/gui/src-tauri/src/dto/session.rs b/gui/src-tauri/src/dto/session.rsindex a4bcc19d..4d7d4513 100644--- a/gui/src-tauri/src/dto/session.rs+++ b/gui/src-tauri/src/dto/session.rs@@ -117,6 +117,38 @@ pub struct ChatBindingDto {pub conversation_id: String,}+/// Coarse session state carried by the harness's `session_recap` wire event+/// (#419). Mirrored from the harness's closed vocabulary.+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, TS)]+#[serde(rename_all = "snake_case")]+#[ts(rename = "SessionRecapStatus")]+pub enum SessionRecapStatusDto {+ NeedsInput,+ Completed,+ Failed,+}++/// What produced the recap: the free turn-end heuristic, or the detached+/// cheap-model pass (#419).+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, TS)]+#[serde(rename_all = "snake_case")]+#[ts(rename = "SessionRecapSource")]+pub enum SessionRecapSourceDto {+ Heuristic,+ Model,+}++/// One-line harness-produced recap of a session's state, shown in the agent+/// overview (#419).+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]+#[serde(rename_all = "camelCase")]+#[ts(rename = "SessionRecap")]+pub struct SessionRecapDto {+ pub text: String,+ pub status: SessionRecapStatusDto,+ pub source: SessionRecapSourceDto,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, TS)]#[serde(rename_all = "camelCase")]#[ts(rename = "ConversationViewSnapshot")]@@ -132,6 +164,11 @@ pub struct ConversationViewSnapshotDto {#[serde(skip_serializing_if = "Option::is_none")]#[ts(optional)]pub goal: Option<String>,+ /// Latest harness `session_recap` for this chat (#419). Omitted until the+ /// first turn completes.+ #[serde(skip_serializing_if = "Option::is_none")]+ #[ts(optional)]+ pub recap: Option<SessionRecapDto>,pub followup: Option<super::followup::FollowupRequestDto>,}diff --git a/gui/src-tauri/src/runtime/simple.rs b/gui/src-tauri/src/runtime/simple.rsindex 4cd72300..0dd9c063 100644--- a/gui/src-tauri/src/runtime/simple.rs+++ b/gui/src-tauri/src/runtime/simple.rs@@ -43,6 +43,9 @@ struct ConversationState {/// (harness semantics). Surfaced to the GUI's task-progress dock.todos: Vec<SessionTodoDto>,goal: Option<String>,+ /// Latest harness `session_recap` (#419) — the agent overview's one-liner.+ /// Session-local: not persisted; a restored chat earns a fresh one.+ recap: Option<SessionRecapDto>,/// Persistent ultracode (multi-agent workflow) mode, scoped to this chat.ultracode_enabled: bool,updated_at: i64,@@ -526,6 +529,7 @@ impl RuntimeManager {ultracode_enabled: false,todos: Vec::new(),goal: None,+ recap: None,updated_at: now_millis(),});conversation.plan_mode = plan_mode;@@ -987,6 +991,18 @@ impl RuntimeManager {.await;self.emit().await?;}+ Some("session_recap") => {+ // #419: the harness's turn-end recap (heuristic first, a+ // cheap-model one possibly later) — session metadata, not+ // a chat message. Emitted before `turn`, so it lands here.+ if let Some(recap) = parse_session_recap(&event) {+ self.mutate_conversation(conversation_id, move |conversation| {+ conversation.recap = Some(recap);+ })+ .await;+ self.emit().await?;+ }+ }Some("turn") => break,Some("error") => {let raw_message = event@@ -1079,6 +1095,16 @@ impl RuntimeManager {continue;};match event.get("type").and_then(serde_json::Value::as_str) {+ // #419: a between-turns model recap can surface while we wait+ // for a control ack — keep it, and keep waiting for the ack.+ Some("session_recap") => {+ if let Some(recap) = parse_session_recap(&event) {+ self.mutate_conversation(conversation_id, move |conversation| {+ conversation.recap = Some(recap);+ })+ .await;+ }+ }Some("model" | "compact" | "mode" | "agent" | "effort" | "fast" | "ultracode") => {break event;}@@ -1789,6 +1815,7 @@ impl RuntimeManager {ultracode_enabled: false,todos: Vec::new(),goal: None,+ recap: None,updated_at: now_millis(),},);@@ -2499,6 +2526,7 @@ fn load_persisted_conversations() -> HashMap<String, ConversationState> {ultracode_enabled: conversation.ultracode_enabled,todos: Vec::new(),goal: conversation.goal,+ recap: None,updated_at: conversation.updated_at,},)@@ -2587,6 +2615,29 @@ fn first_workspace_conversation_id(state: &RuntimeState, workspace_path: &str) -.map(|conversation| conversation.conversation_id.clone())}+/// Parse a `session_recap` wire event (#419). Unknown/missing status or+/// source degrade to completed/heuristic; an empty text is not a recap.+fn parse_session_recap(event: &serde_json::Value) -> Option<SessionRecapDto> {+ let text = event.get("text")?.as_str()?.trim();+ if text.is_empty() {+ return None;+ }+ let status = match event.get("status").and_then(serde_json::Value::as_str) {+ Some("needs_input") => SessionRecapStatusDto::NeedsInput,+ Some("failed") => SessionRecapStatusDto::Failed,+ _ => SessionRecapStatusDto::Completed,+ };+ let source = match event.get("source").and_then(serde_json::Value::as_str) {+ Some("model") => SessionRecapSourceDto::Model,+ _ => SessionRecapSourceDto::Heuristic,+ };+ Some(SessionRecapDto {+ text: text.to_string(),+ status,+ source,+ })+}+fn conversation_view(conversation: &ConversationState,followup: Option<FollowupRequestDto>,@@ -2599,6 +2650,7 @@ fn conversation_view(request_agent_ids: conversation.request_agent_ids.clone(),todos: conversation.todos.clone(),goal: conversation.goal.clone(),+ recap: conversation.recap.clone(),followup,}}@@ -4276,6 +4328,7 @@ mod tests {ultracode_enabled: false,todos: Vec::new(),goal: None,+ recap: None,updated_at: 10,},);@@ -4683,6 +4736,7 @@ mod tests {ultracode_enabled: false,todos: Vec::new(),goal: None,+ recap: None,updated_at: 10,},);@@ -4701,6 +4755,7 @@ mod tests {ultracode_enabled: false,todos: Vec::new(),goal: None,+ recap: None,updated_at: 20,},);diff --git a/gui/src/services/desktop/types/contracts.generated.ts b/gui/src/services/desktop/types/contracts.generated.tsindex e1cebb22..70f1cf64 100644--- a/gui/src/services/desktop/types/contracts.generated.ts+++ b/gui/src/services/desktop/types/contracts.generated.ts@@ -25,6 +25,12 @@ export type SessionTodoStatus = "pending" | "in_progress" | "completed" | "canceexport type SessionTodo = { id: string, content: string, status: SessionTodoStatus, };+export type SessionRecapStatus = "needs_input" | "completed" | "failed";++export type SessionRecapSource = "heuristic" | "model";++export type SessionRecap = { text: string, status: SessionRecapStatus, source: SessionRecapSource, };+export type ConversationSessionSummary = { conversationId: string, title: string, updatedAt: string | null, isDraft: boolean, isRunning: boolean, hasPendingFollowup: boolean, };export type ChatBinding = { workspacePath: string, conversationId: string, };@@ -34,7 +40,12 @@ export type ConversationViewSnapshot = { workspacePath: string, conversationId:* Steering objective for this chat, set via `/goal`. Surfaced in the UI as* the goal chip above the composer. Omitted from the payload when unset.*/-goal?: string, followup: FollowupRequest | null, };+goal?: string,+/**+ * Latest harness `session_recap` for this chat (#419). Omitted until the+ * first turn completes.+ */+recap?: SessionRecap, followup: FollowupRequest | null, };export type WorkspaceKind = "project" | "managed_chat";diff --git a/gui/src/services/desktop/types/contracts.ts b/gui/src/services/desktop/types/contracts.tsindex 37a0a126..f2b7a4ff 100644--- a/gui/src/services/desktop/types/contracts.ts+++ b/gui/src/services/desktop/types/contracts.ts@@ -49,6 +49,9 @@ export type {SaveConversationLayoutInput,SendPromptInput,SessionMessage,+ SessionRecap,+ SessionRecapSource,+ SessionRecapStatus,SessionSnapshot,SessionTodo,SessionTodoStatus,diff --git a/src/agent.zig b/src/agent.zigindex 13e7f5f9..02db444e 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -200,6 +200,8 @@ pub const Agent = struct {thinking_text: std.ArrayList(u8) = .empty, // buffered reasoning, so a fold can unfold (#92)ai_title_done: bool = false, // the one-time AI tab-title call has run this sessiontitle_generation: u64 = 0, // invalidates detached results across /clear, /new, and manual /rename+ session_recap: ?@import("recap.zig").Recap = null, // last turn-end recap (#419): the session_recap wire event, and /status's recap line+ recap_generation: u64 = 0, // bumped at every turn start: supersedes detached recap jobs still in flight (#419)arg_live: ArgLive = .{}, // live attempt_completion/ask_user argument textstreamed_args: ArgTool = .none, // which meta tool's prose streamed live this requeststreamed_args_len: usize = 0, // raw bytes emitted for it (gates re-print suppression)diff --git a/src/commands_session.zig b/src/commands_session.zigindex 8607cf34..a9b1cfff 100644--- a/src/commands_session.zig+++ b/src/commands_session.zig@@ -90,6 +90,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.session_title = null; // re-summarize the now-empty conversationroot.ai_title_done = false;root.title_generation +%= 1;+ root.session_recap = null; // #419: nothing to recap in an empty conversation+ root.recap_generation +%= 1;root.todos.clearRetainingCapacity();const had_goal = root.goal != null;resetConversationSteering(root);@@ -112,6 +114,8 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,root.session_title = null;root.ai_title_done = false; // let the new session earn its own AI titleroot.title_generation +%= 1;+ root.session_recap = null;+ root.recap_generation +%= 1;root.tui_header_shown = false;root.session_name = try std.fmt.allocPrint(arena, "session-{d}", .{unixMs(root.io)});prompts.resetSessionCompacted(root, arena); // #445: after the rename, so the re-arm reads the NEW sessiondiff --git a/src/hooks.zig b/src/hooks.zigindex 71d769c8..d0a5ecab 100644--- a/src/hooks.zig+++ b/src/hooks.zig@@ -113,6 +113,15 @@ pub fn denialText(gpa: Allocator, h: Hook, stderr: []const u8) ?[]u8 {return std.fmt.allocPrint(gpa, "blocked by pre_tool hook: {s}{s}{s}", .{ msg, sep, h.suggest }) catch null;}+/// turn_end lifecycle hooks (best-effort): every configured hook gets the+/// success payload; stderr is freed here so the loop body stays lean.+pub fn runTurnEndHooks(gpa: Allocator, io: Io) void {+ for (root.g_hooks.turn_end) |h| {+ const res = runHookCmd(gpa, io, h.command, "{\"event\":\"turn_end\",\"ok\":true}", h.timeout_ms);+ if (res.stderr.len > 0) gpa.free(res.stderr);+ }+}+/// Run one hook command: /bin/sh -c, event JSON on stdin, stderr captured/// (capped), killed at its timeout. Returns the exit code (null on timeout/// or spawn failure) and the trimmed stderr (gpa-owned).diff --git a/src/main_test.zig b/src/main_test.zigindex ce02bfaf..e23da8fc 100644--- a/src/main_test.zig+++ b/src/main_test.zig@@ -323,6 +323,7 @@ test "/save and /resume report a failed name copy instead of ending the REPL" {// unreferenced module's test {} blocks silently compile to nothing.test {_ = @import("startup_tests.zig");+ _ = @import("recap.zig"); // #419: session-recap bounds/heuristic/parsing tests}test "failure (#253): fd-quota errors carry actionable advice, system-wide says ulimit won't help" {diff --git a/src/mainloop.zig b/src/mainloop.zigindex 381cb5ed..b6989d93 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -39,6 +39,7 @@ const hooks = @import("hooks.zig");const readline = @import("readline.zig");const title_mod = @import("title.zig");const mainloop_title = @import("mainloop_title.zig");+const mainloop_recap = @import("mainloop_recap.zig");const review = @import("review.zig");const terminal = @import("term.zig");@@ -61,6 +62,8 @@ pub const Ctx = struct {pub fn run(ctx: *Ctx) !void {var title_jobs: mainloop_title.Jobs = .{};defer title_jobs.deinit(ctx);+ var recap_jobs: mainloop_recap.Jobs = .{};+ defer recap_jobs.deinit(ctx);defer session.flushSavesAtExit(); // #273: the turn-path autosaves write in the background — no queued one may outlive this loop, on ANY exit (#364 stamps this teardown phase)defer ctx.root.closeCodexWs(); // #424: the held WS + response-id anchor deliberately span turns, so only loop exit may free them — without this they are the gpa's only exit leaksdefer terminal.tty.releaseTerminal(); // #396: registered LAST so LIFO runs it FIRST — the tty goes back before the save/telemetry/learning phases that can take seconds@@ -78,6 +81,7 @@ pub fn run(ctx: *Ctx) !void {while (true) {// Titles can land between interactions but never join the response path.title_jobs.poll(ctx);+ recap_jobs.poll(ctx); // #419: a settled model recap emits here, before the next read// Drain streamed follow-ups before reading fresh input (empty in JSON/GUI).repl_glue.resetSteerPartial();const steer_entry: ?repl_glue.SteerEntry = repl_glue.popSteer();@@ -114,6 +118,7 @@ pub fn run(ctx: *Ctx) !void {// The title may have completed while readline was waiting. Apply it// before starting the newly-entered turn, still without ever waiting.title_jobs.poll(ctx);+ recap_jobs.poll(ctx);const line = std.mem.trim(u8, raw_line, " \t\r");if (line.len == 0) continue;// `/goal [30m] <objective>` and `/loop [30m] <prompt>` are ONE autonomous run: same@@ -386,6 +391,7 @@ pub fn run(ctx: *Ctx) !void {ctx.root.pending_image = null;} else try ctx.root.messages.append(try messages.textMessage(ctx.arena, "user", ultracode_msg.text));ctx.root.snapshots.?.turn += 1; // tag file edits in this turn (matches /rewind numbering)+ ctx.root.recap_generation +%= 1; // #419: a starting turn supersedes any recap job still in flightif (telemetry.g_telem) |t| t.countTurn();// Trajectory: claim this turn's node id up front so subagents spawned during the turn can attach to it as their parent.const turn_id: u64 = if (trace.g_traj) |tj| blk: {@@ -516,6 +522,8 @@ pub fn run(ctx: *Ctx) !void {if (isolated_review)try ctx.root.messages.append(try messages.textMessage(ctx.arena, "assistant", final_text));const session_context_tokens = if (isolated_review) ctx.root.effectiveContextTokens() else post_turn_context_tokens;+ // #419: heuristic session_recap precedes the terminal turn event; model recap scheduled here.+ mainloop_recap.onTurnEnd(ctx, &recap_jobs, final_text);if (main_mod.json_mode) {const emitted_text = if (final_text.len == 0 and ctx.root.partial_text.items.len > 0)std.mem.trim(u8, ctx.root.partial_text.items, " \t\r\n")@@ -540,12 +548,7 @@ pub fn run(ctx: *Ctx) !void {// turn_end lifecycle hooks (best-effort; interrupted/errored turns// `continue` above and never reach here, so ok is always true).- if (main_mod.g_hooks.turn_end.len > 0) {- for (main_mod.g_hooks.turn_end) |h| {- const res = hooks.runHookCmd(ctx.gpa, ctx.io, h.command, "{\"event\":\"turn_end\",\"ok\":true}", h.timeout_ms);- if (res.stderr.len > 0) ctx.gpa.free(res.stderr);- }- }+ hooks.runTurnEndHooks(ctx.gpa, ctx.io);if (session_context_tokens >= ctx.root.provider.compactAt()) {// Trim on failure only when we're genuinely against the window — atdiff --git a/src/mainloop_recap.zig b/src/mainloop_recap.zignew file mode 100644index 00000000..793d6b2c--- /dev/null+++ b/src/mainloop_recap.zig@@ -0,0 +1,127 @@+//! Detached session-recap jobs for the root loop (#419) — mainloop_title.zig's+//! shape with a per-turn settle debounce. The caller context is generic so+//! this module stays independent of `mainloop.zig`'s orchestration type.+//!+//! Turn end emits the FREE recap synchronously (`onTurnEnd`: the heuristic+//! event precedes the terminal `turn` event so stream-until-turn clients like+//! the GUI always see it), then schedules the cheap-model recap. The job runs+//! while the loop idles; `poll` applies it only when no newer turn has+//! started (the generation check IS the debounce — a streaming turn bumps the+//! generation, so recaps never thrash mid-turn). Emission then happens at the+//! next poll point: in --json mode that is just before the next prompt is+//! read, which is the harness's first chance to write while blocked on stdin.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const main_mod = @import("main.zig");+const provider_mod = @import("provider.zig");+const recap_mod = @import("recap.zig");+const tier_ladder = @import("subagent_tier_ladder.zig");++const Recap = recap_mod.Recap;++const Job = struct {+ future: ?Io.Future(void) = null,+ input: []const u8, // gpa-owned digest: the session arena must stay off-thread+ result: ?Recap = null, // text gpa-owned, published before done.release+ done: std.atomic.Value(bool) = .init(false),+ generation: u64,+};++/// The cheapest rung the root provider's ladder knows (#291), as a ready+/// Provider. Null — silently, per #419 — when the family has no cheaper rung,+/// the root already sits on it, or no key exists for the provider.+fn cheapProvider(ctx: anytype) ?provider_mod.Provider {+ const root_p = ctx.root.provider;+ const ladder = tier_ladder.forProvider(root_p.id) orelse return null;+ const model = ladder.modelFor(.small) orelse ladder.modelFor(.mid) orelse return null;+ if (std.mem.eql(u8, model, root_p.model)) return null; // already bottom rung+ return ctx.keys.providerById(root_p.id, model) catch null;+}++fn publish(ctx: anytype, recap: Recap, source: []const u8) void {+ const stored = ctx.arena.dupe(u8, recap.text) catch return;+ ctx.root.session_recap = .{ .status = recap.status, .text = stored };+ if (main_mod.json_mode) ctx.root.emit(.{+ .type = "session_recap",+ .text = stored,+ .status = @tagName(recap.status),+ .source = source,+ });+}++/// Turn end, success path: the heuristic recap lands first (free, and ordered+/// before the terminal `turn` event), then the model recap is scheduled.+/// `final_text` borrows turn-scoped memory — everything the job keeps is+/// duped before it spawns.+pub fn onTurnEnd(ctx: anytype, jobs: *Jobs, final_text: []const u8) void {+ publish(ctx, recap_mod.heuristic(final_text, false), "heuristic");+ jobs.start(ctx);+}++fn detachedTask(job: *Job, gpa: Allocator, io: Io, client: *std.http.Client, provider: provider_mod.Provider, budget: ?*@import("run_budget.zig").RunBudget, tracer: ?*@import("trace.zig").Tracer) void {+ job.result = recap_mod.recapTask(gpa, io, client, provider, job.input, budget, tracer);+ job.done.store(true, .release);+}++/// Cheap-model recap jobs are polled without waiting and canceled at close.+pub const Jobs = struct {+ items: std.ArrayList(*Job) = .empty,++ fn start(self: *Jobs, ctx: anytype) void {+ // Same reserve as the AI title: cosmetic work never consumes the+ // final provider-call slot the root turn is owed.+ if (ctx.root.run_budget) |budget| if (budget.remaining() <= 1) return;+ const provider = cheapProvider(ctx) orelse return;+ const digest = recap_mod.buildDigest(ctx.arena, ctx.root.messages.items) catch return;+ if (digest.len == 0) return;+ const job = ctx.gpa.create(Job) catch return;+ const owned_input = ctx.gpa.dupe(u8, digest) catch {+ ctx.gpa.destroy(job);+ return;+ };+ job.* = .{ .input = owned_input, .generation = ctx.root.recap_generation };+ const args = .{ job, ctx.gpa, ctx.io, ctx.root.client, provider, ctx.root.run_budget, ctx.root.tracer };+ job.future = ctx.io.concurrent(detachedTask, args) catch ctx.io.async(detachedTask, args);+ self.items.append(ctx.gpa, job) catch {+ if (job.future) |*future| future.cancel(ctx.io);+ if (job.result) |recap| ctx.gpa.free(recap.text);+ ctx.gpa.free(job.input);+ ctx.gpa.destroy(job);+ };+ }++ pub fn poll(self: *Jobs, ctx: anytype) void {+ var i: usize = 0;+ while (i < self.items.items.len) {+ const job = self.items.items[i];+ if (!job.done.load(.acquire)) {+ i += 1;+ continue;+ }+ if (job.future) |*future| future.await(ctx.io); // done=true: never blocks+ job.future = null;+ if (job.result) |recap| {+ // A turn that started after this job was scheduled supersedes+ // it — the newer turn's own recap will describe the session.+ if (job.generation == ctx.root.recap_generation) publish(ctx, recap, "model");+ ctx.gpa.free(recap.text);+ }+ ctx.gpa.free(job.input);+ _ = self.items.orderedRemove(i);+ ctx.gpa.destroy(job);+ }+ }++ pub fn deinit(self: *Jobs, ctx: anytype) void {+ for (self.items.items) |job| {+ if (job.future) |*future| future.cancel(ctx.io);+ if (job.result) |recap| ctx.gpa.free(recap.text);+ ctx.gpa.free(job.input);+ ctx.gpa.destroy(job);+ }+ self.items.deinit(ctx.gpa);+ }+};diff --git a/src/recap.zig b/src/recap.zignew file mode 100644index 00000000..04383fdf--- /dev/null+++ b/src/recap.zig@@ -0,0 +1,300 @@+//! Session recaps (#419): a one-line "what is this session doing" summary plus+//! a coarse status, emitted harness-side as the `session_recap` wire event so+//! the GUI agent overview (and any other --json/serve client) can show every+//! session's state without watching its stream.+//!+//! Two sources, one event shape:+//! - heuristic: derived synchronously at turn end from the final text (free,+//! zero-latency) — the always-available floor, and the ONLY source when no+//! cheap model is reachable (no ladder rung, no key, call failed).+//! - model: a detached cheap-tier call over a strictly bounded digest of the+//! recent history (last 8 messages, 600 chars each, tool calls by name+//! only), scheduled at turn end and debounced by mainloop_recap.zig so a+//! streaming turn never thrashes it.+//!+//! The model reply contract is two lines — `STATUS: <NEEDS_INPUT|COMPLETED|+//! FAILED>` and `RECAP: <one line>` — parsed by parseModelReply; anything+//! unparseable is dropped (null), never emitted.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const messages = @import("messages.zig");+const providers = @import("providers.zig");+const provider_mod = @import("provider.zig");+const title_mod = @import("title.zig");++const Agent = agent_mod.Agent;+const Provider = provider_mod.Provider;+const Value = std.json.Value;++/// Coarse session state for the overview chip. `working` is deliberately+/// absent: recaps are computed at turn end, and mid-turn liveness is the+/// client's own streaming signals, not a recap.+pub const Status = enum {+ needs_input,+ completed,+ failed,++ pub fn parse(s: []const u8) ?Status {+ if (std.ascii.eqlIgnoreCase(s, "needs_input")) return .needs_input;+ if (std.ascii.eqlIgnoreCase(s, "completed")) return .completed;+ if (std.ascii.eqlIgnoreCase(s, "failed")) return .failed;+ return null;+ }+};++pub const Recap = struct {+ status: Status,+ text: []const u8,+};++// Strict input bounds (#419): cheap means the digest can never grow with the+// session — last N messages, each capped, tool calls named but never quoted.+pub const max_messages = 8;+pub const max_message_chars = 600;+/// Cap on the emitted one-liner, codepoints, word-boundaried like titles.+pub const max_recap_codepoints = 120;++/// First non-empty line of `s`, trimmed and capped at `max_codepoints`+/// codepoints on a word boundary (titleFromPrompt's convention). Empty when+/// nothing usable remains.+fn firstLine(s: []const u8, max_codepoints: usize) []const u8 {+ var it = std.mem.splitScalar(u8, s, '\n');+ while (it.next()) |line| {+ const trimmed = std.mem.trim(u8, line, " \t\r");+ if (trimmed.len == 0) continue;+ var end: usize = 0;+ var codepoints: usize = 0;+ while (end < trimmed.len and codepoints < max_codepoints) {+ const cp_len = std.unicode.utf8ByteSequenceLength(trimmed[end]) catch 1;+ end += cp_len;+ codepoints += 1;+ }+ var out = std.mem.trim(u8, trimmed[0..@min(end, trimmed.len)], " \t\r");+ if (codepoints >= max_codepoints and end < trimmed.len) {+ if (std.mem.lastIndexOfScalar(u8, out, ' ')) |sp| {+ if (sp >= 12) out = std.mem.trim(u8, out[0..sp], " ");+ }+ }+ return out;+ }+ return "";+}++/// The no-model recap: the turn's own closing line is the summary, and a+/// closing question reads as waiting on the human. `errored` marks the+/// stall/drop/api-failure paths so the chip says failed, not completed.+pub fn heuristic(final_text: []const u8, errored: bool) Recap {+ if (errored) return .{ .status = .failed, .text = "Turn ended on an error" };+ const line = firstLine(final_text, max_recap_codepoints);+ if (line.len == 0) return .{ .status = .completed, .text = "Turn complete" };+ const status: Status = if (line[line.len - 1] == '?') .needs_input else .completed;+ return .{ .status = status, .text = line };+}++/// One digest line for a history message: a role/type label, tool calls by+/// name only, and text capped at max_message_chars. Returns "" for messages+/// with neither text nor tool names (images, control envelopes).+fn digestLine(arena: Allocator, m: Value) ![]const u8 {+ if (m != .object) return "";+ const obj = m.object;+ const label: []const u8 = blk: {+ if (obj.get("role")) |r| if (r == .string) break :blk r.string;+ if (obj.get("type")) |t| if (t == .string) break :blk t.string;+ break :blk "message";+ };+ var b: std.ArrayList(u8) = .empty;+ try b.appendSlice(arena, label);+ // Tool calls by name only: openai tool_calls[], anthropic tool_use+ // blocks, responses function_call items — never their arguments.+ var named: usize = 0;+ if (obj.get("tool_calls")) |tc| if (tc == .array) {+ for (tc.array.items) |call| {+ if (call != .object) continue;+ const name_value = if (call.object.get("function")) |f| blk: {+ if (f != .object) break :blk null;+ break :blk f.object.get("name");+ } else call.object.get("name");+ if (name_value) |n| if (n == .string) {+ try b.appendSlice(arena, if (named == 0) " called " else ", ");+ try b.appendSlice(arena, n.string);+ named += 1;+ };+ }+ };+ if (obj.get("content")) |c| if (c == .array) {+ for (c.array.items) |blk_item| {+ if (blk_item != .object) continue;+ const bt = if (blk_item.object.get("type")) |t| (if (t == .string) t.string else "") else "";+ if (std.mem.eql(u8, bt, "tool_use") or std.mem.eql(u8, bt, "function_call"))+ if (blk_item.object.get("name")) |n| if (n == .string) {+ try b.appendSlice(arena, if (named == 0) " called " else ", ");+ try b.appendSlice(arena, n.string);+ named += 1;+ };+ }+ };+ // Text: providers.extractText covers string content and text-block+ // arrays; responses function_call_output carries its result in "output".+ var text = providers.extractText(arena, m);+ if (text.len == 0)+ if (obj.get("output")) |o| if (o == .string) {+ text = o.string;+ };+ const line = firstLine(text, max_message_chars);+ if (line.len > 0) {+ try b.appendSlice(arena, ": ");+ try b.appendSlice(arena, line);+ }+ if (named == 0 and line.len == 0) return "";+ return b.items;+}++/// The bounded recap digest handed to the cheap model: the last+/// max_messages history messages, one line each. Arena-owned.+pub fn buildDigest(arena: Allocator, history: []const Value) ![]const u8 {+ const start = if (history.len > max_messages) history.len - max_messages else 0;+ var b: std.ArrayList(u8) = .empty;+ for (history[start..]) |m| {+ const line = digestLine(arena, m) catch continue;+ if (line.len == 0) continue;+ try b.appendSlice(arena, line);+ try b.append(arena, '\n');+ }+ return b.items;+}++/// Parse the cheap model's two-line reply. Lenient about ordering, blank+/// lines and case; strict about the RECAP line existing — without it the+/// reply is not a recap and the caller keeps the heuristic one.+pub fn parseModelReply(reply: []const u8) ?Recap {+ var status: Status = .completed;+ var text: []const u8 = "";+ var it = std.mem.splitScalar(u8, reply, '\n');+ while (it.next()) |raw| {+ const line = std.mem.trim(u8, raw, " \t\r");+ if (std.ascii.startsWithIgnoreCase(line, "status:")) {+ if (Status.parse(std.mem.trim(u8, line["status:".len..], " \t"))) |s| status = s;+ } else if (std.ascii.startsWithIgnoreCase(line, "recap:")) {+ text = firstLine(line["recap:".len..], max_recap_codepoints);+ }+ }+ if (text.len == 0) return null;+ return .{ .status = status, .text = text };+}++/// Detached cheap-model recap over the bounded digest — titleTask's shape:+/// its own arena, a throwaway one-message sub-Agent, a tiny output cap, null+/// on any failure (no auth, transport, unparseable reply) so the caller+/// silently keeps the heuristic recap. `input` must be gpa/stable-owned: the+/// task reads it off-thread. Result text is gpa-owned; caller frees.+pub fn recapTask(gpa: Allocator, io: Io, client: *std.http.Client, provider: Provider, input: []const u8, run_budget: ?*@import("run_budget.zig").RunBudget, tracer: ?*@import("trace.zig").Tracer) ?Recap {+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var agent: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = client,+ .provider = provider,+ .messages = std.json.Array.init(arena),+ .sub = true, // pool thread: never touches stdout or the main agent's state+ .label = "recap",+ .out = null,+ .tracer = tracer,+ .run_budget = run_budget,+ .call_kind = .recap,+ .responses_output_limit = 128,+ .sys_override = "You write one-line status recaps of coding sessions for a multi-session dashboard. Reply with EXACTLY two lines:\nSTATUS: <NEEDS_INPUT|COMPLETED|FAILED>\nRECAP: <one line, present tense, at most 120 characters — what the agent just did or is waiting on>\nNEEDS_INPUT means the session is waiting on the human (a question, an approval); COMPLETED means the last task finished; FAILED means it ended on an error.",+ };+ defer agent.tools_used.deinit(gpa);+ const instr = std.fmt.allocPrint(arena, "Recent session activity (latest last; tool calls shown by name only):\n{s}", .{input}) catch return null;+ agent.messages.append(messages.textMessage(arena, "user", instr) catch return null) catch return null;+ const root = agent.request(null) catch return null;+ const recap = parseModelReply(title_mod.assistantText(provider.kind, root)) orelse return null;+ return .{ .status = recap.status, .text = gpa.dupe(u8, recap.text) catch return null };+}++test "heuristic: closing line is the recap, a trailing question means needs_input" {+ const done = heuristic("Fixed the parser and added tests.", false);+ try std.testing.expectEqual(Status.completed, done.status);+ try std.testing.expectEqualStrings("Fixed the parser and added tests.", done.text);+ const asking = heuristic("I can do either. Which one do you want?", false);+ try std.testing.expectEqual(Status.needs_input, asking.status);+ const empty = heuristic(" \n ", false);+ try std.testing.expectEqual(Status.completed, empty.status);+ try std.testing.expect(empty.text.len > 0); // never an empty chip+ const err = heuristic("partial", true);+ try std.testing.expectEqual(Status.failed, err.status);+}++test "heuristic: multi-line replies recap to their first line, capped on a word boundary" {+ const line = heuristic("First line says it all.\nSecond line is detail.", false);+ try std.testing.expectEqualStrings("First line says it all.", line.text);+ var long: [400]u8 = undefined;+ @memset(&long, 'x');+ // spaces every 10 chars so the word-boundary backoff has somewhere to go+ var i: usize = 10;+ while (i < long.len) : (i += 11) long[i] = ' ';+ const capped = heuristic(&long, false);+ try std.testing.expect(capped.text.len <= max_recap_codepoints);+ try std.testing.expect(capped.text.len >= 12); // backoff never strands a stub+}++test "buildDigest: bounds history to the last 8 messages and caps each line" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var history: std.ArrayList(Value) = .empty;+ var i: usize = 0;+ while (i < 12) : (i += 1) {+ const text = try std.fmt.allocPrint(arena, "message number {d}", .{i});+ try history.append(arena, try messages.textMessage(arena, "user", text));+ }+ const digest = try buildDigest(arena, history.items);+ try std.testing.expect(std.mem.indexOf(u8, digest, "message number 3") == null); // older than the window+ try std.testing.expect(std.mem.indexOf(u8, digest, "message number 11") != null);+ var lines: usize = 0;+ var it = std.mem.splitScalar(u8, std.mem.trim(u8, digest, "\n"), '\n');+ while (it.next()) |_| lines += 1;+ try std.testing.expectEqual(@as(usize, max_messages), lines);+}++test "buildDigest: tool calls appear by name only, never with arguments" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var msg: std.json.ObjectMap = .empty;+ try msg.put(arena, "role", .{ .string = "assistant" });+ var call: std.json.ObjectMap = .empty;+ var function: std.json.ObjectMap = .empty;+ try function.put(arena, "name", .{ .string = "bash" });+ try function.put(arena, "arguments", .{ .string = "{\"command\":\"rm -rf /\"}" });+ try call.put(arena, "function", .{ .object = function });+ var calls: std.json.Array = .init(arena);+ try calls.append(.{ .object = call });+ try msg.put(arena, "tool_calls", .{ .array = calls });+ var history = std.json.Array.init(arena);+ try history.append(.{ .object = msg });+ const digest = try buildDigest(arena, history.items);+ try std.testing.expect(std.mem.indexOf(u8, digest, "bash") != null);+ try std.testing.expect(std.mem.indexOf(u8, digest, "rm -rf") == null); // arguments never quoted+}++test "parseModelReply: two-line contract, case- and order-lenient, strict on RECAP" {+ const recap = parseModelReply("STATUS: NEEDS_INPUT\nRECAP: Waiting on the user to pick a layout").?;+ try std.testing.expectEqual(Status.needs_input, recap.status);+ try std.testing.expectEqualStrings("Waiting on the user to pick a layout", recap.text);+ const swapped = parseModelReply("recap: shipped the fix\nstatus: completed").?;+ try std.testing.expectEqual(Status.completed, swapped.status);+ // unknown status degrades to completed rather than failing the recap+ try std.testing.expectEqual(Status.completed, parseModelReply("STATUS: BORED\nRECAP: still going").?.status);+ // no RECAP line → not a recap at all+ try std.testing.expect(parseModelReply("STATUS: COMPLETED") == null);+ try std.testing.expect(parseModelReply("just some prose") == null);+ try std.testing.expect(parseModelReply("") == null);+}diff --git a/src/run_budget.zig b/src/run_budget.zigindex 6b3f913a..c910e9e2 100644--- a/src/run_budget.zig+++ b/src/run_budget.zig@@ -27,6 +27,7 @@ pub const CallKind = enum {workflow_retry,judge,title,+ recap,compaction,};diff --git a/src/schema.zig b/src/schema.zigindex 98948b42..bcb33fd4 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -387,7 +387,7 @@ fn writeToolEntry(s: *std.json.Stringify, kind: Provider.Kind, name: []const u8,/// a per-commit git describe) — bump this only when the schema or JSONL/// protocol changes shape, so SDK regeneration stays byte-stable across/// commits.-pub const schema_version = "0.10"; // #330: every --json/serve event carries a monotonic `seq`+pub const schema_version = "0.11"; // #419: session_recap event (one-line session summary + status, heuristic/model)/// Emit the machine-readable interface description for `harness --schema`:/// providers, models, built-in tools (name/description/parameters), and thediff --git a/src/schema_protocol.zig b/src/schema_protocol.zigindex 9e078764..9457c591 100644--- a/src/schema_protocol.zig+++ b/src/schema_protocol.zig@@ -47,6 +47,7 @@ pub const json =\\ {"type": "tool_call_finished", "name": "tool", "is_error": false, "ms": 0},\\ {"type": "agent_usage", "id": "sa-...", "ok": true, "duration_ms": 0, "tool_calls": 0, "context_tokens": 0, "cache_read_tokens": 0},\\ {"type": "finalizing"},+ \\ {"type": "session_recap", "text": "one-line session summary", "status": "needs_input|completed|failed", "source": "heuristic|model (heuristic precedes every completed turn's terminal event; a model recap may follow later)"},\\ {"type": "turn", "text": "final assistant text", "context_tokens": 0, "cost_usd": 0.0, "complete": true, "metadata_complete": true},\\ {"type": "system_prompt", "ok": true, "append": false, "chars": 0},\\ {"type": "model", "ok": true, "provider": "provider", "model": "model", "context": 0, "note": "context kept"},