Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
6067028
Add failing coverage for Claude TaskCreate/TaskUpdate todo ingestion
austinywang Aug 3, 2026
ad73eaf
Populate workspace todos from Claude's TaskCreate/TaskUpdate calls
austinywang Aug 3, 2026
5c18a43
Address review: authoritative task ids, per-workstream row ownership,…
austinywang Aug 3, 2026
4e61c29
Retire the provisional checklist row when a task adopts its real id
austinywang Aug 3, 2026
1d0c06a
Address review feedback: unknown statuses, ordering docs, resume cove…
austinywang Aug 3, 2026
86d8e26
Claim a task id only when the update actually keeps a row
austinywang Aug 3, 2026
07b8a65
Drive the checklist from completed task calls, not pre-execution intent
austinywang Aug 3, 2026
dc04fd7
Keep ownership across resumable sessions; fix empty snapshots and det…
austinywang Aug 3, 2026
d0db71a
Persist each agent checklist row's owning task so ownership survives …
austinywang Aug 4, 2026
7995a11
Harden whole-list todo snapshots: stable ids, cancelled tasks, parse …
austinywang Aug 4, 2026
e003e1c
Order task deltas and keep duplicate id-less entries distinct
austinywang Aug 4, 2026
a4594a1
Reject self-reported task failures and protect whole-list snapshots
austinywang Aug 4, 2026
6c1143d
Keep id-less task identity across a reword; bound seeded workstreams
austinywang Aug 4, 2026
14b2c2b
Re-home task events to the surface's current workspace; recover id-le…
austinywang Aug 4, 2026
b78f7ab
Fail closed on id-less reidentification; retire rows in a workspace l…
austinywang Aug 4, 2026
9ebd6b0
Acknowledge task deltas, re-home them for real, and retire rows from …
austinywang Aug 4, 2026
9ea7999
Widen retirement and recovery to every window; validate the push ackn…
austinywang Aug 4, 2026
58a1a93
Reject stale concurrent TaskUpdates that would un-complete a task
austinywang Aug 4, 2026
a928107
Skip the retirement sweep when the workstream has not moved
austinywang Aug 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34677,6 +34677,14 @@ export default CMUXSessionRestore;
eventDict["tool_input"] = feedToolInput
}
}
// Claude reports a created task's authoritative id only in the tool
// result, so forward it alongside the request for the task tools.
// https://github.com/manaflow-ai/cmux/issues/8960
if hookEventName == "PostToolUse",
toolName == "TaskCreate" || toolName == "TaskUpdate" || toolName == "TodoWrite",
let postToolUseResponseInput {
eventDict["tool_response"] = postToolUseResponseInput
}
if let context = feedContextForEvent(
source: source,
hookEventName: hookEventName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,26 @@ public struct WorkstreamEvent: Codable, Sendable, Equatable {
public let receivedAt: Date
public let extraFieldsJSON: String?

/// The agent's `tool_response` payload, when the hook forwarded one.
///
/// Not a first-class wire field: `PostToolUse` producers that carry a tool
/// result put it in the passthrough bag, and this reads it back out. Used
/// to adopt authoritative ids reported only by a completed tool call.
public var toolResponseJSON: String? {
guard let extraFieldsJSON,
let data = extraFieldsJSON.data(using: .utf8),
let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any]
else { return nil }
for key in ["tool_response", "toolResponse", "tool_result", "toolResult"] {
guard let value = root[key] else { continue }
if let string = value as? String { return string }
if let encoded = try? JSONSerialization.data(withJSONObject: value, options: [.sortedKeys, .fragmentsAllowed]) {
return String(data: encoded, encoding: .utf8)
}
}
return nil
}

public init(
sessionId: String,
hookEventName: HookEventName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ public final class WorkstreamStore {
/// carries forward prompt/preamble context from nearby telemetry rows.
private var lastContextByWorkstream: [String: WorkstreamContext] = [:]

/// Running task list per workstream, accumulated from the agent's
/// per-task tool calls (`TaskCreate` / `TaskUpdate`), which report one
/// task at a time rather than the whole list.
///
/// Each accumulator caps its own retained tasks and ids, and an entry is
/// dropped on `SessionEnd`. That hook is not guaranteed — an agent that
/// crashes or is killed never sends it — so the map itself is also bounded
/// and evicts the least recently updated workstream.
private var taskToolTodosByWorkstream: [String: WorkstreamTaskToolTodos] = [:]
private var taskToolWorkstreamsByRecency: [String] = []

/// Upper bound on tracked workstreams. Well above any plausible number of
/// concurrently live agent sessions, so eviction only ever reaches
/// abandoned ones.
private static let maxTrackedTaskToolWorkstreams = 64

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
/// Creates a store for Feed workstream items.
///
/// - Parameters:
Expand Down Expand Up @@ -141,6 +157,52 @@ public final class WorkstreamStore {
}
}

/// Applies one completed task-tool call, keeping the per-workstream map
/// bounded so an agent that dies without a `SessionEnd` cannot leak its
/// accumulator for the life of the process.
private func applyTaskTool(
workstreamId: String,
toolName: String,
toolInputJSON: String?,
toolResponseJSON: String?,
isError: Bool
) -> WorkstreamTaskToolOutcome {
var accumulator = taskToolTodosByWorkstream[workstreamId] ?? WorkstreamTaskToolTodos()
let outcome = accumulator.apply(
toolName: toolName,
toolInputJSON: toolInputJSON,
toolResponseJSON: toolResponseJSON,
isError: isError
)
guard case .list = outcome else { return outcome }
taskToolTodosByWorkstream[workstreamId] = accumulator
taskToolWorkstreamsByRecency.removeAll { $0 == workstreamId }
taskToolWorkstreamsByRecency.append(workstreamId)
while taskToolWorkstreamsByRecency.count > Self.maxTrackedTaskToolWorkstreams {
let evicted = taskToolWorkstreamsByRecency.removeFirst()
taskToolTodosByWorkstream[evicted] = nil
}
return outcome
}

private func forgetTaskTools(forWorkstream workstreamId: String) {
taskToolTodosByWorkstream[workstreamId] = nil
taskToolWorkstreamsByRecency.removeAll { $0 == workstreamId }
}

/// Every agent task id this workstream has ever owned, including tasks it
/// has since deleted.
///
/// The workspace-checklist sync uses this to retire exactly the rows this
/// agent owns and leave rows owned by the user, or by another agent
/// sharing the workspace, untouched.
///
/// - Parameter workstreamId: The workstream (agent session) id.
/// - Returns: The owned agent task ids, empty when nothing was accumulated.
public func ownedTaskIds(forWorkstream workstreamId: String) -> Set<String> {
taskToolTodosByWorkstream[workstreamId]?.ownedIds ?? []
}

// MARK: - Actions

/// Sends a user-initiated action through the transport and marks the
Expand Down Expand Up @@ -308,11 +370,30 @@ public final class WorkstreamStore {
)
)
case .preToolUse:
// Task-tool calls are deliberately NOT applied here: a pre-execution
// event only states intent, and TaskCreate has no id yet. The
// checklist is driven from PostToolUse instead.
return (.toolUse, .toolUse(toolName: event.toolName ?? "", toolInputJSON: toolInput))
case .postToolUse:
let toolName = event.toolName ?? ""
// Claude's task tools (and the legacy whole-list TodoWrite) reach
// us as ordinary tool calls; fold the completed ones into the
// workstream's running checklist instead of anonymous telemetry.
if isWorkstreamTaskTool(toolName) {
let outcome = applyTaskTool(
workstreamId: event.sessionId,
toolName: toolName,
toolInputJSON: event.toolInputJSON,
toolResponseJSON: event.toolResponseJSON,
isError: event.isError ?? false
)
if case .list(let todos) = outcome {
return (.todos, .todos(todos))
}
}
return (
.toolResult,
.toolResult(toolName: event.toolName ?? "", resultJSON: toolInput, isError: event.isError ?? false)
.toolResult(toolName: toolName, resultJSON: toolInput, isError: event.isError ?? false)
)
case .preCompact:
return (.toolUse, .toolUse(toolName: titleProvider(event) ?? event.hookEventName.rawValue, toolInputJSON: toolInput))
Expand All @@ -337,11 +418,28 @@ public final class WorkstreamStore {
case .sessionStart:
return (.sessionStart, .sessionStart)
case .sessionEnd:
// The agent is gone; its accumulated task list can never receive
// another delta, so retire the entry instead of retaining it for
// the life of the process.
forgetTaskTools(forWorkstream: event.sessionId)
return (.sessionEnd, .sessionEnd)
case .stop:
return (.stop, .stop(reason: Self.stopReason(from: event.toolInputJSON)))
case .todoWrite:
return (.todos, .todos(Self.todos(from: event.toolInputJSON)))
// Whole-list producers (the OpenCode plugin) go through the same
// accumulator so ownership unions across snapshots and a task
// dropped from a later report can still be retired.
let outcome = applyTaskTool(
workstreamId: event.sessionId,
toolName: "TodoWrite",
toolInputJSON: event.toolInputJSON,
toolResponseJSON: nil,
isError: false
)
guard case .list(let todos) = outcome else {
return (.todos, .todos([]))
}
return (.todos, .todos(todos))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
case .notification:
return (.toolResult, .toolResult(toolName: "notification", resultJSON: toolInput, isError: false))
}
Expand Down Expand Up @@ -489,38 +587,4 @@ public final class WorkstreamStore {
}
return nil
}

