Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix: eleven more open issues (#261 #63 #296 #289 #309 #307 #285 #317 #312 #314 #102 #108 #249 #321 #112 #320 #270 #253)

justrach14ce01585e49
diff --git a/apps/ios/Graff/Sources/ChatView.swift b/apps/ios/Graff/Sources/ChatView.swift
index dcd077f8..0ff00cc5 100644
--- a/apps/ios/Graff/Sources/ChatView.swift
+++ b/apps/ios/Graff/Sources/ChatView.swift
@@ -13,6 +13,9 @@ struct ChatView: View {
@State private var serveSessionID: String?
@State private var streaming = false
@State private var didAutoSend = false
+ // #59: the streaming task was discarded, so the composer's "working" glyph
+ // was a dead button. Holding it makes stop a real action.
+ @State private var turnTask: Task<Void, Never>?
private enum CubeLiveness { case unknown, alive, stopped, gone }
@State private var cubeLiveness: CubeLiveness = .unknown
@@ -41,6 +44,14 @@ struct ChatView: View {
withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }
}
}
+ // A turn that ends with no new text still changes what the row
+ // says (#307/#285): scroll so the failure notice is not left
+ // hidden behind the composer.
+ .onChange(of: session.messages.last?.state) {
+ if let last = session.messages.last {
+ withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }
+ }
+ }
}
if session.planPending {
@@ -70,7 +81,7 @@ struct ChatView: View {
Composer(draft: $draft, streaming: streaming,
disabled: session.cube != nil && cubeLiveness != .alive && cubeLiveness != .unknown,
- onSend: send)
+ onSend: send, onStop: stop)
.padding(.horizontal)
.padding(.bottom, 8)
}
@@ -95,7 +106,18 @@ struct ChatView: View {
session.messages.append(ChatMessage(role: .user, text: t))
streaming = true
session.status = .working
- Task { await runTurn(t) }
+ announce("Message sent. Assistant is responding.")
+ turnTask = Task { await runTurn(t) }
+ }
+
+ // #59: cancelling the turn task terminates the NDJSON stream (the client
+ // already wires onTermination) and runTurn records .cancelled on the turn.
+ private func stop() { turnTask?.cancel() }
+
+ // #317: VoiceOver gets nothing out of an animated dot row, so the start and
+ // the terminal state of a turn are spoken once each - not per token.
+ private func announce(_ message: String) {
+ AccessibilityNotification.Announcement(message).post()
}
// For cube sessions the agent is told where it is and what credentials it
@@ -114,38 +136,64 @@ struct ChatView: View {
@MainActor
private func runTurn(_ text: String) async {
- defer { streaming = false }
+ defer { streaming = false; turnTask = nil }
+ var turnID: UUID?
+ var outcome: TurnState = .completed
do {
if serveSessionID == nil {
serveSessionID = try await client.createSession(model: session.model,
yolo: session.cube != nil,
appendSystemPrompt: cubeSystemNote)
}
- session.messages.append(ChatMessage(role: .assistant, text: ""))
- let idx = session.messages.count - 1
+ // #309: the row is addressed by its stable id for the rest of the
+ // turn - hydration may rewrite session.messages under us.
+ let placeholder = ChatMessage(role: .assistant, text: "", state: .streaming)
+ let id = placeholder.id
+ turnID = id
+ session.messages.append(placeholder)
for try await ev in client.streamTurn(sessionID: serveSessionID!, text: text) {
switch ev {
case .reasoning(let r):
- session.messages[idx].reasoning = (session.messages[idx].reasoning ?? "") + r
+ session.messages.updateTurn(id) { $0.reasoning = ($0.reasoning ?? "") + r }
case .text(let d):
- session.messages[idx].text += d
+ session.messages.updateTurn(id) { $0.text += d }
case .turn(let final, _, _):
- session.messages[idx].text = final
+ session.messages.updateTurn(id) { $0.text = final }
case .error(let m):
- session.messages[idx].text = "Error: " + m
+ // #285: a server-reported error is not model prose, so it
+ // lands on the turn's state rather than in its text.
+ outcome = .failed(m)
case .toolCall(let name):
- session.messages[idx].reasoning = ((session.messages[idx].reasoning ?? "") + "\n⚙️ \(name)")
- .trimmingCharacters(in: .whitespacesAndNewlines)
+ session.messages.updateTurn(id) {
+ $0.reasoning = (($0.reasoning ?? "") + "\n⚙️ \(name)")
+ .trimmingCharacters(in: .whitespacesAndNewlines)
+ }
case .other:
break
}
}
- session.status = .idle
+ // Falling out of the loop without a throw means a terminal event
+ // arrived - the client reports a bare EOF as prematureEnd (#307).
+ // A cancelled consumer ends the stream quietly, so ask (#59).
+ if Task.isCancelled { outcome = .cancelled }
} catch {
- session.messages.append(ChatMessage(role: .assistant,
- text: "Transport error: \(error.localizedDescription)"))
- session.status = .idle
+ outcome = Task.isCancelled ? .cancelled : .failed(error.localizedDescription)
}
+ if let turnID {
+ // #285: one submission, one assistant record - the failure updates
+ // the turn it belongs to instead of appending a second bubble.
+ session.messages.updateTurn(turnID) { $0.state = outcome }
+ } else if case .failed(let why) = outcome {
+ // createSession failed before any placeholder existed; the failure
+ // still needs exactly one record to sit on.
+ session.messages.append(ChatMessage(role: .assistant, text: "", state: .failed(why)))
+ }
+ switch outcome {
+ case .failed(let why): announce("Turn failed. \(why)")
+ case .cancelled: announce("Turn stopped.")
+ case .completed, .streaming: announce("Assistant finished responding.")
+ }
+ session.status = .idle
session.lastActivity = "just now"
AppSessionSync.save(session)
}
@@ -154,8 +202,16 @@ struct ChatView: View {
private func hydrateIfNeeded() async {
guard session.needsHydration, !didHydrate else { return }
didHydrate = true
+ let localCount = session.messages.count
if let full = try? await Gateway.fetchAppSession(session.id.uuidString.lowercased()) {
- session.messages = AppSessionSync.messages(fromTranscript: full.transcript)
+ // #309: the composer stays live while this request is in flight, so
+ // anything appended meanwhile belongs to the running turn. History
+ // is restored in front of it instead of replacing the array
+ // wholesale, which used to erase a just-sent message.
+ let live = session.messages.count > localCount
+ ? Array(session.messages[localCount...])
+ : []
+ session.messages = AppSessionSync.messages(fromTranscript: full.transcript) + live
session.needsHydration = false
}
}
@@ -220,6 +276,28 @@ struct TaskProgressCard: View {
struct MessageBubble: View {
let message: ChatMessage
private var isBlank: Bool { message.text.isEmpty && (message.reasoning?.isEmpty ?? true) }
+ // #307: only a turn that is actually streaming may animate. Emptiness is
+ // not evidence of progress - a failed turn, or a blank record reloaded from
+ // history, used to keep the dots pulsing forever.
+ private var isTyping: Bool {
+ message.role == .assistant && message.state == .streaming && isBlank
+ }
+
+ // #317: the whole bubble is one VoiceOver element that says who spoke, what
+ // was said, and how the turn ended - not three decorative circles.
+ private var voiceOverLabel: String {
+ var parts = [message.role == .user ? "You said" : "Assistant"]
+ if let r = message.reasoning, !r.isEmpty { parts.append("Reasoning: \(r)") }
+ if !message.text.isEmpty { parts.append(message.text) }
+ switch message.state {
+ case .streaming: if isBlank { parts.append("Responding") }
+ case .failed(let why): parts.append("Turn failed: \(why)")
+ case .cancelled: parts.append("Turn stopped")
+ case .completed: break
+ }
+ return parts.joined(separator: ". ")
+ }
+
var body: some View {
HStack {
if message.role == .user { Spacer(minLength: 40) }
@@ -232,9 +310,20 @@ struct MessageBubble: View {
if !message.text.isEmpty {
Text(message.text)
.foregroundStyle(message.role == .user ? Color.white : Color.primary)
- } else if message.role == .assistant && isBlank {
+ } else if isTyping {
TypingIndicator()
}
+ // #285: the failure reason is turn metadata, rendered as such,
+ // so it can never be mistaken for model-authored text.
+ if case .failed(let why) = message.state {
+ Label(why, systemImage: "exclamationmark.triangle.fill")
+ .font(.caption)
+ .foregroundStyle(.red)
+ } else if message.state == .cancelled {
+ Label("Stopped", systemImage: "stop.circle")
+ .font(.caption)
+ .foregroundStyle(.secondary)
+ }
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
@@ -242,12 +331,16 @@ struct MessageBubble: View {
.clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
if message.role == .assistant { Spacer(minLength: 40) }
}
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel(voiceOverLabel)
+ .accessibilityAddTraits(message.state == .streaming ? .updatesFrequently : [])
}
}
// Three pulsing dots shown in the assistant bubble while a turn is in flight
// but no reasoning/text has streamed yet (e.g. during a tool call) - so an
-// in-progress turn never looks like an empty, stuck bubble.
+// in-progress turn never looks like an empty, stuck bubble. Shown only for a
+// .streaming turn (#307), and spoken as one status element (#317).
struct TypingIndicator: View {
@State private var animating = false
var body: some View {
@@ -263,6 +356,9 @@ struct TypingIndicator: View {
}
.padding(.vertical, 2)
.onAppear { animating = true }
+ .accessibilityElement(children: .ignore)
+ .accessibilityLabel("Assistant is responding")
+ .accessibilityAddTraits(.updatesFrequently)
}
}
@@ -291,6 +387,9 @@ struct Composer: View {
var streaming: Bool = false
var disabled: Bool = false
let onSend: () -> Void
+ // #59: while a turn streams the button is a live stop, not a greyed-out
+ // ellipsis whose action is still onSend.
+ var onStop: () -> Void = {}
var body: some View {
HStack(spacing: 10) {
TextField(disabled ? "Resume the cube to continue" : "Type a message", text: $draft, axis: .vertical)
@@ -299,12 +398,18 @@ struct Composer: View {
.padding(.vertical, 11)
.glassCapsule()
.disabled(streaming || disabled)
- Button(action: onSend) {
- Image(systemName: streaming ? "ellipsis" : "arrow.up")
+ .accessibilityLabel("Message")
+ .accessibilityHint(streaming
+ ? "Unavailable while the assistant is responding"
+ : "Write a message to the assistant")
+ Button(action: streaming ? onStop : onSend) {
+ Image(systemName: streaming ? "stop.fill" : "arrow.up")
.font(.headline.weight(.bold))
}
.buttonStyle(.glassProminent)
- .disabled(streaming || disabled || draft.trimmingCharacters(in: .whitespaces).isEmpty)
+ .tint(streaming ? .red : nil)
+ .disabled(!streaming && (disabled || draft.trimmingCharacters(in: .whitespaces).isEmpty))
+ .accessibilityLabel(streaming ? "Stop responding" : "Send message")
}
}
}
diff --git a/apps/ios/Graff/Sources/CubeBroker.swift b/apps/ios/Graff/Sources/CubeBroker.swift
index 735def60..9ae0552d 100644
--- a/apps/ios/Graff/Sources/CubeBroker.swift
+++ b/apps/ios/Graff/Sources/CubeBroker.swift
@@ -10,6 +10,24 @@ struct CubeConnection: Codable, Equatable {
let serveToken: String
let previewToken: String?
var githubLogin: String? = nil // set when the cube carries repo access
+ // When the installation token wired into this cube dies. A cube outlives
+ // its 1-hour token, and the reuse fast path used to hand the connection
+ // straight back (#314) — so git/gh inside kept running on dead credentials
+ // while the chat still told the model GitHub was wired up.
+ var githubTokenExpiry: Date? = nil
+
+ // Re-mint a few minutes early: a turn that starts on a nearly-dead token
+ // still has to finish its clone/push.
+ static let githubRefreshSkew: TimeInterval = 5 * 60
+
+ // Nothing to refresh when the cube never carried repo access. An expiry we
+ // never recorded (a connection stored before #314) counts as expired — its
+ // real age is unknowable, so assume the worst and re-key once.
+ func githubNeedsRefresh(asOf now: Date = Date()) -> Bool {
+ guard githubLogin != nil else { return false }
+ guard let expiry = githubTokenExpiry else { return true }
+ return expiry.timeIntervalSince(now) <= Self.githubRefreshSkew
+ }
private static let account = "cube-connection"
static func stored() -> CubeConnection? {
@@ -30,6 +48,17 @@ struct MintedGitHub: Decodable {
let token: String
let expires_at: String
let account_login: String
+
+ // #314: the wire carries an ISO-8601 instant; the stored connection needs a
+ // Date it can compare against on reuse. An unparseable stamp falls back to
+ // an hour out, which is what the endpoint promises anyway.
+ var expiry: Date {
+ let f = ISO8601DateFormatter()
+ if let d = f.date(from: expires_at) { return d }
+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
+ if let d = f.date(from: expires_at) { return d }
+ return Date().addingTimeInterval(3600)
+ }
}
// Client-side mirror of `graff cube new` (the CLI got the capability first).
@@ -49,88 +78,129 @@ enum CubeBroker {
static func launch(purpose: String, onStep: @escaping @MainActor (String) -> Void) async throws -> CubeConnection {
var resumeID: String? = nil
var wasRunning = false
+ var refreshingGitHub = false
if let old = CubeConnection.stored() {
await onStep("Checking the last cube…")
let state = (try? await Gateway.sandboxInfo(old.sandboxID))?.state ?? "gone"
- if state == "started" && !old.base.isEmpty && !old.serveToken.isEmpty {
+ let staleGitHub = old.githubNeedsRefresh()
+ if state == "started" && !old.base.isEmpty && !old.serveToken.isEmpty && !staleGitHub {
await onStep("Reusing the running cube (no new spin-up cost)")
return old
}
// started-but-credential-less happens when a history row from
// another device seeded the stored connection: re-key it in place.
+ // A running cube whose installation token has aged out lands here
+ // too (#314): the token is baked into the serve process environment
+ // as much as into the credential files, so a re-key — mint, rewrite,
+ // restart serve — is what makes the "fresh token every bring-up"
+ // promise above true on the reuse path. Still no reinstall, so this
+ // stays the cheap rung of the ladder.
if state == "started" || state == "stopped" {
resumeID = old.sandboxID
wasRunning = state == "started"
+ refreshingGitHub = wasRunning && staleGitHub
} else {
CubeConnection.clearStored()
}
}
- let id: String
- if let rid = resumeID {
- await onStep(wasRunning ? "Re-keying the running cube (no reinstall)…"
- : "Waking the stopped cube (cheaper — no reinstall)…")
- if !wasRunning { _ = try await Gateway.startSandbox(rid) }
- id = rid
- } else {
- await onStep("Creating sandbox (full spin-up)…")
- id = try await Gateway.createSandbox(purpose: purpose).id
- }
+ // #312: what this launch is on the hook for. The New Session sheet can
+ // be dismissed mid-provisioning; the cube this launch paid to bring up
+ // then has to go back down (Gateway.createSandbox's autoStopMinutes: 30
+ // caps the bleed, it never undoes the spin-up). A cube that was already
+ // running when we found it is not ours to stop.
+ var broughtUp: String? = nil
+ do {
+ let id: String
+ if let rid = resumeID {
+ await onStep(refreshingGitHub
+ ? "GitHub token expired — re-keying the cube (no reinstall)…"
+ : wasRunning ? "Re-keying the running cube (no reinstall)…"
+ : "Waking the stopped cube (cheaper — no reinstall)…")
+ if !wasRunning {
+ _ = try await Gateway.startSandbox(rid)
+ broughtUp = rid
+ }
+ id = rid
+ } else {
+ // #312: never buy a cube for a sheet that is already gone.
+ try Task.checkCancellation()
+ await onStep("Creating sandbox (full spin-up)…")
+ id = try await Gateway.createSandbox(purpose: purpose).id
+ broughtUp = id
+ }
- var state = ""
- var waits = 0
- while state != "started" && waits < 60 {
- state = (try? await Gateway.sandboxInfo(id).state) ?? state
- if state == "started" { break }
- try await Task.sleep(for: .seconds(2))
- waits += 1
- }
- guard state == "started" else { throw StepError(message: "sandbox never reached started (\(state))") }
-
- if resumeID == nil {
- await onStep("Installing graff…")
- let inst = try await Gateway.exec(id,
- command: "curl -fsSL https://raw.githubusercontent.com/justrach/codegraff/main/install.sh | bash",
- timeoutSeconds: 120)
- guard inst.exitCode == 0 else {
- throw StepError(message: "graff install failed: \(String((inst.result ?? "").suffix(200)))")
+ var state = ""
+ var waits = 0
+ while state != "started" && waits < 60 {
+ state = (try? await Gateway.sandboxInfo(id).state) ?? state
+ if state == "started" { break }
+ try await Task.sleep(for: .seconds(2))
+ waits += 1
}
- }
+ guard state == "started" else { throw StepError(message: "sandbox never reached started (\(state))") }
- // Fresh token every bring-up — the previous one expires after an hour.
- let github = await provisionGitHub(sandboxID: id, onStep: onStep)
+ if resumeID == nil {
+ await onStep("Installing graff…")
+ let inst = try await Gateway.exec(id,
+ command: "curl -fsSL https://raw.githubusercontent.com/justrach/codegraff/main/install.sh | bash",
+ timeoutSeconds: 120)
+ guard inst.exitCode == 0 else {
+ throw StepError(message: "graff install failed: \(String((inst.result ?? "").suffix(200)))")
+ }
+ }
- // A resumed cube may still have an old serve bound to the port
- // (re-key case, or a crashed-but-lingering process after a wake).
- if resumeID != nil {
- _ = try? await Gateway.exec(id, command: "pkill -f 'graff serve' >/dev/null 2>&1; sleep 1; true", timeoutSeconds: 20)
- }
- await onStep("Starting graff serve…")
- guard let key = Gateway.apiKey else { throw StepError(message: "not signed in") }
- let token = freshToken()
- let env = github.map { "CODEGRAFF_API_KEY=\(key) GH_TOKEN=\($0.token) GITHUB_LOGIN=\($0.account_login)" }
- ?? "CODEGRAFF_API_KEY=\(key)"
- _ = try await Gateway.exec(id,
- command: "\(env) exec $HOME/bin/graff serve --host 0.0.0.0 --port \(port) --token \(token)",
- timeoutSeconds: 60, async: true)
- var up = false
- for _ in 0..<20 {
- if let probe = try? await Gateway.exec(id,
- command: "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:\(port)/", timeoutSeconds: 15) {
- let code = (probe.result ?? "").trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n'"))
- if !code.isEmpty && code != "000" { up = true; break }
+ // Fresh token every bring-up — the previous one expires after an hour.
+ let github = await provisionGitHub(sandboxID: id, onStep: onStep)
+ // provisionGitHub swallows its own errors, cancellation included, so
+ // ask again before spending anything more on an abandoned launch (#312).
+ try Task.checkCancellation()
+
+ // A resumed cube may still have an old serve bound to the port
+ // (re-key case, or a crashed-but-lingering process after a wake).
+ if resumeID != nil {
+ _ = try? await Gateway.exec(id, command: "pkill -f 'graff serve' >/dev/null 2>&1; sleep 1; true", timeoutSeconds: 20)
+ }
+ await onStep("Starting graff serve…")
+ guard let key = Gateway.apiKey else { throw StepError(message: "not signed in") }
+ let token = freshToken()
+ let env = github.map { "CODEGRAFF_API_KEY=\(key) GH_TOKEN=\($0.token) GITHUB_LOGIN=\($0.account_login)" }
+ ?? "CODEGRAFF_API_KEY=\(key)"
+ _ = try await Gateway.exec(id,
+ command: "\(env) exec $HOME/bin/graff serve --host 0.0.0.0 --port \(port) --token \(token)",
+ timeoutSeconds: 60, async: true)
+ var up = false
+ for _ in 0..<20 {
+ if let probe = try? await Gateway.exec(id,
+ command: "curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:\(port)/", timeoutSeconds: 15) {
+ let code = (probe.result ?? "").trimmingCharacters(in: CharacterSet(charactersIn: " \t\r\n'"))
+ if !code.isEmpty && code != "000" { up = true; break }
+ }
+ try await Task.sleep(for: .seconds(1))
+ }
+ guard up else { throw StepError(message: "serve never came up in the sandbox") }
+
+ await onStep("Minting preview URL…")
+ let pv = try await Gateway.preview(id, port: port)
+ let base = pv.url.hasSuffix("/") ? String(pv.url.dropLast()) : pv.url
+ let conn = CubeConnection(sandboxID: id, base: base, serveToken: token,
+ previewToken: pv.token, githubLogin: github?.account_login,
+ githubTokenExpiry: github?.expiry)
+ conn.store()
+ return conn
+ } catch {
+ // #312: put back only what this launch brought up, and only when the
+ // caller walked away — a genuine spin-up failure keeps its sandbox so
+ // the next attempt can resume it instead of paying again.
+ if Task.isCancelled, let id = broughtUp {
+ await onStep("Cancelled — stopping the cube…")
+ // Detached on purpose: every URLSession call made from a
+ // cancelled task fails instantly, and this rollback is the one
+ // thing that still has to happen.
+ await Task.detached { _ = try? await Gateway.stopSandbox(id) }.value
}
- try await Task.sleep(for: .seconds(1))
+ throw error
}
- guard up else { throw StepError(message: "serve never came up in the sandbox") }
-
- await onStep("Minting preview URL…")
- let pv = try await Gateway.preview(id, port: port)
- let base = pv.url.hasSuffix("/") ? String(pv.url.dropLast()) : pv.url
- let conn = CubeConnection(sandboxID: id, base: base, serveToken: token,
- previewToken: pv.token, githubLogin: github?.account_login)
- conn.store()
- return conn
}
// GitHub for the cube — the same access @codegraff-bot gets. Degrades to a
diff --git a/apps/ios/Graff/Sources/GraffApp.swift b/apps/ios/Graff/Sources/GraffApp.swift
index 114a34d4..3b0f00e1 100644
--- a/apps/ios/Graff/Sources/GraffApp.swift
+++ b/apps/ios/Graff/Sources/GraffApp.swift
@@ -18,6 +18,10 @@ struct GraffApp: App {
// Headless "build for me" proof: broker a cube, have the agent
// create a file in it via bash, verify through gateway exec.
CubeAutoTestView()
+ } else if CommandLine.arguments.contains("--autotest-turnstate") {
+ // Turn-model invariants (#307/#285/#309) checked in memory —
+ // no network, no taps, so it runs anywhere the app launches.
+ TurnStateCheckView()
} else if CommandLine.arguments.contains("--autotest-compose") {
// Render the new-session compose sheet standalone for visual QA.
NewSessionView { _ in }
@@ -60,6 +64,70 @@ struct AutoTestView: View {
}
}
+// Launch with `--autotest-turnstate` to assert the turn model's invariants
+// in-process — the only regression guard these views have, since the app has no
+// test target and CI does not build it. Every line is also printed, so
+// `xcrun simctl launch --console-pty … --autotest-turnstate` can gate on
+// TURNSTATE-PASS.
+struct TurnStateCheckView: View {
+ var body: some View {
+ Text(Self.report)
+ .font(.system(.footnote, design: .monospaced))
+ .padding()
+ }
+
+ static var report: String {
+ var lines: [String] = []
+ func check(_ name: String, _ ok: Bool) { lines.append((ok ? "ok " : "FAIL ") + name) }
+
+ let user = ChatMessage(role: .user, text: "hi")
+ let turn = ChatMessage(role: .assistant, text: "", state: .streaming)
+ let capturedIndex = [user, turn].count - 1 // what runTurn used to keep
+
+ // #309: hydration lands mid-turn and rewrites the transcript. The live
+ // row has moved, so only its id can still find it.
+ let history = (0..<4).map { ChatMessage(role: .assistant, text: "old \($0)") }
+ var hydrated = history + [user, turn]
+ check("hydration invalidates the captured index",
+ hydrated[capturedIndex].id != turn.id)
+ hydrated.updateTurn(turn.id) { $0.text += "streamed" }
+ check("update by id reaches the live turn",
+ hydrated.last?.id == turn.id && hydrated.last?.text == "streamed")
+ check("update by id touches nothing else",
+ hydrated.filter { $0.text == "streamed" }.count == 1)
+
+ // A shorter hydrated array is where the captured index used to trap.
+ var dropped = [ChatMessage(role: .user, text: "only")]
+ check("captured index is out of bounds after hydration",
+ capturedIndex >= dropped.count)
+ dropped.updateTurn(turn.id) { $0.text = "must not appear" }
+ check("update by id on a dropped turn is a safe no-op",
+ dropped.count == 1 && dropped[0].text == "only")
+
+ // #285: a failure updates the turn it belongs to, never appends.
+ var failing = [user, turn]
+ failing.updateTurn(turn.id) { $0.state = .failed("The network connection was lost.") }
+ check("failure stays on one assistant record",
+ failing.count == 2 && failing[1].state == .failed("The network connection was lost."))
+ check("failure reason is not model prose", failing[1].text.isEmpty)
+
+ // #307: a blank record reloaded from history is finished, not typing.
+ check("history defaults to completed",
+ ChatMessage(role: .assistant, text: "").state == .completed)
+ check("garbage NDJSON does not decode",
+ GraffServeClient.decode("<html>502 Bad Gateway</html>") == nil)
+ var sawTurn = false
+ if case .some(.turn) = GraffServeClient.decode("{\"type\":\"turn\",\"text\":\"done\"}") { sawTurn = true }
+ check("a terminal turn record decodes", sawTurn)
+
+ let failures = lines.filter { $0.hasPrefix("FAIL") }.count
+ let summary = failures == 0 ? "TURNSTATE-PASS" : "TURNSTATE-FAIL (\(failures))"
+ print(summary)
+ for l in lines { print(l) }
+ return ([summary] + lines).joined(separator: "\n")
+ }
+}
+
// MARK: - Liquid Glass helpers
extension View {
func glassPanel(_ radius: CGFloat = 22) -> some View {
@@ -73,11 +141,37 @@ extension View {
// MARK: - Model
enum Role { case user, assistant }
+// How a turn ended. The assistant row has to carry this itself: an empty
+// bubble is not evidence that work is still in flight (#307), and a transport
+// failure belongs ON the turn instead of becoming a second assistant record
+// (#285) or having nowhere to land when the turn is stopped (#59).
+enum TurnState: Equatable {
+ case streaming
+ case completed
+ case failed(String)
+ case cancelled
+}
+
struct ChatMessage: Identifiable {
let id = UUID()
let role: Role
var text: String
var reasoning: String? = nil
+ // Defaults to .completed so history (samples, hydrated transcripts) is
+ // never mistaken for an in-flight turn; runTurn passes .streaming
+ // explicitly for the row it is filling in.
+ var state: TurnState = .completed
+}
+
+extension Array where Element == ChatMessage {
+ // #309: the only way to touch an in-flight turn. Addressing it by its
+ // stable id means a hydration that replaces the transcript mid-stream can
+ // no longer misapply an event to a historical row - or trap, when the
+ // hydrated array is shorter than the index the turn captured.
+ mutating func updateTurn(_ id: UUID, _ mutate: (inout ChatMessage) -> Void) {
+ guard let i = firstIndex(where: { $0.id == id }) else { return }
+ mutate(&self[i])
+ }
}
enum TodoStatus {
diff --git a/apps/ios/Graff/Sources/GraffServeClient.swift b/apps/ios/Graff/Sources/GraffServeClient.swift
index 836c671a..8c18c93e 100644
--- a/apps/ios/Graff/Sources/GraffServeClient.swift
+++ b/apps/ios/Graff/Sources/GraffServeClient.swift
@@ -12,8 +12,18 @@ enum GraffEvent {
enum GraffError: LocalizedError {
case badResponse(String)
+ // #307: a 200 whose NDJSON body ends without a terminal `turn`/`error`
+ // record is a truncated turn, not a successful one.
+ case prematureEnd
+ // #307: an undecodable line means the protocol broke mid-stream; skipping
+ // it let a truncated stream take the same false-success path.
+ case malformedEvent(String)
var errorDescription: String? {
- switch self { case .badResponse(let s): return s }
+ switch self {
+ case .badResponse(let s): return s
+ case .prematureEnd: return "The turn stream ended before the agent finished."
+ case .malformedEvent(let s): return "Unreadable turn stream record: \(s)"
+ }
}
}
@@ -83,13 +93,23 @@ struct GraffServeClient {
continuation.finish(throwing: GraffError.badResponse("turn HTTP \(Self.status(resp))"))
return
}
+ // #307: exactly one terminal `turn`/`error` record ends a
+ // turn. Anything else that stops the line loop - EOF, a
+ // truncated or malformed record - is a transport failure,
+ // so a caller can never read silence as success.
+ var sawTerminal = false
for try await line in bytes.lines {
- guard !line.isEmpty, let ev = Self.decode(line) else { continue }
+ if line.isEmpty { continue } // NDJSON keepalive padding
+ guard let ev = Self.decode(line) else {
+ continuation.finish(throwing:
+ GraffError.malformedEvent(String(line.prefix(80))))
+ return
+ }
continuation.yield(ev)
- if case .turn = ev { break }
- if case .error = ev { break }
+ if case .turn = ev { sawTerminal = true; break }
+ if case .error = ev { sawTerminal = true; break }
}
- continuation.finish()
+ continuation.finish(throwing: sawTerminal ? nil : GraffError.prematureEnd)
} catch {
continuation.finish(throwing: error)
}
diff --git a/apps/ios/Graff/Sources/NewSessionView.swift b/apps/ios/Graff/Sources/NewSessionView.swift
index 14ae1d9f..c37e2498 100644
--- a/apps/ios/Graff/Sources/NewSessionView.swift
+++ b/apps/ios/Graff/Sources/NewSessionView.swift
@@ -16,13 +16,22 @@ struct NewSessionView: View {
@State private var signedIn = Gateway.apiKey != nil
@State private var showAccount = false
@State private var handedOff = false
+ // #312: the launch used to run in an untracked Task, so tearing the sheet
+ // down left it provisioning a cube nobody would ever see. Hold the handle
+ // so dismissal can cancel it, and remember that we walked away.
+ @State private var launchTask: Task<Void, Never>? = nil
+ @State private var abandoned = false
var body: some View {
NavigationStack {
Group {
switch phase {
case .compose: compose
- case .launching: launching
+ case .launching:
+ // Cancelling is the point of this button (#312): it stops the
+ // cube coming up rather than just hiding the progress.
+ launching
+ .toolbar { ToolbarItem(placement: .topBarLeading) { Button("Cancel") { finish() } } }
case .chat:
ChatView(session: $session, autoSend: prompt)
.toolbar { ToolbarItem(placement: .topBarTrailing) { Button("Done") { finish() } } }
@@ -46,7 +55,7 @@ struct NewSessionView: View {
if signedIn {
Button {
phase = .launching
- Task { await launch() }
+ launchTask = Task { await launch() }
} label: {
Label("Start building", systemImage: "play.fill").frame(maxWidth: .infinity)
}
@@ -109,11 +118,22 @@ struct NewSessionView: View {
do {
let conn = try await CubeBroker.launch(purpose: "graff-ios") { msg in steps.append(msg) }
let title = trimmed.count > 42 ? String(trimmed.prefix(42)) + "…" : trimmed
- session = AgentSession(title: title.isEmpty ? "Cloud session" : title, model: "codegraff",
- status: .working, lastActivity: "now", todos: [], messages: [], cube: conn)
+ let created = AgentSession(title: title.isEmpty ? "Cloud session" : title, model: "codegraff",
+ status: .working, lastActivity: "now", todos: [], messages: [], cube: conn)
+ session = created
+ // #312: the sheet can go away in the gap between the cube coming up
+ // and this line. The cube is real and already billed, so hand it to
+ // the Sessions list instead of orphaning it — rollback only covers
+ // launches cancellation actually caught in flight.
+ guard !abandoned else {
+ if !handedOff { handedOff = true; onCreated(created) }
+ return
+ }
phase = .chat
} catch {
- phase = .failed(error.localizedDescription)
+ // A cancelled launch is not a failure — the sheet is already gone,
+ // and CubeBroker has stopped whatever it brought up (#312).
+ if !Task.isCancelled { phase = .failed(error.localizedDescription) }
}
}
@@ -124,6 +144,12 @@ struct NewSessionView: View {
if case .chat = phase {
handedOff = true
onCreated(session)
+ } else {
+ // #312: leaving mid-provisioning used to bill a cube into the void.
+ // Cancelling lets CubeBroker unwind and stop what it brought up.
+ abandoned = true
+ launchTask?.cancel()
+ launchTask = nil
}
dismiss()
}
@@ -150,8 +176,40 @@ struct CubeAutoTestView: View {
.task { await run() }
}
+ // Pure-logic leg: the token-expiry rule that decides whether a running cube
+ // may be reused as-is (#314). No network and no key, so it runs on every
+ // autotest launch — the closest thing this app has to a unit test.
+ @MainActor
+ private func checkTokenExpiry() {
+ let now = Date()
+ func conn(_ login: String?, _ expiry: Date?) -> CubeConnection {
+ CubeConnection(sandboxID: "s", base: "b", serveToken: "t", previewToken: nil,
+ githubLogin: login, githubTokenExpiry: expiry)
+ }
+ var ok = conn("octo", now.addingTimeInterval(3600)).githubNeedsRefresh(asOf: now) == false
+ ok = ok && conn("octo", now.addingTimeInterval(-60)).githubNeedsRefresh(asOf: now)
+ ok = ok && conn("octo", now.addingTimeInterval(120)).githubNeedsRefresh(asOf: now)
+ ok = ok && conn("octo", nil).githubNeedsRefresh(asOf: now) // stored before #314
+ ok = ok && conn(nil, nil).githubNeedsRefresh(asOf: now) == false // no repo access to refresh
+ // A connection stored before #314 still has to decode, expiry-less.
+ let legacy = #"{"sandboxID":"s","base":"b","serveToken":"t","githubLogin":"octo"}"#
+ let old = try? JSONDecoder().decode(CubeConnection.self, from: Data(legacy.utf8))
+ ok = ok && old?.githubNeedsRefresh(asOf: now) == true
+ // ...and the expiry has to survive the Keychain round-trip.
+ let rt = (try? JSONEncoder().encode(conn("octo", now.addingTimeInterval(3600))))
+ .flatMap { try? JSONDecoder().decode(CubeConnection.self, from: $0) }
+ ok = ok && rt?.githubNeedsRefresh(asOf: now) == false
+ // The mint-token wire hands the expiry over as an ISO-8601 stamp.
+ let iso = "2026-07-31T12:00:00Z"
+ let parsed = MintedGitHub(token: "x", expires_at: iso, account_login: "octo").expiry
+ ok = ok && ISO8601DateFormatter().date(from: iso)
+ .map { abs(parsed.timeIntervalSince($0)) < 0.5 } == true
+ lines.append(ok ? "CUBE-TOKEN-EXPIRY-PASS" : "CUBE-TOKEN-EXPIRY-FAIL")
+ }
+
@MainActor
private func run() async {
+ checkTokenExpiry()
guard let k = ProcessInfo.processInfo.environment["GRAFF_GATEWAY_KEY"] else {
lines.append("FAIL: no GRAFF_GATEWAY_KEY in env")
return
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 6851973f..fb5e0260 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -10,7 +10,7 @@
"src/main.zig",
"src/repl.zig"
],
- "test_count_baseline": 530,
+ "test_count_baseline": 575,
"required_invariants": [
{
"id": "goal-epochs",
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index 2fb8fc66..649cfde8 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -133,10 +133,11 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
}
if (tools) |t| {
try s.objectField("tools");
+ // #261 follow-up: the rest need the root-schema repair too.
if (is_kimi)
try writeKimiTools(&s, self.scratchAlloc(), t)
else
- try s.print("{s}", .{t});
+ try serde.writeOpenAITools(&s, self.scratchAlloc(), t);
if (force_tool) {
try s.objectField("tool_choice");
try s.write("required");
@@ -213,7 +214,7 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
}
if (tools) |t| {
try s.objectField("tools");
- try s.print("{s}", .{t});
+ try serde.writeOpenAITools(&s, self.scratchAlloc(), t); // #261 follow-up
try s.objectField("tool_choice");
try s.write(if (force_tool) "required" else "auto");
try s.objectField("parallel_tool_calls");
@@ -377,8 +378,9 @@ test "retained reasoning: openai-chat history replays reasoning_content on the n
.out = null,
.sys_normal = "system",
};
- const body = try agent.buildBody(null, false, true, true);
+ const body = try agent.buildBody("[{\"type\":\"function\",\"function\":{\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{}}}]", false, true, true);
defer std.testing.allocator.free(body);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"parameters\":{\"type\":\"object\"}") != null); // #261 follow-up: repaired on every non-kimi openai endpoint
// Both turns' reasoning must reach the wire. DeepSeek's thinking mode
// REQUIRES the tool-call turn's reasoning_content to be replayed on every
@@ -496,9 +498,10 @@ test "retained reasoning: codex full resend keeps encrypted reasoning items and
.out = null,
.sys_normal = "system",
};
- const body = try agent.buildBody("[]", false, true, true);
+ const body = try agent.buildBody("[{\"type\":\"function\",\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{},\"strict\":false}]", false, true, true);
defer std.testing.allocator.free(body);
+ try std.testing.expect(std.mem.indexOf(u8, body, "\"parameters\":{\"type\":\"object\"}") != null); // #261 follow-up: repaired on the responses wire too
// Ask the backend to hand reasoning back encrypted...
try std.testing.expect(std.mem.indexOf(u8, body, "\"include\":[\"reasoning.encrypted_content\"]") != null);
// ...and send the prior turn's reasoning item straight back. store:false
diff --git a/src/cli.zig b/src/cli.zig
index 74c86b3c..6a7caf51 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -119,7 +119,8 @@ pub const usage_text =
\\keys: <PROVIDER>_API_KEY env vars, `graff key set`, or `graff login`;
\\a Codex CLI login is picked up automatically.
\\inside the REPL: /help lists commands, a bare "/" opens the command menu,
- \\"@" opens a fuzzy file picker (drag-and-dropped files paste as their path),
+ \\"@" opens a fuzzy file picker (a drag-and-dropped image attaches as a
+ \\native vision block on vision models; other files paste as their path),
\\esc interrupts a streaming response, "always allow" persists to
\\.harness/settings.json.
\\telemetry: anonymous OTLP usage stats are sent only when
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index e4d49dd0..235e286b 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -48,6 +48,7 @@ pub const commands = [_]Item{
.{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents/*.md" },
.{ .name = "/skills", .usage = "/skills [remove <name>]", .desc = "list available skills; /skills remove <name> disables one" },
.{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },
+ .{ .name = "/doctor", .desc = "read-only health check: goal/todo invariants, and why steering will or will not be appended" },
.{ .name = "/compact", .desc = "summarize history into a fresh context" },
.{ .name = "/rewind", .usage = "/rewind [n]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits" },
.{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },
@@ -75,6 +76,13 @@ pub const names = blk: {
break :blk arr;
};
+test { // #321: /doctor's rules live in doctor.zig, which nothing else references
+ // yet - and a module with no test-root reference has its tests silently
+ // skipped. Hung here beside the catalog entry that introduces the command;
+ // it belongs in main.zig's test block once /doctor is dispatched.
+ _ = @import("doctor.zig");
+}
+
test "catalog is well-formed and names track commands" {
try std.testing.expectEqual(commands.len, names.len);
for (commands, names) |command, name| {
diff --git a/src/doctor.zig b/src/doctor.zig
new file mode 100644
index 00000000..4802992e
--- /dev/null
+++ b/src/doctor.zig
@@ -0,0 +1,493 @@
+//! Read-only health checks behind /doctor (#321).
+//!
+//! What #321 exposed was not a missing fix but a missing REPORT: a completed
+//! goal kept steering unrelated turns, paired with a checklist a different task
+//! had written, and nothing in the harness could say so - the user had to infer
+//! health from conversation text. These checks read harness-owned state and
+//! name what disagrees, under a stable id per finding so support tooling and
+//! automation can key off it instead of parsing prose.
+//!
+//! Pure: `run` takes the state it inspects as a parameter - never a global,
+//! never the filesystem or the process table - so every rule here is unit
+//! tested against a literal `State` with an injected clock. `snapshot` is the
+//! only place an Agent is touched, and it is a field copy.
+//!
+//! This is the goal/todo SLICE of #321. Its session-lease, owned-job, listener
+//! and aggregate-budget checks (DUPLICATE_WORKTREE_OWNER, STALE_SESSION_LEASE,
+//! ORPHANED_OWNED_JOB, JOB_SHARES_ROOT_PGID, LISTENER_AFTER_CLEANUP,
+//! BUDGET_EXCEEDED, ...) need a durable job/session registry that does not
+//! exist yet; they are deliberately absent rather than faked, because a doctor
+//! that reports "healthy" from state it cannot see is worse than no doctor.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Io = std.Io;
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+const Goal = agent_mod.Goal;
+const TodoItem = agent_mod.TodoItem;
+const goal_state = @import("goal_state.zig");
+
+/// Ordered least-to-most severe: `worst` compares them by tag value, so the
+/// declaration order IS the ladder. `error` is spelled as a quoted identifier
+/// so @tagName gives the wire name #321 asks for ("info"/"warn"/"error").
+pub const Severity = enum {
+ info,
+ warn,
+ @"error",
+
+ /// The one lowercase wire name shared by the text table and the JSON, so a
+ /// support script never has to map two vocabularies.
+ pub fn name(self: Severity) []const u8 {
+ return @tagName(self);
+ }
+};
+
+/// One finding. `id` is stable and must never be reworded - it is the key
+/// automation matches on; `title` and `detail` are the human half, and `detail`
+/// carries the evidence (epochs, counts, ages) that makes the finding checkable.
+pub const Check = struct {
+ id: []const u8,
+ severity: Severity,
+ title: []const u8,
+ detail: []const u8,
+};
+
+/// Everything the goal/todo checks read, passed in rather than reached for.
+/// Defaults describe a fresh session with no goal, which is a healthy state.
+pub const State = struct {
+ goal: ?Goal = null,
+ todos: []const TodoItem = &.{},
+ /// An attempt_completion was refused and the promised second call is now
+ /// pre-accepted (goal_state.completionGate). It crosses turn boundaries by
+ /// design (#318), so it is state a doctor can and should read.
+ completion_gate_armed: bool = false,
+ /// Injected clock reading in unix ms. 0 means "no clock supplied": the
+ /// age-dependent rules then report rather than suppress, since an unknown
+ /// age is not evidence of freshness.
+ now_ms: i64 = 0,
+};
+
+/// A goal that replaced live work legitimately starts with no checklist of its
+/// own while the previous epoch's open items sit parked beside it (#318 parks,
+/// it never deletes). That state is normal for a turn or two - the supersession
+/// note is already telling the model to write a fresh list - so the mismatch is
+/// only reported once the goal has had time to write one.
+pub const epoch_mismatch_grace_ms: i64 = 60_000;
+
+/// Copy the goal/todo slice of a live root Agent. The only Agent-aware code
+/// here, kept to a field copy so `run` itself stays testable without one.
+pub fn snapshot(root: *const Agent, now_ms: i64) State {
+ return .{
+ .goal = root.goal,
+ .todos = root.todos.items,
+ .completion_gate_armed = root.completion_gate_armed,
+ .now_ms = now_ms,
+ };
+}
+
+/// Every check, in report order: the always-present evidence line first, then
+/// findings. Read-only by construction - it returns text and mutates nothing.
+pub fn run(arena: Allocator, st: State) Allocator.Error![]const Check {
+ var out: std.ArrayList(Check) = .empty;
+ try out.append(arena, try goalStateLine(arena, st));
+ if (try epochMismatch(arena, st)) |c| try out.append(arena, c);
+ if (try staleGoal(arena, st)) |c| try out.append(arena, c);
+ if (try todoEpochAboveGoal(arena, st)) |c| try out.append(arena, c);
+ if (try armedCompletionGate(arena, st)) |c| try out.append(arena, c);
+ return out.toOwnedSlice(arena);
+}
+
+/// The highest severity present, `.info` when nothing is wrong (the evidence
+/// line is always there, so an empty result never happens).
+pub fn worst(checks: []const Check) Severity {
+ var top: Severity = .info;
+ for (checks) |c| {
+ if (@intFromEnum(c.severity) > @intFromEnum(top)) top = c.severity;
+ }
+ return top;
+}
+
+/// The always-emitted evidence line #321 asks for: goal epoch, status, age,
+/// which epoch owns the checklist, and WHY steering will or will not be
+/// appended. Always `.info` - a healthy run must produce no warnings.
+fn goalStateLine(arena: Allocator, st: State) Allocator.Error!Check {
+ const g = st.goal orelse return .{
+ .id = "GOAL_STATE",
+ .severity = .info,
+ .title = "no standing goal",
+ .detail = "no goal is set, so no goal steering is appended to your turns.",
+ };
+ const open = goal_state.openCount(st.todos, g.epoch);
+ const total = countEpoch(st.todos, g.epoch);
+ const parked = goal_state.parkedOpenCount(st.todos, g.epoch);
+ const steering = if (g.status == .active)
+ "steering IS appended to every non-review turn"
+ else
+ "steering is NOT appended: only an active goal steers";
+ return .{
+ .id = "GOAL_STATE",
+ .severity = .info,
+ .title = "standing goal",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "epoch {d} \"{s}\" [{s}{s}], age {s}; its checklist has {d} open of {d} item(s), and {d} open item(s) are parked under other epochs; {s}.",
+ .{
+ g.epoch,
+ g.objective,
+ @tagName(g.status),
+ if (g.standing) ", standing" else "",
+ ageText(arena, st.now_ms, g.created_ms) catch "unknown",
+ open,
+ total,
+ parked,
+ steering,
+ },
+ ),
+ };
+}
+
+/// #321 GOAL_TODO_EPOCH_MISMATCH: the goal that is steering owns no checklist,
+/// yet open items exist under other epochs - so the list the user (and the
+/// model's todo_read) sees is not this goal's plan. Reported, never repaired:
+/// silently rebinding unrelated todos onto the live epoch is precisely the
+/// #318 defect this check exists to catch.
+fn epochMismatch(arena: Allocator, st: State) Allocator.Error!?Check {
+ const g = st.goal orelse return null;
+ // currentEpoch is 0 for a completed goal: a dead epoch owns nothing, and
+ // its parked list is expected, not a mismatch.
+ const epoch = goal_state.currentEpoch(st.goal);
+ if (epoch == 0) return null;
+ if (goal_state.hasCurrent(st.todos, epoch)) return null;
+ const foreign = goal_state.parkedOpenCount(st.todos, epoch);
+ if (foreign == 0) return null;
+ if (st.now_ms != 0 and g.created_ms != 0 and st.now_ms - g.created_ms < epoch_mismatch_grace_ms) return null;
+ return .{
+ .id = "GOAL_TODO_EPOCH_MISMATCH",
+ .severity = .warn,
+ .title = "the live checklist does not belong to the standing goal",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "goal epoch {d} \"{s}\" has no checklist of its own, but {d} open todo(s) belong to other epochs. Those items are parked (retained, not steering), so the goal has no evidence it is done and the visible list is someone else's plan. Ask the model for a fresh todo_write checklist, or retire the goal with /goal clear - do not rebind the parked items.",
+ .{ g.epoch, g.objective, foreign },
+ ),
+ };
+}
+
+/// #321 STALE_GOAL (the issue's COMPLETED_CHECKLIST_ACTIVE_GOAL): an active
+/// goal whose own checklist is entirely complete keeps steering work already
+/// done. goal_state.reconcileRestored retires exactly this state at load time,
+/// so seeing it live means the session reached it after load and nobody
+/// reconciled. A standing --goal is exempt for reconcileRestored's reason: it
+/// is the user's policy for the session, and a finished checklist is not their
+/// permission to drop it.
+fn staleGoal(arena: Allocator, st: State) Allocator.Error!?Check {
+ const g = st.goal orelse return null;
+ if (g.status != .active or g.standing) return null;
+ if (!goal_state.allDone(st.todos, g.epoch)) return null; // an empty epoch is "no plan yet", never done (#226)
+ return .{
+ .id = "STALE_GOAL",
+ .severity = .warn,
+ .title = "an active goal has already finished its checklist",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "goal epoch {d} \"{s}\" is active with every one of its {d} checklist item(s) completed, so its steering note is re-stating finished work on every turn. Close it with /goal clear, or let the next accepted attempt_completion retire it.",
+ .{ g.epoch, g.objective, countEpoch(st.todos, g.epoch) },
+ ),
+ };
+}
+
+/// A todo may never carry an epoch above the live goal's: goal_state.nextEpoch
+/// mints each goal above every epoch already present, and todos are stamped
+/// with currentEpoch, which is at most the goal's. Above it means the epoch
+/// counter regressed or a checklist from another session was grafted on - the
+/// collision class #318 fixed, reappearing. Loud on purpose.
+fn todoEpochAboveGoal(arena: Allocator, st: State) Allocator.Error!?Check {
+ const g = st.goal orelse return null;
+ var n: usize = 0;
+ var top: u64 = 0;
+ for (st.todos) |t| {
+ if (t.epoch <= g.epoch) continue;
+ n += 1;
+ top = @max(top, t.epoch);
+ }
+ if (n == 0) return null;
+ return .{
+ .id = "TODO_EPOCH_ABOVE_GOAL",
+ .severity = .@"error",
+ .title = "todos are stamped above the standing goal's epoch",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "{d} todo(s) carry epoch(s) up to {d} while the goal is on epoch {d}. Epochs only ever climb, so this state cannot be produced by /goal or todo_write: the session file was merged, hand-edited, or restored across a counter reset. Save the session elsewhere before continuing.",
+ .{ n, top, g.epoch },
+ ),
+ };
+}
+
+/// The completion double-check is spent: a refusal was issued and the next
+/// attempt_completion is pre-accepted (#318), even though the checklist still
+/// has open work. Worth naming because it is the one path on which a goal
+/// closes with items open, and nothing else in the UI shows it.
+fn armedCompletionGate(arena: Allocator, st: State) Allocator.Error!?Check {
+ if (!st.completion_gate_armed) return null;
+ const g = st.goal orelse return null;
+ if (g.status != .active) return null;
+ const open = goal_state.openCount(st.todos, goal_state.currentEpoch(st.goal));
+ if (open == 0) return null;
+ return .{
+ .id = "COMPLETION_GATE_ARMED",
+ .severity = .warn,
+ .title = "the next completion claim will be accepted unchecked",
+ .detail = try std.fmt.allocPrint(
+ arena,
+ "a completion claim on goal epoch {d} was refused, so the promised second attempt_completion is pre-accepted - it will close the goal with {d} item(s) still open. Any todo_write, or a /goal change, re-arms the double-check.",
+ .{ g.epoch, open },
+ ),
+ };
+}
+
+/// Items stamped with `epoch`, completed or not.
+fn countEpoch(todos: []const TodoItem, epoch: u64) usize {
+ var n: usize = 0;
+ for (todos) |t| {
+ if (t.epoch == epoch) n += 1;
+ }
+ return n;
+}
+
+/// Coarse age ("4m", "3h", "2d"). "unknown" when either end of the subtraction
+/// is missing, which is honest: a persisted goal from before timestamps existed
+/// has created_ms 0, and pretending it was born at the epoch would be a lie.
+fn ageText(arena: Allocator, now_ms: i64, created_ms: i64) Allocator.Error![]const u8 {
+ if (now_ms == 0 or created_ms == 0 or now_ms < created_ms) return "unknown";
+ const secs = @divFloor(now_ms - created_ms, 1000);
+ if (secs < 60) return std.fmt.allocPrint(arena, "{d}s", .{secs});
+ if (secs < 3600) return std.fmt.allocPrint(arena, "{d}m", .{@divFloor(secs, 60)});
+ if (secs < 86_400) return std.fmt.allocPrint(arena, "{d}h", .{@divFloor(secs, 3600)});
+ return std.fmt.allocPrint(arena, "{d}d", .{@divFloor(secs, 86_400)});
+}
+
+/// The human-readable half of #321's output contract.
+pub fn render(arena: Allocator, checks: []const Check) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ for (checks) |c| {
+ try aw.writer.print("{s:<5} {s} {s}\n {s}\n", .{ c.severity.name(), c.id, c.title, c.detail });
+ }
+ return aw.writer.buffered();
+}
+
+/// The machine-readable half: a stable array of {id, severity, title, detail}
+/// so support and automation key off ids instead of scraping the table.
+pub fn toJson(arena: Allocator, checks: []const Check) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginArray();
+ for (checks) |c| {
+ try s.beginObject();
+ try s.objectField("id");
+ try s.write(c.id);
+ try s.objectField("severity");
+ try s.write(c.severity.name());
+ try s.objectField("title");
+ try s.write(c.title);
+ try s.objectField("detail");
+ try s.write(c.detail);
+ try s.endObject();
+ }
+ try s.endArray();
+ return aw.writer.buffered();
+}
+
+// ── tests ─────────────────────────────────────────────────────────────────
+
+fn find(checks: []const Check, id: []const u8) ?Check {
+ for (checks) |c| {
+ if (std.mem.eql(u8, c.id, id)) return c;
+ }
+ return null;
+}
+
+test "doctor: a healthy session reports the evidence line and nothing else (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ // No goal at all.
+ const none = try run(ar, .{});
+ try std.testing.expectEqual(@as(usize, 1), none.len);
+ try std.testing.expectEqualStrings("GOAL_STATE", none[0].id);
+ try std.testing.expectEqual(Severity.info, worst(none));
+
+ // An active goal working its own checklist: still no warnings (#321
+ // acceptance 9 - a healthy single-session run is quiet).
+ const todos = [_]TodoItem{
+ .{ .content = "a", .status = "completed", .epoch = 3 },
+ .{ .content = "b", .status = "pending", .epoch = 3 },
+ };
+ const healthy = try run(ar, .{
+ .goal = .{ .objective = "ship", .epoch = 3, .created_ms = 1_000, .updated_ms = 1_000 },
+ .todos = &todos,
+ .now_ms = 5_000_000,
+ });
+ try std.testing.expectEqual(@as(usize, 1), healthy.len);
+ try std.testing.expectEqual(Severity.info, worst(healthy));
+ try std.testing.expect(std.mem.indexOf(u8, healthy[0].detail, "1 open of 2 item(s)") != null);
+ try std.testing.expect(std.mem.indexOf(u8, healthy[0].detail, "steering IS appended") != null);
+ try std.testing.expect(std.mem.indexOf(u8, healthy[0].detail, "age 1h") != null);
+}
+
+test "doctor: GOAL_TODO_EPOCH_MISMATCH names a checklist the goal does not own (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ // Goal B is steering; the only open work belongs to A's parked epoch.
+ const todos = [_]TodoItem{
+ .{ .content = "A's leftover", .status = "pending", .epoch = 1 },
+ .{ .content = "A's finished bit", .status = "completed", .epoch = 1 },
+ };
+ const goal_b: Goal = .{ .objective = "phase B", .epoch = 2, .created_ms = 1_000, .updated_ms = 1_000 };
+ const st: State = .{ .goal = goal_b, .todos = &todos, .now_ms = 1_000 + epoch_mismatch_grace_ms };
+ const checks = try run(ar, st);
+ const hit = find(checks, "GOAL_TODO_EPOCH_MISMATCH") orelse return error.TestExpectedMismatch;
+ try std.testing.expectEqual(Severity.warn, hit.severity);
+ try std.testing.expect(std.mem.indexOf(u8, hit.detail, "1 open todo(s)") != null);
+ try std.testing.expectEqual(Severity.warn, worst(checks));
+
+ // Inside the grace window the same state is the ordinary post-supersession
+ // transient: the supersession note is still asking for a fresh checklist.
+ var fresh = st;
+ fresh.now_ms = 1_000 + epoch_mismatch_grace_ms - 1;
+ try std.testing.expect(find(try run(ar, fresh), "GOAL_TODO_EPOCH_MISMATCH") == null);
+
+ // A goal that owns its own list never mismatches, however much is parked.
+ const owned = [_]TodoItem{
+ .{ .content = "A's leftover", .status = "pending", .epoch = 1 },
+ .{ .content = "B's plan", .status = "pending", .epoch = 2 },
+ };
+ var scoped = st;
+ scoped.todos = &owned;
+ try std.testing.expect(find(try run(ar, scoped), "GOAL_TODO_EPOCH_MISMATCH") == null);
+
+ // Nor does a completed goal: its epoch is dead and its list parked (#318).
+ var done = st;
+ done.goal.?.status = .complete;
+ try std.testing.expect(find(try run(ar, done), "GOAL_TODO_EPOCH_MISMATCH") == null);
+}
+
+test "doctor: STALE_GOAL fires on an active goal with a finished checklist; standing is exempt (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ var todos = [_]TodoItem{
+ .{ .content = "a", .status = "completed", .epoch = 4 },
+ .{ .content = "b", .status = "completed", .epoch = 4 },
+ };
+ const st: State = .{ .goal = .{ .objective = "ship", .epoch = 4 }, .todos = &todos };
+ const hit = find(try run(ar, st), "STALE_GOAL") orelse return error.TestExpectedStale;
+ try std.testing.expectEqual(Severity.warn, hit.severity);
+ try std.testing.expect(std.mem.indexOf(u8, hit.detail, "2 checklist item(s) completed") != null);
+
+ // One open item and it is live work, not stale steering.
+ todos[1].status = "pending";
+ try std.testing.expect(find(try run(ar, st), "STALE_GOAL") == null);
+ todos[1].status = "completed";
+
+ // A standing --goal is the user's policy for the session: reconcileRestored
+ // leaves it alone, and so does the doctor (#318).
+ var standing = st;
+ standing.goal.?.standing = true;
+ try std.testing.expect(find(try run(ar, standing), "STALE_GOAL") == null);
+
+ // An empty epoch is "no plan yet", never done (#226).
+ var empty = st;
+ empty.todos = &.{};
+ try std.testing.expect(find(try run(ar, empty), "STALE_GOAL") == null);
+}
+
+test "doctor: TODO_EPOCH_ABOVE_GOAL is an error, and epochs at or below the goal are not (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ const grafted = [_]TodoItem{
+ .{ .content = "from another session", .status = "pending", .epoch = 9 },
+ .{ .content = "ours", .status = "pending", .epoch = 2 },
+ };
+ const checks = try run(ar, .{ .goal = .{ .objective = "ship", .epoch = 2 }, .todos = &grafted });
+ const hit = find(checks, "TODO_EPOCH_ABOVE_GOAL") orelse return error.TestExpectedAboveGoal;
+ try std.testing.expectEqual(Severity.@"error", hit.severity);
+ try std.testing.expect(std.mem.indexOf(u8, hit.detail, "epoch(s) up to 9") != null);
+ try std.testing.expectEqual(Severity.@"error", worst(checks));
+
+ // The normal shape - everything parked at or below the live goal - is quiet.
+ const normal = [_]TodoItem{
+ .{ .content = "parked", .status = "pending", .epoch = 1 },
+ .{ .content = "ours", .status = "pending", .epoch = 2 },
+ };
+ try std.testing.expect(find(try run(ar, .{ .goal = .{ .objective = "ship", .epoch = 2 }, .todos = &normal }), "TODO_EPOCH_ABOVE_GOAL") == null);
+}
+
+test "doctor: COMPLETION_GATE_ARMED warns only while open work remains (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ var todos = [_]TodoItem{.{ .content = "a", .status = "pending", .epoch = 1 }};
+ var st: State = .{ .goal = .{ .objective = "ship", .epoch = 1 }, .todos = &todos, .completion_gate_armed = true };
+ const hit = find(try run(ar, st), "COMPLETION_GATE_ARMED") orelse return error.TestExpectedArmed;
+ try std.testing.expectEqual(Severity.warn, hit.severity);
+ try std.testing.expect(std.mem.indexOf(u8, hit.detail, "1 item(s) still open") != null);
+
+ // Disarmed, or with the checklist finished, there is nothing to warn about.
+ st.completion_gate_armed = false;
+ try std.testing.expect(find(try run(ar, st), "COMPLETION_GATE_ARMED") == null);
+ st.completion_gate_armed = true;
+ todos[0].status = "completed";
+ try std.testing.expect(find(try run(ar, st), "COMPLETION_GATE_ARMED") == null);
+}
+
+test "doctor: render and toJson carry the stable id and severity (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ const todos = [_]TodoItem{.{ .content = "a\"quoted\"", .status = "completed", .epoch = 4 }};
+ const checks = try run(ar, .{ .goal = .{ .objective = "ship", .epoch = 4 }, .todos = &todos });
+ const text = try render(ar, checks);
+ try std.testing.expect(std.mem.indexOf(u8, text, "info GOAL_STATE") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "warn STALE_GOAL") != null);
+
+ const json = try toJson(ar, checks);
+ try std.testing.expect(std.mem.startsWith(u8, json, "[{\"id\":\"GOAL_STATE\",\"severity\":\"info\""));
+ try std.testing.expect(std.mem.indexOf(u8, json, "\"id\":\"STALE_GOAL\",\"severity\":\"warn\"") != null);
+ // Details quote the objective, so the machine-readable half only survives
+ // if it is escaped: parse it back rather than trusting the substring above.
+ const parsed = try std.json.parseFromSlice(std.json.Value, ar, json, .{});
+ defer parsed.deinit();
+ try std.testing.expectEqual(@as(usize, 2), parsed.value.array.items.len);
+ try std.testing.expectEqualStrings("STALE_GOAL", parsed.value.array.items[1].object.get("id").?.string);
+ try std.testing.expectEqual(Severity.warn, worst(checks));
+}
+
+test "doctor: snapshot copies the goal/todo slice of a live root agent (#321)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+
+ var root: Agent = undefined;
+ root.arena = ar;
+ root.todos = .empty;
+ root.goal = .{ .objective = "ship", .epoch = 2, .created_ms = 7 };
+ root.completion_gate_armed = true;
+ try root.todos.append(ar, .{ .content = "a", .status = "pending", .epoch = 2 });
+
+ const st = snapshot(&root, 9);
+ try std.testing.expectEqual(@as(u64, 2), st.goal.?.epoch);
+ try std.testing.expectEqual(@as(usize, 1), st.todos.len);
+ try std.testing.expect(st.completion_gate_armed);
+ try std.testing.expectEqual(@as(i64, 9), st.now_ms);
+ // And the doctor reads that snapshot exactly as it reads a literal State.
+ try std.testing.expect(find(try run(ar, st), "COMPLETION_GATE_ARMED") != null);
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index 3bf42933..38366098 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -63,6 +63,10 @@ pub const agentWorktreeFinish = agent_worktree.agentWorktreeFinish;
pub const KeepReason = agent_worktree.KeepReason;
pub const keepReasonText = agent_worktree.keepReasonText;
+// #112 (list age column + `prune --older-than`) and #320 (canonical worktree
+// identity) live in their own modules: jobs.zig is at the 600-line cap.
+const worktree_prune = @import("worktree_prune.zig");
+
/// True if the current git working tree has uncommitted *tracked* changes
/// (staged or unstaged). Untracked files (`?? …`) don't count — `git reset
/// --hard` leaves them alone, so they're safe around a worktree land.
@@ -123,20 +127,7 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [
const action = if (args.len > 0) args[0] else "list";
if (std.mem.eql(u8, action, "list") or std.mem.eql(u8, action, "ls")) {
- const r = runCapped(gpa, io, &.{ "git", "worktree", "list" }, 1 << 16, 8192, 30_000) catch {
- try out.writeAll("not a git repository (no worktrees)\n");
- return;
- };
- defer {
- gpa.free(r.stdout);
- gpa.free(r.stderr);
- }
- if (!ranOk(r)) {
- try out.writeAll(r.stderr);
- return;
- }
- try out.writeAll(r.stdout);
- return;
+ return worktree_prune.listWithAge(gpa, io, arena, out);
}
if (std.mem.eql(u8, action, "merge")) {
@@ -237,18 +228,12 @@ pub fn worktreeCommand(gpa: Allocator, io: Io, arena: Allocator, args: []const [
}
if (std.mem.eql(u8, action, "prune")) {
- // Drop git's registrations for worktrees whose dirs were deleted out of band.
- const r = runCapped(gpa, io, &.{ "git", "worktree", "prune" }, 8192, 8192, 30_000) catch {
- try out.writeAll("not a git repository (nothing to prune)\n");
- return;
- };
- gpa.free(r.stdout);
- gpa.free(r.stderr);
- try out.writeAll("✓ pruned stale worktree registrations\n");
- return;
+ // Drops git's registrations for worktrees whose dirs were deleted out of
+ // band, and with `older-than <days>` the stale DIRECTORIES too (#112).
+ return worktree_prune.pruneCommand(gpa, io, arena, out, args[1..]);
}
- try out.print("unknown worktree command '{s}' — use: graff worktree list | merge <name> | remove <name> | prune\n", .{action});
+ try out.print("unknown worktree command '{s}' — use: graff worktree list | merge <name> | remove <name> | prune [older-than <days>]\n", .{action});
}
/// One background bash job (`bash` with run_in_background:true). A pump task
@@ -523,6 +508,11 @@ pub fn jobsReap(gpa: Allocator, io: Io) void {
g_jobs.list.deinit(gpa);
}
+test { // split-out modules: unreferenced, their tests silently never run
+ _ = worktree_prune;
+ _ = @import("worktree_lease.zig");
+}
+
test "foreground tool subprocesses own their process group (#266, #198)" {
const inherited = toolRunOptions(null);
try std.testing.expect(inherited.kill_process_tree);
diff --git a/src/mainloop_trace.zig b/src/mainloop_trace.zig
index 79ef0c79..8c3b1453 100644
--- a/src/mainloop_trace.zig
+++ b/src/mainloop_trace.zig
@@ -4,6 +4,7 @@
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
+const Value = std.json.Value;
const agent_mod = @import("agent.zig");
const pricing = @import("pricing.zig");
@@ -25,6 +26,120 @@ pub fn begin(root: *agent_mod.Agent, io: Io) Before {
};
}
+/// Shape of the turn's final assistant response: counts and block types
+/// only, never a byte of the content itself (#270). An unrelated text-only
+/// refusal and a turn where the model emitted nothing looked identical in
+/// the trace afterwards — both recorded a successful API call, no tool
+/// calls, and nothing else. Recording the shape separates "one text block of
+/// 240 chars, no tools" from "no blocks at all" while staying privacy-safe.
+pub const ResponseShape = struct {
+ blocks: u32 = 0,
+ text_len: u64 = 0,
+ has_text: bool = false,
+ has_tool_use: bool = false,
+ has_thinking: bool = false,
+ has_reasoning: bool = false,
+
+ /// The set of block types present, joined in a fixed order so archived
+ /// rows group: "", "text", "text+tool_use+thinking", … Longest possible
+ /// value is 32 bytes.
+ pub fn typeSet(self: ResponseShape, buf: *[40]u8) []const u8 {
+ var w: Io.Writer = .fixed(buf);
+ inline for (.{
+ .{ self.has_text, "text" },
+ .{ self.has_tool_use, "tool_use" },
+ .{ self.has_thinking, "thinking" },
+ .{ self.has_reasoning, "reasoning" },
+ }) |entry| if (entry[0]) {
+ if (w.buffered().len > 0) w.writeByte('+') catch {};
+ w.writeAll(entry[1]) catch {};
+ };
+ return w.buffered();
+ }
+};
+
+fn jsonStr(obj: std.json.ObjectMap, key: []const u8) []const u8 {
+ const v = obj.get(key) orelse return "";
+ return if (v == .string) v.string else "";
+}
+
+/// A bare Responses output item (no "role") that the model authored.
+fn isModelItem(kind: []const u8) bool {
+ return std.mem.eql(u8, kind, "message") or
+ std.mem.eql(u8, kind, "function_call") or
+ std.mem.eql(u8, kind, "reasoning");
+}
+
+/// Shape of the final response = the trailing run of model-authored history
+/// entries, i.e. everything appended after the last user turn or tool
+/// result. All three wire formats land here, because the history holds
+/// whatever that provider's step function appended: anthropic content
+/// blocks, an openai message with content + tool_calls beside it, or bare
+/// Responses output items (#270).
+pub fn finalResponseShape(messages: []const Value) ResponseShape {
+ var shape: ResponseShape = .{};
+ var i = messages.len;
+ while (i > 0) {
+ i -= 1;
+ if (messages[i] != .object) break;
+ const obj = messages[i].object;
+ const role = jsonStr(obj, "role");
+ const kind = jsonStr(obj, "type");
+ if (role.len > 0) {
+ if (!std.mem.eql(u8, role, "assistant")) break; // user turn / tool result
+ } else if (!isModelItem(kind)) break; // function_call_output, …
+ countEntry(&shape, obj, kind);
+ }
+ return shape;
+}
+
+fn countEntry(shape: *ResponseShape, obj: std.json.ObjectMap, kind: []const u8) void {
+ // A bare Responses item is one block on its own; only "message" carries a
+ // content array, which the shared block walk below handles.
+ if (std.mem.eql(u8, kind, "function_call")) {
+ shape.blocks += 1;
+ shape.has_tool_use = true;
+ return;
+ }
+ if (std.mem.eql(u8, kind, "reasoning")) {
+ shape.blocks += 1;
+ shape.has_reasoning = true;
+ return;
+ }
+ if (obj.get("content")) |content| switch (content) {
+ .array => for (content.array.items) |block| {
+ if (block != .object) continue;
+ shape.blocks += 1;
+ const bt = jsonStr(block.object, "type");
+ if (std.mem.eql(u8, bt, "text") or std.mem.eql(u8, bt, "output_text")) {
+ shape.has_text = true;
+ shape.text_len += jsonStr(block.object, "text").len;
+ } else if (std.mem.eql(u8, bt, "tool_use")) {
+ shape.has_tool_use = true;
+ } else if (std.mem.eql(u8, bt, "thinking") or std.mem.eql(u8, bt, "redacted_thinking")) {
+ shape.has_thinking = true;
+ }
+ },
+ .string => if (content.string.len > 0) {
+ shape.blocks += 1;
+ shape.has_text = true;
+ shape.text_len += content.string.len;
+ },
+ else => {}, // openai sends content:null next to tool_calls
+ };
+ // openai keeps calls and reasoning beside the content, not inside it.
+ if (obj.get("tool_calls")) |tcs| if (tcs == .array and tcs.array.items.len > 0) {
+ shape.blocks += @intCast(tcs.array.items.len);
+ shape.has_tool_use = true;
+ };
+ for ([_][]const u8{ "reasoning_content", "reasoning" }) |key| {
+ if (jsonStr(obj, key).len > 0) {
+ shape.blocks += 1;
+ shape.has_reasoning = true;
+ }
+ }
+}
+
pub fn record(
root: *agent_mod.Agent,
io: Io,
@@ -56,6 +171,11 @@ pub fn record(
.cost_microusd = @intFromFloat(@max(0.0, after.usd - before.cost.usd) * 1_000_000.0),
};
const mutated = !std.mem.eql(u8, &prompt_fp, prev_prompt_fp);
+ // #270: the history still ends with this turn's response here — compaction
+ // and the review-context restore both run after record() returns.
+ const shape = finalResponseShape(root.messages.items);
+ var shape_buf: [40]u8 = undefined;
+ const shape_types = shape.typeSet(&shape_buf);
if (root.tracer) |tracer| tracer.write(.{
.t = tracer.elapsedMs(),
@@ -74,6 +194,11 @@ pub fn record(
.cache_read_tokens = outcome.cache_read_tokens,
.cache_permille = outcome.cachePermille(),
.cost_microusd = outcome.cost_microusd,
+ // Shape only, no content (#270): tells a text-only response apart from
+ // a turn that produced nothing.
+ .resp_blocks = shape.blocks,
+ .resp_types = shape_types,
+ .resp_text_len = shape.text_len,
});
if (trace.g_traj) |trajectory| {
@@ -102,6 +227,9 @@ pub fn record(
.uncached_tokens = outcome.uncached_tokens,
.cache_read_tokens = outcome.cache_read_tokens,
.cost_microusd = outcome.cost_microusd,
+ .resp_blocks = shape.blocks,
+ .resp_types = shape_types,
+ .resp_text_len = shape.text_len,
});
if (!turn_ok) {
const detail: []const u8 = if (result) |_| "" else |err| switch (err) {
@@ -117,3 +245,83 @@ pub fn record(
prev_prompt_fp.* = prompt_fp;
}
}
+
+/// Parse a history array and shape it. ResponseShape holds no pointers into
+/// the tree, so the parse can be freed before the assertions.
+fn testShape(json: []const u8) !ResponseShape {
+ const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, json, .{});
+ defer parsed.deinit();
+ return finalResponseShape(parsed.value.array.items);
+}
+
+test "#270: the turn record separates a text-only response from an empty turn" {
+ var buf: [40]u8 = undefined;
+
+ // The reported event: one text block, no tool calls, benign task. The
+ // trace previously carried nothing that distinguished this from a turn
+ // where the model emitted no blocks at all.
+ const refusal_text = "你好,我无法给到相关内容。";
+ const refusal = try testShape(
+ \\[{"role":"user","content":"serve the two mockups"},
+ \\ {"role":"assistant","content":[{"type":"text","text":"你好,我无法给到相关内容。"}]}]
+ );
+ try std.testing.expectEqual(@as(u32, 1), refusal.blocks);
+ try std.testing.expectEqual(@as(u64, refusal_text.len), refusal.text_len);
+ try std.testing.expectEqualStrings("text", refusal.typeSet(&buf));
+
+ const empty = try testShape(
+ \\[{"role":"user","content":"serve the two mockups"},
+ \\ {"role":"assistant","content":[]}]
+ );
+ try std.testing.expectEqual(@as(u32, 0), empty.blocks);
+ try std.testing.expectEqual(@as(u64, 0), empty.text_len);
+ try std.testing.expectEqualStrings("", empty.typeSet(&buf));
+}
+
+test "#270: a tool-calling turn records tool_use, and only the FINAL response" {
+ var buf: [40]u8 = undefined;
+
+ const calling = try testShape(
+ \\[{"role":"user","content":"serve the two mockups"},
+ \\ {"role":"assistant","content":[{"type":"thinking","thinking":"…"},
+ \\ {"type":"text","text":"serving"},
+ \\ {"type":"tool_use","id":"t1","name":"bash","input":{}}]}]
+ );
+ try std.testing.expectEqual(@as(u32, 3), calling.blocks);
+ try std.testing.expectEqual(@as(u64, "serving".len), calling.text_len);
+ try std.testing.expectEqualStrings("text+tool_use+thinking", calling.typeSet(&buf));
+
+ // The earlier tool-calling message is a previous step, not the response:
+ // the scan stops at the intervening tool result.
+ const after_tools = try testShape(
+ \\[{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"bash","input":{}}]},
+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"ok"}]},
+ \\ {"role":"assistant","content":[{"type":"text","text":"http://localhost:8080"}]}]
+ );
+ try std.testing.expectEqual(@as(u32, 1), after_tools.blocks);
+ try std.testing.expectEqualStrings("text", after_tools.typeSet(&buf));
+}
+
+test "#270: openai and Responses histories shape the same way" {
+ var buf: [40]u8 = undefined;
+
+ // openai keeps the calls beside a null content.
+ const openai = try testShape(
+ \\[{"role":"user","content":"go"},
+ \\ {"role":"assistant","content":null,"reasoning_content":"…",
+ \\ "tool_calls":[{"id":"c1","function":{"name":"bash","arguments":"{}"}}]}]
+ );
+ try std.testing.expectEqual(@as(u32, 2), openai.blocks);
+ try std.testing.expectEqual(@as(u64, 0), openai.text_len);
+ try std.testing.expectEqualStrings("tool_use+reasoning", openai.typeSet(&buf));
+
+ // Responses appends bare output items, so the trailing run spans several.
+ const responses = try testShape(
+ \\[{"type":"function_call_output","call_id":"c1","output":"ok"},
+ \\ {"type":"reasoning","summary":[]},
+ \\ {"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]
+ );
+ try std.testing.expectEqual(@as(u32, 2), responses.blocks);
+ try std.testing.expectEqual(@as(u64, "done".len), responses.text_len);
+ try std.testing.expectEqualStrings("text+reasoning", responses.typeSet(&buf));
+}
diff --git a/src/mcp.zig b/src/mcp.zig
index 22304e32..7490f926 100644
--- a/src/mcp.zig
+++ b/src/mcp.zig
@@ -20,6 +20,8 @@ const mcp_stdio = @import("mcp_stdio.zig");
const mcp_teardown = @import("mcp_teardown.zig");
const mcp_rpc = @import("mcp_rpc.zig");
const smolify_manifest = @import("smolify_manifest.zig");
+const vision = @import("vision.zig"); // #249: MCP image results become staged vision blocks
+const renderContent = @import("mcp_content.zig").renderContent;
const rewriteOneOf = mcp_protocol.rewriteOneOf;
const HttpTransport = mcp_http.HttpTransport;
@@ -61,6 +63,14 @@ pub const Registry = struct {
/// opted out of the probe by `GRAFF_MCP_PROBE=0` — the env var reaches
/// only the config-file path.
stdio_probe: bool = true,
+ /// An image an MCP tool returned, waiting for the next turn to collect it
+ /// (#249). Written under `mutex` by `call`, drained by
+ /// `vision.mcpImageHandoff` — the registry cannot reach the agent itself.
+ pending_image: ?vision.PendingImage = null,
+ /// Whether the active model accepts image blocks. The registry cannot see
+ /// the provider, so the same per-turn handoff refreshes it; false until it
+ /// does, so a result explains the drop rather than promising an attachment.
+ vision_capable: bool = false,
pub fn arena(self: *Registry) Allocator {
return self.arena_state.allocator();
@@ -545,17 +555,14 @@ pub const Registry = struct {
return .{ .text = try out_alloc.dupe(u8, "MCP server returned an input_required result (MRTR); codegraff does not implement it"), .is_error = true };
const is_error = if (result.get("isError")) |v| (v == .bool and v.bool) else false;
- // result.content is an array of {type:"text", text:...} blocks.
var ow: Io.Writer.Allocating = .init(out_alloc);
errdefer ow.deinit();
- if (result.get("content")) |content| if (content == .array) {
- for (content.array.items) |block| {
- if (block == .object) if (block.object.get("text")) |txt| if (txt == .string) {
- if (ow.writer.buffered().len > 0) try ow.writer.writeByte('\n');
- try ow.writer.writeAll(txt.string);
- };
- }
- };
+ if (result.get("content")) |content| try renderContent(&ow.writer, content, .{
+ .arena = reg.arena(),
+ .slot = &reg.pending_image,
+ .label = qualified,
+ .supports_vision = reg.vision_capable,
+ });
// 2025-06-18+ structured tool output: if the server sent only
// structuredContent (no text blocks), surface it instead of "".
if (ow.writer.buffered().len == 0) {
diff --git a/src/mcp_content.zig b/src/mcp_content.zig
new file mode 100644
index 00000000..caa3ec8d
--- /dev/null
+++ b/src/mcp_content.zig
@@ -0,0 +1,47 @@
+//! Rendering an MCP `tools/call` result's `content` array into the text the
+//! model reads, plus the image blocks inside it (#249). Split out of mcp.zig
+//! rather than grown there: that file was already within 30 lines of the
+//! 600-line ceiling.
+
+const std = @import("std");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const vision = @import("vision.zig");
+
+/// Where a staged image goes and what the active model can do with it. The
+/// registry owns the slot; only the per-turn handoff can reach the agent.
+pub const Stage = struct {
+ arena: Allocator,
+ slot: *?vision.PendingImage,
+ label: []const u8,
+ supports_vision: bool,
+};
+
+/// Render `result.content` into `w`.
+///
+/// Image blocks used to fall straight through this walk — it only looked for a
+/// `text` field — so an image-only result reached the model as the empty string
+/// with no hint that pixels had ever come back (#249). Now the first one is
+/// staged as a real vision attachment and every one of them is named in the
+/// text. Living outside `Registry.call` also makes the mixed text+image walk
+/// testable without a live server.
+pub fn renderContent(w: *Io.Writer, content: Value, stage: Stage) !void {
+ if (content != .array) return;
+ for (content.array.items) |block| {
+ if (block != .object) continue;
+ if (block.object.get("text")) |txt| if (txt == .string) {
+ if (w.buffered().len > 0) try w.writeByte('\n');
+ try w.writeAll(txt.string);
+ };
+ if (vision.mcpImageBlock(block)) |img| {
+ const fate: vision.McpImageFate = if (!stage.supports_vision)
+ .no_vision
+ else if (stage.slot.* != null) .already_staged else .staged;
+ if (fate == .staged) stage.slot.* = img.stage(stage.arena, stage.label) catch null;
+ if (w.buffered().len > 0) try w.writeByte('\n');
+ try vision.mcpImageNote(w, img, fate);
+ }
+ }
+}
diff --git a/src/process_runner.zig b/src/process_runner.zig
index 898efdae..176b7d49 100644
--- a/src/process_runner.zig
+++ b/src/process_runner.zig
@@ -93,6 +93,51 @@ pub const CappedRunOptions = struct {
kill_process_tree: bool = false,
};
+/// #253: RLIMIT_NOFILE as this process actually observes it. main() calls
+/// `std.process.raiseFileDescriptorLimit()` at startup but nothing ever
+/// reported the result, so a "ProcessFdQuotaExceeded blocks every shell
+/// command" report could not tell "the soft limit never rose" apart from "it
+/// rose and the parallel tool/subagent fan-out still exhausted it".
+pub const FdLimit = struct { soft: u64, hard: u64 };
+
+/// Same platform predicate as `posix_process_groups`: no rlimits on Windows/WASI.
+const have_rlimits = posix_process_groups;
+
+/// `null` where the platform has no rlimits (Windows/WASI) or the query fails.
+pub fn fdLimitSnapshot() ?FdLimit {
+ if (comptime have_rlimits) {
+ const lim = std.posix.getrlimit(.NOFILE) catch return null;
+ return .{
+ .soft = std.math.cast(u64, lim.cur) orelse std.math.maxInt(u64),
+ .hard = std.math.cast(u64, lim.max) orelse std.math.maxInt(u64),
+ };
+ } else {
+ return null;
+ }
+}
+
+/// #253: the one line the next fd-exhaustion report needs. Rendered into
+/// `buf` rather than printed so it can be asserted on without exhausting a
+/// real descriptor table; truncation is impossible for the shapes we format
+/// but is reported as the bare error name rather than silently dropped.
+pub fn fdQuotaNote(buf: []u8, err_name: []const u8, limit: ?FdLimit) []const u8 {
+ const rendered = if (limit) |lim| std.fmt.bufPrint(
+ buf,
+ " [fd] spawn failed: {s}; RLIMIT_NOFILE soft={d} hard={d} (#253)\n",
+ .{ err_name, lim.soft, lim.hard },
+ ) else std.fmt.bufPrint(
+ buf,
+ " [fd] spawn failed: {s}; RLIMIT_NOFILE unavailable on this platform (#253)\n",
+ .{err_name},
+ );
+ return rendered catch err_name;
+}
+
+fn reportFdQuota(err: anyerror) void {
+ var buf: [160]u8 = undefined;
+ std.debug.print("{s}", .{fdQuotaNote(&buf, @errorName(err), fdLimitSnapshot())});
+}
+
fn setupWindowsJob(child: *std.process.Child, enabled: bool) !WindowsJobHandle {
if (comptime builtin.os.tag == .windows) {
return if (enabled) try WinJob.setup(child) else null;
@@ -126,7 +171,7 @@ pub fn runCapped(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: u
}
pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, stdout_cap: usize, stderr_cap: usize, deadline_ms: u64, options: CappedRunOptions) !CappedRun {
- var child = try std.process.spawn(io, .{
+ var child = std.process.spawn(io, .{
.argv = argv,
.cwd = options.cwd,
.environ_map = options.environ_map,
@@ -135,7 +180,16 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, st
.stderr = .pipe,
.pgid = if (posix_process_groups and options.kill_process_tree) 0 else null,
.start_suspended = builtin.os.tag == .windows and options.kill_process_tree,
- });
+ }) catch |err| switch (err) {
+ // #253: fd quota is the one spawn failure where the *limit* is the
+ // evidence, and it is gone by the time anyone reads the transcript.
+ // Name it at the failure site; the error itself propagates unchanged.
+ error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded => {
+ reportFdQuota(err);
+ return err;
+ },
+ else => return err,
+ };
var setup_cleanup_needed = true;
errdefer if (setup_cleanup_needed) child.kill(io);
const group_id: GroupId = if (posix_process_groups) child.id.? else {};
@@ -200,3 +254,73 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, st
pub fn ranOk(run: CappedRun) bool {
return run.term == .exited and run.term.exited == 0;
}
+
+/// #253: descriptor high-water probe. `dup` always hands back the LOWEST free
+/// slot, so claiming a fixed burst and taking the highest number returned
+/// counts everything the process is holding below that ceiling — unlike a
+/// single `dup`, which only sees the lowest gap and is blind to a leak that
+/// sits above one. Every descriptor claimed here is released again.
+fn fdHighWater() i32 {
+ var claimed: [64]i32 = undefined;
+ var n: usize = 0;
+ var high: i32 = -1;
+ while (n < claimed.len) : (n += 1) {
+ const fd = std.posix.system.dup(0);
+ if (fd < 0) break;
+ claimed[n] = fd;
+ if (fd > high) high = fd;
+ }
+ for (claimed[0..n]) |fd| _ = std.posix.system.close(fd);
+ return high;
+}
+
+test "#253: timed-out runs do not leak the child's stdout/stderr descriptors" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ const timeout_run = struct {
+ fn once(a: Allocator, i: Io) !void {
+ const r = try runCapped(a, i, &.{ "/bin/sh", "-c", "sleep 30" }, 1024, 1024, 50);
+ a.free(r.stdout);
+ a.free(r.stderr);
+ try std.testing.expect(r.timed_out);
+ }
+ }.once;
+
+ // Two warm-up runs first: whatever the Io backend claims once is then
+ // already inside the baseline, so only per-run growth can move the probe.
+ try timeout_run(gpa, io);
+ try timeout_run(gpa, io);
+ const warm = fdHighWater();
+ var i: usize = 0;
+ while (i < 6) : (i += 1) try timeout_run(gpa, io);
+ const after = fdHighWater();
+ // A branch that terminated the child but never closed its two pipes would
+ // push this out by 12. The tolerance absorbs unrelated one-off
+ // descriptors, never a per-run leak.
+ try std.testing.expect(after - warm < 4);
+}
+
+test "#253: fdLimitSnapshot observes a real NOFILE soft limit" {
+ const snapshot = fdLimitSnapshot();
+ if (comptime !have_rlimits) {
+ try std.testing.expect(snapshot == null);
+ return;
+ }
+ const lim = snapshot orelse return error.NoFdLimitObserved;
+ // main() raises the soft limit at startup; a snapshot that cannot even see
+ // the POSIX floor is reporting nothing useful.
+ try std.testing.expect(lim.soft >= 20);
+ try std.testing.expect(lim.hard >= lim.soft);
+}
+
+test "#253: fdQuotaNote names the error and the observed limit" {
+ var buf: [160]u8 = undefined;
+ const with = fdQuotaNote(&buf, "ProcessFdQuotaExceeded", .{ .soft = 256, .hard = 10240 });
+ try std.testing.expect(std.mem.indexOf(u8, with, "ProcessFdQuotaExceeded") != null);
+ try std.testing.expect(std.mem.indexOf(u8, with, "soft=256") != null);
+ try std.testing.expect(std.mem.indexOf(u8, with, "hard=10240") != null);
+ try std.testing.expect(std.mem.indexOf(u8, with, "#253") != null);
+ const without = fdQuotaNote(&buf, "SystemFdQuotaExceeded", null);
+ try std.testing.expect(std.mem.indexOf(u8, without, "unavailable") != null);
+}
diff --git a/src/readline.zig b/src/readline.zig
index cd86a7a9..13a6f133 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -50,7 +50,8 @@ const agent_mod = @import("agent.zig");
const session = @import("session.zig");
const Agent = agent_mod.Agent;
const saveSession = session.saveSession;
-const HistoryNav = @import("readline_history.zig").HistoryNav;
+const rl_history = @import("readline_history.zig");
+const HistoryNav = rl_history.HistoryNav;
/// Read one input line with a tiny raw-mode editor: ↑/↓ walk history,
/// Tab completes/cycles (models, providers, slash commands), backspace edits,
@@ -369,14 +370,12 @@ pub fn readLine(
const ps = params[0..pn];
const word_mod = std.mem.indexOfScalar(u8, ps, ';') != null; // 1;3 (alt) / 1;5 (ctrl)
switch (final) {
- 'A' => if (nav.up(gpa, history.items, buf.items)) |text| { // up → history back; snapshots draft (#101)
- setLine(gpa, buf, text);
- cur = buf.items.len;
+ 'A' => if (nav.up(gpa, history.items, rl_history.g_history_images.slice(), buf.items, root.pending_image)) |step| { // up → history back; snapshots draft (#101)
+ replayStep(root, gpa, buf, &cur, &marks, step);
redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);
},
- 'B' => if (nav.down(history.items)) |text| { // down → history forward; restores draft past newest (#101)
- setLine(gpa, buf, text);
- cur = buf.items.len;
+ 'B' => if (nav.down(history.items, rl_history.g_history_images.slice())) |step| { // down → history forward; restores draft past newest (#101)
+ replayStep(root, gpa, buf, &cur, &marks, step);
redraw(out, buf.items, cur, marks.items, &rstate, prompt_col);
},
'C' => { // right (word-right with a modifier)
@@ -529,9 +528,33 @@ pub fn readLine(
}
const trimmed = std.mem.trim(u8, buf.items, " \t\r");
- if (trimmed.len > 0 and util.rememberInput(buf.items) and (history.items.len == 0 or !std.mem.eql(u8, history.items[history.items.len - 1], buf.items))) {
+ // The staged image is part of the entry's identity, so the same words with
+ // a different attachment are not a duplicate (#108). root.pending_image is
+ // still set here — mainloop consumes it after readLine returns.
+ const images = rl_history.g_history_images.slice();
+ if (trimmed.len > 0 and util.rememberInput(buf.items) and !rl_history.repeatsLast(history.items, images, buf.items, root.pending_image)) {
const dup = gpa.dupe(u8, buf.items) catch return buf.items;
- history.append(gpa, dup) catch {};
+ history.append(gpa, dup) catch return buf.items;
+ // Session-arena backed, like the base64 payload it points at, so this
+ // outlives the entry without a free of its own (#108).
+ rl_history.g_history_images.record(root.arena, history.items.len - 1, root.pending_image);
}
return buf.items;
}
+
+/// Apply one history step to the editor: text into the buffer, and the entry's
+/// attachment back onto the agent so resending sends the image and not just the
+/// literal "[Image]" marker (#108). A text-only entry clears whatever was staged.
+fn replayStep(
+ root: *Agent,
+ gpa: Allocator,
+ buf: *std.ArrayList(u8),
+ cur: *usize,
+ marks: *std.ArrayList([]const u8),
+ step: rl_history.Step,
+) void {
+ setLine(gpa, buf, step.text);
+ cur.* = buf.items.len;
+ root.pending_image = step.image;
+ if (step.image != null) addMark(gpa, marks, "[Image]"); // re-highlight the marker the replayed text carries
+}
diff --git a/src/readline_history.zig b/src/readline_history.zig
index d915da40..f8d3b81a 100644
--- a/src/readline_history.zig
+++ b/src/readline_history.zig
@@ -1,47 +1,125 @@
-//! Prompt history + unsent-draft navigation for the line editor (#101).
-//! Split out of readline.zig, which sat at 599 of its 600-line cap and so
-//! could not absorb any further change. Pure over std — no terminal, agent, or
-//! session state — which is what makes it directly unit-testable.
+//! Prompt history + unsent-draft navigation for the line editor (#101), and
+//! the staged-image sidecar that lets a replayed prompt carry its attachment
+//! back with it (#108). Split out of readline.zig, which sat at 599 of its
+//! 600-line cap and so could not absorb any further change. Pure over std plus
+//! the PendingImage type — no terminal, agent, or session state — which is what
+//! makes it directly unit-testable.
const std = @import("std");
const Allocator = std.mem.Allocator;
+const PendingImage = @import("vision.zig").PendingImage;
+
+/// One history step: the text the buffer should show, plus the image that was
+/// staged when that text was submitted (#108). `image` is borrowed from the
+/// agent's session arena; the caller re-stages it on the agent as-is.
+pub const Step = struct { text: []const u8, image: ?PendingImage = null };
/// History + unsent-draft navigation for the line editor (#101). Mirrors the
/// GUI's promptHistoryNavigation.ts: stepping UP out of the fresh slot snapshots
/// the half-typed draft; stepping DOWN past the newest entry restores it instead
/// of clearing the line. `idx == history.len` is the fresh (editing) slot.
+/// `images` is index-aligned with `history` and may be shorter — entries loaded
+/// from ~/.simple-harness-history predate this process and carry no image.
pub const HistoryNav = struct {
idx: usize,
draft: ?[]const u8 = null, // owned snapshot of the unsent line; freed by the caller
+ draft_image: ?PendingImage = null, // the attachment staged alongside that draft (#108)
pub fn init(history_len: usize) HistoryNav {
return .{ .idx = history_len };
}
- /// UP / older. `current` is the live buffer. Returns the text the buffer
- /// should show next, or null to leave it unchanged (already at the oldest).
- /// Leaving the fresh slot snapshots `current` as the draft to restore later.
- pub fn up(self: *HistoryNav, gpa: Allocator, history: []const []const u8, current: []const u8) ?[]const u8 {
+ /// UP / older. `current`/`current_image` are the live buffer and the image
+ /// staged on the agent right now. Returns the step the buffer should show
+ /// next, or null to leave it unchanged (already at the oldest). Leaving the
+ /// fresh slot snapshots both halves of the draft to restore later.
+ pub fn up(
+ self: *HistoryNav,
+ gpa: Allocator,
+ history: []const []const u8,
+ images: []const ?PendingImage,
+ current: []const u8,
+ current_image: ?PendingImage,
+ ) ?Step {
if (self.idx == 0) return null;
if (self.idx == history.len) { // leaving the fresh slot: keep the draft
if (self.draft) |d| gpa.free(d);
self.draft = gpa.dupe(u8, current) catch null;
+ self.draft_image = current_image;
}
self.idx -= 1;
- return history[self.idx];
+ return .{ .text = history[self.idx], .image = imageAt(images, self.idx) };
}
- /// DOWN / newer. Returns the text to show next, or null to leave it
+ /// DOWN / newer. Returns the step to show next, or null to leave the buffer
/// unchanged (already at the fresh slot). Past the newest entry, restores the
/// snapshotted draft (or "" when there was none) instead of clearing it.
- pub fn down(self: *HistoryNav, history: []const []const u8) ?[]const u8 {
+ pub fn down(self: *HistoryNav, history: []const []const u8, images: []const ?PendingImage) ?Step {
if (self.idx >= history.len) return null;
self.idx += 1;
- if (self.idx == history.len) return self.draft orelse "";
- return history[self.idx];
+ if (self.idx == history.len) return .{ .text = self.draft orelse "", .image = self.draft_image };
+ return .{ .text = history[self.idx], .image = imageAt(images, self.idx) };
+ }
+};
+
+fn imageAt(images: []const ?PendingImage, idx: usize) ?PendingImage {
+ return if (idx < images.len) images[idx] else null;
+}
+
+/// Images staged with each submitted history entry, index-aligned with the
+/// caller's `history` list (#108). Kept beside the text rather than in it so
+/// ~/.simple-harness-history stays plain text: a line replayed from an earlier
+/// run simply has no image here. Backed by the agent's session arena, which
+/// already owns the base64 payloads, so nothing is freed independently.
+pub const ImageSidecar = struct {
+ items: std.ArrayList(?PendingImage) = .empty,
+
+ /// Remember the image (if any) submitted with the entry now at `index`.
+ /// Pads with null so the first image of a session still lands at the right
+ /// index when history was loaded from disk.
+ pub fn record(self: *ImageSidecar, arena: Allocator, index: usize, img: ?PendingImage) void {
+ while (self.items.items.len < index) self.items.append(arena, null) catch return;
+ if (index < self.items.items.len) {
+ self.items.items[index] = img;
+ return;
+ }
+ self.items.append(arena, img) catch {};
+ }
+
+ pub fn slice(self: *const ImageSidecar) []const ?PendingImage {
+ return self.items.items;
}
};
+/// The one interactive history's sidecar. A module global because mainloop owns
+/// `history` and readLine returns between every entry, so there is nowhere else
+/// for per-entry attachments to live (#108).
+pub var g_history_images: ImageSidecar = .{};
+
+/// Would appending `line` just repeat the newest entry? Consecutive duplicates
+/// are suppressed, but text equality alone is not the right identity (#108):
+/// the same words with a different (or no) attachment are a different prompt,
+/// so replaying one and resending it must not collapse the two.
+pub fn repeatsLast(
+ history: []const []const u8,
+ images: []const ?PendingImage,
+ line: []const u8,
+ img: ?PendingImage,
+) bool {
+ if (history.len == 0) return false;
+ const last = history.len - 1;
+ if (!std.mem.eql(u8, history[last], line)) return false;
+ return sameImage(imageAt(images, last), img);
+}
+
+fn sameImage(a: ?PendingImage, b: ?PendingImage) bool {
+ const x = a orelse return b == null;
+ const y = b orelse return false;
+ return std.mem.eql(u8, x.media_type, y.media_type) and std.mem.eql(u8, x.b64, y.b64);
+}
+
+const no_images: []const ?PendingImage = &.{};
+
test "HistoryNav: up snapshots the draft, down past newest restores it (#101)" {
const gpa = std.testing.allocator;
const history = [_][]const u8{ "first", "second" };
@@ -49,17 +127,17 @@ test "HistoryNav: up snapshots the draft, down past newest restores it (#101)" {
defer if (nav.draft) |d| gpa.free(d);
// up from the fresh slot → newest entry, draft snapshotted
- try std.testing.expectEqualStrings("second", nav.up(gpa, &history, "draft in progress").?);
+ try std.testing.expectEqualStrings("second", nav.up(gpa, &history, no_images, "draft in progress", null).?.text);
// up again → older entry
- try std.testing.expectEqualStrings("first", nav.up(gpa, &history, "second").?);
+ try std.testing.expectEqualStrings("first", nav.up(gpa, &history, no_images, "second", null).?.text);
// up at the oldest → no change
- try std.testing.expect(nav.up(gpa, &history, "first") == null);
+ try std.testing.expect(nav.up(gpa, &history, no_images, "first", null) == null);
// down → back to newest
- try std.testing.expectEqualStrings("second", nav.down(&history).?);
+ try std.testing.expectEqualStrings("second", nav.down(&history, no_images).?.text);
// down past newest → the draft is restored, NOT cleared (the bug)
- try std.testing.expectEqualStrings("draft in progress", nav.down(&history).?);
+ try std.testing.expectEqualStrings("draft in progress", nav.down(&history, no_images).?.text);
// down at the fresh slot → no change
- try std.testing.expect(nav.down(&history) == null);
+ try std.testing.expect(nav.down(&history, no_images) == null);
}
test "HistoryNav: no draft → fresh slot returns empty, no leak (#101)" {
@@ -67,6 +145,89 @@ test "HistoryNav: no draft → fresh slot returns empty, no leak (#101)" {
const history = [_][]const u8{"only"};
var nav: HistoryNav = .init(history.len);
defer if (nav.draft) |d| gpa.free(d);
- try std.testing.expectEqualStrings("only", nav.up(gpa, &history, "").?);
- try std.testing.expectEqualStrings("", nav.down(&history).?); // empty draft → empty line, as today
+ try std.testing.expectEqualStrings("only", nav.up(gpa, &history, no_images, "", null).?.text);
+ try std.testing.expectEqualStrings("", nav.down(&history, no_images).?.text); // empty draft → empty line, as today
+}
+
+test "HistoryNav: empty history navigates nowhere (#102)" {
+ const gpa = std.testing.allocator;
+ const history = [_][]const u8{};
+ var nav: HistoryNav = .init(history.len);
+ defer if (nav.draft) |d| gpa.free(d);
+ try std.testing.expect(nav.up(gpa, &history, no_images, "draft", null) == null);
+ try std.testing.expect(nav.down(&history, no_images) == null);
+ try std.testing.expect(nav.draft == null); // nothing to restore, so nothing snapshotted
+}
+
+test "HistoryNav: repeated up clamps at the oldest, keeping the draft (#102)" {
+ const gpa = std.testing.allocator;
+ const history = [_][]const u8{ "first", "second", "third" };
+ var nav: HistoryNav = .init(history.len);
+ defer if (nav.draft) |d| gpa.free(d);
+ try std.testing.expectEqualStrings("third", nav.up(gpa, &history, no_images, "draft in progress", null).?.text);
+ try std.testing.expectEqualStrings("second", nav.up(gpa, &history, no_images, "third", null).?.text);
+ try std.testing.expectEqualStrings("first", nav.up(gpa, &history, no_images, "second", null).?.text);
+ for (0..3) |_| try std.testing.expect(nav.up(gpa, &history, no_images, "first", null) == null);
+ try std.testing.expectEqual(@as(usize, 0), nav.idx); // pinned at the oldest, not wrapped
+ // and the draft survived the clamped attempts
+ try std.testing.expectEqualStrings("second", nav.down(&history, no_images).?.text);
+ try std.testing.expectEqualStrings("third", nav.down(&history, no_images).?.text);
+ try std.testing.expectEqualStrings("draft in progress", nav.down(&history, no_images).?.text);
+}
+
+test "HistoryNav: replay re-stages the entry's image, text-only clears it (#108)" {
+ const gpa = std.testing.allocator;
+ const shot: PendingImage = .{ .media_type = "image/png", .b64 = "iVBORw0KGgo=", .label = "/tmp/shot.png" };
+ const history = [_][]const u8{ "[Image] what is this?", "plain question" };
+ const images = [_]?PendingImage{ shot, null };
+ var nav: HistoryNav = .init(history.len);
+ defer if (nav.draft) |d| gpa.free(d);
+
+ // newest entry is text-only → replaying it must clear a staged image
+ const newest = nav.up(gpa, &history, &images, "", shot).?;
+ try std.testing.expectEqualStrings("plain question", newest.text);
+ try std.testing.expect(newest.image == null);
+
+ // the image prompt replays with its attachment, not just the "[Image]" text
+ const older = nav.up(gpa, &history, &images, "plain question", null).?;
+ try std.testing.expectEqualStrings("[Image] what is this?", older.text);
+ try std.testing.expectEqualStrings("iVBORw0KGgo=", older.image.?.b64);
+ try std.testing.expectEqualStrings("image/png", older.image.?.media_type);
+
+ // back down past the newest: the draft's own attachment comes back too
+ _ = nav.down(&history, &images);
+ const back = nav.down(&history, &images).?;
+ try std.testing.expectEqualStrings("", back.text);
+ try std.testing.expectEqualStrings("iVBORw0KGgo=", back.image.?.b64);
+}
+
+test "ImageSidecar: records past disk-loaded entries and stays aligned (#108)" {
+ const gpa = std.testing.allocator;
+ const shot: PendingImage = .{ .media_type = "image/png", .b64 = "AAA=", .label = "/tmp/a.png" };
+ var side: ImageSidecar = .{};
+ defer side.items.deinit(gpa);
+
+ // history[0..2] came from ~/.simple-harness-history (text only); this
+ // session submits an image prompt at index 2.
+ side.record(gpa, 2, shot);
+ try std.testing.expectEqual(@as(usize, 3), side.slice().len);
+ try std.testing.expect(side.slice()[0] == null);
+ try std.testing.expect(side.slice()[1] == null);
+ try std.testing.expectEqualStrings("AAA=", side.slice()[2].?.b64);
+ side.record(gpa, 3, null);
+ try std.testing.expect(side.slice()[3] == null);
+}
+
+test "repeatsLast: same text with a different image stays distinct (#108)" {
+ const a: PendingImage = .{ .media_type = "image/png", .b64 = "AAA=", .label = "/tmp/a.png" };
+ const b: PendingImage = .{ .media_type = "image/png", .b64 = "BBB=", .label = "/tmp/b.png" };
+ const history = [_][]const u8{"describe this"};
+ const images = [_]?PendingImage{a};
+ try std.testing.expect(repeatsLast(&history, &images, "describe this", a)); // identical resend → one entry
+ try std.testing.expect(!repeatsLast(&history, &images, "describe this", b)); // new image → new entry
+ try std.testing.expect(!repeatsLast(&history, &images, "describe this", null)); // image dropped → new entry
+ try std.testing.expect(!repeatsLast(&history, &images, "something else", a));
+ try std.testing.expect(!repeatsLast(&.{}, no_images, "first ever", null));
+ // text-only history (no sidecar entry at all) still de-dupes as before
+ try std.testing.expect(repeatsLast(&history, no_images, "describe this", null));
}
diff --git a/src/scoring_slot_test.zig b/src/scoring_slot_test.zig
index f46dbbff..4a710f93 100644
--- a/src/scoring_slot_test.zig
+++ b/src/scoring_slot_test.zig
@@ -57,7 +57,11 @@ test "canonicalSlot + telemetrySlot compose: a real phase title reaches a cell o
try std.testing.expectEqualStrings("find", compose("find security bugs"));
try std.testing.expectEqualStrings("verify", compose("verify each finding"));
try std.testing.expectEqualStrings("synthesize", compose("Synthesize the results"));
- try std.testing.expectEqualStrings("transform", compose("transform each file"));
+ // #296 — `transform` is a PIPELINE stage label, and pipeline stages never
+ // reach scoreVariants, so it was dropped from the vocabulary rather than
+ // left advertising a cell nothing could fill. It is now uncelled like any
+ // other off-vocabulary title; see the D-shape comment in shapes.zig.
+ try std.testing.expectEqualStrings("", compose("transform each file"));
// A customer name in a phase title reaches no cell and leaves no plaintext.
try std.testing.expectEqualStrings("", compose("Migrate Acme billing schema"));
// And the composed result is always vocabulary-or-empty, never caller text.
diff --git a/src/serde.zig b/src/serde.zig
index bc317b2d..2af99a8e 100644
--- a/src/serde.zig
+++ b/src/serde.zig
@@ -177,10 +177,14 @@ fn hasSchemaComposition(obj: std.json.ObjectMap) bool {
/// ever got a chance to run. A tool's argument schema is an object by
/// construction on both wires, so say so. A schema that already declares a
/// type, or that defers to a root composition keyword, is left untouched.
-fn defaultRootObjectType(arena: Allocator, value: *Value) Allocator.Error!void {
- if (value.* != .object) return;
- if (value.object.get("type") != null or hasSchemaComposition(value.object)) return;
+///
+/// Reports whether it changed anything, so a writer that would otherwise pass
+/// the catalog through verbatim can keep the original bytes.
+fn defaultRootObjectType(arena: Allocator, value: *Value) Allocator.Error!bool {
+ if (value.* != .object) return false;
+ if (value.object.get("type") != null or hasSchemaComposition(value.object)) return false;
try value.object.put(arena, "type", .{ .string = "object" });
+ return true;
}
/// Kimi's official Anthropic adapter places a cache breakpoint on the final
@@ -193,7 +197,7 @@ pub fn writeAnthropicTools(s: *std.json.Stringify, arena: Allocator, raw: []cons
if (value != .array or value.array.items.len == 0) return s.print("{s}", .{raw});
for (value.array.items) |*tool| {
if (tool.* != .object) continue;
- if (tool.object.getPtr("input_schema")) |schema| try defaultRootObjectType(arena, schema);
+ if (tool.object.getPtr("input_schema")) |schema| _ = try defaultRootObjectType(arena, schema);
}
try s.beginArray();
for (value.array.items, 0..) |tool, i| {
@@ -275,7 +279,7 @@ fn normalizeKimiSchema(arena: Allocator, value: *Value, root: bool) Allocator.Er
// The root never guesses (#261 wants "object" there, and inferredKimiType's
// fallback is "string"); every child keeps the kimi-code inference.
if (root) {
- try defaultRootObjectType(arena, value);
+ _ = try defaultRootObjectType(arena, value);
} else if (obj.get("type") == null and !hasSchemaComposition(obj.*)) {
if (inferredKimiType(obj.*)) |kind| try obj.put(arena, "type", .{ .string = kind });
}
@@ -318,6 +322,35 @@ pub fn writeKimiTools(s: *std.json.Stringify, arena: Allocator, raw: []const u8)
try s.write(value);
}
+/// Issue #261 follow-up: writeKimiTools and writeAnthropicTools repair a
+/// typeless MCP root schema, but every other OpenAI-compatible endpoint got the
+/// catalog bytes verbatim — and any endpoint validating as strictly as Moonshot
+/// rejects the whole request ("parameters.type is required and must be
+/// 'object'") before a single tool can run. Repair the root for both OpenAI
+/// tool shapes: chat completions nests the schema at `function.parameters`,
+/// the Responses API keeps it flat at `parameters`.
+///
+/// Only the root type is added — no child inference (that is Kimi-only), and a
+/// catalog that needs no repair, or that we cannot parse, goes out as its
+/// original bytes so the usual request keeps a byte-identical cached prefix.
+pub fn writeOpenAITools(s: *std.json.Stringify, arena: Allocator, raw: []const u8) !void {
+ const value = std.json.parseFromSliceLeaky(Value, arena, raw, .{ .allocate = .alloc_always }) catch return s.print("{s}", .{raw});
+ if (value != .array) return s.print("{s}", .{raw});
+ var repaired = false;
+ for (value.array.items) |*tool| {
+ if (tool.* != .object) continue;
+ const params = if (tool.object.getPtr("function")) |f|
+ (if (f.* == .object) f.object.getPtr("parameters") else null)
+ else
+ tool.object.getPtr("parameters");
+ if (params) |p| {
+ if (try defaultRootObjectType(arena, p)) repaired = true;
+ }
+ }
+ if (!repaired) return s.print("{s}", .{raw});
+ try s.write(value);
+}
+
/// Serialize one chat-completions history message. Everything is echoed
/// verbatim except an assistant tool-call turn whose `content` is null, which
/// several providers reject — that one is rebuilt with `content: ""`.
@@ -367,6 +400,13 @@ fn renderKimiTools(arena: Allocator, raw: []const u8) ![]const u8 {
return aw.writer.buffered();
}
+fn renderOpenAITools(arena: Allocator, raw: []const u8) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try writeOpenAITools(&s, arena, raw);
+ return aw.writer.buffered();
+}
+
fn renderAnthropicTools(arena: Allocator, raw: []const u8, cache: bool) ![]const u8 {
var aw: Io.Writer.Allocating = .init(arena);
var s: std.json.Stringify = .{ .writer = &aw.writer };
@@ -413,3 +453,35 @@ test "anthropic tools give a typeless MCP input_schema type object (#261)" {
const typed = "[{\"name\":\"t\",\"description\":\"\",\"input_schema\":{\"type\":\"object\",\"properties\":{}}}]";
try std.testing.expectEqualStrings(typed, try renderAnthropicTools(arena, typed, false));
}
+
+test "openai and responses tools give a typeless MCP root schema type object (#261)" {
+ var arena_state: std.heap.ArenaAllocator = .init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ // Chat completions: mcp.zig substitutes `{}` for a server that advertises
+ // no inputSchema, and renderRootTools nests it under function.parameters.
+ const chat = try renderOpenAITools(arena, "[{\"type\":\"function\",\"function\":{\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{}}}]");
+ try std.testing.expectEqualStrings(
+ "[{\"type\":\"function\",\"function\":{\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{\"type\":\"object\"}}}]",
+ chat,
+ );
+
+ // Responses: the same tool, flat, with `strict` after the schema.
+ const responses = try renderOpenAITools(arena, "[{\"type\":\"function\",\"name\":\"mcp__s__t\",\"description\":\"\",\"parameters\":{},\"strict\":false}]");
+ try std.testing.expect(std.mem.indexOf(u8, responses, "\"parameters\":{\"type\":\"object\"},\"strict\":false") != null);
+
+ // Only the root is repaired: a typeless child keeps no type here (that
+ // inference is Kimi's stricter validator, not JSON Schema).
+ const props = try renderOpenAITools(arena, "[{\"type\":\"function\",\"function\":{\"name\":\"t\",\"description\":\"\",\"parameters\":{\"properties\":{\"path\":{}}}}}]");
+ try std.testing.expect(std.mem.indexOf(u8, props, "\"parameters\":{\"properties\":{\"path\":{}},\"type\":\"object\"}") != null);
+
+ // A declared type, a root composition keyword, and an unparsable catalog
+ // all reach the wire as their original bytes — whitespace included, since
+ // a catalog that needs no repair is never re-serialized.
+ const typed = "[{\"type\":\"function\",\"name\":\"t\",\"description\":\"\",\"parameters\":{\"type\": \"object\", \"properties\": {}},\"strict\":false}]";
+ try std.testing.expectEqualStrings(typed, try renderOpenAITools(arena, typed));
+ const composed = "[{\"type\":\"function\",\"function\":{\"name\":\"t\",\"description\":\"\",\"parameters\":{\"anyOf\":[{\"type\":\"object\"}]}}}]";
+ try std.testing.expectEqualStrings(composed, try renderOpenAITools(arena, composed));
+ try std.testing.expectEqualStrings("not json", try renderOpenAITools(arena, "not json"));
+}
diff --git a/src/session.zig b/src/session.zig
index fa45283e..f23e3134 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -18,6 +18,7 @@ const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
const util = @import("util.zig");
const goal_state = @import("goal_state.zig");
+const session_lock = @import("session_lock.zig"); // the locked write path (#289)
const Agent = agent_mod.Agent;
const Keys = provider_mod.Keys;
const unixMs = util.unixMs;
@@ -286,10 +287,9 @@ pub fn saveSession(root: *Agent, arena: Allocator, name: []const u8) !void {
try s.write(@min(context_estimate.local, @as(u64, std.math.maxInt(i64))));
try s.endObject();
- Io.Dir.cwd().createDir(root.io, ".graff", .default_dir) catch {};
- Io.Dir.cwd().createDir(root.io, sessions_dir, .default_dir) catch {};
- const path = try sessionPath(arena, name);
- try Io.Dir.cwd().writeFile(root.io, .{ .sub_path = path, .data = aw.writer.buffered() });
+ // #289: two graffs in one workspace share this file — writeSession makes the
+ // parent dirs and takes an exclusive advisory lock, so the loser reports.
+ try session_lock.writeSession(root.io, .cwd(), try sessionPath(arena, name), aw.writer.buffered());
}
/// Parse the persisted `goal` field into a structured Goal (#223). A bare string
diff --git a/src/session_lock.zig b/src/session_lock.zig
new file mode 100644
index 00000000..b9fabeee
--- /dev/null
+++ b/src/session_lock.zig
@@ -0,0 +1,79 @@
+//! The session file's write path: parent directories, an exclusive advisory
+//! lock, and the write itself. Two graff instances in one workspace share
+//! `.graff/sessions/<name>.session.json`, and an unlocked whole-file write let
+//! the second one silently clobber the first (#289, item 4). Split out of
+//! session.zig, which is at the 600-line cap.
+//!
+//! The lock is ADVISORY and best effort: a filesystem that cannot lock (some
+//! network mounts) degrades to the old unlocked write rather than refusing to
+//! save. Only real contention — another live graff holding this very session —
+//! is reported, as `error.SessionOpenInAnotherGraff`; /save and the one-shot
+//! saver already print the error name, so the user sees which failure it was.
+
+const std = @import("std");
+const Io = std.Io;
+
+/// Write `data` to `path` under `dir` while holding an exclusive advisory lock
+/// on the session file, creating the parent directory chain first.
+///
+/// std.Io takes the lock with `flock(LOCK_EX|LOCK_NB)` on POSIX and
+/// `NtLockFile` on Windows, so the platform difference (Windows has no flock)
+/// is handled there instead of by a raw syscall here.
+///
+/// The open must NOT truncate: on Linux and Windows the lock is taken *after*
+/// the open, so `O_TRUNC` would already have emptied the other graff's session
+/// file by the time we discovered the contention. We open at the existing
+/// length, and only once the lock is ours overwrite from byte 0 and cut the
+/// file back to the new length.
+pub fn writeSession(io: Io, dir: Io.Dir, path: []const u8, data: []const u8) !void {
+ if (std.fs.path.dirname(path)) |parent| dir.createDirPath(io, parent) catch {};
+ const file = dir.createFile(io, path, .{
+ .truncate = false,
+ .lock = .exclusive,
+ .lock_nonblocking = true,
+ }) catch |err| switch (err) {
+ // Another graff is live on this session: report, never clobber.
+ error.WouldBlock => return error.SessionOpenInAnotherGraff,
+ // #289: locking is advisory. A filesystem with no working locks (some
+ // network mounts report either of these) must still save the session —
+ // degrade to the pre-#289 unlocked write instead of losing the file.
+ error.FileLocksUnsupported, error.SystemResources => {
+ return dir.writeFile(io, .{ .sub_path = path, .data = data });
+ },
+ else => return err,
+ };
+ defer file.close(io);
+ try file.writePositionalAll(io, data, 0);
+ try file.setLength(io, data.len);
+}
+
+test "a second graff reports contention instead of clobbering the session (#289)" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const path = ".graff/sessions/wf.session.json";
+ const first = "{\"title\":\"first graff\",\"messages\":[1,2,3]}";
+
+ // Creates .graff/sessions/ on the way, like the old inline createDir pair.
+ try writeSession(io, tmp.dir, path, first);
+
+ // A second graff holding the same session file, exactly as writeSession
+ // holds it. flock/NtLockFile are per open file description, so this
+ // conflicts even though it is the same process.
+ const held = try tmp.dir.createFile(io, path, .{ .truncate = false, .lock = .exclusive, .lock_nonblocking = true });
+ const second = "{\"t\":2}"; // shorter: a clobbering write would leave a tail
+ try std.testing.expectError(error.SessionOpenInAnotherGraff, writeSession(io, tmp.dir, path, second));
+ held.close(io); // the other graff exits and the lock goes with it
+
+ // Read only after the lock is gone: Windows byte-range locks are mandatory.
+ const kept = try tmp.dir.readFileAlloc(io, path, std.testing.allocator, .limited(4096));
+ defer std.testing.allocator.free(kept);
+ try std.testing.expectEqualStrings(first, kept);
+
+ // With the lock free the write goes through, and truncates to the new
+ // length rather than leaving the longer previous session's tail behind.
+ try writeSession(io, tmp.dir, path, second);
+ const now = try tmp.dir.readFileAlloc(io, path, std.testing.allocator, .limited(4096));
+ defer std.testing.allocator.free(now);
+ try std.testing.expectEqualStrings(second, now);
+}
diff --git a/src/shapes.zig b/src/shapes.zig
index 53f1ffbe..18a072a3 100644
--- a/src/shapes.zig
+++ b/src/shapes.zig
@@ -40,14 +40,17 @@ pub const canonical_slots = [_][]const u8{
// C — design/solve
"variants",
"build",
- // D — migration/mechanical.
- // KNOWN GAP: pipeline stages call runSub directly and never reach the
- // variant-scoring path, so a spec-compliant `transform` stage cannot fill
- // its cell today — it is scoreable only via an off-catalog phase of the same
- // name. Kept in the vocabulary because it is the right name and becomes
- // reachable the moment pipeline stages are scored; see the pipeline-scoring
- // issue. Migration execution is unaffected — only learning/promotion is.
- "transform",
+ // D — migration/mechanical has NO slot: shape D is a pipeline, and a
+ // pipeline stage cannot be scored (#296). `transform` used to sit here and
+ // advertise a cell nothing could ever fill — pipeline stages call runSub
+ // directly and never reach scoreVariants, the one path that derives a slot,
+ // so the only way to score one was to disobey the catalog and run it as a
+ // phase. Dropped rather than scored: a tournament needs an axis a stage
+ // does not have. One stage carries ONE system_prompt, so its N "variants"
+ // would be N ITEMS — the same genome on different inputs — and ranking
+ // those measures item difficulty, not prompt quality. Restore `transform`
+ // only together with per-stage prompt variants; migration EXECUTION is
+ // unaffected either way, the catalog still names the stage below.
// E — feature
"scope",
"implement",
@@ -188,6 +191,30 @@ test "shape catalog names every canonical slot it depends on" {
}
}
+test "#296: no canonical slot is reachable only through a pipeline stage" {
+ // Only the PHASES path scores: scoreVariants derives the slot with
+ // canonicalSlot(phase title), and pipeline stages call runSub directly.
+ // So a slot the catalog names ONLY inside shape D (the pipeline shape)
+ // declares a MAP-Elites cell nothing can ever fill. `transform` was exactly
+ // that, and this pins it shut — re-adding it to canonical_slots turns this
+ // red, because D's stage list is the only place the catalog says the word.
+ const d = std.mem.indexOf(u8, shape_catalog_note, "D migration/mechanical").?;
+ const e = std.mem.indexOf(u8, shape_catalog_note, "E feature").?;
+ // The trailing prose (scaling advice, the isolation warning) names stages
+ // by example, so the E window has to stop before it or this proves nothing.
+ const tail = std.mem.indexOf(u8, shape_catalog_note, "Scale to the ask").?;
+ for (canonical_slots) |slot| {
+ const in_a_phase_shape = std.mem.indexOf(u8, shape_catalog_note[0..d], slot) != null or
+ std.mem.indexOf(u8, shape_catalog_note[e..tail], slot) != null;
+ try std.testing.expect(in_a_phase_shape);
+ }
+ // Migration EXECUTION is untouched: the catalog still tells the model to
+ // run a `transform` stage, it just no longer claims a fitness cell for it.
+ try std.testing.expect(std.mem.indexOf(u8, shape_catalog_note, "transform") != null);
+ try std.testing.expectEqualStrings("", canonicalSlot("transform"));
+ try std.testing.expectEqualStrings("", canonicalSlot("transform each file"));
+}
+
test "shape catalog covers all five shapes and stays within a sane token budget" {
for ([_][]const u8{ "A review/audit", "B research/understand", "C design/solve", "D migration/mechanical", "E feature" }) |shape| {
try std.testing.expect(std.mem.indexOf(u8, shape_catalog_note, shape) != null);
diff --git a/src/trace.zig b/src/trace.zig
index 544dcab5..d73d930a 100644
--- a/src/trace.zig
+++ b/src/trace.zig
@@ -477,6 +477,13 @@ test "writeJsonLine signals a file-write failure so the tracer can disable (#242
try std.testing.expect(writeJsonLine(std.testing.allocator, &wb, identity, .{ .ev = "ws", .detail = "connecting" }));
}
+test { // #270: mainloop_trace writes the per-turn record through this file, but
+ // unit_tests' root is main.zig — a module only reachable transitively is
+ // never analyzed for tests. Pull its final-response-shape tests in here,
+ // where the tracer they feed lives.
+ _ = @import("mainloop_trace.zig");
+}
+
test "run-scoped paths separate traces and trajectories" {
const trace_path = try tracePath(std.testing.allocator, "abc123");
defer std.testing.allocator.free(trace_path);
diff --git a/src/vision.zig b/src/vision.zig
index 8b931364..9a7f4e59 100644
--- a/src/vision.zig
+++ b/src/vision.zig
@@ -117,7 +117,12 @@ pub fn stageImagePath(root: *Agent, path: []const u8) StageResult {
/// once the image is visible — so non-image `@[path]` entries the agent should
/// open with its tools are untouched. No-op for non-vision providers, when an
/// image is already staged (e.g. via /image), or when no image marker is found.
+///
+/// Also the per-turn home of the MCP image handoff (#249): mainloop calls this
+/// once per user message with the root agent in hand, which is the only place
+/// that holds both the registry and the provider.
pub fn stageGuiImageAttachment(root: *Agent, msg: []const u8) void {
+ if (root.registry) |reg| if (mcpImageHandoff(reg, visionCapable(root.provider), &root.pending_image)) return; // #249
if (root.pending_image != null) return;
if (!visionCapable(root.provider)) return;
var search: usize = 0;
@@ -130,6 +135,77 @@ pub fn stageGuiImageAttachment(root: *Agent, msg: []const u8) void {
}
}
+/// An MCP `tools/call` content block that carries pixels:
+/// `{type:"image", data:"<base64>", mimeType:"image/png"}` (#249). The strings
+/// are borrowed from the parsed response, so `stage` copies them out before the
+/// per-call response arena dies.
+pub const McpImageBlock = struct {
+ media_type: []const u8,
+ b64: []const u8,
+ bytes: usize, // decoded size, for the line the model reads
+
+ pub fn stage(self: McpImageBlock, arena: Allocator, label: []const u8) !PendingImage {
+ return .{
+ .media_type = try arena.dupe(u8, self.media_type),
+ .b64 = try arena.dupe(u8, self.b64),
+ .label = try arena.dupe(u8, label),
+ };
+ }
+};
+
+/// The same ceiling `stageImagePath` reads a file under.
+const max_mcp_image_bytes = 5 * 1024 * 1024;
+
+/// Recognize an MCP image content block. Null for anything else — a text block,
+/// a non-`image/*` mime, base64 we cannot decode, or a payload over the ceiling
+/// — so a malformed result is rejected at our boundary instead of turning into
+/// a provider 400 one call later.
+pub fn mcpImageBlock(block: Value) ?McpImageBlock {
+ if (block != .object) return null;
+ const t = block.object.get("type") orelse return null;
+ if (t != .string or !std.mem.eql(u8, t.string, "image")) return null;
+ const data = block.object.get("data") orelse return null;
+ if (data != .string) return null;
+ // mimeType is required by the spec; default rather than drop an otherwise
+ // usable image, but refuse a mime that is not an image at all.
+ const mime = if (block.object.get("mimeType")) |m| (if (m == .string) m.string else "") else "";
+ const media_type = if (mime.len == 0) "image/png" else mime;
+ if (!std.mem.startsWith(u8, media_type, "image/")) return null;
+ const bytes = std.base64.standard.Decoder.calcSizeForSlice(data.string) catch return null;
+ if (bytes == 0 or bytes > max_mcp_image_bytes) return null;
+ return .{ .media_type = media_type, .b64 = data.string, .bytes = bytes };
+}
+
+/// What became of an image block, so the tool result says it out loud instead
+/// of dropping the pixels in silence the way it used to (#249).
+pub const McpImageFate = enum { staged, no_vision, already_staged };
+
+pub fn mcpImageNote(w: *Io.Writer, blk: McpImageBlock, fate: McpImageFate) !void {
+ try w.print("[image: {s}, {d} bytes — {s}]", .{ blk.media_type, blk.bytes, switch (fate) {
+ .staged => "attached to your next turn",
+ .no_vision => no_vision_message,
+ .already_staged => "not attached: another image is already queued for the next turn",
+ } });
+}
+
+/// Move an image an MCP tool staged on the registry into the agent's slot, and
+/// tell the registry whether this model takes images at all — the registry sees
+/// the pixels but has no route to the provider (#249). `reg` is a
+/// `*mcp.Registry`, taken as anytype so vision.zig need not import back into the
+/// MCP client. Returns true when an image was promoted.
+pub fn mcpImageHandoff(reg: anytype, supports_vision: bool, slot: *?PendingImage) bool {
+ reg.mutex.lockUncancelable(reg.io); // `call` stages from agent pool threads
+ defer reg.mutex.unlock(reg.io);
+ reg.vision_capable = supports_vision;
+ const img = reg.pending_image orelse return false;
+ reg.pending_image = null;
+ // A text-only model, or /image already won this turn: drop it rather than
+ // let it surface several turns later, stripped of its context.
+ if (!supports_vision or slot.* != null) return false;
+ slot.* = img;
+ return true;
+}
+
/// macOS: dump the clipboard image (if any) to a temp PNG via osascript and
/// return its path; null if the clipboard holds no image (or not macOS).
/// (A terminal can't receive clipboard image bytes over stdin, so we ask the OS.)
@@ -287,3 +363,117 @@ test "pasteMessage: every non-image outcome has a distinct, non-empty line" {
// The staged-failure path reuses the same sentence rather than duplicating it.
try std.testing.expectEqualStrings(no_vision_message, pasteMessage(.no_vision));
}
+
+/// Parse one JSON literal into `a` — the MCP content blocks these tests feed in.
+fn parseBlock(a: Allocator, json: []const u8) !Value {
+ return std.json.parseFromSliceLeaky(Value, a, json, .{ .allocate = .alloc_always });
+}
+
+test "mcpImageBlock: an MCP image block round-trips base64 + mimeType (#249)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const png = "\x89PNG\r\n\x1a\n"; // 8 bytes of a real PNG signature
+ var b64_buf: [16]u8 = undefined;
+ const b64 = std.base64.standard.Encoder.encode(&b64_buf, png);
+ const json = try std.fmt.allocPrint(a, "{{\"type\":\"image\",\"data\":\"{s}\",\"mimeType\":\"image/png\"}}", .{b64});
+
+ const img = mcpImageBlock(try parseBlock(a, json)) orelse return error.ImageBlockNotRecognized;
+ try std.testing.expectEqualStrings("image/png", img.media_type);
+ try std.testing.expectEqual(@as(usize, png.len), img.bytes);
+
+ const staged = try img.stage(a, "mcp__shots__grab");
+ try std.testing.expectEqualStrings("image/png", staged.media_type);
+ try std.testing.expectEqualStrings(b64, staged.b64);
+ try std.testing.expectEqualStrings("mcp__shots__grab", staged.label);
+ var round_trip: [png.len]u8 = undefined;
+ try std.base64.standard.Decoder.decode(&round_trip, staged.b64);
+ try std.testing.expectEqualSlices(u8, png, &round_trip);
+
+ // Everything that is not a usable image stays out of the vision path.
+ try std.testing.expect(mcpImageBlock(try parseBlock(a, "{\"type\":\"text\",\"text\":\"hi\"}")) == null);
+ try std.testing.expect(mcpImageBlock(try parseBlock(a, "{\"type\":\"image\",\"data\":\"!!not-base64!!\"}")) == null);
+ try std.testing.expect(mcpImageBlock(try parseBlock(a, "{\"type\":\"image\",\"data\":\"aGVsbG8=\",\"mimeType\":\"text/plain\"}")) == null);
+ // mimeType is optional in the wild; default instead of dropping the pixels.
+ const defaulted = mcpImageBlock(try parseBlock(a, "{\"type\":\"image\",\"data\":\"aGVsbG8=\"}")) orelse return error.ImageBlockNotRecognized;
+ try std.testing.expectEqualStrings("image/png", defaulted.media_type);
+}
+
+test "renderContent: a text+image MCP result keeps both and stages the image (#249)" {
+ const mcp_content = @import("mcp_content.zig");
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const content = try parseBlock(a,
+ \\[{"type":"text","text":"here is the screenshot"},
+ \\ {"type":"image","data":"aGVsbG8=","mimeType":"image/jpeg"}]
+ );
+ var slot: ?PendingImage = null;
+ var w: Io.Writer.Allocating = .init(a);
+ try mcp_content.renderContent(&w.writer, content, .{ .arena = a, .slot = &slot, .label = "mcp__shots__grab", .supports_vision = true });
+
+ const text = w.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, text, "here is the screenshot") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "image/jpeg") != null);
+ const img = slot orelse return error.ImageNotStaged;
+ try std.testing.expectEqualStrings("image/jpeg", img.media_type);
+ try std.testing.expectEqualStrings("aGVsbG8=", img.b64);
+ try std.testing.expectEqualStrings("mcp__shots__grab", img.label);
+}
+
+test "renderContent: an image-only result is never silently empty (#249)" {
+ const mcp_content = @import("mcp_content.zig");
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const content = try parseBlock(a, "[{\"type\":\"image\",\"data\":\"aGVsbG8=\",\"mimeType\":\"image/png\"}]");
+
+ // Vision model: staged, and the text says so.
+ var slot: ?PendingImage = null;
+ var w: Io.Writer.Allocating = .init(a);
+ try mcp_content.renderContent(&w.writer, content, .{ .arena = a, .slot = &slot, .label = "t", .supports_vision = true });
+ try std.testing.expect(slot != null);
+ try std.testing.expect(std.mem.indexOf(u8, w.writer.buffered(), "image/png") != null);
+
+ // Text-only model: nothing staged, but the model is TOLD, rather than
+ // receiving "" and inferring the tool did nothing.
+ var slot2: ?PendingImage = null;
+ var w2: Io.Writer.Allocating = .init(a);
+ try mcp_content.renderContent(&w2.writer, content, .{ .arena = a, .slot = &slot2, .label = "t", .supports_vision = false });
+ try std.testing.expect(slot2 == null);
+ try std.testing.expect(std.mem.indexOf(u8, w2.writer.buffered(), no_vision_message) != null);
+ try std.testing.expect(w2.writer.buffered().len > 0);
+}
+
+test "mcpImageHandoff: registry image reaches the agent slot, vision models only (#249)" {
+ const mcp = @import("mcp.zig");
+ const io = std.testing.io;
+ var reg = mcp.Registry.empty(std.testing.allocator, io);
+ defer reg.deinit();
+ const img: PendingImage = .{ .media_type = "image/png", .b64 = "aGVsbG8=", .label = "mcp__shots__grab" };
+
+ // Text-only model: the fact is pushed to the registry and the image is
+ // dropped rather than surfacing turns later out of context.
+ reg.pending_image = img;
+ var slot: ?PendingImage = null;
+ try std.testing.expect(!mcpImageHandoff(&reg, false, &slot));
+ try std.testing.expect(slot == null);
+ try std.testing.expect(!reg.vision_capable);
+ try std.testing.expect(reg.pending_image == null);
+
+ // Vision model: promoted, and the registry slot is cleared so one image is
+ // never attached to two turns.
+ reg.pending_image = img;
+ try std.testing.expect(mcpImageHandoff(&reg, true, &slot));
+ try std.testing.expect(reg.vision_capable);
+ try std.testing.expect(reg.pending_image == null);
+ try std.testing.expectEqualStrings("aGVsbG8=", slot.?.b64);
+
+ // /image already won this turn: keep the user's pick, drop the tool's.
+ reg.pending_image = .{ .media_type = "image/gif", .b64 = "R0lG", .label = "later" };
+ try std.testing.expect(!mcpImageHandoff(&reg, true, &slot));
+ try std.testing.expectEqualStrings("aGVsbG8=", slot.?.b64);
+ try std.testing.expect(reg.pending_image == null);
+}
diff --git a/src/workflow.zig b/src/workflow.zig
index 9a3be3de..eca7a616 100644
--- a/src/workflow.zig
+++ b/src/workflow.zig
@@ -38,6 +38,10 @@ const failureAllowsRetry = subagent_run.failureAllowsRetry;
const fleet = @import("fleet.zig");
const Isolation = fleet.Isolation; // #276 P0-1
const telemetry = @import("telemetry.zig");
+// #63: stable workflow/phase/task ids + the additive `workflow_progress`
+// JSONL event, so the REPL can map a run from state instead of scraping the
+// std.debug.print lines below. Also holds the run manifest (see below).
+const wfp = @import("workflow_progress.zig");
const max_workflow_phases = 5;
@@ -302,6 +306,12 @@ fn runPipeline(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
const wf_start = Io.Timestamp.now(ctx.io, .awake);
std.debug.print(" [workflow] pipeline: {d} item(s) × {d} stage(s), no barrier\n", .{ items.len, stages.len });
+ // #63 — same fact, as state: phase_index 0 is the run-level event, since a
+ // pipeline has stages rather than phases. Per-stage events would have to be
+ // threaded into pipelineChain (one chain per item, on its own pool thread);
+ // that is left to the follow-up that renders them.
+ const run_id = try wfp.nextRunId(arena);
+ wfp.phase(ctx.io, arena, run_id, 0, stages.len, "pipeline", "started", items.len);
// Spawn one chain per item — all joined before any fallible work so an early
// return can never abandon a running chain.
@@ -324,56 +334,16 @@ fn runPipeline(ctx: ToolCtx, pv: Value, outer_context: []const u8) !ToolOutput {
return .{ .text = try gpa.dupe(u8, std.mem.trimEnd(u8, aw.writer.buffered(), "\n")) };
}
-// ── U2: all-failed abort + run manifest ─────────────────────────────────────
-// A phase where every task failed used to still feed {{prev}} — a bare
-// "(no result — task failed)" header per task — into the next phase, so a
-// synthesis stage confidently answered from zero evidence (the worst output
-// class: a wrong answer that looks researched). buildAbortText and
-// buildManifest are kept PURE (no ctx/io) so both are unit-testable without
-// running a real subagent.
-
-pub const PhaseTally = struct {
- phase_no: usize,
- total_phases: usize,
- title: []const u8,
- ok: usize,
- total: usize,
- retried: usize,
- skipped_when: ?[]const u8 = null,
-};
-
-/// Build the hard-stop text for a phase where every task failed: the
-/// assembled per-task failure headers plus a line naming the phase, so the
-/// caller (or a human) can see exactly why the run stopped instead of
-/// silently receiving empty "evidence". `details` is parallel to `labels`
-/// (#248): each entry is that task's capped one-line error excerpt, or "" when
-/// the task left nothing to report.
-pub fn buildAbortText(arena: Allocator, labels: []const []const u8, details: []const []const u8, phase_no: usize, total_phases: usize, title: []const u8) ![]const u8 {
- var aw: Io.Writer.Allocating = .init(arena);
- for (labels, details) |label, detail| {
- try aw.writer.print("### {s} (no result — task failed)\n", .{label});
- if (detail.len > 0) try aw.writer.print("{s}\n", .{detail});
- try aw.writer.writeAll("\n");
- }
- try aw.writer.print("workflow aborted: every task in phase {d}/{d} ({s}) failed", .{ phase_no, total_phases, title });
- return aw.writer.buffered();
-}
+// U2's all-failed abort text, the run manifest and PhaseTally moved to
+// workflow_progress.zig alongside the #63 structured events (this file is at
+// the 600-line cap and both are "what did this run do" reporting). Aliased
+// back so workflow_test.zig and the call sites below still reach them here.
+pub const PhaseTally = wfp.PhaseTally;
+pub const buildAbortText = wfp.buildAbortText;
+pub const buildManifest = wfp.buildManifest;
-/// Build the trailing "## workflow" manifest block from one tally per phase —
-/// currently the only way the orchestrator learns a phase was skipped, or
-/// that a synthesis stage is about to work from partial (some-tasks-failed)
-/// evidence rather than a clean phase.
-pub fn buildManifest(arena: Allocator, tallies: []const PhaseTally) ![]const u8 {
- var aw: Io.Writer.Allocating = .init(arena);
- try aw.writer.writeAll("## workflow\n");
- for (tallies) |t| {
- if (t.skipped_when) |w| {
- try aw.writer.print("phase {d}/{d} {s}: SKIPPED (when=\"{s}\")\n", .{ t.phase_no, t.total_phases, t.title, w });
- } else {
- try aw.writer.print("phase {d}/{d} {s}: {d}/{d} ok, {d} retried\n", .{ t.phase_no, t.total_phases, t.title, t.ok, t.total, t.retried });
- }
- }
- return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");
+test { // a new module's tests run only when something references it (see main.zig)
+ _ = wfp;
}
/// Dynamic workflows as data: sequential phases, parallel tasks. Each task
@@ -417,6 +387,9 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
defer arena_state.deinit();
const arena = arena_state.allocator();
+ // #63 — one stable id per run; every phase/task event below keys to it.
+ const run_id = try wfp.nextRunId(arena);
+
// Telemetry: one "workflow" record per run — phase/task/failure counts
// and wall-clock — emitted however the run ends.
const wf_start = Io.Timestamp.now(ctx.io, .awake);
@@ -451,10 +424,12 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
// skipped final phase just returns the prior phase's results (early-exit).
if (phase_no > 1) if (phase.get("when")) |wv| if (wv == .string and !gateAllows(prev_results, wv.string)) {
std.debug.print(" [workflow] phase {d}/{d}: {s} — SKIPPED (when \"{s}\" absent)\n", .{ phase_no, phases.len, title, wv.string });
+ wfp.phase(ctx.io, arena, run_id, phase_no, phases.len, title, "skipped", tasks.len); // #63
tallies[phase_no - 1] = .{ .phase_no = phase_no, .total_phases = phases.len, .title = title, .ok = 0, .total = tasks.len, .retried = 0, .skipped_when = wv.string };
continue;
};
std.debug.print(" [workflow] phase {d}/{d}: {s} ({d} task(s))\n", .{ phase_no, phases.len, title, tasks.len });
+ wfp.phase(ctx.io, arena, run_id, phase_no, phases.len, title, "started", tasks.len); // #63
// Resolve prompts: substitute or append the previous phase results.
// raws keeps each task's pre-substitution spec (a stable eval-set id for
@@ -496,10 +471,16 @@ pub fn execWorkflow(ctx: ToolCtx, input: Value) !ToolOutput {
// can never abandon running subagents or free their result slots.
const futures = try arena.alloc(Io.Future(ToolOutput), tasks.len);
const outputs = try arena.alloc(ToolOutput, tasks.len);
- for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures) |label, prompt, override, niche, isolation, isolation_fallback, *fut| {
+ for (labels, prompts, overrides, niches, isolations, isolation_fallbacks, futures, 1..) |label, prompt, override, niche, isolation, isolation_fallback, *fut, task_no| {
+ wfp.task(ctx.io, arena, run_id, phase_no, task_no, tasks.len, label, "running"); // #63
fut.* = ctx.io.async(workflowTask, .{ ctx, label, prompt, override, niche, isolation, isolation_fallback });
}
- for (futures, outputs) |*fut, *out| out.* = fut.await(ctx.io);
+ for (futures, outputs, labels, 1..) |*fut, *out, label, task_no| {
+ out.* = fut.await(ctx.io);
+ // #63 — terminal per task, so a UI can settle that row without
+ // waiting for the phase (and before the retry pass below reruns it).
+ wfp.task(ctx.io, arena, run_id, phase_no, task_no, tasks.len, label, if (out.is_error) "failed" else "completed");
+ }
defer for (outputs) |out| gpa.free(out.text);
wf_tasks += tasks.len;
diff --git a/src/workflow_progress.zig b/src/workflow_progress.zig
new file mode 100644
index 00000000..37e93847
--- /dev/null
+++ b/src/workflow_progress.zig
@@ -0,0 +1,262 @@
+//! Structured workflow progress (#63) plus the text run manifest, split out of
+//! workflow.zig (which sits at the 600-line cap). Both answer "what did this
+//! run do" — one for a machine, one for the model reading the tool result.
+//!
+//! Why the events exist (#63): an ultracode run reached the REPL only as
+//! std.debug.print lines (" [workflow] phase 1/2: find (3 task(s))"), so any
+//! UI wanting a live workflow map had to scrape text. `workflow_progress` is
+//! ADDITIVE — the human lines stay, tool_call/tool_result are untouched — and
+//! rides the SAME --json stdout path as every other event (main_mod.g_out
+//! under g_gui_mu), so parallel task emits can never interleave mid-line.
+//!
+//! Deliberately NOT here: the navigable REPL element #63 also asks for. That
+//! is a separable follow-up; this module is the state it will render.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const main_mod = @import("main.zig");
+const shapes = @import("shapes.zig");
+const util = @import("util.zig");
+
+/// Titles and task labels are free text from the model. Cap them so one absurd
+/// title can never turn a progress line into a megabyte of JSONL.
+const label_cap = 200;
+
+/// Monotonic counter behind the `wf-N` ids. Atomic because two workflows can be
+/// in flight on different pool threads (a background job's run alongside the
+/// root turn's), and the ids have to stay distinct.
+var g_next_run: std.atomic.Value(u64) = .init(1);
+
+/// Test seam: when set, events render here instead of stdout. Lets a unit test
+/// prove the workflow.zig call sites actually fire without a live --json
+/// session (the real path needs both a stdout writer and a working Io).
+pub var g_test_sink: ?*Io.Writer.Allocating = null;
+
+pub const PhaseEvent = struct {
+ type: []const u8 = "workflow_progress",
+ workflow_id: []const u8,
+ /// "" for the run-level event (phase_index 0), "<workflow_id>/p<n>" otherwise.
+ phase_id: []const u8,
+ /// 1-based. 0 means the run itself — a pipeline has stages, not phases.
+ phase_index: usize,
+ phase_count: usize,
+ /// The canonical slot from shapes.zig, "" when the title is off-vocabulary.
+ /// A CLOSED vocabulary is what a consumer can switch on; the authored text
+ /// rides along as `title`, which is what it renders.
+ phase: []const u8,
+ title: []const u8,
+ /// started | skipped
+ status: []const u8,
+ task_count: usize,
+};
+
+pub const TaskEvent = struct {
+ type: []const u8 = "workflow_progress",
+ workflow_id: []const u8,
+ phase_id: []const u8,
+ task_id: []const u8,
+ /// 1-based, within the phase.
+ task_index: usize,
+ task_count: usize,
+ task: []const u8,
+ /// running | completed | failed
+ status: []const u8,
+};
+
+fn writeLine(w: *Io.Writer, ev: anytype) void {
+ var s: std.json.Stringify = .{ .writer = w };
+ s.write(ev) catch return;
+ w.writeByte('\n') catch return;
+}
+
+/// One complete JSON object per line on the shared --json stdout. Best-effort
+/// throughout: a progress event must never be able to fail a workflow, so every
+/// error path is a silent return.
+fn emit(io: Io, ev: anytype) void {
+ if (g_test_sink) |sink| return writeLine(&sink.writer, ev);
+ if (!main_mod.json_mode) return;
+ const w = main_mod.g_out orelse return;
+ // The same lock guiEmit/printDelta take: workflow tasks emit from pool
+ // threads, and a half-written line would corrupt the SDK's JSONL parse.
+ main_mod.g_gui_mu.lockUncancelable(io);
+ defer main_mod.g_gui_mu.unlock(io);
+ writeLine(w, ev);
+ w.flush() catch return;
+}
+
+/// A fresh `wf-N` id, arena-allocated so every phase and task event of the run
+/// keys to the same string.
+pub fn nextRunId(arena: Allocator) ![]const u8 {
+ return std.fmt.allocPrint(arena, "wf-{d}", .{g_next_run.fetchAdd(1, .monotonic)});
+}
+
+fn phaseId(arena: Allocator, run_id: []const u8, index: usize) ?[]const u8 {
+ if (index == 0) return "";
+ return std.fmt.allocPrint(arena, "{s}/p{d}", .{ run_id, index }) catch null;
+}
+
+/// Phase lifecycle (#63). `index` is 1-based; 0 is the run-level event a
+/// pipeline emits in place of a phase.
+pub fn phase(io: Io, arena: Allocator, run_id: []const u8, index: usize, count: usize, title: []const u8, status: []const u8, task_count: usize) void {
+ emit(io, PhaseEvent{
+ .workflow_id = run_id,
+ .phase_id = phaseId(arena, run_id, index) orelse return,
+ .phase_index = index,
+ .phase_count = count,
+ .phase = shapes.canonicalSlot(title),
+ .title = util.utf8Prefix(title, label_cap),
+ .status = status,
+ .task_count = task_count,
+ });
+}
+
+/// Task lifecycle inside a phase (#63). `index` is 1-based within the phase.
+pub fn task(io: Io, arena: Allocator, run_id: []const u8, phase_index: usize, index: usize, count: usize, label: []const u8, status: []const u8) void {
+ const pid = phaseId(arena, run_id, phase_index) orelse return;
+ emit(io, TaskEvent{
+ .workflow_id = run_id,
+ .phase_id = pid,
+ .task_id = std.fmt.allocPrint(arena, "{s}/t{d}", .{ pid, index }) catch return,
+ .task_index = index,
+ .task_count = count,
+ .task = util.utf8Prefix(label, label_cap),
+ .status = status,
+ });
+}
+
+// ── U2: all-failed abort + run manifest ─────────────────────────────────────
+// A phase where every task failed used to still feed {{prev}} — a bare
+// "(no result — task failed)" header per task — into the next phase, so a
+// synthesis stage confidently answered from zero evidence (the worst output
+// class: a wrong answer that looks researched). buildAbortText and
+// buildManifest are kept PURE (no ctx/io) so both are unit-testable without
+// running a real subagent.
+
+pub const PhaseTally = struct {
+ phase_no: usize,
+ total_phases: usize,
+ title: []const u8,
+ ok: usize,
+ total: usize,
+ retried: usize,
+ skipped_when: ?[]const u8 = null,
+};
+
+/// Build the hard-stop text for a phase where every task failed: the
+/// assembled per-task failure headers plus a line naming the phase, so the
+/// caller (or a human) can see exactly why the run stopped instead of
+/// silently receiving empty "evidence". `details` is parallel to `labels`
+/// (#248): each entry is that task's capped one-line error excerpt, or "" when
+/// the task left nothing to report.
+pub fn buildAbortText(arena: Allocator, labels: []const []const u8, details: []const []const u8, phase_no: usize, total_phases: usize, title: []const u8) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ for (labels, details) |label, detail| {
+ try aw.writer.print("### {s} (no result — task failed)\n", .{label});
+ if (detail.len > 0) try aw.writer.print("{s}\n", .{detail});
+ try aw.writer.writeAll("\n");
+ }
+ try aw.writer.print("workflow aborted: every task in phase {d}/{d} ({s}) failed", .{ phase_no, total_phases, title });
+ return aw.writer.buffered();
+}
+
+/// Build the trailing "## workflow" manifest block from one tally per phase —
+/// currently the only way the orchestrator learns a phase was skipped, or
+/// that a synthesis stage is about to work from partial (some-tasks-failed)
+/// evidence rather than a clean phase.
+pub fn buildManifest(arena: Allocator, tallies: []const PhaseTally) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ try aw.writer.writeAll("## workflow\n");
+ for (tallies) |t| {
+ if (t.skipped_when) |w| {
+ try aw.writer.print("phase {d}/{d} {s}: SKIPPED (when=\"{s}\")\n", .{ t.phase_no, t.total_phases, t.title, w });
+ } else {
+ try aw.writer.print("phase {d}/{d} {s}: {d}/{d} ok, {d} retried\n", .{ t.phase_no, t.total_phases, t.title, t.ok, t.total, t.retried });
+ }
+ }
+ return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");
+}
+
+// ── tests ───────────────────────────────────────────────────────────────────
+// Imported here only so the tests below can drive the real engine; workflow.zig
+// imports this module back, which Zig allows (no comptime cycle).
+const tools = @import("tools.zig");
+const workflow = @import("workflow.zig");
+
+test "workflow_progress (#63): a phase transition emits structured state, not just a log line" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ var sink: Io.Writer.Allocating = .init(a);
+ g_test_sink = &sink;
+ defer g_test_sink = null;
+
+ // A phase whose task entries are not objects returns AFTER the phase-start
+ // emit and BEFORE any subagent is spawned, so this drives the real
+ // execWorkflow call site with no network and no fan-out.
+ var ctx: tools.ToolCtx = undefined;
+ ctx.gpa = std.testing.allocator;
+ ctx.io = std.testing.io;
+ ctx.from_sub = false;
+ const input = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"phases\":[{\"title\":\"find security bugs\",\"tasks\":[1,2]}]}", .{});
+ const out = try workflow.execWorkflow(ctx, input);
+ std.testing.allocator.free(out.text);
+
+ const line = std.mem.trimEnd(u8, sink.writer.buffered(), "\n");
+ // Exactly one event, and one complete JSON object on its own line.
+ try std.testing.expect(line.len > 0);
+ try std.testing.expect(std.mem.indexOfScalar(u8, line, '\n') == null);
+ const ev = try std.json.parseFromSliceLeaky(std.json.Value, a, line, .{});
+ try std.testing.expectEqualStrings("workflow_progress", ev.object.get("type").?.string);
+ try std.testing.expectEqualStrings("started", ev.object.get("status").?.string);
+ // The phase is named from the CLOSED slot vocabulary so a consumer can key
+ // on it; the authored text rides along as `title` for rendering.
+ try std.testing.expectEqualStrings("find", ev.object.get("phase").?.string);
+ try std.testing.expectEqualStrings("find security bugs", ev.object.get("title").?.string);
+ try std.testing.expectEqual(@as(i64, 1), ev.object.get("phase_index").?.integer);
+ try std.testing.expectEqual(@as(i64, 1), ev.object.get("phase_count").?.integer);
+ try std.testing.expectEqual(@as(i64, 2), ev.object.get("task_count").?.integer);
+ // Stable ids: the phase id is derived from the run id.
+ const wf = ev.object.get("workflow_id").?.string;
+ try std.testing.expect(std.mem.startsWith(u8, wf, "wf-"));
+ const pid = ev.object.get("phase_id").?.string;
+ try std.testing.expect(std.mem.startsWith(u8, pid, wf));
+ try std.testing.expectEqualStrings("/p1", pid[wf.len..]);
+}
+
+test "workflow_progress (#63): task ids nest under the phase, and a run-level event carries no phase" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ var sink: Io.Writer.Allocating = .init(a);
+ g_test_sink = &sink;
+ defer g_test_sink = null;
+
+ const run = try nextRunId(a);
+ task(std.testing.io, a, run, 2, 3, 4, "read ChatWorkRow.tsx", "running");
+ // phase_index 0 is the run-level event a pipeline emits: no phase, no id.
+ phase(std.testing.io, a, run, 0, 2, "pipeline", "started", 5);
+
+ var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, sink.writer.buffered(), "\n"), '\n');
+ const t = try std.json.parseFromSliceLeaky(std.json.Value, a, lines.next().?, .{});
+ try std.testing.expectEqualStrings("workflow_progress", t.object.get("type").?.string);
+ try std.testing.expectEqualStrings("running", t.object.get("status").?.string);
+ try std.testing.expectEqualStrings("read ChatWorkRow.tsx", t.object.get("task").?.string);
+ try std.testing.expectEqual(@as(i64, 3), t.object.get("task_index").?.integer);
+ try std.testing.expectEqual(@as(i64, 4), t.object.get("task_count").?.integer);
+ const pid = t.object.get("phase_id").?.string;
+ try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "{s}/p2", .{run}), pid);
+ try std.testing.expectEqualStrings(try std.fmt.allocPrint(a, "{s}/t3", .{pid}), t.object.get("task_id").?.string);
+
+ const p = try std.json.parseFromSliceLeaky(std.json.Value, a, lines.next().?, .{});
+ try std.testing.expectEqual(@as(i64, 0), p.object.get("phase_index").?.integer);
+ try std.testing.expectEqualStrings("", p.object.get("phase_id").?.string);
+ // "pipeline" is not a canonical slot, so the closed-vocabulary field is
+ // empty rather than minting a cell name nothing can score.
+ try std.testing.expectEqualStrings("", p.object.get("phase").?.string);
+ try std.testing.expectEqualStrings("pipeline", p.object.get("title").?.string);
+ try std.testing.expect(lines.next() == null);
+}
diff --git a/src/worktree_lease.zig b/src/worktree_lease.zig
new file mode 100644
index 00000000..19f24d0d
--- /dev/null
+++ b/src/worktree_lease.zig
@@ -0,0 +1,230 @@
+//! Canonical worktree identity and the duplicate-owner preflight (#320).
+//!
+//! Two graff sessions started in different subdirectories of the same checkout
+//! (or through a symlink) must resolve to ONE identity, while two separate
+//! `git worktree add` checkouts must not collide. `git rev-parse --git-dir
+//! --git-common-dir` answers both at once: the common dir is shared by a repo
+//! and every worktree linked to it, so `git_dir == common_dir` means "the main
+//! checkout" and anything else is a linked worktree whose git dir is already
+//! unique per worktree. Both are resolved by git itself, so a symlinked or
+//! nested cwd collapses onto the same string.
+//!
+//! What is deliberately NOT here: the durable lease registry. `ownerVerdict` is
+//! the whole decision — given a record it says self / live-foreign / stale —
+//! and it already honours #320's rule that a pid alone may never signal an
+//! owner. Nothing writes records yet, so no root session is warned at startup;
+//! that needs a registry file plus a call site in startup.zig.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const process_runner = @import("process_runner.zig");
+const runCapped = process_runner.runCapped;
+const ranOk = process_runner.ranOk;
+
+pub const Identity = struct {
+ /// Stable string two sessions can compare. Empty only when even the cwd
+ /// fallback failed.
+ id: []const u8 = "",
+ kind: Kind = .not_git,
+
+ pub const Kind = enum { not_git, main_checkout, linked_worktree };
+};
+
+/// Trim and drop a trailing slash so `/repo/.git` and `/repo/.git/` compare
+/// equal. Returns a slice of the input.
+fn normalizePath(p: []const u8) []const u8 {
+ const t = std.mem.trim(u8, p, " \t\r\n");
+ if (t.len <= 1) return t;
+ return std.mem.trimEnd(u8, t, "/");
+}
+
+/// Pure half of the #320 identity: `git_dir`/`common_dir` are the `git rev-parse
+/// --path-format=absolute --git-dir --git-common-dir` answers (empty when git
+/// could not be asked), `fallback_path` the canonical cwd used outside a repo.
+pub fn canonicalIdentity(git_dir: []const u8, common_dir: []const u8, fallback_path: []const u8) Identity {
+ const g = normalizePath(git_dir);
+ const c = normalizePath(common_dir);
+ if (g.len == 0) return .{ .id = normalizePath(fallback_path), .kind = .not_git };
+ // git_dir == common_dir is exactly "this is the repo's own checkout"; a
+ // linked worktree's git dir is <common>/worktrees/<name>, already unique.
+ if (c.len == 0 or std.mem.eql(u8, g, c)) return .{ .id = g, .kind = .main_checkout };
+ return .{ .id = g, .kind = .linked_worktree };
+}
+
+/// One recorded root-session owner of a worktree identity. `start_ns` is the
+/// process START time, not just the pid: after a crash the OS may hand the same
+/// pid to something unrelated, and #320 requires that never look like an owner.
+pub const Owner = struct {
+ pid: i32 = 0,
+ start_ns: u64 = 0,
+ session_id: []const u8 = "",
+ identity: []const u8 = "",
+ last_seen_ms: i64 = 0,
+};
+
+pub const OwnerVerdict = enum {
+ /// This record is the running session asking.
+ self,
+ /// A record for a different worktree — never a conflict.
+ other_worktree,
+ /// Another root session is alive in MY worktree: the #320 warning case.
+ live_foreign,
+ /// The owner exited (or its pid now belongs to something else).
+ stale_dead,
+ /// Not enough evidence to claim anyone owns it; treated as stale.
+ stale_unverifiable,
+};
+
+/// `live_start_ns` is the START time of whatever process currently holds
+/// `rec.pid`, or null when no such process exists or it could not be read.
+pub fn ownerVerdict(rec: Owner, my_identity: []const u8, my_pid: i32, live_start_ns: ?u64) OwnerVerdict {
+ if (rec.identity.len == 0 or my_identity.len == 0) return .stale_unverifiable;
+ if (!std.mem.eql(u8, rec.identity, my_identity)) return .other_worktree;
+ // A record with no start identity can only be matched by pid, and pid alone
+ // is precisely what #320 says must not signal an owner.
+ if (rec.start_ns == 0) return .stale_unverifiable;
+ const live = live_start_ns orelse return .stale_dead;
+ if (live != rec.start_ns) return .stale_dead; // pid reuse, not the owner
+ if (rec.pid == my_pid) return .self;
+ return .live_foreign;
+}
+
+/// The #320 preflight: the first live foreign owner of MY worktree, if any.
+/// Everything else — my own record, another worktree's, a crashed or pid-reused
+/// one — is silent, so a stale registry can never block a startup.
+/// `live_start_ns[i]` pairs with `records[i]`; a short slice reads as "unknown".
+pub fn duplicateOwner(records: []const Owner, live_start_ns: []const ?u64, my_identity: []const u8, my_pid: i32) ?Owner {
+ for (records, 0..) |rec, i| {
+ const live = if (i < live_start_ns.len) live_start_ns[i] else null;
+ if (ownerVerdict(rec, my_identity, my_pid, live) == .live_foreign) return rec;
+ }
+ return null;
+}
+
+pub fn duplicateOwnerWarning(arena: Allocator, rec: Owner, age_ms: i64) []const u8 {
+ const mins = @divTrunc(if (age_ms > 0) age_ms else 0, std.time.ms_per_min);
+ return std.fmt.allocPrint(
+ arena,
+ "⚠ another graff session already owns this worktree\n pid {d} · session {s} · active {d}m\n you would both be editing the same uncommitted tree — restart with -w for an isolated worktree, or continue knowing edits can collide\n",
+ .{ rec.pid, if (rec.session_id.len > 0) rec.session_id else "unknown", mins },
+ ) catch "⚠ another graff session already owns this worktree\n";
+}
+
+fn revParse(gpa: Allocator, io: Io, arena: Allocator, flag: []const u8) []const u8 {
+ // --path-format=absolute so a nested cwd yields the same string as the repo
+ // root. Old git without the flag just fails and we degrade to the cwd.
+ const r = runCapped(gpa, io, &.{ "git", "rev-parse", "--path-format=absolute", flag }, 8192, 8192, 15_000) catch return "";
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ if (!ranOk(r)) return "";
+ return arena.dupe(u8, std.mem.trim(u8, r.stdout, " \t\r\n")) catch "";
+}
+
+/// `<main checkout>/.git`, shared by the repo and every worktree linked to it.
+pub fn gitCommonDir(gpa: Allocator, io: Io, arena: Allocator) []const u8 {
+ return revParse(gpa, io, arena, "--git-common-dir");
+}
+
+/// Live canonical identity for this process's working directory.
+pub fn currentIdentity(gpa: Allocator, io: Io, arena: Allocator) Identity {
+ const git_dir = revParse(gpa, io, arena, "--git-dir");
+ const common = gitCommonDir(gpa, io, arena);
+ var buf: [4096]u8 = undefined;
+ const cwd = blk: {
+ const n = Io.Dir.cwd().realPathFile(io, ".", &buf) catch break :blk "";
+ break :blk arena.dupe(u8, buf[0..n]) catch "";
+ };
+ return canonicalIdentity(git_dir, common, cwd);
+}
+
+pub fn identityLine(arena: Allocator, id: Identity) []const u8 {
+ const kind = switch (id.kind) {
+ .main_checkout => "main checkout",
+ .linked_worktree => "linked worktree",
+ .not_git => "not a git repository",
+ };
+ return std.fmt.allocPrint(arena, "identity: {s} ({s})", .{ if (id.id.len > 0) id.id else "unknown", kind }) catch "identity: unknown";
+}
+
+test "canonicalIdentity: one id per worktree, distinct across linked worktrees (#320)" {
+ // Subdirectory / symlinked cwd: git resolves both to the same git dir, so
+ // the identity is the same string.
+ const main_a = canonicalIdentity("/repo/.git", "/repo/.git", "/repo");
+ const main_b = canonicalIdentity("/repo/.git/", "/repo/.git", "/repo/src/deep");
+ try std.testing.expectEqual(Identity.Kind.main_checkout, main_a.kind);
+ try std.testing.expectEqualStrings(main_a.id, main_b.id);
+
+ // A linked worktree has its own git dir, so it never collides with main…
+ const linked = canonicalIdentity("/repo/.git/worktrees/wt1", "/repo/.git", "/elsewhere/wt1");
+ try std.testing.expectEqual(Identity.Kind.linked_worktree, linked.kind);
+ try std.testing.expect(!std.mem.eql(u8, linked.id, main_a.id));
+ // …nor with a sibling worktree of the same repo.
+ const sibling = canonicalIdentity("/repo/.git/worktrees/wt2", "/repo/.git", "/elsewhere/wt2");
+ try std.testing.expect(!std.mem.eql(u8, linked.id, sibling.id));
+
+ // Outside a repo we still have an identity: the canonical cwd.
+ const loose = canonicalIdentity("", "", "/tmp/scratch/");
+ try std.testing.expectEqual(Identity.Kind.not_git, loose.kind);
+ try std.testing.expectEqualStrings("/tmp/scratch", loose.id);
+}
+
+test "ownerVerdict: only a verified live process in MY worktree is an owner (#320)" {
+ const me = "/repo/.git";
+ const rec: Owner = .{ .pid = 4242, .start_ns = 777, .session_id = "s-1", .identity = me };
+
+ try std.testing.expectEqual(OwnerVerdict.live_foreign, ownerVerdict(rec, me, 99, 777));
+ try std.testing.expectEqual(OwnerVerdict.self, ownerVerdict(rec, me, 4242, 777));
+ // Separate git worktrees do not conflict.
+ try std.testing.expectEqual(OwnerVerdict.other_worktree, ownerVerdict(rec, "/repo/.git/worktrees/wt1", 99, 777));
+ // Crashed owner: the pid is simply gone.
+ try std.testing.expectEqual(OwnerVerdict.stale_dead, ownerVerdict(rec, me, 99, null));
+ // PID reuse: the pid is live but it is a different process.
+ try std.testing.expectEqual(OwnerVerdict.stale_dead, ownerVerdict(rec, me, 99, 778));
+ // No start identity recorded — unverifiable is stale, never a warning.
+ var no_start = rec;
+ no_start.start_ns = 0;
+ try std.testing.expectEqual(OwnerVerdict.stale_unverifiable, ownerVerdict(no_start, me, 99, 777));
+}
+
+test "duplicateOwner: picks the live foreign session and ignores stale records (#320)" {
+ const me = "/repo/.git";
+ const records = [_]Owner{
+ .{ .pid = 1, .start_ns = 10, .session_id = "dead", .identity = me },
+ .{ .pid = 2, .start_ns = 20, .session_id = "other-wt", .identity = "/repo/.git/worktrees/wt1" },
+ .{ .pid = 3, .start_ns = 30, .session_id = "mine", .identity = me },
+ .{ .pid = 4, .start_ns = 40, .session_id = "live", .identity = me },
+ };
+ const live = [_]?u64{ null, 20, 30, 40 };
+ const found = duplicateOwner(&records, &live, me, 3) orelse return error.ExpectedDuplicate;
+ try std.testing.expectEqualStrings("live", found.session_id);
+ try std.testing.expectEqual(@as(i32, 4), found.pid);
+
+ // Alone in the worktree: only my own record matches, so no warning.
+ const solo = [_]Owner{records[2]};
+ try std.testing.expect(duplicateOwner(&solo, &.{30}, me, 3) == null);
+ // A registry we cannot read at all must not manufacture an owner.
+ try std.testing.expect(duplicateOwner(&records, &.{}, me, 3) == null);
+}
+
+test "duplicateOwnerWarning: names the pid, the session and an escape hatch (#320)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const text = duplicateOwnerWarning(arena_state.allocator(), .{ .pid = 4242, .start_ns = 1, .session_id = "s-1" }, 5 * std.time.ms_per_min);
+ try std.testing.expect(std.mem.indexOf(u8, text, "4242") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "s-1") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "5m") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "-w") != null);
+}
+
+test "identityLine: says which kind of checkout, and stays honest when unknown" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ try std.testing.expect(std.mem.indexOf(u8, identityLine(a, .{ .id = "/repo/.git", .kind = .main_checkout }), "main checkout") != null);
+ try std.testing.expect(std.mem.indexOf(u8, identityLine(a, .{ .id = "/repo/.git/worktrees/w", .kind = .linked_worktree }), "linked worktree") != null);
+ try std.testing.expect(std.mem.indexOf(u8, identityLine(a, .{}), "unknown") != null);
+}
diff --git a/src/worktree_prune.zig b/src/worktree_prune.zig
new file mode 100644
index 00000000..97e92104
--- /dev/null
+++ b/src/worktree_prune.zig
@@ -0,0 +1,431 @@
+//! The age column on `graff worktree list` and the retention policy behind
+//! `graff worktree prune --older-than <days>` (#112). Split out of jobs.zig,
+//! which sits against the 600-line cap.
+//!
+//! Removal reuses agent_worktree.worktreeKeepReason — the same predicate that
+//! guards subagent worktree cleanup — so a worktree that is dirty, holds
+//! commits nothing else references, or cannot be verified is never removed no
+//! matter how old it is. Age only ever makes that gate STRICTER, and retention
+//! stays opt-in: bare `prune` still only drops git registrations.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const process_runner = @import("process_runner.zig");
+const runCapped = process_runner.runCapped;
+const ranOk = process_runner.ranOk;
+const agent_worktree = @import("agent_worktree.zig");
+const KeepReason = agent_worktree.KeepReason;
+const worktreeKeepReason = agent_worktree.worktreeKeepReason;
+const keepReasonText = agent_worktree.keepReasonText;
+const worktree_lease = @import("worktree_lease.zig");
+const unixMs = @import("util.zig").unixMs;
+
+/// Age we could not establish. Never "0" — an unreadable mtime must keep the
+/// worktree, not make it look brand new (or, worse, infinitely old).
+pub const unknown_age_ms: i64 = -1;
+
+pub const Entry = struct {
+ path: []const u8 = "",
+ head: []const u8 = "",
+ branch: []const u8 = "", // refs/heads/… , empty when detached or bare
+ bare: bool = false,
+ detached: bool = false,
+ locked: bool = false,
+ prunable: bool = false,
+};
+
+/// Parse `git worktree list --porcelain`. Fields borrow `porcelain`.
+pub fn parseEntries(arena: Allocator, porcelain: []const u8) Allocator.Error![]Entry {
+ var list: std.ArrayList(Entry) = .empty;
+ var it = std.mem.splitScalar(u8, porcelain, '\n');
+ while (it.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (line.len == 0) continue;
+ if (std.mem.startsWith(u8, line, "worktree ")) {
+ try list.append(arena, .{ .path = line["worktree ".len..] });
+ continue;
+ }
+ if (list.items.len == 0) continue; // attribute before any record: ignore
+ const e = &list.items[list.items.len - 1];
+ if (std.mem.startsWith(u8, line, "HEAD ")) {
+ e.head = line["HEAD ".len..];
+ } else if (std.mem.startsWith(u8, line, "branch ")) {
+ e.branch = line["branch ".len..];
+ } else if (std.mem.eql(u8, line, "bare")) {
+ e.bare = true;
+ } else if (std.mem.eql(u8, line, "detached")) {
+ e.detached = true;
+ } else if (std.mem.startsWith(u8, line, "locked")) {
+ e.locked = true;
+ } else if (std.mem.startsWith(u8, line, "prunable")) {
+ e.prunable = true;
+ }
+ }
+ return list.toOwnedSlice(arena);
+}
+
+/// The main checkout's path, derived from `--git-common-dir` (`<main>/.git`).
+/// `git worktree list` documents the main worktree first, but the safety of a
+/// whole repo should not rest on output ordering (#112).
+pub fn mainWorktreePath(common_dir: []const u8) []const u8 {
+ const t = std.mem.trimEnd(u8, std.mem.trim(u8, common_dir, " \t\r\n"), "/");
+ if (std.mem.eql(u8, t, ".git")) return ".";
+ if (!std.mem.endsWith(u8, t, "/.git")) return ""; // bare repo, or unknown shape
+ return t[0 .. t.len - "/.git".len];
+}
+
+pub fn shortBranch(refname: []const u8) []const u8 {
+ return if (std.mem.startsWith(u8, refname, "refs/heads/")) refname["refs/heads/".len..] else refname;
+}
+
+/// Branch names graff itself mints for scratch worktrees (`-w` tabs and
+/// isolated subagents). `prune` deletes only these: a hand-made branch NAME is
+/// user state even once its commits are reachable from somewhere else.
+pub fn isGraffScratchBranch(refname: []const u8) bool {
+ const name = shortBranch(refname);
+ return std.mem.startsWith(u8, name, "worktree-") or std.mem.startsWith(u8, name, "graff/agents/");
+}
+
+/// True when some ref OTHER than the worktree's own branch contains its HEAD,
+/// i.e. its commits are reachable without it. `refs` is one refname per line
+/// from `git branch --all --contains <head> --format=%(refname)`.
+pub fn containedElsewhere(refs: []const u8, own_branch: []const u8) bool {
+ var it = std.mem.tokenizeScalar(u8, refs, '\n');
+ while (it.next()) |raw| {
+ const ref = std.mem.trim(u8, raw, " \t\r*+");
+ if (ref.len == 0) continue;
+ if (own_branch.len > 0 and std.mem.eql(u8, ref, own_branch)) continue;
+ return true;
+ }
+ return false;
+}
+
+/// Sentinel fed to `worktreeKeepReason` as the creation base when a worktree's
+/// HEAD is reachable from nowhere else. It is deliberately not a sha, so the
+/// base != head comparison there reports `.committed`.
+const unique_commits_base = "graff:unique-commits";
+
+/// A prune candidate has no recorded creation base (unlike a subagent worktree,
+/// which records one at spawn), so translate the equivalent question git CAN
+/// answer — is this HEAD reachable from another ref? — into the base that makes
+/// worktreeKeepReason give the right verdict.
+pub fn containmentBase(head: []const u8, contained: bool) []const u8 {
+ if (head.len == 0) return ""; // unknown head: worktreeKeepReason says unverifiable
+ return if (contained) head else unique_commits_base;
+}
+
+pub const PruneVerdict = enum { remove, keep_main, keep_too_new, keep_dirty, keep_committed, keep_unverifiable };
+
+/// The whole retention decision, pure. Safety comes BEFORE age: an ancient
+/// worktree that still holds uncommitted work or branch-only commits stays,
+/// however far past the retention window it is.
+pub fn pruneVerdict(is_main: bool, keep: KeepReason, age_ms: i64, older_than_ms: i64) PruneVerdict {
+ if (is_main) return .keep_main; // never the user's own repo
+ switch (keep) {
+ .dirty => return .keep_dirty,
+ .committed => return .keep_committed,
+ .unverifiable => return .keep_unverifiable,
+ .removed => {},
+ }
+ if (age_ms < 0) return .keep_unverifiable; // unreadable mtime is not "age 0"
+ return if (age_ms >= older_than_ms) .remove else .keep_too_new;
+}
+
+pub fn verdictText(v: PruneVerdict) []const u8 {
+ return switch (v) {
+ .remove => "",
+ .keep_main => "the main checkout",
+ .keep_too_new => "newer than the retention window",
+ .keep_dirty => keepReasonText(.dirty),
+ .keep_committed => keepReasonText(.committed),
+ .keep_unverifiable => keepReasonText(.unverifiable),
+ };
+}
+
+/// `--older-than <days>`; fractional days allowed so `--older-than 0.5` cleans
+/// up within a day. Anything not a finite, non-negative, plausible number is
+/// rejected rather than silently widening the window to "everything".
+pub fn parseOlderThanMs(text: []const u8) ?i64 {
+ const days = std.fmt.parseFloat(f64, std.mem.trim(u8, text, " \t")) catch return null;
+ if (!(days >= 0) or !(days <= 3650)) return null; // NaN fails both comparisons
+ return @intFromFloat(days * @as(f64, @floatFromInt(std.time.ms_per_day)));
+}
+
+/// Age column vocabulary: the same shape /sessions uses, but from an elapsed
+/// span so the formatting stays testable without a clock.
+pub fn formatAge(buf: []u8, age_ms: i64) []const u8 {
+ if (age_ms < 0) return "?";
+ const s = @divTrunc(age_ms, std.time.ms_per_s);
+ if (s < 60) return "new";
+ if (s < std.time.s_per_hour) return std.fmt.bufPrint(buf, "{d}m", .{@divTrunc(s, 60)}) catch "?";
+ if (s < std.time.s_per_day) return std.fmt.bufPrint(buf, "{d}h", .{@divTrunc(s, std.time.s_per_hour)}) catch "?";
+ return std.fmt.bufPrint(buf, "{d}d", .{@divTrunc(s, std.time.s_per_day)}) catch "?";
+}
+
+fn worktreeAgeMs(io: Io, now_ms: i64, path: []const u8) i64 {
+ const st = Io.Dir.cwd().statFile(io, path, .{}) catch return unknown_age_ms;
+ const mtime_ms: i64 = @intCast(@divTrunc(st.mtime.nanoseconds, std.time.ns_per_ms));
+ const age = now_ms - mtime_ms;
+ return if (age < 0) 0 else age; // clock skew, not a stale worktree
+}
+
+/// `worktreeKeepReason` for a listed worktree, gathering the two facts it needs
+/// from git. Any failed probe stays `.unverifiable`, i.e. keeps the worktree.
+fn keepReasonFor(gpa: Allocator, io: Io, e: Entry) KeepReason {
+ const st = runCapped(gpa, io, &.{ "git", "-C", e.path, "status", "--porcelain" }, 1 << 16, 8192, 30_000) catch return .unverifiable;
+ defer {
+ gpa.free(st.stdout);
+ gpa.free(st.stderr);
+ }
+ if (!ranOk(st)) return .unverifiable;
+ if (e.head.len == 0) return .unverifiable;
+ const refs = runCapped(gpa, io, &.{ "git", "branch", "--all", "--contains", e.head, "--format=%(refname)" }, 1 << 16, 8192, 30_000) catch return .unverifiable;
+ defer {
+ gpa.free(refs.stdout);
+ gpa.free(refs.stderr);
+ }
+ if (!ranOk(refs)) return .unverifiable;
+ const base = containmentBase(e.head, containedElsewhere(refs.stdout, e.branch));
+ return worktreeKeepReason(true, st.stdout, base, e.head);
+}
+
+/// Remove the directory git registered for `e`. No `--force`: we already proved
+/// the tree is clean, so git's own refusal is a second belt — #112 must not
+/// turn `prune` into a data-loss command.
+fn removeWorktree(gpa: Allocator, io: Io, e: Entry) bool {
+ const rm = runCapped(gpa, io, &.{ "git", "worktree", "remove", e.path }, 8192, 8192, 60_000) catch return false;
+ defer {
+ gpa.free(rm.stdout);
+ gpa.free(rm.stderr);
+ }
+ if (!ranOk(rm)) return false;
+ if (isGraffScratchBranch(e.branch)) {
+ if (runCapped(gpa, io, &.{ "git", "branch", "-D", shortBranch(e.branch) }, 8192, 8192, 30_000)) |b| {
+ gpa.free(b.stdout);
+ gpa.free(b.stderr);
+ } else |_| {}
+ }
+ return true;
+}
+
+fn listPorcelain(gpa: Allocator, io: Io) ?process_runner.CappedRun {
+ const r = runCapped(gpa, io, &.{ "git", "worktree", "list", "--porcelain" }, 1 << 18, 8192, 30_000) catch return null;
+ if (!ranOk(r)) {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ return null;
+ }
+ return r;
+}
+
+/// `graff worktree list`: every worktree with how long it has sat untouched,
+/// under the canonical identity of the checkout you are standing in (#320).
+pub fn listWithAge(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer) !void {
+ const r = listPorcelain(gpa, io) orelse {
+ try out.writeAll("not a git repository (no worktrees)\n");
+ return;
+ };
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ try out.print("{s}\n", .{worktree_lease.identityLine(arena, worktree_lease.currentIdentity(gpa, io, arena))});
+ const entries = try parseEntries(arena, r.stdout);
+ const main_path = mainWorktreePath(worktree_lease.gitCommonDir(gpa, io, arena));
+ const now_ms = unixMs(io);
+ for (entries, 0..) |e, i| {
+ var abuf: [24]u8 = undefined;
+ const age = formatAge(&abuf, worktreeAgeMs(io, now_ms, e.path));
+ const label = if (e.branch.len > 0) shortBranch(e.branch) else if (e.detached) "(detached)" else if (e.bare) "(bare)" else "";
+ const is_main = i == 0 or (main_path.len > 0 and std.mem.eql(u8, e.path, main_path));
+ try out.print("{s: <5} {s} [{s}]{s}\n", .{ age, e.path, label, if (is_main) " (main checkout)" else "" });
+ }
+}
+
+/// `graff worktree prune [--older-than <days>]`. The registration sweep is
+/// unconditional (that is what prune always did); directory removal only
+/// happens when the user names a retention window (#112).
+pub fn pruneCommand(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, args: []const []const u8) !void {
+ const p = runCapped(gpa, io, &.{ "git", "worktree", "prune" }, 8192, 8192, 30_000) catch {
+ try out.writeAll("not a git repository (nothing to prune)\n");
+ return;
+ };
+ gpa.free(p.stdout);
+ gpa.free(p.stderr);
+ try out.writeAll("✓ pruned stale worktree registrations\n");
+
+ const window = parseOlderThanArg(args) orelse {
+ try out.writeAll(" directories left alone — `graff worktree prune older-than <days>` also removes stale ones\n");
+ return;
+ };
+ const older_than_ms = window orelse {
+ try out.writeAll("usage: graff worktree prune [older-than <days>] (days: a non-negative number)\n");
+ return;
+ };
+ try removeStale(gpa, io, arena, out, older_than_ms);
+}
+
+/// null = the window was not asked for; `.?` = null means it was asked for with
+/// a value we refuse.
+///
+/// Both spellings are accepted on purpose. `older-than <days>` is the one that
+/// works today: args.zig's global flag loop fatals on any unrecognised `--flag`
+/// before a subcommand ever sees it, and only `mcp`/`learn` are on its
+/// pass-everything-through list. `--older-than` is the spelling #112 asks for,
+/// so it is honoured here and lights up as soon as `worktree` joins that list.
+pub fn parseOlderThanArg(args: []const []const u8) ??i64 {
+ for (args, 0..) |a, i| {
+ const key = std.mem.trimStart(u8, a, "-");
+ if (std.mem.startsWith(u8, key, "older-than=")) return parseOlderThanMs(key["older-than=".len..]);
+ if (std.mem.eql(u8, key, "older-than")) {
+ if (i + 1 >= args.len) return @as(?i64, null);
+ return parseOlderThanMs(args[i + 1]);
+ }
+ }
+ return null;
+}
+
+fn removeStale(gpa: Allocator, io: Io, arena: Allocator, out: *Io.Writer, older_than_ms: i64) !void {
+ const r = listPorcelain(gpa, io) orelse return;
+ defer {
+ gpa.free(r.stdout);
+ gpa.free(r.stderr);
+ }
+ const entries = try parseEntries(arena, r.stdout);
+ const main_path = mainWorktreePath(worktree_lease.gitCommonDir(gpa, io, arena));
+ const now_ms = unixMs(io);
+ var removed: usize = 0;
+ for (entries, 0..) |e, i| {
+ const is_main = i == 0 or (main_path.len > 0 and std.mem.eql(u8, e.path, main_path));
+ const verdict = pruneVerdict(is_main, keepReasonFor(gpa, io, e), worktreeAgeMs(io, now_ms, e.path), older_than_ms);
+ switch (verdict) {
+ .keep_main => continue,
+ .remove => if (removeWorktree(gpa, io, e)) {
+ removed += 1;
+ try out.print(" removed {s}\n", .{e.path});
+ } else {
+ try out.print(" kept {s} — git refused to remove it\n", .{e.path});
+ },
+ else => try out.print(" kept {s} — {s}\n", .{ e.path, verdictText(verdict) }),
+ }
+ }
+ try out.print("✓ removed {d} stale worktree director{s}\n", .{ removed, if (removed == 1) @as([]const u8, "y") else "ies" });
+}
+
+test "pruneVerdict: age never overrides the #276 safety gate (#112)" {
+ const week = 7 * std.time.ms_per_day;
+ const ancient = 400 * std.time.ms_per_day;
+ // Only a clean, verifiable, base-identical worktree past the window goes.
+ try std.testing.expectEqual(PruneVerdict.remove, pruneVerdict(false, .removed, week, week));
+ try std.testing.expectEqual(PruneVerdict.remove, pruneVerdict(false, .removed, ancient, week));
+ try std.testing.expectEqual(PruneVerdict.keep_too_new, pruneVerdict(false, .removed, week - 1, week));
+ // …and being ancient buys nothing when the worktree still holds work.
+ try std.testing.expectEqual(PruneVerdict.keep_dirty, pruneVerdict(false, .dirty, ancient, week));
+ try std.testing.expectEqual(PruneVerdict.keep_committed, pruneVerdict(false, .committed, ancient, week));
+ try std.testing.expectEqual(PruneVerdict.keep_unverifiable, pruneVerdict(false, .unverifiable, ancient, week));
+ // An unreadable mtime keeps the worktree instead of reading as brand new.
+ try std.testing.expectEqual(PruneVerdict.keep_unverifiable, pruneVerdict(false, .removed, unknown_age_ms, week));
+ // The main checkout is never a candidate, whatever git says about it.
+ try std.testing.expectEqual(PruneVerdict.keep_main, pruneVerdict(true, .removed, ancient, week));
+ try std.testing.expectEqual(PruneVerdict.keep_main, pruneVerdict(true, .removed, ancient, 0));
+}
+
+test "parseOlderThanMs: rejects anything that would widen the window silently (#112)" {
+ try std.testing.expectEqual(@as(?i64, 7 * std.time.ms_per_day), parseOlderThanMs("7"));
+ try std.testing.expectEqual(@as(?i64, std.time.ms_per_day / 2), parseOlderThanMs("0.5"));
+ try std.testing.expectEqual(@as(?i64, 0), parseOlderThanMs(" 0 "));
+ try std.testing.expectEqual(@as(?i64, null), parseOlderThanMs("-1"));
+ try std.testing.expectEqual(@as(?i64, null), parseOlderThanMs("nan"));
+ try std.testing.expectEqual(@as(?i64, null), parseOlderThanMs("inf"));
+ try std.testing.expectEqual(@as(?i64, null), parseOlderThanMs("seven"));
+ try std.testing.expectEqual(@as(?i64, null), parseOlderThanMs(""));
+}
+
+test "parseOlderThanArg: absent window keeps prune non-destructive, bad value is an error (#112)" {
+ try std.testing.expect(parseOlderThanArg(&.{}) == null);
+ try std.testing.expect(parseOlderThanArg(&.{"--dry"}) == null);
+ const three = @as(?i64, 3 * std.time.ms_per_day);
+ // The spelling that survives args.zig's global flag loop today…
+ try std.testing.expectEqual(three, parseOlderThanArg(&.{ "older-than", "3" }).?);
+ try std.testing.expectEqual(three, parseOlderThanArg(&.{"older-than=3"}).?);
+ // …and the one #112 names, ready for when `worktree` gets pass-through.
+ try std.testing.expectEqual(three, parseOlderThanArg(&.{ "--older-than", "3" }).?);
+ try std.testing.expectEqual(three, parseOlderThanArg(&.{"--older-than=3"}).?);
+ try std.testing.expect(parseOlderThanArg(&.{"older-than"}).? == null); // missing value
+ try std.testing.expect(parseOlderThanArg(&.{ "--older-than", "soon" }).? == null);
+}
+
+test "parseEntries: reads paths, heads, branches and flags from --porcelain (#112)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const out = try parseEntries(arena_state.allocator(),
+ \\worktree /repo
+ \\HEAD aaaa
+ \\branch refs/heads/main
+ \\
+ \\worktree /repo/.graff/worktrees/foo
+ \\HEAD bbbb
+ \\branch refs/heads/worktree-foo
+ \\
+ \\worktree /repo/.graff/worktrees/bar
+ \\HEAD cccc
+ \\detached
+ \\prunable gitdir file points to non-existent location
+ \\
+ );
+ try std.testing.expectEqual(@as(usize, 3), out.len);
+ try std.testing.expectEqualStrings("/repo", out[0].path);
+ try std.testing.expectEqualStrings("refs/heads/worktree-foo", out[1].branch);
+ try std.testing.expectEqualStrings("bbbb", out[1].head);
+ try std.testing.expect(out[2].detached and out[2].prunable);
+ try std.testing.expectEqualStrings("", out[2].branch);
+}
+
+test "mainWorktreePath: the repo itself is identified by its common dir, not list order (#112)" {
+ try std.testing.expectEqualStrings("/repo", mainWorktreePath("/repo/.git\n"));
+ try std.testing.expectEqualStrings("/repo", mainWorktreePath("/repo/.git/"));
+ try std.testing.expectEqualStrings(".", mainWorktreePath(".git"));
+ try std.testing.expectEqualStrings("", mainWorktreePath("")); // unknown: fall back to list order
+ try std.testing.expectEqualStrings("", mainWorktreePath("/repo/bare.git"));
+}
+
+test "containedElsewhere/containmentBase: branch-only commits map to .committed (#112)" {
+ const own = "refs/heads/worktree-foo";
+ try std.testing.expect(!containedElsewhere("refs/heads/worktree-foo\n", own));
+ try std.testing.expect(containedElsewhere("refs/heads/worktree-foo\nrefs/heads/main\n", own));
+ try std.testing.expect(containedElsewhere("refs/remotes/origin/main\n", own));
+ try std.testing.expect(!containedElsewhere("\n \n", own));
+
+ // Reachable from main → nothing unique here → removable.
+ try std.testing.expectEqual(KeepReason.removed, worktreeKeepReason(true, "", containmentBase("bbbb", true), "bbbb"));
+ // Reachable from nowhere else → its commits exist ONLY here.
+ try std.testing.expectEqual(KeepReason.committed, worktreeKeepReason(true, "", containmentBase("bbbb", false), "bbbb"));
+ // No head at all → unverifiable, so it is kept.
+ try std.testing.expectEqual(KeepReason.unverifiable, worktreeKeepReason(true, "", containmentBase("", true), ""));
+}
+
+test "isGraffScratchBranch: prune deletes graff's own branches, never a hand-made one (#112)" {
+ try std.testing.expect(isGraffScratchBranch("refs/heads/worktree-foo"));
+ try std.testing.expect(isGraffScratchBranch("refs/heads/graff/agents/sa-1-aa11"));
+ try std.testing.expect(!isGraffScratchBranch("refs/heads/main"));
+ try std.testing.expect(!isGraffScratchBranch("refs/heads/feature/my-worktree-thing"));
+ try std.testing.expectEqualStrings("worktree-foo", shortBranch("refs/heads/worktree-foo"));
+}
+
+test "formatAge: the list column, and '?' when the mtime could not be read (#112)" {
+ var buf: [24]u8 = undefined;
+ try std.testing.expectEqualStrings("?", formatAge(&buf, unknown_age_ms));
+ try std.testing.expectEqualStrings("new", formatAge(&buf, 30 * std.time.ms_per_s));
+ try std.testing.expectEqualStrings("5m", formatAge(&buf, 5 * std.time.ms_per_min));
+ try std.testing.expectEqualStrings("3h", formatAge(&buf, 3 * std.time.ms_per_hour));
+ try std.testing.expectEqualStrings("9d", formatAge(&buf, 9 * std.time.ms_per_day + 3 * std.time.ms_per_hour));
+}
+
+test "verdictText: every kept reason explains itself, reusing the #276 wording" {
+ try std.testing.expectEqualStrings(keepReasonText(.dirty), verdictText(.keep_dirty));
+ try std.testing.expectEqualStrings(keepReasonText(.committed), verdictText(.keep_committed));
+ try std.testing.expect(std.mem.indexOf(u8, verdictText(.keep_too_new), "retention") != null);
+ try std.testing.expectEqualStrings("", verdictText(.remove));
+}