private static func todos(from json: String?) -> [WorkstreamTaskTodo] {
let rawTodos: [Any]
if let dict = jsonObject(from: json) as? [String: Any] {
rawTodos = dict["todos"] as? [Any] ?? []
} else {
rawTodos = jsonObject(from: json) as? [Any] ?? []
}
return rawTodos.enumerated().compactMap { idx, raw in
guard let dict = raw as? [String: Any] else { return nil }
let content = (dict["content"] as? String)
?? (dict["text"] as? String)
?? (dict["title"] as? String)
?? ""
guard !content.isEmpty else { return nil }
let rawState = (dict["state"] as? String)
?? (dict["status"] as? String)
?? "pending"
let state: WorkstreamTaskTodo.State
switch rawState {
case "completed", "done":
state = .completed
case "inProgress", "in_progress", "active":
state = .inProgress
default:
state = .pending
}
return WorkstreamTaskTodo(
id: (dict["id"] as? String) ?? "todo\(idx)",
content: content,
state: state
)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import Foundation
#if canImport(CryptoKit)
import CryptoKit
#endif

extension WorkstreamTaskTodo {
/// A stable workspace-checklist identity for this todo inside
/// `workstreamId`.
///
/// Agent task ids are per-session counters (`"1"`, `"2"`, …) while the
/// workspace checklist is keyed by `UUID`, so the pair is hashed into a
/// deterministic UUID. Deriving it (instead of keeping a side table) means
/// the same task keeps its checklist row across app restarts and across
/// every entrypoint that syncs the list, and scoping it by workstream
/// keeps two concurrent agents in one workspace from colliding on the
/// shared `"1"`, `"2"` numbering.
///
/// - Parameter workstreamId: The owning workstream (agent session) id.
/// - Returns: A deterministic RFC 4122 UUID for this `(workstream, task)`.
public func stableChecklistItemId(workstreamId: String) -> UUID {
workstreamChecklistItemId(workstreamId: workstreamId, taskId: id)
}
}

/// The deterministic checklist identity for one agent task id.
///
/// Exposed separately from ``WorkstreamTaskTodo/stableChecklistItemId(workstreamId:)``
/// so callers can derive the identity of a task they no longer hold (for
/// example, retiring rows for tasks the agent has deleted).
///
/// - Parameters:
/// - workstreamId: The owning workstream (agent session) id.
/// - taskId: The agent's task id.
/// - Returns: A deterministic RFC 4122 UUID for this `(workstream, task)`.
public func workstreamChecklistItemId(workstreamId: String, taskId: String) -> UUID {
derivedChecklistUUID(from: "cmux.workstream.todo\u{0}\(workstreamId)\u{0}\(taskId)")
}

private func derivedChecklistUUID(from seed: String) -> UUID {
let data = Data(seed.utf8)
var bytes: [UInt8]
#if canImport(CryptoKit)
bytes = Array(SHA256.hash(data: data).prefix(16))
#else
bytes = Array(repeating: 0, count: 16)
for (index, byte) in data.enumerated() {
bytes[index % 16] = bytes[index % 16] &+ byte &+ UInt8(truncatingIfNeeded: index)
}
#endif
Comment on lines +39 to +49

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Drop the non-CryptoKit fallback instead of keeping a weak digest.

This package lives under Packages/macOS/, and CryptoKit is available on every platform it builds for, so the #else branch never compiles. The fallback also folds bytes additively into 16 slots, which collides easily. A collision would map two different (workstreamId, taskId) pairs onto one checklist row, and the identity is persisted across restarts. Remove the branch and require CryptoKit, or replace the fold with a real digest if a non-Apple platform is actually a target.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@Packages/macOS/CMUXAgentLaunch/Sources/CMUXAgentLaunch/Workstream/WorkstreamTaskTodo`+ChecklistIdentity.swift
around lines 39 - 49, Update derivedChecklistUUID to require CryptoKit and
always derive the 16-byte UUID seed from SHA256.hash; remove the `#if`
canImport(CryptoKit) conditional and the additive zero-filled fallback branch,
preserving the existing deterministic UUID derivation.

// RFC 4122 version 4 / variant bits so the value is a well-formed UUID.
bytes[6] = (bytes[6] & 0x0F) | 0x40
bytes[8] = (bytes[8] & 0x3F) | 0x80
return UUID(uuid: (
bytes[0], bytes[1], bytes[2], bytes[3],
bytes[4], bytes[5], bytes[6], bytes[7],
bytes[8], bytes[9], bytes[10], bytes[11],
bytes[12], bytes[13], bytes[14], bytes[15]
))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import Foundation

/// The outcome of feeding one task-tool call to ``WorkstreamTaskToolTodos``.
///
/// Distinguishing ``ignored`` from an empty ``list(_:)`` matters: deleting the
/// agent's last task is a real empty-list transition that must retire its
/// checklist rows, while an unparseable payload must fall through to ordinary
/// tool telemetry and leave the checklist alone.
enum WorkstreamTaskToolOutcome: Equatable {
/// The payload carried nothing usable; the caller should fall back to
/// plain tool-use telemetry.
case ignored
/// The workstream's task list after applying the call.
case list([WorkstreamTaskTodo])
}
Loading