From 1a142d551918ddbab798a18541149739e66dd616 Mon Sep 17 00:00:00 2001 From: jctanner Date: Thu, 29 Oct 2026 14:32:52 -0400 Subject: [PATCH 01/16] fix(#8908): render Claude Workflow progress Display task and agent lifecycle changes alongside useful runtime notices. Keep partial updates and optional run IDs consistent, preserve failure context, and distinguish repeated events from unchanged snapshots. Redact and bound displayed metadata without changing raw stream capture, model output, tool traces, or usage accounting. Add regression coverage and document event handling and producer limits. Signed-off-by: jctanner --- docs/cli/run.md | 51 ++++ docs/runtimes/claude.md | 6 + internal/cli/run.go | 6 +- internal/cli/workflow_progress_test.go | 33 ++ internal/runtime/claude_progress.go | 15 + .../runtime/claude_progress_review_test.go | 185 +++++++++++ internal/runtime/claude_status_progress.go | 239 +++++++++++++++ .../runtime/claude_status_progress_test.go | 154 ++++++++++ internal/runtime/claude_task_progress.go | 142 +++++++++ internal/runtime/claude_task_updates_test.go | 105 +++++++ .../runtime/claude_workflow_progress_test.go | 288 ++++++++++++++++++ internal/runtime/renderer.go | 23 +- internal/runtime/status_progress.go | 72 +++++ internal/runtime/task_progress.go | 249 +++++++++++++++ 14 files changed, 1562 insertions(+), 6 deletions(-) create mode 100644 internal/cli/workflow_progress_test.go create mode 100644 internal/runtime/claude_progress_review_test.go create mode 100644 internal/runtime/claude_status_progress.go create mode 100644 internal/runtime/claude_status_progress_test.go create mode 100644 internal/runtime/claude_task_progress.go create mode 100644 internal/runtime/claude_task_updates_test.go create mode 100644 internal/runtime/claude_workflow_progress_test.go create mode 100644 internal/runtime/status_progress.go create mode 100644 internal/runtime/task_progress.go diff --git a/docs/cli/run.md b/docs/cli/run.md index 2129095362..afdcd0b96f 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -111,6 +111,57 @@ cases fail earlier: See [pi § Per-persona model configuration](../runtimes/pi.md#per-persona-model-configuration). +## Live Claude Workflow progress + +When Claude Code emits background task and Workflow progress, `fullsend run` +prints task identity, agent labels, attributed phases, state changes, and +available tool names/context. For example: + +```console + ⚙ Task wf-example / agent reader [Read]: read input — running + ⚙ Task wf-example / agent reader [Read]: read input — completed + ⚙ Task wf-example / agent creator [Create]: strategy-create — running (tool: Bash: python3 create.py) +``` + +Unchanged snapshots and counter-only updates do not repeat the same display +line. Text is sanitized, credential-redacted, and bounded before display or +retention in the bounded display cache. Concurrent tasks and agents retain +separate identities. Partial lifecycle patches retain known task labels and +state; explicit starts can reset an identity. Late running snapshots do not +reopen a known terminal task or agent. + +The display handles these structured Claude events when the runtime emits +them. Task progress shapes were checked against Claude Code 2.1.296 capture +and the embedded 2.1.312 emitter/schema; availability varies by version. + +| Event | Console behavior | +| --- | --- | +| `task_started` | Task identity and description; ambient/hidden starts suppress subsequent progress while tracked. | +| `task_progress` | Task description, last tool and progress summary; Workflow agent phase, tool context, state, blocked/error and cached-result metadata. | +| `task_updated` | Pending, running, paused, completed, failed and killed states; description-only patches and bounded errors. | +| `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | +| `task_summary` | Changed mid-turn summary; a null/empty value clears deduplication silently. | +| `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | +| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. | +| `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | +| `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | +| `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | +| `rate_limit_event` | Warnings, rejection, supplied reset time and subsequent recovery; routine initial allowed status suppressed. | + +Declared `workflow_phase` records do not prove live advancement and are not +rendered as phase starts. Internal `workflow_log` entries are filtered out +of SDK progress by the inspected Claude 2.1.312 producer; Fullsend cannot +display records absent from its input stream. This is not a stream of full +nested tool stdout/stderr, prompts, result bodies or hook output. Unknown +message kinds/states and malformed records are ignored for display; raw +events remain in `output.jsonl` for diagnosis and future compatibility work. + +Task completion and session idle are distinct from the run's validated +business result. Progress counters do not add to token/cost totals. The +periodic `Agent running (...)` heartbeat still reports elapsed time rather +than proving progress. The display is advisory, not a durable task registry; +very large sessions can evict cached identity and deduplication state. + ## Output artifacts Each run produces artifacts in the output directory. Relative `--output-dir` diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index 27e43cdd91..bd8307a5b1 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -10,6 +10,12 @@ fullsend run triage --model opus --effort high Choosing between runtimes is in [Agent runtimes](../runtimes.md). Selection, precedence and the config keys live there too. +Background Workflow phase/agent changes and runtime lifecycle/status notices +are displayed from Claude's structured event stream. See +[live Workflow progress](../cli/run.md#live-claude-workflow-progress) +for the display behavior and its limits; it does not include full nested tool +stdout/stderr. + ## Models Pass an alias or a model id. fullsend resolves `opus`, `sonnet` and `haiku` itself and passes the diff --git a/internal/cli/run.go b/internal/cli/run.go index 774cd82f0c..d66c617872 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2768,6 +2768,10 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep collector.attachInput(agentSpan, agentPrompt, promptHidesAlterations(validationFeedback, promptSanitized)) toolSpans := newToolSpanTracker(tracer, agentCtx) toolSpans.runnerEnv = h.RunnerEnv + renderer := agentruntime.NewEventRenderer(printer) + renderer.RedactProgress = func(text string) string { + return redactSecretLiterals(text, h.RunnerEnv) + } var metrics agentruntime.RunMetrics hooksSettings := "" if h.SecurityEnabled() { @@ -2792,7 +2796,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep Forge: forgePlatform, ModelAliases: configModelAliases, ForgeClient: playbackForgeClient, - OnEvent: iterationEventHandler(agentruntime.NewEventRenderer(printer).Handle, collector, toolSpans), + OnEvent: iterationEventHandler(renderer.Handle, collector, toolSpans), }, printer, agentStart, &metrics) close(heartbeatDone) lastIterElapsed = time.Since(agentStart) diff --git a/internal/cli/workflow_progress_test.go b/internal/cli/workflow_progress_test.go new file mode 100644 index 0000000000..0e7b9f5574 --- /dev/null +++ b/internal/cli/workflow_progress_test.go @@ -0,0 +1,33 @@ +package cli + +import ( + "strings" + "testing" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/ui" + "github.com/stretchr/testify/assert" +) + +func TestIterationEventHandler_WorkflowProgressIsDisplayOnly(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "") + const secret = "opaque-workflow-runner-secret-for-test" + const provider = "opaque-workflow-provider-secret-for-test" + t.Setenv("GH_WORKFLOW_TOKEN", provider) + var output strings.Builder + renderer := agentruntime.NewEventRenderer(ui.New(&output)) + renderer.RedactProgress = func(s string) string { return redactSecretLiterals(s, map[string]string{"PUSH_TOKEN": secret}) } + collector := newContentCollector(4096) + tracker, _, agent := toolSpanFixture(t) + defer agent.End() + handler := iterationEventHandler(renderer.Handle, collector, tracker) + handler(agentruntime.TaskProgressEvent{TaskID: "workflow", State: agentruntime.TaskPaused, Label: secret, Detail: provider}) + handler(agentruntime.StatusProgressEvent{Kind: "notice", Label: "Hook", Detail: secret + " " + provider}) + assert.Contains(t, output.String(), "paused") + assert.Contains(t, output.String(), "Hook") + assert.NotContains(t, output.String(), secret) + assert.NotContains(t, output.String(), provider) + assert.Empty(t, collector.parts, "status metadata must not become model output") + assert.Zero(t, tracker.created, "status metadata must not fabricate tool spans") + assert.Empty(t, tracker.open) +} diff --git a/internal/runtime/claude_progress.go b/internal/runtime/claude_progress.go index f09798dd87..72c5a94882 100644 --- a/internal/runtime/claude_progress.go +++ b/internal/runtime/claude_progress.go @@ -338,6 +338,16 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error { continue } switch se.Subtype { + case "task_started", "task_progress", "task_updated", "task_notification": + for _, progress := range decodeClaudeTaskProgress(line, se.Subtype) { + onEvent(progress) + } + case "hook_started", "hook_progress", "hook_response", "task_summary", + "informational", "notification", "status", "session_state_changed", + "permission_denied", "background_tasks_changed": + if progress, ok := decodeClaudeStatusProgress(line, se.Subtype); ok { + onEvent(progress) + } case "init": onEvent(InitEvent{ Model: se.Model, @@ -362,6 +372,11 @@ func parseClaudeStream(r io.Reader, onEvent func(AgentEvent)) error { }) } + case "rate_limit_event": + if progress, ok := decodeClaudeRateLimit(line); ok { + onEvent(progress) + } + case "stream_event": seenStreamEvent = true var wrapper streamEventWrapper diff --git a/internal/runtime/claude_progress_review_test.go b/internal/runtime/claude_progress_review_test.go new file mode 100644 index 0000000000..f35d5b14d8 --- /dev/null +++ b/internal/runtime/claude_progress_review_test.go @@ -0,0 +1,185 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestWorkflowReviewTerminalNotificationKeepsContext(t *testing.T) { + for _, state := range []string{"completed", "failed", "stopped"} { + t.Run(state, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + stream := fmt.Sprintf(`{"type":"system","subtype":"task_started","task_id":"one","description":"Work"} +{"type":"system","subtype":"task_progress","task_id":"one","description":"Work","last_tool_name":"Bash"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":%q,"error":"context retained"}} +{"type":"system","subtype":"task_notification","task_id":"one","status":%q,"summary":"PRIVATE"} +`, state, state) + stderr := captureStderr(t, func() { + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + }) + if strings.Count(out.String(), "— "+state) != 1 || strings.Count(stderr, "— "+state) != 1 { + t.Fatalf("terminal message duplicated: %s", out.String()) + } + if !strings.Contains(out.String(), "context retained") || strings.Contains(out.String(), "PRIVATE") { + t.Fatal(out.String()) + } + // A supplied worker-restart cause is new information and must replace + // the prior detail, rather than being swallowed by the partial merge. + if state == "stopped" { + r.isCI = false + if err := parseClaudeStream(strings.NewReader(`{"type":"system","subtype":"task_notification","task_id":"one","status":"stopped","reason":"worker_restart"}`+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "worker restarted") { + t.Fatal(out.String()) + } + } + }) + } +} + +func TestWorkflowReviewUnkeyedWarningsAreOccurrences(t *testing.T) { + for _, subtype := range []string{"informational", "permission_denied", "notification"} { + t.Run(subtype, func(t *testing.T) { + line := fmt.Sprintf(`{"type":"system","subtype":%q,"level":"warning","content":"Retry required","tool_name":"Bash","decision_reason":"Retry required","text":"Retry required"}`, subtype) + "\n" + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(line+line), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Retry required") != 2 { + t.Fatalf("lost repeated %s: %s", subtype, out.String()) + } + }) + } +} + +func TestWorkflowReviewRequestCyclesStayQuiet(t *testing.T) { + cycle := `{"type":"system","subtype":"status","status":"requesting"} +{"type":"system","subtype":"status","status":null} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(strings.Repeat(cycle, 20)), r.Handle); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatal("per-request status chatter: " + out.String()) + } + if err := parseClaudeStream(strings.NewReader(`{"type":"system","subtype":"status","status":"compacting"}`+"\n"+cycle+cycle), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "compacting") != 1 || strings.Count(out.String(), "ready") != 1 { + t.Fatal(out.String()) + } +} + +func TestWorkflowReviewRunIDPromotionPreservesHiddenAndTerminal(t *testing.T) { + for _, hidden := range []bool{false, true} { + t.Run(fmt.Sprint(hidden), func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := fmt.Sprintf(`{"type":"system","subtype":"task_started","task_id":"one","description":"Initial","ambient":%t} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"completed"}} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","description":"STALE"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"run1","status":"completed"} +`, hidden) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "STALE") { + t.Fatal("promotion lost terminal guard: " + out.String()) + } + if hidden && out.Len() != 0 { + t.Fatal("promotion exposed ambient task: " + out.String()) + } + if !hidden && strings.Count(out.String(), "completed") != 1 { + t.Fatal("promotion lost terminal identity: " + out.String()) + } + }) + } +} + +func TestWorkflowReviewNewRunWithoutStartReceivesOptionalCompletion(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"old","description":"Old"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"old","status":"completed"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"new","description":"New"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"old","description":"LATE OLD"} +{"type":"system","subtype":"task_notification","task_id":"one","status":"completed"} +` + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "New — completed") || strings.Contains(out.String(), "LATE OLD") { + t.Fatal(out.String()) + } +} + +func TestWorkflowReviewSubtypeFieldsDecodeIndependently(t *testing.T) { + line := `{"type":"system","subtype":"informational","level":"warning","content":"Still useful","hook_id":42,"status":{},"tasks":false}` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(line+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Still useful") { + t.Fatal("unrelated optional fields discarded notice") + } +} + +func TestWorkflowReviewNewStartResetsAgents(t *testing.T) { + for _, run := range []string{"", ` ,"run_id":"run1"`} { + t.Run(run, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + started := `{"type":"system","subtype":"task_started","task_id":"one"` + run + `}` + "\n" + finished := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"Read"}]}` + "\n" + restart := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"Fresh agent"}]}` + "\n" + if err := parseClaudeStream(strings.NewReader(started+finished+started+restart), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Fresh agent — running") { + t.Fatal("new start did not reset agent guard: " + out.String()) + } + }) + } +} + +func TestWorkflowReviewJoiningFieldsCannotRecreateCommands(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "task:", Label: "label", State: TaskRunning}) + r.Handle(StatusProgressEvent{Kind: "warning", Label: "warning:", Detail: "detail"}) + if strings.Contains(out.String(), "::") { + t.Fatal("field joins recreated command delimiter: " + out.String()) + } +} + +func TestWorkflowReviewRestartWithoutRunIDKeepsOldRunHistory(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := `{"type":"system","subtype":"task_started","task_id":"one","description":"Old"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"A","description":"Old"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"A","status":"completed"} +{"type":"system","subtype":"task_started","task_id":"one","description":"New"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"A","description":"STALE"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"A","status":"completed"} +{"type":"system","subtype":"task_progress","task_id":"one","description":"Current work"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"B","description":"Current work"} +{"type":"system","subtype":"task_notification","task_id":"one","status":"completed"} +` + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "STALE") || strings.Count(out.String(), "completed") != 2 || strings.Count(out.String(), "Current work — running") != 1 || !strings.Contains(out.String(), "Current work — completed") { + t.Fatal("old run stole restarted task: " + out.String()) + } +} diff --git a/internal/runtime/claude_status_progress.go b/internal/runtime/claude_status_progress.go new file mode 100644 index 0000000000..32558be2d2 --- /dev/null +++ b/internal/runtime/claude_status_progress.go @@ -0,0 +1,239 @@ +package runtime + +import ( + "encoding/json" + "fmt" + "strings" + "time" +) + +// This is an explicit display allowlist, not a generic JSON dump. In +// particular hook stdout/stderr/output, prompts, terminal summaries, and +// arbitrary future payloads must stay out of console/CI annotations. +func decodeClaudeStatusProgress(line []byte, subtype string) (StatusProgressEvent, bool) { + e := StatusProgressEvent{Kind: subtype} + switch subtype { + case "hook_started", "hook_progress", "hook_response": + var wire struct { + HookID string `json:"hook_id"` + HookName string `json:"hook_name"` + HookEvent string `json:"hook_event"` + Outcome string `json:"outcome"` + ExitCode *int `json:"exit_code"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + if strings.TrimSpace(wire.HookID) == "" { + return e, false + } + e.Kind = "hook" + e.ID = wire.HookID + e.Label = "Hook " + wire.HookName + if wire.HookEvent != "" { + e.Label += " [" + wire.HookEvent + "]" + } + e.State = "running" + if subtype == "hook_response" { + switch wire.Outcome { + case "success": + e.State = "completed" + case "error": + e.State = "failed" + case "cancelled": + e.State = "stopped" + default: + return e, false + } + if wire.ExitCode != nil { + e.Detail = fmt.Sprintf("exit %d", *wire.ExitCode) + } + } + case "task_summary": + var wire struct { + Detail *string `json:"detail"` + Summary *string `json:"summary"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + e.Label = "Task summary" + if wire.Detail != nil { + e.Detail = *wire.Detail + } else if wire.Summary != nil { + e.Detail = *wire.Summary + } + e.Clear = strings.TrimSpace(e.Detail) == "" + case "informational": + var wire struct { + Level string `json:"level"` + Content string `json:"content"` + ToolUseID string `json:"tool_use_id"` + PreventContinuation bool `json:"prevent_continuation"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + // Claude marks info as transcript-only. Keep salient console levels. + switch wire.Level { + case "notice", "suggestion", "warning": + default: + return e, false + } + if strings.TrimSpace(wire.Content) == "" { + return e, false + } + e.ID = wire.ToolUseID + e.Occurrence = strings.TrimSpace(e.ID) == "" + e.Label = "Claude " + wire.Level + e.Detail = wire.Content + if wire.PreventContinuation { + e.State = "continuation stopped" + } + case "notification": + var wire struct { + Key string `json:"key"` + Text string `json:"text"` + Priority string `json:"priority"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + if strings.TrimSpace(wire.Text) == "" { + return e, false + } + e.ID = wire.Key + e.Occurrence = strings.TrimSpace(e.ID) == "" + e.Label = "Claude notification" + e.State = wire.Priority + e.Detail = wire.Text + case "status": + var wire struct { + Status *string `json:"status"` + CompactResult string `json:"compact_result"` + CompactError string `json:"compact_error"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + e.Label = "Claude status" + if wire.Status == nil { + if wire.CompactResult == "failed" { + e.State = "compaction failed" + e.Detail = wire.CompactError + } else { + e.State = "ready" + e.Recovery = true + } + } else { + switch *wire.Status { + case "compacting": + e.State = *wire.Status + default: + return e, false + } + } + case "session_state_changed": + var wire struct { + State string `json:"state"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + e.Label = "Session" + switch wire.State { + case "idle", "running", "requires_action": + e.State = strings.ReplaceAll(wire.State, "_", " ") + default: + return e, false + } + case "permission_denied": + var wire struct { + ToolUseID string `json:"tool_use_id"` + ToolName string `json:"tool_name"` + AgentID string `json:"agent_id"` + DecisionReason string `json:"decision_reason"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + if wire.ToolName == "" { + return e, false + } + e.ID = wire.ToolUseID + e.Occurrence = strings.TrimSpace(e.ID) == "" + e.Label = "Permission denied: " + wire.ToolName + if wire.AgentID != "" { + e.Label += " / agent " + wire.AgentID + } + e.Detail = wire.DecisionReason + // message is a tool_result body, deliberately not forwarded. + case "background_tasks_changed": + var wire struct { + Tasks json.RawMessage `json:"tasks"` + } + if json.Unmarshal(line, &wire) != nil { + return e, false + } + + var tasks []json.RawMessage + if len(wire.Tasks) == 0 || string(wire.Tasks) == "null" || json.Unmarshal(wire.Tasks, &tasks) != nil { + return e, false + } + count := 0 + for _, raw := range tasks { + var task struct { + TaskID string `json:"task_id"` + Ambient bool `json:"ambient"` + } + if json.Unmarshal(raw, &task) == nil && strings.TrimSpace(task.TaskID) != "" && !task.Ambient { + count++ + } + } + e.Label = "Background tasks" + e.Detail = fmt.Sprintf("%d reported (membership only)", count) + default: + return e, false + } + return e, true +} + +func decodeClaudeRateLimit(line []byte) (StatusProgressEvent, bool) { + var wire struct { + Info struct { + Status string `json:"status"` + Limit string `json:"rateLimitType"` + ResetsAt int64 `json:"resetsAt"` + } `json:"rate_limit_info"` + } + if json.Unmarshal(line, &wire) != nil { + return StatusProgressEvent{}, false + } + e := StatusProgressEvent{Kind: "rate_limit", Label: "Rate limit"} + switch wire.Info.Status { + case "allowed": + e.State = "allowed" + e.Recovery = true + case "allowed_warning": + e.State = "approaching limit" + case "rejected": + e.State = "rejected" + default: + return e, false + } + e.Detail = wire.Info.Limit + if wire.Info.ResetsAt > 0 { + if e.Detail != "" { + e.Detail += "; " + } + e.Detail += "resets " + time.Unix(wire.Info.ResetsAt, 0).UTC().Format(time.RFC3339) + } + return e, true +} diff --git a/internal/runtime/claude_status_progress_test.go b/internal/runtime/claude_status_progress_test.go new file mode 100644 index 0000000000..deea6afb5d --- /dev/null +++ b/internal/runtime/claude_status_progress_test.go @@ -0,0 +1,154 @@ +package runtime + +import ( + "bytes" + "fmt" + "io" + "strings" + "testing" +) + +// Shapes below are reduced from the embedded SDK schemas/emitter in Claude +// 2.1.312. Raw output/prompt/result fields are included to prove exclusion. +func TestClaudeStatusProgressShapes(t *testing.T) { + cases := []struct{ name, line, want string }{ + {"hook start", `{"type":"system","subtype":"hook_started","hook_id":"h1","hook_name":"guard","hook_event":"PreToolUse"}`, "Hook guard [PreToolUse] — running"}, + {"hook progress", `{"type":"system","subtype":"hook_progress","hook_id":"h1","hook_name":"guard","stdout":"PRIVATE","stderr":"PRIVATE","output":"PRIVATE"}`, "Hook guard — running"}, + {"hook success", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"success","exit_code":0,"output":"PRIVATE"}`, "completed: exit 0"}, + {"hook failed", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"error","exit_code":2}`, "failed: exit 2"}, + {"hook cancelled", `{"type":"system","subtype":"hook_response","hook_id":"h1","outcome":"cancelled"}`, "stopped"}, + {"summary", `{"type":"system","subtype":"task_summary","detail":"Refining strategy"}`, "Task summary: Refining strategy"}, + {"older summary", `{"type":"system","subtype":"task_summary","summary":"Reviewing change"}`, "Task summary: Reviewing change"}, + {"notice", `{"type":"system","subtype":"informational","level":"notice","content":"Retrying a phase"}`, "Claude notice: Retrying a phase"}, + {"suggestion", `{"type":"system","subtype":"informational","level":"suggestion","content":"Check access"}`, "Claude suggestion: Check access"}, + {"stopped continuation", `{"type":"system","subtype":"informational","level":"warning","content":"Hook blocked continuation","prevent_continuation":true}`, "continuation stopped: Hook blocked continuation"}, + {"notification", `{"type":"system","subtype":"notification","key":"budget","text":"Budget nearly used","priority":"high"}`, "Claude notification — high: Budget nearly used"}, + {"compacting", `{"type":"system","subtype":"status","status":"compacting","compact_output_chars":27}`, "Claude status — compacting"}, + {"compaction failure", `{"type":"system","subtype":"status","status":null,"compact_result":"failed","compact_error":"provider refused"}`, "compaction failed: provider refused"}, + {"session running", `{"type":"system","subtype":"session_state_changed","state":"running"}`, "Session — running"}, + {"session idle", `{"type":"system","subtype":"session_state_changed","state":"idle"}`, "Session — idle"}, + {"requires action", `{"type":"system","subtype":"session_state_changed","state":"requires_action"}`, "Session — requires action"}, + {"permission", `{"type":"system","subtype":"permission_denied","tool_name":"Bash","tool_use_id":"t1","agent_id":"a1","decision_reason":"policy denied","message":"PRIVATE tool result"}`, "Permission denied: Bash / agent a1: policy denied"}, + {"background membership", `{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"one"},{"task_id":"ambient","ambient":true},null,42,{"task_id":""}]}`, "Background tasks: 1 reported (membership only)"}, + {"empty membership", `{"type":"system","subtype":"background_tasks_changed","tasks":[]}`, "Background tasks: 0 reported (membership only)"}, + {"rate warning", `{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","rateLimitType":"five_hour","resetsAt":1700000000}}`, "Rate limit — approaching limit: five_hour; resets 2023-11-14T22:13:20Z"}, + {"rate rejected", `{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"}}`, "Rate limit — rejected"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(tc.line+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), tc.want) { + t.Fatalf("missing %q in %q", tc.want, out.String()) + } + if strings.Contains(out.String(), "PRIVATE") { + t.Fatal("private output exposed") + } + }) + } +} + +func TestClaudeStatusIgnoresNonDisplayAndMalformed(t *testing.T) { + lines := []string{ + `{broken`, + `{"type":"system","subtype":"hook_started"}`, + `{"type":"system","subtype":"hook_response","hook_id":"one","outcome":"future"}`, + `{"type":"system","subtype":"informational","level":"info","content":"transcript only"}`, + `{"type":"system","subtype":"informational","level":"warning","content":" "}`, + `{"type":"system","subtype":"notification","text":" "}`, + `{"type":"system","subtype":"task_summary","detail":null}`, + `{"type":"system","subtype":"status","status":null}`, + `{"type":"system","subtype":"status","status":"future"}`, + `{"type":"system","subtype":"status","status":"requesting"}`, + `{"type":"system","subtype":"session_state_changed","state":"future"}`, + `{"type":"system","subtype":"permission_denied"}`, + `{"type":"system","subtype":"background_tasks_changed"}`, + `{"type":"system","subtype":"background_tasks_changed","tasks":null}`, + `{"type":"system","subtype":"background_tasks_changed","tasks":42}`, + `{"type":"system","subtype":"future_display","content":"PRIVATE"}`, + `{"type":"rate_limit_event","rate_limit_info":{"status":"future"}}`, + `{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"}}`, + `{"type":"rate_limit_event","rate_limit_info":42}`, + } + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(strings.Join(lines, "\n")+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatalf("unexpected output: %q", out.String()) + } + if _, ok := decodeClaudeStatusProgress([]byte(`{"hook_id":42}`), "hook_started"); ok { + t.Fatal("invalid fields accepted") + } + if _, ok := decodeClaudeStatusProgress([]byte(`{}`), "future"); ok { + t.Fatal("unknown subtype accepted") + } + if _, ok := decodeClaudeRateLimit([]byte(`{broken`)); ok { + t.Fatal("invalid rate event accepted") + } +} + +func TestClaudeStatusTransitionsAndDedup(t *testing.T) { + stream := `{"type":"system","subtype":"status","status":"compacting"} +{"type":"system","subtype":"status","status":"compacting","compact_output_chars":500} +{"type":"system","subtype":"status","status":null} +{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"}} +{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"}} +{"type":"rate_limit_event","rate_limit_info":{"status":"rejected"}} +{"type":"rate_limit_event","rate_limit_info":{"status":"allowed"}} +{"type":"system","subtype":"task_summary","detail":"Reviewing"} +{"type":"system","subtype":"task_summary","detail":"Reviewing"} +{"type":"system","subtype":"task_summary","detail":null} +{"type":"system","subtype":"task_summary","detail":"Reviewing"} +` + var raw, out bytes.Buffer + metrics := &RunMetrics{} + r := newTestRenderer(&out) + err := parseClaudeStream(io.TeeReader(strings.NewReader(stream), &raw), func(e AgentEvent) { recordClaudeMetrics(metrics, e); r.Handle(e) }) + if err != nil { + t.Fatal(err) + } + for text, count := range map[string]int{"compacting": 1, "ready": 1, "rejected": 1, "allowed": 1, "Reviewing": 2} { + if got := strings.Count(out.String(), text); got != count { + t.Errorf("%s count=%d want=%d: %s", text, got, count, out.String()) + } + } + if raw.String() != stream { + t.Fatal("raw events changed") + } + if metrics.InputTokens != 0 || metrics.OutputTokens != 0 || metrics.ToolCalls.Load() != 0 || metrics.TotalCostUSD != 0 { + t.Fatal("advisories altered metrics") + } +} + +func TestStatusProgressRendererSafetyAndBounds(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + const secret = "opaque-status-secret-for-test" + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, secret, "[REDACTED]") } + e := StatusProgressEvent{Kind: "notification", ID: "one", Label: secret + "\n::error::", State: "\x1b[31mwarning\x1b[0m", Detail: secret + strings.Repeat("界", 500)} + stderr := captureStderr(t, func() { r.Handle(TextEvent{Text: "before"}); r.Handle(e); r.Handle(e) }) + if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Contains(out.String(), "\x1b") { + t.Fatal("unsafe status display") + } + if strings.Count(stderr, "::notice::") != 1 || !strings.Contains(out.String(), "before\n") { + t.Fatal("bad CI/block boundary") + } + if len([]rune(out.String())) > 500 { + t.Fatal("unbounded status") + } + r.Handle(StatusProgressEvent{}) + r.Handle(StatusProgressEvent{Kind: "empty"}) + r.isCI = false + for i := range maxTaskProgressEntries + 1 { + r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row"}) + } + if len(r.statusProgressSeen) > maxTaskProgressEntries { + t.Fatal("unbounded status cache") + } +} diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go new file mode 100644 index 0000000000..9c1b6871c6 --- /dev/null +++ b/internal/runtime/claude_task_progress.go @@ -0,0 +1,142 @@ +package runtime + +import ( + "encoding/json" + "strings" +) + +// Optional snapshots remain raw so malformed entries cannot discard a useful +// lifecycle event. Prompt/result bodies and terminal summaries are not decoded. +type claudeTaskProgress struct { + TaskID string `json:"task_id"` + RunID string `json:"run_id"` + Description string `json:"description"` + Status string `json:"status"` + LastToolName string `json:"last_tool_name"` + Summary json.RawMessage `json:"summary"` + Reason string `json:"reason"` + Ambient bool `json:"ambient"` + SkipTranscript bool `json:"skip_transcript"` + Patch json.RawMessage `json:"patch"` + WorkflowProgress json.RawMessage `json:"workflow_progress"` +} + +type claudeWorkflowAgentProgress struct { + Type string `json:"type"` + Index int `json:"index"` + AgentID string `json:"agentId"` + Label string `json:"label"` + PhaseTitle string `json:"phaseTitle"` + State string `json:"state"` + LastToolName string `json:"lastToolName"` + LastToolSummary string `json:"lastToolSummary"` + Error string `json:"error"` + Blocked bool `json:"blocked"` + Cached bool `json:"cached"` +} + +func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { + var task claudeTaskProgress + if json.Unmarshal(line, &task) != nil || strings.TrimSpace(task.TaskID) == "" { + return nil + } + event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, Label: task.Description} + switch subtype { + case "task_started": + event.State = TaskRunning + event.Started = true + event.Hidden = task.Ambient || task.SkipTranscript + case "task_progress": + event.State = TaskRunning + event.ToolName = task.LastToolName + _ = json.Unmarshal(task.Summary, &event.Summary) + case "task_updated": + var patch struct { + Status *string `json:"status"` + Description *string `json:"description"` + Error *string `json:"error"` + } + if len(task.Patch) > 0 { + if json.Unmarshal(task.Patch, &patch) != nil { + return nil + } + if patch.Status != nil { + task.Status = *patch.Status + } + if patch.Description != nil { + event.Label = *patch.Description + event.LabelSet = true + } + if patch.Error != nil { + event.Detail = *patch.Error + event.DetailSet = true + } + } + event.State = claudeTaskState(task.Status) + event.Update = true + case "task_notification": + event.Update = true + event.State = claudeTaskState(task.Status) + // summary is a possibly complete result, unlike task_progress.summary. + if task.Reason == "worker_restart" { + event.Detail = "worker restarted" + event.DetailSet = true + } + default: + return nil + } + var events []TaskProgressEvent + useful := event.LabelSet || event.DetailSet || event.Detail != "" || event.ToolName != "" || event.Summary != "" + if (event.State != "" || useful) && (subtype != "task_progress" || task.Description != "" || useful) { + events = append(events, event) + } + if subtype != "task_progress" { + return events + } + var entries []json.RawMessage + if json.Unmarshal(task.WorkflowProgress, &entries) != nil { + return events + } + for _, entry := range entries { + var agent claudeWorkflowAgentProgress + if json.Unmarshal(entry, &agent) != nil || agent.Type != "workflow_agent" || (agent.AgentID == "" && agent.Index <= 0) { + continue + } + state := claudeTaskState(agent.State) + if state == "" { + continue + } + events = append(events, TaskProgressEvent{ + TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, + Label: agent.Label, Phase: agent.PhaseTitle, State: state, + ToolName: agent.LastToolName, ToolSummary: agent.LastToolSummary, + Detail: agent.Error, Blocked: agent.Blocked, Cached: agent.Cached, + }) + } + return events +} + +func claudeTaskState(state string) TaskState { + switch state { + case "start", "started", "progress", "running": + return TaskRunning + case "done", "completed": + return TaskCompleted + case "error", "failed": + return TaskFailed + case "killed", "stopped", "cancelled", "canceled": + return TaskStopped + case "queued": + return TaskQueued + case "pending": + return TaskPending + case "paused": + return TaskPaused + case "retrying": + return TaskRetrying + case "skipped": + return TaskSkipped + default: + return "" + } +} diff --git a/internal/runtime/claude_task_updates_test.go b/internal/runtime/claude_task_updates_test.go new file mode 100644 index 0000000000..d25f62d8a7 --- /dev/null +++ b/internal/runtime/claude_task_updates_test.go @@ -0,0 +1,105 @@ +package runtime + +import ( + "bytes" + "strings" + "testing" +) + +func TestClaudeTaskPartialUpdatesAndResume(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"run1","description":"Initial"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"pending","description":"Waiting for gate"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"paused"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"description":"Resume authorized"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"running"}} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","description":"Working","last_tool_name":"Bash","summary":"Testing the patch"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"failed","error":"provider refused"}} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","description":"STALE progress"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"run1","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"STALE child"}]} +{"type":"system","subtype":"task_notification","task_id":"one","status":"failed","summary":"PRIVATE full result"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + for _, want := range []string{"Waiting for gate — pending", "Waiting for gate — paused", "Resume authorized — paused", "Resume authorized — running", "tool: Bash", "Testing the patch", "failed", "provider refused"} { + if !strings.Contains(out.String(), want) { + t.Errorf("missing %q: %s", want, out.String()) + } + } + for _, bad := range []string{"PRIVATE", "STALE"} { + if strings.Contains(out.String(), bad) { + t.Errorf("unexpected %q", bad) + } + } + // A real new start may reuse a task ID. Missing run IDs inherit only the + // current run, and a second explicit run does not merge the old label. + if err := parseClaudeStream(strings.NewReader(`{"type":"system","subtype":"task_started","task_id":"one","run_id":"run2","description":"Fresh run"}`+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "Fresh run — running") { + t.Fatal("new start was suppressed") + } +} + +func TestClaudeWorkflowAgentDetails(t *testing.T) { + line := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","blocked":true,"error":"schema refused","label":"Create"},{"type":"workflow_agent","index":2,"state":"done","cached":true,"label":"Read","resultPreview":"PRIVATE"},{"type":"workflow_agent","index":3,"state":"paused","label":"Review"}]}` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(line+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + for _, want := range []string{"failed (blocked)", "schema refused", "completed (cached)", "Review — paused"} { + if !strings.Contains(out.String(), want) { + t.Errorf("missing %q: %s", want, out.String()) + } + } + if strings.Contains(out.String(), "PRIVATE") { + t.Fatal("result leaked") + } +} + +func TestClaudeAmbientTasksStayHidden(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"ambient","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"ambient","description":"PRIVATE","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"PRIVATE"}]} +{"type":"system","subtype":"task_updated","task_id":"ambient","patch":{"status":"completed"}} +{"type":"system","subtype":"task_notification","task_id":"ambient","status":"completed"} +{"type":"system","subtype":"task_started","task_id":"skip","skip_transcript":true,"description":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if out.Len() != 0 { + t.Fatalf("ambient tasks leaked: %s", out.String()) + } +} + +func TestClaudeTaskErrorOnlyAndExplicitEmptyLabel(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"one","description":"Old title"} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"description":""}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"error":"Details changed"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"failed"}} +{"type":"system","subtype":"task_updated","task_id":"one","patch":{"error":""}} +{"type":"system","subtype":"task_updated","task_id":"unknown","patch":{"description":"Orphan patch"}} +{"type":"system","subtype":"task_notification","task_id":"orphan","status":"stopped","reason":"worker_restart","summary":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Old title") != 1 || !strings.Contains(out.String(), "Task one — running — Details changed") || !strings.Contains(out.String(), "Task one — failed — Details changed") || !strings.Contains(out.String(), "Task one — failed\n") || !strings.Contains(out.String(), "Orphan patch — updated") || !strings.Contains(out.String(), "worker restarted") { + t.Fatal(out.String()) + } + if strings.Contains(out.String(), "PRIVATE") { + t.Fatal("terminal summary leaked") + } + for _, state := range []string{"pending", "paused"} { + if string(claudeTaskState(state)) != state { + t.Fatalf("state %s missing", state) + } + } +} diff --git a/internal/runtime/claude_workflow_progress_test.go b/internal/runtime/claude_workflow_progress_test.go new file mode 100644 index 0000000000..b2782e7209 --- /dev/null +++ b/internal/runtime/claude_workflow_progress_test.go @@ -0,0 +1,288 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "reflect" + "strings" + "testing" + "unicode/utf8" + + "github.com/fullsend-ai/fullsend/internal/security" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +// Reduced from the Claude 2.1.296 stream attached to #8908. The phase +// inventory is static; the agent transitions and description carry progress. +const claudeWorkflowProgressFixture = `{"type":"system","subtype":"task_started","task_id":"wf-example","run_id":"run-example","task_type":"local_workflow","description":"Strategy pipeline"} +{"type":"system","subtype":"task_progress","task_id":"wf-example","run_id":"run-example","description":"Read: read input","usage":{"total_tokens":0,"tool_uses":0},"workflow_progress":[{"type":"workflow_phase","index":1,"title":"Read"},{"type":"workflow_phase","index":2,"title":"Create"},{"type":"workflow_phase","index":3,"title":"Not reached"},{"type":"workflow_agent","index":1,"agentId":"reader","label":"read input","phaseTitle":"Read","state":"start"}]} +{"type":"system","subtype":"task_progress","task_id":"wf-example","run_id":"run-example","description":"Create: strategy-create","usage":{"total_tokens":14434,"tool_uses":2},"workflow_progress":[{"type":"workflow_phase","index":1,"title":"Read"},{"type":"workflow_phase","index":2,"title":"Create"},{"type":"workflow_phase","index":3,"title":"Not reached"},{"type":"workflow_agent","index":1,"agentId":"reader","label":"read input","phaseTitle":"Read","state":"done","tokens":14434,"toolCalls":2,"durationMs":7194},{"type":"workflow_agent","index":2,"agentId":"creator","label":"strategy-create","phaseTitle":"Create","state":"start","lastToolName":"Bash","lastToolSummary":"python3 create.py"}]} +{"type":"system","subtype":"task_updated","task_id":"wf-example","run_id":"run-example","patch":{"status":"completed"}} +{"type":"system","subtype":"task_notification","task_id":"wf-example","run_id":"run-example","status":"completed","summary":"Strategy pipeline complete"} +` + +func TestClaudeWorkflowProgressConsole(t *testing.T) { + var raw, console bytes.Buffer + metrics := &RunMetrics{} + err := progressParser(io.TeeReader(strings.NewReader(claudeWorkflowProgressFixture), &raw), ui.New(&console), metrics) + if err != nil { + t.Fatal(err) + } + output := console.String() + for _, want := range []string{"wf-example", "Read", "read input", "Create", "strategy-create", "Bash", "completed"} { + if !strings.Contains(output, want) { + t.Errorf("console missing %q: %s", want, output) + } + } + if strings.Contains(output, "Not reached") { + t.Error("predeclared phase must not be rendered as live progress") + } + if raw.String() != claudeWorkflowProgressFixture { + t.Error("raw stream capture changed") + } + if metrics.InputTokens != 0 || metrics.OutputTokens != 0 || metrics.ToolCalls.Load() != 0 || metrics.TotalCostUSD != 0 { + t.Errorf("task progress must not change usage accounting: %+v", metrics) + } +} + +func TestClaudeTaskLifecycle(t *testing.T) { + tests := []struct { + name, line string + want TaskState + }{ + {"start", `{"type":"system","subtype":"task_started","task_id":"one","description":"Pipeline"}`, TaskRunning}, + {"progress without snapshot", `{"type":"system","subtype":"task_progress","task_id":"one","description":"Read: input"}`, TaskRunning}, + {"completed update", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"completed"}}`, TaskCompleted}, + {"failed notification", `{"type":"system","subtype":"task_notification","task_id":"one","status":"failed","summary":"DO NOT PRINT full result"}`, TaskFailed}, + {"stopped update", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"killed"}}`, TaskStopped}, + {"top level status", `{"type":"system","subtype":"task_updated","task_id":"one","status":"running"}`, TaskRunning}, + {"unknown subtype", `{"type":"system","subtype":"future_task_event","task_id":"one","status":"completed"}`, ""}, + {"unknown state", `{"type":"system","subtype":"task_notification","task_id":"one","status":"future-state"}`, ""}, + {"empty id", `{"type":"system","subtype":"task_progress","description":"input"}`, ""}, + {"blank id", `{"type":"system","subtype":"task_started","task_id":" "}`, ""}, + {"invalid id", `{"type":"system","subtype":"task_started","task_id":42}`, ""}, + {"broken patch", `{"type":"system","subtype":"task_updated","task_id":"one","patch":[]}`, ""}, + {"nonstatus patch", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"elapsed":1}}`, ""}, + {"wrong status type", `{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":42}}`, ""}, + {"snapshot only static", `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_phase","index":1,"title":"Not started"}]}`, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var events []AgentEvent + if err := parseClaudeStream(strings.NewReader(tt.line+"\n"), func(e AgentEvent) { events = append(events, e) }); err != nil { + t.Fatal(err) + } + if tt.want == "" { + if len(events) != 0 { + t.Fatalf("unexpected events: %+v", events) + } + return + } + if len(events) != 1 { + t.Fatalf("want one event, got %+v", events) + } + e, ok := events[0].(TaskProgressEvent) + if !ok || e.TaskID != "one" || e.State != tt.want { + t.Fatalf("wrong event: %+v", events[0]) + } + if strings.Contains(e.Label, "DO NOT PRINT") { + t.Fatal("notification result summary must not become progress text") + } + }) + } + if got := decodeClaudeTaskProgress([]byte(`{broken`), "task_progress"); len(got) != 0 { + t.Fatalf("malformed JSON yielded events: %+v", got) + } +} + +func TestClaudeWorkflowProgressToleratesMalformedEntries(t *testing.T) { + line := `{"type":"system","subtype":"task_progress","task_id":"task-one","run_id":"run-one","workflow_progress":[null,42,{"type":"workflow_phase","title":"Not started"},{"type":"workflow_agent","state":"start"},{"type":"workflow_agent","index":4,"state":"future-state"},{"type":"workflow_agent","index":3,"state":"done","label":"first","phaseTitle":"Read","lastToolName":"Read","lastToolSummary":"input.json"},{"type":"workflow_agent","agentId":"child","state":"queued","label":"second"}]}` + got := decodeClaudeTaskProgress([]byte(line), "task_progress") + want := []TaskProgressEvent{ + {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json"}, + {TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "second", State: TaskQueued}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("got %+v, want %+v", got, want) + } + for _, snapshot := range []string{`{}`, `"wrong"`, `null`} { + line := `{"task_id":"one","description":"still running","workflow_progress":` + snapshot + `}` + got := decodeClaudeTaskProgress([]byte(line), "task_progress") + if len(got) != 1 || got[0].Label != "still running" { + t.Errorf("bad optional snapshot must not drop task description: %+v", got) + } + } +} + +func TestClaudeTaskStates(t *testing.T) { + for _, pair := range []struct { + wire string + want TaskState + }{ + {"start", TaskRunning}, {"started", TaskRunning}, {"progress", TaskRunning}, {"running", TaskRunning}, + {"done", TaskCompleted}, {"completed", TaskCompleted}, {"error", TaskFailed}, {"failed", TaskFailed}, + {"killed", TaskStopped}, {"stopped", TaskStopped}, {"cancelled", TaskStopped}, {"canceled", TaskStopped}, + {"queued", TaskQueued}, {"retrying", TaskRetrying}, {"skipped", TaskSkipped}, {"unknown", ""}, + } { + if got := claudeTaskState(pair.wire); got != pair.want { + t.Errorf("%s = %s, want %s", pair.wire, got, pair.want) + } + } +} + +func TestClaudeWorkflowProgressMetricsUnchanged(t *testing.T) { + // Task usage is an aggregate snapshot of overlapping/nested agents, not + // another incremental TokensEvent or ResultEvent to add to the counters. + line := `{"type":"result","num_turns":3,"total_cost_usd":0.25,"usage":{"input_tokens":11,"output_tokens":22,"cache_read_input_tokens":33,"cache_creation_input_tokens":44}}` + "\n" + var metrics RunMetrics + err := parseClaudeStream(strings.NewReader(claudeWorkflowProgressFixture+line+claudeWorkflowProgressFixture), func(e AgentEvent) { + recordClaudeMetrics(&metrics, e) + }) + if err != nil { + t.Fatal(err) + } + if metrics.NumTurns != 3 || metrics.TotalCostUSD != 0.25 || metrics.InputTokens != 11 || + metrics.OutputTokens != 22 || metrics.CacheReadInputTokens != 33 || metrics.CacheCreationInputTokens != 44 || metrics.ToolCalls.Load() != 0 { + t.Fatalf("progress altered authoritative accounting: %+v", &metrics) + } +} + +func TestTaskProgressRendererDeduplicates(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + e := TaskProgressEvent{TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "refine", Phase: "Refine", State: TaskRunning, ToolName: "Read"} + for range 135 { + r.Handle(e) + } + if lines := strings.Count(console.String(), "Task task-one"); lines != 1 { + t.Fatalf("repeated snapshots rendered %d times", lines) + } + e.ToolName = "Bash" + r.Handle(e) + e.State = TaskCompleted + r.Handle(e) + r.Handle(e) + if lines := strings.Count(console.String(), "Task task-one"); lines != 3 { + t.Fatalf("tool/state transitions should render exactly once: %s", console.String()) + } +} + +func TestTaskProgressRendererIdentityAndLifecycle(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "first-run", AgentID: "worker", Label: "review", State: TaskRunning}, + {TaskID: "two", AgentID: "worker", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentID: "different", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentIndex: 1, Label: "review", State: TaskQueued}, + {TaskID: "one", AgentIndex: 2, Label: "review", State: TaskQueued}, + {TaskID: "one", AgentID: "worker", RunID: "another-run", Label: "review", State: TaskRunning}, + {TaskID: "one", State: TaskFailed}, + {TaskID: "two", State: TaskStopped}, + } { + r.Handle(e) + } + if lines := strings.Count(console.String(), "Task "); lines != 8 { + t.Fatalf("concurrent identities/statuses were lost: %s", console.String()) + } + for _, want := range []string{"agent #1", "agent #2", "failed", "stopped"} { + if !strings.Contains(console.String(), want) { + t.Errorf("missing %q: %s", want, console.String()) + } + } + before := console.String() + r.Handle(TaskProgressEvent{State: TaskRunning}) + r.Handle(TaskProgressEvent{TaskID: "one"}) + if console.String() != before { + t.Error("incomplete events must not render") + } +} + +func TestTaskProgressRendererBoundedState(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + for i := range maxTaskProgressEntries + 1 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), State: TaskRunning}) + } + if len(r.taskProgressSeen) > maxTaskProgressEntries { + t.Fatalf("unbounded dedup state: %d", len(r.taskProgressSeen)) + } +} + +func TestTaskProgressRendererRedactsAndSanitizes(t *testing.T) { + const opaque = "opaque-progress-credential-for-test" + security.RegisterRuntimeSecret(opaque) + const token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789ABCD" + var console bytes.Buffer + r := newTestRenderer(&console) + r.Handle(TaskProgressEvent{ + TaskID: "id\n::error::" + opaque, + AgentID: token, Phase: "\x1b[31mCreate\x1b[0m", Label: "hello%0Aworld\r\n::warning::", + State: TaskRunning, ToolName: "Bash", ToolSummary: "token=" + token + " secret=" + opaque, + }) + output := console.String() + for _, forbidden := range []string{opaque, token, "\x1b", "::", "%0A", "\r"} { + if strings.Contains(output, forbidden) { + t.Errorf("unsafe field %q escaped sanitization: %q", forbidden, output) + } + } + if lines := strings.Count(output, "\n"); lines != 1 { + t.Errorf("sandbox text injected extra console lines: %q", output) + } + long := strings.Repeat("界", 200) + got := taskProgressText(long, 80) + if !utf8.ValidString(got) || utf8.RuneCountInString(got) != 81 || !strings.HasSuffix(got, "…") { + t.Errorf("invalid UTF-8 truncation: %q", got) + } + if got := taskProgressText(token, 10); strings.Contains(got, token[:10]) { + t.Errorf("credential was truncated before redaction: %q", got) + } +} + +func TestTaskProgressRendererCIAndBlockBoundary(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var console bytes.Buffer + r := newTestRenderer(&console) + r.Handle(TextEvent{Text: "before"}) + e := TaskProgressEvent{TaskID: "one", Label: "Create\n::error:: injected", State: TaskRunning} + stderr := captureStderr(t, func() { + r.Handle(e) + r.Handle(e) + }) + if strings.Count(stderr, "::notice::") != 1 || strings.Contains(stderr, "::error::") { + t.Errorf("expected one safe CI notice: %q", stderr) + } + if !strings.Contains(console.String(), "before\n") { + t.Errorf("task progress did not close the streaming block: %q", console.String()) + } +} + +func TestTaskProgressRendererCallerRedaction(t *testing.T) { + const secret = "opaque-runner-credential-for-test" + var console bytes.Buffer + r := newTestRenderer(&console) + r.RedactProgress = func(text string) string { + return strings.ReplaceAll(text, secret, "[REDACTED]") + } + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, + Label: secret + strings.Repeat("界", 200), ToolName: "Bash", ToolSummary: secret}) + if strings.Contains(console.String(), secret) || !strings.Contains(console.String(), "[REDACTED]") { + t.Errorf("caller-owned secret escaped redaction: %q", console.String()) + } +} + +func TestTaskProgressDoesNotExposeExtraFields(t *testing.T) { + var console bytes.Buffer + line := `{"type":"system","subtype":"task_progress","task_id":"one","description":"Review","prompt":"PRIVATE PROMPT","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"review","resultPreview":"PRIVATE RESULT","promptPreview":"PRIVATE PROMPT"}]}` + if !json.Valid([]byte(line)) { + t.Fatal("invalid test fixture") + } + if err := progressParser(strings.NewReader(line), ui.New(&console), &RunMetrics{}); err != nil { + t.Fatal(err) + } + if strings.Contains(console.String(), "PRIVATE") { + t.Errorf("prompt/result content reached progress display: %s", console.String()) + } +} diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index b22f011101..37a735a1d2 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -1,6 +1,7 @@ package runtime import ( + "crypto/sha256" "fmt" "os" @@ -12,11 +13,19 @@ import ( // It tracks block state (text/thinking) so transitions between event // types produce clean output boundaries. type EventRenderer struct { - printer *ui.Printer - isCI bool - inText bool - inThinking bool - seenInit bool + // RedactProgress removes caller-owned credential literals from progress + // metadata before normalization/truncation. Pattern and registered + // runtime-secret redaction apply even when this callback is nil. + RedactProgress func(string) string + + printer *ui.Printer + isCI bool + inText bool + inThinking bool + seenInit bool + taskProgressSeen map[taskProgressKey]taskProgressDisplay + taskProgressRuns map[[sha256.Size]byte][sha256.Size]byte + statusProgressSeen map[[sha256.Size]byte]string } // NewEventRenderer creates a renderer that writes to the given printer. @@ -34,6 +43,10 @@ var ( // Handle dispatches a single AgentEvent to the appropriate rendering method. func (r *EventRenderer) Handle(evt AgentEvent) { switch e := evt.(type) { + case StatusProgressEvent: + r.statusProgress(e) + case TaskProgressEvent: + r.taskProgress(e) case InitEvent: if r.seenInit { return diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go new file mode 100644 index 0000000000..70a42e9916 --- /dev/null +++ b/internal/runtime/status_progress.go @@ -0,0 +1,72 @@ +package runtime + +import ( + "crypto/sha256" + "fmt" + "os" +) + +// StatusProgressEvent is advisory runtime display metadata. It carries no +// tool output, prompts, result bodies, or authoritative run/usage outcomes. +type StatusProgressEvent struct { + Kind string + ID string + Label string + State string + Detail string + // Clear resets the row silently. Recovery is displayed only after a + // prior status, avoiding a routine initial "allowed" rate-limit message. + Clear bool + Recovery bool + // Occurrence is an unkeyed one-off message, not a state snapshot. + Occurrence bool +} + +func (StatusProgressEvent) agentEvent() {} + +func (r *EventRenderer) statusProgress(e StatusProgressEvent) { + if e.Kind == "" { + return + } + key := sha256.Sum256([]byte(e.Kind + "\x00" + e.ID)) + previous := r.statusProgressSeen[key] + if e.Clear { + delete(r.statusProgressSeen, key) + return + } + if e.Recovery && previous == "" { + return + } + msg := r.progressText(e.Label, 120) + if msg == "" { + return + } + if state := r.progressText(e.State, 60); state != "" { + msg += " — " + state + } + if detail := r.progressText(e.Detail, 240); detail != "" { + msg += ": " + detail + } + msg = sanitizeOutput(msg) + if !e.Occurrence && previous == msg { + return + } + if !e.Occurrence { + if r.statusProgressSeen == nil { + r.statusProgressSeen = make(map[[sha256.Size]byte]string) + } + if len(r.statusProgressSeen) >= maxTaskProgressEntries { + clear(r.statusProgressSeen) + } + r.statusProgressSeen[key] = msg + } + r.printProgress(msg) +} + +func (r *EventRenderer) printProgress(msg string) { + r.endBlock() + if r.isCI { + fmt.Fprintf(os.Stderr, "::notice::%s\n", msg) + } + r.printer.ToolProgress(msg) +} diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go new file mode 100644 index 0000000000..ad4dda15a9 --- /dev/null +++ b/internal/runtime/task_progress.go @@ -0,0 +1,249 @@ +package runtime + +import ( + "crypto/sha256" + "fmt" + "strings" + "unicode/utf8" +) + +// TaskState describes task/agent progress, not validated business completion. +type TaskState string + +const ( + TaskPending TaskState = "pending" + TaskPaused TaskState = "paused" + TaskRunning TaskState = "running" + TaskCompleted TaskState = "completed" + TaskFailed TaskState = "failed" + TaskStopped TaskState = "stopped" + TaskQueued TaskState = "queued" + TaskRetrying TaskState = "retrying" + TaskSkipped TaskState = "skipped" +) + +// TaskProgressEvent carries live background task or Workflow agent metadata. +// An empty AgentID and zero AgentIndex describe the task itself. Phase is +// agent attribution, never an inventory of declared phases. Progress does not +// update token/cost accounting and carries no prompts or tool result bodies. +type TaskProgressEvent struct { + TaskID string + RunID string + AgentID string + AgentIndex int + Label string + Phase string + State TaskState + ToolName string + ToolSummary string + Summary string + Detail string + Blocked bool + Cached bool + // Update carries a partial lifecycle patch. Missing fields retain their + // sanitized display values. LabelSet/DetailSet permit explicit empty fields. + Update bool + LabelSet bool + DetailSet bool + Started bool + Hidden bool +} + +func (TaskProgressEvent) agentEvent() {} + +// Bound retained display state even if a runtime sends unlimited identities. +// Hashing IDs also avoids retaining arbitrarily large sandbox strings as keys. +const maxTaskProgressEntries = 1024 + +type taskProgressKey struct { + task, run, agent [sha256.Size]byte + index int +} + +type taskProgressDisplay struct { + event TaskProgressEvent + message string +} + +func (r *EventRenderer) taskProgress(e TaskProgressEvent) { + if e.TaskID == "" || (e.State == "" && !e.Update) { + return + } + key := r.taskProgressIdentity(&e) + taskHash := key.task + runHash := key.run + previous := r.taskProgressSeen[key] + parentKey := taskProgressKey{task: taskHash, run: runHash, agent: sha256.Sum256(nil)} + parent := r.taskProgressSeen[parentKey].event + if !e.Started && (parent.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || terminalTaskState(previous.event.State)))) { + return + } + // Sanitize before retaining metadata, not just before printing it. This + // cache contains bounded display fields and hashed raw identities only. + e.TaskID = r.progressText(e.TaskID, 80) + e.RunID = r.progressText(e.RunID, 80) + e.AgentID = r.progressText(e.AgentID, 80) + e.Label = r.progressText(e.Label, 160) + e.Phase = r.progressText(e.Phase, 80) + e.ToolName = r.progressText(e.ToolName, 50) + e.ToolSummary = r.progressText(e.ToolSummary, 160) + e.Summary = r.progressText(e.Summary, 200) + e.Detail = r.progressText(e.Detail, 200) + e.State = TaskState(r.progressText(string(e.State), 40)) + if !e.Started { + old := previous.event + if e.Label == "" && !e.LabelSet { + e.Label = old.Label + } + if e.State == "" { + e.State = old.State + } + if e.Update { + e.ToolName = old.ToolName + e.ToolSummary = old.ToolSummary + e.Summary = old.Summary + if !e.DetailSet { + e.Detail = old.Detail + } + } + if e.RunID == "" { + e.RunID = old.RunID + } + } + if e.State != "" && e.State != TaskRunning { + e.Summary = "" + } + if len(r.taskProgressSeen) >= maxTaskProgressEntries { + clear(r.taskProgressSeen) + clear(r.taskProgressRuns) + } + if _, exists := r.taskProgressRuns[taskHash]; !exists { + r.taskProgressRuns[taskHash] = runHash + } + if e.Hidden { + r.taskProgressSeen[parentKey] = taskProgressDisplay{event: e} + return + } + msg := "Task " + e.TaskID + if e.AgentID != "" { + msg += " / agent " + e.AgentID + } else if e.AgentIndex > 0 { + msg += fmt.Sprintf(" / agent #%d", e.AgentIndex) + } + if e.Phase != "" { + msg += " [" + e.Phase + "]" + } + if e.Label != "" { + msg += ": " + e.Label + } + if e.State != "" { + msg += " — " + string(e.State) + } else { + msg += " — updated" + } + if e.Blocked { + msg += " (blocked)" + } + if e.Cached { + msg += " (cached)" + } + if e.ToolName != "" { + msg += " (tool: " + e.ToolName + if e.ToolSummary != "" { + msg += ": " + e.ToolSummary + } + msg += ")" + } + if e.Summary != "" { + msg += " — " + e.Summary + } + if e.Detail != "" { + msg += " — " + e.Detail + } + msg = sanitizeOutput(msg) + r.taskProgressSeen[key] = taskProgressDisplay{event: e, message: msg} + if previous.message == msg { + return + } + r.printProgress(msg) +} + +// Resolve optional run IDs without splitting a task when its first run ID +// arrives late. An explicit new start resets its run's agent rows too. Known +// older runs remain addressable, but cannot steal later run-less updates. +func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressKey { + if r.taskProgressSeen == nil { + r.taskProgressSeen = make(map[taskProgressKey]taskProgressDisplay) + r.taskProgressRuns = make(map[[sha256.Size]byte][sha256.Size]byte) + } + task := sha256.Sum256([]byte(e.TaskID)) + run := r.taskProgressRuns[task] + zero := [sha256.Size]byte{} + if e.RunID != "" { + run = sha256.Sum256([]byte(e.RunID)) + } + if e.Started { + if e.RunID == "" { + run = zero + } + for key := range r.taskProgressSeen { + if key.task == task && key.run == run { + delete(r.taskProgressSeen, key) + } + } + r.taskProgressRuns[task] = run + } else if e.RunID != "" { + current := r.taskProgressRuns[task] + if current != run { + known := false + for key := range r.taskProgressSeen { + if key.task == task && key.run == run { + known = true + break + } + } + if !known { + if current == zero { + // Keep old named runs when an anonymous restart is active. Only a + // genuinely unseen run may adopt the anonymous generation's rows. + for key, display := range r.taskProgressSeen { + if key.task == task && key.run == zero { + delete(r.taskProgressSeen, key) + key.run = run + r.taskProgressSeen[key] = display + } + } + } else { + parent := taskProgressKey{task: task, run: current, agent: sha256.Sum256(nil)} + e.Hidden = r.taskProgressSeen[parent].event.Hidden + } + r.taskProgressRuns[task] = run + } + } + } + return taskProgressKey{task: task, run: run, agent: sha256.Sum256([]byte(e.AgentID)), index: e.AgentIndex} +} + +func terminalTaskState(state TaskState) bool { + return state == TaskCompleted || state == TaskFailed || state == TaskStopped || state == TaskSkipped +} + +func (r *EventRenderer) progressText(s string, limit int) string { + if r.RedactProgress != nil { + s = r.RedactProgress(s) + } + return taskProgressText(s, limit) +} + +// Sanitize and redact complete fields before truncation, so an escape, CI +// command, or credential cannot be exposed by chopping off its suffix first. +func taskProgressText(s string, limit int) string { + s = strings.Join(strings.Fields(sanitizeOutput(s)), " ") + if result := progressRedactor.Scan(s); !result.Safe { + s = result.Sanitized + } + if utf8.RuneCountInString(s) > limit { + s = string([]rune(s)[:limit]) + "…" + } + return s +} From 498385e31b6abe40f5eae58d932da8c1151dd8a9 Mon Sep 17 00:00:00 2001 From: jctanner Date: Thu, 29 Oct 2026 15:49:48 -0400 Subject: [PATCH 02/16] fix(#8908): preserve sparse progress metadata Retain hook attribution and workflow agent context when snapshots omit optional fields, while allowing explicit empty and false values to clear metadata. Reset omitted transient flags on state changes, scope visibility to each run, and keep hidden agent records separate from parent task state. Centralize event definitions and shared rendering helpers, document the snapshot contract, and separate wire tests from generic renderer tests. Generate the synthetic redaction fixture instead of storing its token shape. Signed-off-by: jctanner --- docs/cli/run.md | 9 +- internal/runtime/claude_pr_review_test.go | 112 +++++++++++++ .../runtime/claude_progress_review_test.go | 10 -- internal/runtime/claude_status_progress.go | 23 +-- .../runtime/claude_status_progress_test.go | 29 ---- internal/runtime/claude_task_progress.go | 58 +++++-- .../runtime/claude_workflow_progress_test.go | 131 +--------------- internal/runtime/event.go | 81 ++++++++++ internal/runtime/event_test.go | 7 +- internal/runtime/renderer.go | 10 +- internal/runtime/status_progress.go | 56 +++---- internal/runtime/status_progress_test.go | 69 ++++++++ internal/runtime/task_progress.go | 81 ++++------ internal/runtime/task_progress_test.go | 147 ++++++++++++++++++ 14 files changed, 543 insertions(+), 280 deletions(-) create mode 100644 internal/runtime/claude_pr_review_test.go create mode 100644 internal/runtime/status_progress_test.go create mode 100644 internal/runtime/task_progress_test.go diff --git a/docs/cli/run.md b/docs/cli/run.md index afdcd0b96f..7ed265ede3 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -128,7 +128,14 @@ line. Text is sanitized, credential-redacted, and bounded before display or retention in the bounded display cache. Concurrent tasks and agents retain separate identities. Partial lifecycle patches retain known task labels and state; explicit starts can reset an identity. Late running snapshots do not -reopen a known terminal task or agent. +reopen a known terminal task or agent. Sparse agent snapshots retain known +labels, phases and tool context. Error, blocked and cached metadata persists +within a state; state changes clear omitted transient metadata. Explicit +empty strings and false flags also clear their corresponding fields. +Visibility belongs to each run: promoting its first late run ID preserves +its hidden classification, while a distinct named run does not inherit an +older run's visibility. Hook names and event attribution survive sparse +progress/completion messages for the same hook ID. The display handles these structured Claude events when the runtime emits them. Task progress shapes were checked against Claude Code 2.1.296 capture diff --git a/internal/runtime/claude_pr_review_test.go b/internal/runtime/claude_pr_review_test.go new file mode 100644 index 0000000000..1acc464f5b --- /dev/null +++ b/internal/runtime/claude_pr_review_test.go @@ -0,0 +1,112 @@ +package runtime + +import ( + "bytes" + "strings" + "testing" +) + +func TestClaudeReviewHookCompletionRetainsIdentity(t *testing.T) { + stream := `{"type":"system","subtype":"hook_started","hook_id":"guard-1","hook_name":"guard","hook_event":"PreToolUse"} +{"type":"system","subtype":"hook_progress","hook_id":"guard-1","stdout":"PRIVATE"} +{"type":"system","subtype":"hook_response","hook_id":"guard-1","outcome":"success","exit_code":0,"output":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Hook guard [PreToolUse]") != 2 || strings.Count(out.String(), "running") != 1 || !strings.Contains(out.String(), "Hook guard [PreToolUse] — completed: exit 0") || strings.Contains(out.String(), "PRIVATE") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewAgentCounterSnapshotRetainsContext(t *testing.T) { + detailed := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","label":"Create","phaseTitle":"Build","lastToolName":"Bash","lastToolSummary":"run checks","error":"access refused","blocked":true,"cached":true}]}` + "\n" + sparse := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","tokens":20,"toolCalls":3}]}` + "\n" + clear := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","label":"","phaseTitle":"","lastToolName":"","lastToolSummary":"","error":"","blocked":false,"cached":false}]}` + "\n" + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(detailed+sparse), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Task one") != 1 { + t.Fatal("counter update erased context: " + out.String()) + } + for _, want := range []string{"[Build]", "Create", "Bash: run checks", "access refused", "(blocked)", "(cached)"} { + if !strings.Contains(out.String(), want) { + t.Fatalf("missing %s: %s", want, out.String()) + } + } + if err := parseClaudeStream(strings.NewReader(clear+sparse), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Task one") != 2 || !strings.HasSuffix(out.String(), "Task one / agent #1 — failed\n") { + t.Fatal("explicit clears not retained: " + out.String()) + } +} + +func TestClaudeReviewDistinctRunDoesNotInheritHiddenParent(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"old","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"new","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"New worker"}]} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"new","description":"Visible new run"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"old","description":"PRIVATE"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "New worker — completed") || !strings.Contains(out.String(), "Visible new run — running") || strings.Contains(out.String(), "PRIVATE") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewAgentToolChangeDoesNotKeepOldSummary(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","lastToolName":"Bash","lastToolSummary":"OLD COMMAND"}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"progress","lastToolName":"Read"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "(tool: Read)") || strings.Contains(out.String(), "Read: OLD COMMAND") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewHookIdentityExplicitClear(t *testing.T) { + stream := `{"type":"system","subtype":"hook_started","hook_id":"one","hook_name":"guard","hook_event":"PreToolUse"} +{"type":"system","subtype":"hook_progress","hook_id":"one","hook_name":"","hook_event":""} +{"type":"system","subtype":"hook_response","hook_id":"one","hook_name":null,"hook_event":null,"outcome":"success"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "guard") != 1 || !strings.HasSuffix(out.String(), "Hook — completed\n") { + t.Fatal(out.String()) + } +} + +func TestClaudeReviewAgentRecoveryClearsTransientMetadata(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"retrying","label":"Create","error":"rate limited","blocked":true,"cached":true}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"Create","lastToolName":"Bash"}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"Create"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + for _, transient := range []string{"(blocked)", "(cached)", "rate limited"} { + if strings.Count(out.String(), transient) != 1 { + t.Fatalf("%s survived recovery: %s", transient, out.String()) + } + } + if !strings.Contains(out.String(), "Create — running (tool: Bash)") || !strings.Contains(out.String(), "Create — completed (tool: Bash)") { + t.Fatal(out.String()) + } +} diff --git a/internal/runtime/claude_progress_review_test.go b/internal/runtime/claude_progress_review_test.go index f35d5b14d8..7010c02de6 100644 --- a/internal/runtime/claude_progress_review_test.go +++ b/internal/runtime/claude_progress_review_test.go @@ -153,16 +153,6 @@ func TestWorkflowReviewNewStartResetsAgents(t *testing.T) { } } -func TestWorkflowReviewJoiningFieldsCannotRecreateCommands(t *testing.T) { - var out bytes.Buffer - r := newTestRenderer(&out) - r.Handle(TaskProgressEvent{TaskID: "task:", Label: "label", State: TaskRunning}) - r.Handle(StatusProgressEvent{Kind: "warning", Label: "warning:", Detail: "detail"}) - if strings.Contains(out.String(), "::") { - t.Fatal("field joins recreated command delimiter: " + out.String()) - } -} - func TestWorkflowReviewRestartWithoutRunIDKeepsOldRunHistory(t *testing.T) { var out bytes.Buffer r := newTestRenderer(&out) diff --git a/internal/runtime/claude_status_progress.go b/internal/runtime/claude_status_progress.go index 32558be2d2..6e48a1296b 100644 --- a/internal/runtime/claude_status_progress.go +++ b/internal/runtime/claude_status_progress.go @@ -7,7 +7,7 @@ import ( "time" ) -// This is an explicit display allowlist, not a generic JSON dump. In +// decodeClaudeStatusProgress applies an explicit display allowlist. In // particular hook stdout/stderr/output, prompts, terminal summaries, and // arbitrary future payloads must stay out of console/CI annotations. func decodeClaudeStatusProgress(line []byte, subtype string) (StatusProgressEvent, bool) { @@ -15,11 +15,11 @@ func decodeClaudeStatusProgress(line []byte, subtype string) (StatusProgressEven switch subtype { case "hook_started", "hook_progress", "hook_response": var wire struct { - HookID string `json:"hook_id"` - HookName string `json:"hook_name"` - HookEvent string `json:"hook_event"` - Outcome string `json:"outcome"` - ExitCode *int `json:"exit_code"` + HookID string `json:"hook_id"` + HookName *string `json:"hook_name"` + HookEvent *string `json:"hook_event"` + Outcome string `json:"outcome"` + ExitCode *int `json:"exit_code"` } if json.Unmarshal(line, &wire) != nil { return e, false @@ -30,9 +30,14 @@ func decodeClaudeStatusProgress(line []byte, subtype string) (StatusProgressEven } e.Kind = "hook" e.ID = wire.HookID - e.Label = "Hook " + wire.HookName - if wire.HookEvent != "" { - e.Label += " [" + wire.HookEvent + "]" + e.Label = "Hook" + if wire.HookName != nil { + e.Subject = *wire.HookName + e.SubjectSet = true + } + if wire.HookEvent != nil { + e.Context = *wire.HookEvent + e.ContextSet = true } e.State = "running" if subtype == "hook_response" { diff --git a/internal/runtime/claude_status_progress_test.go b/internal/runtime/claude_status_progress_test.go index deea6afb5d..e3a8d74c1c 100644 --- a/internal/runtime/claude_status_progress_test.go +++ b/internal/runtime/claude_status_progress_test.go @@ -2,7 +2,6 @@ package runtime import ( "bytes" - "fmt" "io" "strings" "testing" @@ -124,31 +123,3 @@ func TestClaudeStatusTransitionsAndDedup(t *testing.T) { t.Fatal("advisories altered metrics") } } - -func TestStatusProgressRendererSafetyAndBounds(t *testing.T) { - t.Setenv("GITHUB_ACTIONS", "true") - var out bytes.Buffer - r := newTestRenderer(&out) - const secret = "opaque-status-secret-for-test" - r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, secret, "[REDACTED]") } - e := StatusProgressEvent{Kind: "notification", ID: "one", Label: secret + "\n::error::", State: "\x1b[31mwarning\x1b[0m", Detail: secret + strings.Repeat("界", 500)} - stderr := captureStderr(t, func() { r.Handle(TextEvent{Text: "before"}); r.Handle(e); r.Handle(e) }) - if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Contains(out.String(), "\x1b") { - t.Fatal("unsafe status display") - } - if strings.Count(stderr, "::notice::") != 1 || !strings.Contains(out.String(), "before\n") { - t.Fatal("bad CI/block boundary") - } - if len([]rune(out.String())) > 500 { - t.Fatal("unbounded status") - } - r.Handle(StatusProgressEvent{}) - r.Handle(StatusProgressEvent{Kind: "empty"}) - r.isCI = false - for i := range maxTaskProgressEntries + 1 { - r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row"}) - } - if len(r.statusProgressSeen) > maxTaskProgressEntries { - t.Fatal("unbounded status cache") - } -} diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go index 9c1b6871c6..b242b13f9a 100644 --- a/internal/runtime/claude_task_progress.go +++ b/internal/runtime/claude_task_progress.go @@ -22,17 +22,17 @@ type claudeTaskProgress struct { } type claudeWorkflowAgentProgress struct { - Type string `json:"type"` - Index int `json:"index"` - AgentID string `json:"agentId"` - Label string `json:"label"` - PhaseTitle string `json:"phaseTitle"` - State string `json:"state"` - LastToolName string `json:"lastToolName"` - LastToolSummary string `json:"lastToolSummary"` - Error string `json:"error"` - Blocked bool `json:"blocked"` - Cached bool `json:"cached"` + Type string `json:"type"` + Index int `json:"index"` + AgentID string `json:"agentId"` + Label *string `json:"label"` + PhaseTitle *string `json:"phaseTitle"` + State string `json:"state"` + LastToolName *string `json:"lastToolName"` + LastToolSummary *string `json:"lastToolSummary"` + Error *string `json:"error"` + Blocked *bool `json:"blocked"` + Cached *bool `json:"cached"` } func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { @@ -106,12 +106,36 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { if state == "" { continue } - events = append(events, TaskProgressEvent{ - TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, - Label: agent.Label, Phase: agent.PhaseTitle, State: state, - ToolName: agent.LastToolName, ToolSummary: agent.LastToolSummary, - Detail: agent.Error, Blocked: agent.Blocked, Cached: agent.Cached, - }) + event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, State: state} + if agent.Label != nil { + event.Label = *agent.Label + event.LabelSet = true + } + if agent.PhaseTitle != nil { + event.Phase = *agent.PhaseTitle + event.PhaseSet = true + } + if agent.LastToolName != nil { + event.ToolName = *agent.LastToolName + event.ToolNameSet = true + } + if agent.LastToolSummary != nil { + event.ToolSummary = *agent.LastToolSummary + event.ToolSummarySet = true + } + if agent.Error != nil { + event.Detail = *agent.Error + event.DetailSet = true + } + if agent.Blocked != nil { + event.Blocked = *agent.Blocked + event.BlockedSet = true + } + if agent.Cached != nil { + event.Cached = *agent.Cached + event.CachedSet = true + } + events = append(events, event) } return events } diff --git a/internal/runtime/claude_workflow_progress_test.go b/internal/runtime/claude_workflow_progress_test.go index b2782e7209..5c4647043e 100644 --- a/internal/runtime/claude_workflow_progress_test.go +++ b/internal/runtime/claude_workflow_progress_test.go @@ -3,14 +3,11 @@ package runtime import ( "bytes" "encoding/json" - "fmt" "io" "reflect" "strings" "testing" - "unicode/utf8" - "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -101,8 +98,8 @@ func TestClaudeWorkflowProgressToleratesMalformedEntries(t *testing.T) { line := `{"type":"system","subtype":"task_progress","task_id":"task-one","run_id":"run-one","workflow_progress":[null,42,{"type":"workflow_phase","title":"Not started"},{"type":"workflow_agent","state":"start"},{"type":"workflow_agent","index":4,"state":"future-state"},{"type":"workflow_agent","index":3,"state":"done","label":"first","phaseTitle":"Read","lastToolName":"Read","lastToolSummary":"input.json"},{"type":"workflow_agent","agentId":"child","state":"queued","label":"second"}]}` got := decodeClaudeTaskProgress([]byte(line), "task_progress") want := []TaskProgressEvent{ - {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json"}, - {TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "second", State: TaskQueued}, + {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json", LabelSet: true, PhaseSet: true, ToolNameSet: true, ToolSummarySet: true}, + {TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "second", State: TaskQueued, LabelSet: true}, } if !reflect.DeepEqual(got, want) { t.Fatalf("got %+v, want %+v", got, want) @@ -149,130 +146,6 @@ func TestClaudeWorkflowProgressMetricsUnchanged(t *testing.T) { } } -func TestTaskProgressRendererDeduplicates(t *testing.T) { - var console bytes.Buffer - r := newTestRenderer(&console) - e := TaskProgressEvent{TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "refine", Phase: "Refine", State: TaskRunning, ToolName: "Read"} - for range 135 { - r.Handle(e) - } - if lines := strings.Count(console.String(), "Task task-one"); lines != 1 { - t.Fatalf("repeated snapshots rendered %d times", lines) - } - e.ToolName = "Bash" - r.Handle(e) - e.State = TaskCompleted - r.Handle(e) - r.Handle(e) - if lines := strings.Count(console.String(), "Task task-one"); lines != 3 { - t.Fatalf("tool/state transitions should render exactly once: %s", console.String()) - } -} - -func TestTaskProgressRendererIdentityAndLifecycle(t *testing.T) { - var console bytes.Buffer - r := newTestRenderer(&console) - for _, e := range []TaskProgressEvent{ - {TaskID: "one", RunID: "first-run", AgentID: "worker", Label: "review", State: TaskRunning}, - {TaskID: "two", AgentID: "worker", Label: "review", State: TaskRunning}, - {TaskID: "one", AgentID: "different", Label: "review", State: TaskRunning}, - {TaskID: "one", AgentIndex: 1, Label: "review", State: TaskQueued}, - {TaskID: "one", AgentIndex: 2, Label: "review", State: TaskQueued}, - {TaskID: "one", AgentID: "worker", RunID: "another-run", Label: "review", State: TaskRunning}, - {TaskID: "one", State: TaskFailed}, - {TaskID: "two", State: TaskStopped}, - } { - r.Handle(e) - } - if lines := strings.Count(console.String(), "Task "); lines != 8 { - t.Fatalf("concurrent identities/statuses were lost: %s", console.String()) - } - for _, want := range []string{"agent #1", "agent #2", "failed", "stopped"} { - if !strings.Contains(console.String(), want) { - t.Errorf("missing %q: %s", want, console.String()) - } - } - before := console.String() - r.Handle(TaskProgressEvent{State: TaskRunning}) - r.Handle(TaskProgressEvent{TaskID: "one"}) - if console.String() != before { - t.Error("incomplete events must not render") - } -} - -func TestTaskProgressRendererBoundedState(t *testing.T) { - var console bytes.Buffer - r := newTestRenderer(&console) - for i := range maxTaskProgressEntries + 1 { - r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), State: TaskRunning}) - } - if len(r.taskProgressSeen) > maxTaskProgressEntries { - t.Fatalf("unbounded dedup state: %d", len(r.taskProgressSeen)) - } -} - -func TestTaskProgressRendererRedactsAndSanitizes(t *testing.T) { - const opaque = "opaque-progress-credential-for-test" - security.RegisterRuntimeSecret(opaque) - const token = "ghp_abcdefghijklmnopqrstuvwxyz0123456789ABCD" - var console bytes.Buffer - r := newTestRenderer(&console) - r.Handle(TaskProgressEvent{ - TaskID: "id\n::error::" + opaque, - AgentID: token, Phase: "\x1b[31mCreate\x1b[0m", Label: "hello%0Aworld\r\n::warning::", - State: TaskRunning, ToolName: "Bash", ToolSummary: "token=" + token + " secret=" + opaque, - }) - output := console.String() - for _, forbidden := range []string{opaque, token, "\x1b", "::", "%0A", "\r"} { - if strings.Contains(output, forbidden) { - t.Errorf("unsafe field %q escaped sanitization: %q", forbidden, output) - } - } - if lines := strings.Count(output, "\n"); lines != 1 { - t.Errorf("sandbox text injected extra console lines: %q", output) - } - long := strings.Repeat("界", 200) - got := taskProgressText(long, 80) - if !utf8.ValidString(got) || utf8.RuneCountInString(got) != 81 || !strings.HasSuffix(got, "…") { - t.Errorf("invalid UTF-8 truncation: %q", got) - } - if got := taskProgressText(token, 10); strings.Contains(got, token[:10]) { - t.Errorf("credential was truncated before redaction: %q", got) - } -} - -func TestTaskProgressRendererCIAndBlockBoundary(t *testing.T) { - t.Setenv("GITHUB_ACTIONS", "true") - var console bytes.Buffer - r := newTestRenderer(&console) - r.Handle(TextEvent{Text: "before"}) - e := TaskProgressEvent{TaskID: "one", Label: "Create\n::error:: injected", State: TaskRunning} - stderr := captureStderr(t, func() { - r.Handle(e) - r.Handle(e) - }) - if strings.Count(stderr, "::notice::") != 1 || strings.Contains(stderr, "::error::") { - t.Errorf("expected one safe CI notice: %q", stderr) - } - if !strings.Contains(console.String(), "before\n") { - t.Errorf("task progress did not close the streaming block: %q", console.String()) - } -} - -func TestTaskProgressRendererCallerRedaction(t *testing.T) { - const secret = "opaque-runner-credential-for-test" - var console bytes.Buffer - r := newTestRenderer(&console) - r.RedactProgress = func(text string) string { - return strings.ReplaceAll(text, secret, "[REDACTED]") - } - r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, - Label: secret + strings.Repeat("界", 200), ToolName: "Bash", ToolSummary: secret}) - if strings.Contains(console.String(), secret) || !strings.Contains(console.String(), "[REDACTED]") { - t.Errorf("caller-owned secret escaped redaction: %q", console.String()) - } -} - func TestTaskProgressDoesNotExposeExtraFields(t *testing.T) { var console bytes.Buffer line := `{"type":"system","subtype":"task_progress","task_id":"one","description":"Review","prompt":"PRIVATE PROMPT","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"review","resultPreview":"PRIVATE RESULT","promptPreview":"PRIVATE PROMPT"}]}` diff --git a/internal/runtime/event.go b/internal/runtime/event.go index c3f2158646..4c3d1e465c 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -160,3 +160,84 @@ type PluginErrorEvent struct { } func (PluginErrorEvent) agentEvent() {} + +// TaskState describes task/agent progress, not validated business completion. +type TaskState string + +const ( + TaskPending TaskState = "pending" + TaskPaused TaskState = "paused" + TaskRunning TaskState = "running" + TaskCompleted TaskState = "completed" + TaskFailed TaskState = "failed" + TaskStopped TaskState = "stopped" + TaskQueued TaskState = "queued" + TaskRetrying TaskState = "retrying" + TaskSkipped TaskState = "skipped" +) + +// TaskProgressEvent carries live background task or Workflow agent metadata. +// An empty AgentID and zero AgentIndex describe the task itself. Phase is +// agent attribution, never an inventory of declared phases. Progress does not +// update token/cost accounting and carries no prompts or tool result bodies. +// Consumers receive repeated snapshots and partial patches, not reconciled +// transitions. EventRenderer merges and deduplicates after caller-specific +// credential redaction; custom OnEvent consumers must reconcile their own +// state. Nonempty values are supplied values; the Set flags distinguish an +// explicitly empty string/false flag from absent optional metadata. Agent +// error/blocked/cached fields are state-relative: omitted values survive +// repeated snapshots of the same state, but not a state transition. +type TaskProgressEvent struct { + TaskID string + RunID string + AgentID string + AgentIndex int + Label string + Phase string + State TaskState + ToolName string + ToolSummary string + Summary string + Detail string + Blocked bool + Cached bool + // Update is a task lifecycle patch; it retains prior tool context. + // LabelSet/DetailSet apply to task and agent metadata; Phase/Tool/Blocked/ + // Cached Set flags apply only to agent snapshots. Started is task-level. + Update bool + LabelSet bool + DetailSet bool + PhaseSet bool + ToolNameSet bool + ToolSummarySet bool + BlockedSet bool + CachedSet bool + Started bool + Hidden bool +} + +func (TaskProgressEvent) agentEvent() {} + +// StatusProgressEvent is advisory runtime display metadata. It carries no +// tool output, prompts, result bodies, or authoritative run/usage outcomes. +type StatusProgressEvent struct { + Kind string + ID string + Label string + State string + Detail string + // Subject/Context attribute a status, such as a hook name and event. + // Set flags permit clearing; omitted fields retain sanitized prior values. + Subject string + Context string + SubjectSet bool + ContextSet bool + // Clear resets the row silently. Recovery is displayed only after a + // prior status, avoiding a routine initial "allowed" rate-limit message. + Clear bool + Recovery bool + // Occurrence is an unkeyed one-off message, not a state snapshot. + Occurrence bool +} + +func (StatusProgressEvent) agentEvent() {} diff --git a/internal/runtime/event_test.go b/internal/runtime/event_test.go index 42ff2afb81..4535089603 100644 --- a/internal/runtime/event_test.go +++ b/internal/runtime/event_test.go @@ -6,6 +6,9 @@ func TestAgentEventInterfaceSatisfied(t *testing.T) { // Compile-time verification that all concrete types satisfy AgentEvent. var events []AgentEvent events = append(events, + TaskProgressEvent{TaskID: "task", State: TaskRunning}, + StatusProgressEvent{Kind: "hook", Label: "Hook"}, + ModelFallbackEvent{From: "old", To: "new"}, InitEvent{Model: "claude-opus-4-6", Version: "1.0.0"}, ThinkingEvent{Text: "thinking..."}, TextEvent{Text: "hello"}, @@ -17,7 +20,7 @@ func TestAgentEventInterfaceSatisfied(t *testing.T) { ToolResultEvent{ID: "toolu_01abc", Result: "file contents"}, PluginErrorEvent{Plugin: "demo@inline", Type: "path-not-found", Path: "/plugins/demo", Message: "not found"}, ) - if len(events) != 10 { - t.Errorf("expected 10 event types, got %d", len(events)) + if len(events) != 13 { + t.Errorf("expected 13 event types, got %d", len(events)) } } diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index 37a735a1d2..b0a491be13 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -25,7 +25,7 @@ type EventRenderer struct { seenInit bool taskProgressSeen map[taskProgressKey]taskProgressDisplay taskProgressRuns map[[sha256.Size]byte][sha256.Size]byte - statusProgressSeen map[[sha256.Size]byte]string + statusProgressSeen map[[sha256.Size]byte]statusProgressDisplay } // NewEventRenderer creates a renderer that writes to the given printer. @@ -178,3 +178,11 @@ func (r *EventRenderer) endBlock() { r.inThinking = false } } + +func (r *EventRenderer) printProgress(msg string) { + r.endBlock() + if r.isCI { + fmt.Fprintf(os.Stderr, "::notice::%s\n", msg) + } + r.printer.ToolProgress(msg) +} diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go index 70a42e9916..ecd79c93bc 100644 --- a/internal/runtime/status_progress.go +++ b/internal/runtime/status_progress.go @@ -1,29 +1,13 @@ package runtime -import ( - "crypto/sha256" - "fmt" - "os" -) +import "crypto/sha256" -// StatusProgressEvent is advisory runtime display metadata. It carries no -// tool output, prompts, result bodies, or authoritative run/usage outcomes. -type StatusProgressEvent struct { - Kind string - ID string - Label string - State string - Detail string - // Clear resets the row silently. Recovery is displayed only after a - // prior status, avoiding a routine initial "allowed" rate-limit message. - Clear bool - Recovery bool - // Occurrence is an unkeyed one-off message, not a state snapshot. - Occurrence bool +type statusProgressDisplay struct { + message string + subject string + context string } -func (StatusProgressEvent) agentEvent() {} - func (r *EventRenderer) statusProgress(e StatusProgressEvent) { if e.Kind == "" { return @@ -34,13 +18,27 @@ func (r *EventRenderer) statusProgress(e StatusProgressEvent) { delete(r.statusProgressSeen, key) return } - if e.Recovery && previous == "" { + if e.Recovery && previous.message == "" { return } msg := r.progressText(e.Label, 120) if msg == "" { return } + subject := r.progressText(e.Subject, 120) + context := r.progressText(e.Context, 80) + if subject == "" && !e.SubjectSet { + subject = previous.subject + } + if context == "" && !e.ContextSet { + context = previous.context + } + if subject != "" { + msg += " " + subject + } + if context != "" { + msg += " [" + context + "]" + } if state := r.progressText(e.State, 60); state != "" { msg += " — " + state } @@ -48,25 +46,17 @@ func (r *EventRenderer) statusProgress(e StatusProgressEvent) { msg += ": " + detail } msg = sanitizeOutput(msg) - if !e.Occurrence && previous == msg { + if !e.Occurrence && previous.message == msg { return } if !e.Occurrence { if r.statusProgressSeen == nil { - r.statusProgressSeen = make(map[[sha256.Size]byte]string) + r.statusProgressSeen = make(map[[sha256.Size]byte]statusProgressDisplay) } if len(r.statusProgressSeen) >= maxTaskProgressEntries { clear(r.statusProgressSeen) } - r.statusProgressSeen[key] = msg + r.statusProgressSeen[key] = statusProgressDisplay{message: msg, subject: subject, context: context} } r.printProgress(msg) } - -func (r *EventRenderer) printProgress(msg string) { - r.endBlock() - if r.isCI { - fmt.Fprintf(os.Stderr, "::notice::%s\n", msg) - } - r.printer.ToolProgress(msg) -} diff --git a/internal/runtime/status_progress_test.go b/internal/runtime/status_progress_test.go new file mode 100644 index 0000000000..575d9a97e3 --- /dev/null +++ b/internal/runtime/status_progress_test.go @@ -0,0 +1,69 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestStatusProgressRendererSafetyAndBounds(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + const secret = "opaque-status-secret-for-test" + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, secret, "[REDACTED]") } + e := StatusProgressEvent{Kind: "notification", ID: "one", Label: secret + "\n::error::", State: "\x1b[31mwarning\x1b[0m", Detail: secret + strings.Repeat("界", 500)} + stderr := captureStderr(t, func() { r.Handle(TextEvent{Text: "before"}); r.Handle(e); r.Handle(e) }) + if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Contains(out.String(), "\x1b") { + t.Fatal("unsafe status display") + } + if strings.Count(stderr, "::notice::") != 1 || !strings.Contains(out.String(), "before\n") { + t.Fatal("bad CI/block boundary") + } + if len([]rune(out.String())) > 500 { + t.Fatal("unbounded status") + } + r.Handle(StatusProgressEvent{}) + r.Handle(StatusProgressEvent{Kind: "empty"}) + r.isCI = false + for i := range maxTaskProgressEntries + 1 { + r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row"}) + } + if len(r.statusProgressSeen) > maxTaskProgressEntries { + t.Fatal("unbounded status cache") + } +} + +func TestWorkflowReviewJoiningFieldsCannotRecreateCommands(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "task:", Label: "label", State: TaskRunning}) + r.Handle(StatusProgressEvent{Kind: "warning", Label: "warning:", Detail: "detail"}) + if strings.Contains(out.String(), "::") { + t.Fatal("field joins recreated command delimiter: " + out.String()) + } +} + +func TestStatusProgressAttributionRedactedBeforeRetention(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + const secret = "opaque-hook-attribution-secret-for-test" + var out bytes.Buffer + r := newTestRenderer(&out) + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, secret, "[REDACTED]") } + stderr := captureStderr(t, func() { + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: "Hook", State: "running", Subject: secret + strings.Repeat("界", 200), Context: secret + "\n::error::", SubjectSet: true, ContextSet: true}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: "Hook", State: "completed"}) + }) + if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Count(stderr, "::notice::") != 2 { + t.Fatal("unsafe hook attribution") + } + for _, display := range r.statusProgressSeen { + if strings.Contains(display.subject+display.context+display.message, secret) || len([]rune(display.subject)) > 121 || len([]rune(display.context)) > 81 { + t.Fatal("unsafe or unbounded cached attribution") + } + } + if strings.Count(out.String(), "[REDACTED]") != 4 { + t.Fatal("sparse completion lost redacted attribution: " + out.String()) + } +} diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index ad4dda15a9..f5cefaf24e 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -7,50 +7,6 @@ import ( "unicode/utf8" ) -// TaskState describes task/agent progress, not validated business completion. -type TaskState string - -const ( - TaskPending TaskState = "pending" - TaskPaused TaskState = "paused" - TaskRunning TaskState = "running" - TaskCompleted TaskState = "completed" - TaskFailed TaskState = "failed" - TaskStopped TaskState = "stopped" - TaskQueued TaskState = "queued" - TaskRetrying TaskState = "retrying" - TaskSkipped TaskState = "skipped" -) - -// TaskProgressEvent carries live background task or Workflow agent metadata. -// An empty AgentID and zero AgentIndex describe the task itself. Phase is -// agent attribution, never an inventory of declared phases. Progress does not -// update token/cost accounting and carries no prompts or tool result bodies. -type TaskProgressEvent struct { - TaskID string - RunID string - AgentID string - AgentIndex int - Label string - Phase string - State TaskState - ToolName string - ToolSummary string - Summary string - Detail string - Blocked bool - Cached bool - // Update carries a partial lifecycle patch. Missing fields retain their - // sanitized display values. LabelSet/DetailSet permit explicit empty fields. - Update bool - LabelSet bool - DetailSet bool - Started bool - Hidden bool -} - -func (TaskProgressEvent) agentEvent() {} - // Bound retained display state even if a runtime sends unlimited identities. // Hashing IDs also avoids retaining arbitrarily large sandbox strings as keys. const maxTaskProgressEntries = 1024 @@ -75,7 +31,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { previous := r.taskProgressSeen[key] parentKey := taskProgressKey{task: taskHash, run: runHash, agent: sha256.Sum256(nil)} parent := r.taskProgressSeen[parentKey].event - if !e.Started && (parent.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || terminalTaskState(previous.event.State)))) { + if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || terminalTaskState(previous.event.State)))) { return } // Sanitize before retaining metadata, not just before printing it. This @@ -106,6 +62,9 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { e.Detail = old.Detail } } + if e.AgentID != "" || e.AgentIndex > 0 { + mergeAgentProgress(&e, old) + } if e.RunID == "" { e.RunID = old.RunID } @@ -121,7 +80,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { r.taskProgressRuns[taskHash] = runHash } if e.Hidden { - r.taskProgressSeen[parentKey] = taskProgressDisplay{event: e} + r.taskProgressSeen[key] = taskProgressDisplay{event: e} return } msg := "Task " + e.TaskID @@ -213,10 +172,9 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK r.taskProgressSeen[key] = display } } - } else { - parent := taskProgressKey{task: task, run: current, agent: sha256.Sum256(nil)} - e.Hidden = r.taskProgressSeen[parent].event.Hidden } + // Distinct named runs have independent visibility. Only promotion of + // anonymous rows above carries visibility within the same generation. r.taskProgressRuns[task] = run } } @@ -224,6 +182,31 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK return taskProgressKey{task: task, run: run, agent: sha256.Sum256([]byte(e.AgentID)), index: e.AgentIndex} } +// mergeAgentProgress retains already-sanitized optional metadata when a +// snapshot only changes counters. Explicit empty/false fields can clear it. +// Error/blocked/cached metadata is state-relative: a transition drops omitted +// transient values instead of describing a recovered agent as still blocked. +func mergeAgentProgress(e *TaskProgressEvent, old TaskProgressEvent) { + if !e.PhaseSet && e.Phase == "" { + e.Phase = old.Phase + } + if !e.ToolNameSet && e.ToolName == "" { + e.ToolName = old.ToolName + } + if !e.ToolSummarySet && e.ToolSummary == "" && e.ToolName == old.ToolName { + e.ToolSummary = old.ToolSummary + } + if !e.DetailSet && e.Detail == "" && e.State == old.State { + e.Detail = old.Detail + } + if !e.BlockedSet && !e.Blocked && e.State == old.State { + e.Blocked = old.Blocked + } + if !e.CachedSet && !e.Cached && e.State == old.State { + e.Cached = old.Cached + } +} + func terminalTaskState(state TaskState) bool { return state == TaskCompleted || state == TaskFailed || state == TaskStopped || state == TaskSkipped } diff --git a/internal/runtime/task_progress_test.go b/internal/runtime/task_progress_test.go new file mode 100644 index 0000000000..75d5cb66c1 --- /dev/null +++ b/internal/runtime/task_progress_test.go @@ -0,0 +1,147 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +func TestTaskProgressRendererDeduplicates(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + e := TaskProgressEvent{TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "refine", Phase: "Refine", State: TaskRunning, ToolName: "Read"} + for range 135 { + r.Handle(e) + } + if lines := strings.Count(console.String(), "Task task-one"); lines != 1 { + t.Fatalf("repeated snapshots rendered %d times", lines) + } + e.ToolName = "Bash" + r.Handle(e) + e.State = TaskCompleted + r.Handle(e) + r.Handle(e) + if lines := strings.Count(console.String(), "Task task-one"); lines != 3 { + t.Fatalf("tool/state transitions should render exactly once: %s", console.String()) + } +} + +func TestTaskProgressRendererIdentityAndLifecycle(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "first-run", AgentID: "worker", Label: "review", State: TaskRunning}, + {TaskID: "two", AgentID: "worker", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentID: "different", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentIndex: 1, Label: "review", State: TaskQueued}, + {TaskID: "one", AgentIndex: 2, Label: "review", State: TaskQueued}, + {TaskID: "one", AgentID: "worker", RunID: "another-run", Label: "review", State: TaskRunning}, + {TaskID: "one", State: TaskFailed}, + {TaskID: "two", State: TaskStopped}, + } { + r.Handle(e) + } + if lines := strings.Count(console.String(), "Task "); lines != 8 { + t.Fatalf("concurrent identities/statuses were lost: %s", console.String()) + } + for _, want := range []string{"agent #1", "agent #2", "failed", "stopped"} { + if !strings.Contains(console.String(), want) { + t.Errorf("missing %q: %s", want, console.String()) + } + } + before := console.String() + r.Handle(TaskProgressEvent{State: TaskRunning}) + r.Handle(TaskProgressEvent{TaskID: "one"}) + if console.String() != before { + t.Error("incomplete events must not render") + } +} + +func TestTaskProgressRendererBoundedState(t *testing.T) { + var console bytes.Buffer + r := newTestRenderer(&console) + for i := range maxTaskProgressEntries + 1 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), State: TaskRunning}) + } + if len(r.taskProgressSeen) > maxTaskProgressEntries { + t.Fatalf("unbounded dedup state: %d", len(r.taskProgressSeen)) + } +} + +func TestTaskProgressRendererRedactsAndSanitizes(t *testing.T) { + const opaque = "opaque-progress-credential-for-test" + security.RegisterRuntimeSecret(opaque) + // Generate a scanner-shaped dummy; no stored credential fixture. + token := "ghp_" + strings.Repeat("0", 36) + var console bytes.Buffer + r := newTestRenderer(&console) + r.Handle(TaskProgressEvent{ + TaskID: "id\n::error::" + opaque, + AgentID: token, Phase: "\x1b[31mCreate\x1b[0m", Label: "hello%0Aworld\r\n::warning::", + State: TaskRunning, ToolName: "Bash", ToolSummary: "token=" + token + " secret=" + opaque, + }) + output := console.String() + for _, forbidden := range []string{opaque, token, "\x1b", "::", "%0A", "\r"} { + if strings.Contains(output, forbidden) { + t.Errorf("unsafe field %q escaped sanitization: %q", forbidden, output) + } + } + if lines := strings.Count(output, "\n"); lines != 1 { + t.Errorf("sandbox text injected extra console lines: %q", output) + } + long := strings.Repeat("界", 200) + got := taskProgressText(long, 80) + if !utf8.ValidString(got) || utf8.RuneCountInString(got) != 81 || !strings.HasSuffix(got, "…") { + t.Errorf("invalid UTF-8 truncation: %q", got) + } + if got := taskProgressText(token, 10); strings.Contains(got, token[:10]) { + t.Errorf("credential was truncated before redaction: %q", got) + } +} + +func TestTaskProgressRendererCIAndBlockBoundary(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var console bytes.Buffer + r := newTestRenderer(&console) + r.Handle(TextEvent{Text: "before"}) + e := TaskProgressEvent{TaskID: "one", Label: "Create\n::error:: injected", State: TaskRunning} + stderr := captureStderr(t, func() { + r.Handle(e) + r.Handle(e) + }) + if strings.Count(stderr, "::notice::") != 1 || strings.Contains(stderr, "::error::") { + t.Errorf("expected one safe CI notice: %q", stderr) + } + if !strings.Contains(console.String(), "before\n") { + t.Errorf("task progress did not close the streaming block: %q", console.String()) + } +} + +func TestTaskProgressRendererCallerRedaction(t *testing.T) { + const secret = "opaque-runner-credential-for-test" + var console bytes.Buffer + r := newTestRenderer(&console) + r.RedactProgress = func(text string) string { + return strings.ReplaceAll(text, secret, "[REDACTED]") + } + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, + Label: secret + strings.Repeat("界", 200), ToolName: "Bash", ToolSummary: secret}) + if strings.Contains(console.String(), secret) || !strings.Contains(console.String(), "[REDACTED]") { + t.Errorf("caller-owned secret escaped redaction: %q", console.String()) + } +} + +func TestTaskProgressHiddenAgentCannotReplaceParent(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", AgentIndex: 1, State: TaskCompleted, Hidden: true, Label: "PRIVATE"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "Visible parent"}) + r.Handle(TaskProgressEvent{TaskID: "one", AgentIndex: 1, State: TaskRunning, Label: "PRIVATE"}) + if strings.Contains(out.String(), "PRIVATE") || !strings.Contains(out.String(), "Visible parent — running") { + t.Fatal(out.String()) + } +} From 2f8dba378805578f466076556bf09fb56f1cd424 Mon Sep 17 00:00:00 2001 From: jctanner Date: Thu, 29 Oct 2026 18:59:18 -0400 Subject: [PATCH 03/16] fix(#8908): keep Workflow agent rows stable by index Key indexed Workflow agents by task, run and index. Retain learned agent IDs as redacted display metadata without treating ID-only updates as new progress, and keep ID-based identity when an index is absent. Document workflow_progress and task_summary as undocumented Claude Code internals that can change or disappear in patch releases. Distinguish embedded-schema checks and synthetic tests from recorded live validation. Signed-off-by: jctanner --- docs/cli/run.md | 24 +++++++--- internal/runtime/claude_pr_review_test.go | 26 +++++++++++ internal/runtime/claude_status_progress.go | 3 ++ internal/runtime/claude_task_progress.go | 23 +++++----- internal/runtime/event.go | 10 +++-- internal/runtime/task_progress.go | 51 +++++++++++++++++----- internal/runtime/task_progress_test.go | 27 ++++++++++++ 7 files changed, 133 insertions(+), 31 deletions(-) diff --git a/docs/cli/run.md b/docs/cli/run.md index 7ed265ede3..cdf64185f4 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -118,9 +118,9 @@ prints task identity, agent labels, attributed phases, state changes, and available tool names/context. For example: ```console - ⚙ Task wf-example / agent reader [Read]: read input — running - ⚙ Task wf-example / agent reader [Read]: read input — completed - ⚙ Task wf-example / agent creator [Create]: strategy-create — running (tool: Bash: python3 create.py) + ⚙ Task wf-example / agent #1 (reader) [Read]: read input — running + ⚙ Task wf-example / agent #1 (reader) [Read]: read input — completed + ⚙ Task wf-example / agent #2 (creator) [Create]: strategy-create — running (tool: Bash: python3 create.py) ``` Unchanged snapshots and counter-only updates do not repeat the same display @@ -139,15 +139,27 @@ progress/completion messages for the same hook ID. The display handles these structured Claude events when the runtime emits them. Task progress shapes were checked against Claude Code 2.1.296 capture -and the embedded 2.1.312 emitter/schema; availability varies by version. +and the embedded 2.1.312 emitter/schema; this is version-bound compatibility, +not a promise of a stable public protocol. In particular, `workflow_progress` +(including `workflow_agent` metadata) and `system/task_summary` are +**undocumented internal Claude Code extensions**, not public Agent SDK +contracts in the inspected version. They may change or disappear without +notice in any Claude patch release. Support is best-effort; unsupported +shapes are ignored for display and raw events remain available for diagnosis. +A newly recorded live 2.1.312 Workflow stream has not been qualified here. + +Workflow agents use their positive index as stable identity within a task/run. +A late `agentId` is retained as display attribution, and learning it alone +does not add another progress line. If the index is absent, the agent ID is +the identity fallback. | Event | Console behavior | | --- | --- | | `task_started` | Task identity and description; ambient/hidden starts suppress subsequent progress while tracked. | -| `task_progress` | Task description, last tool and progress summary; Workflow agent phase, tool context, state, blocked/error and cached-result metadata. | +| `task_progress` | Task description, last tool and progress summary; best-effort decoding of the undocumented internal `workflow_progress` agent metadata. | | `task_updated` | Pending, running, paused, completed, failed and killed states; description-only patches and bounded errors. | | `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | -| `task_summary` | Changed mid-turn summary; a null/empty value clears deduplication silently. | +| `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | | `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | | `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. | | `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | diff --git a/internal/runtime/claude_pr_review_test.go b/internal/runtime/claude_pr_review_test.go index 1acc464f5b..2562061741 100644 --- a/internal/runtime/claude_pr_review_test.go +++ b/internal/runtime/claude_pr_review_test.go @@ -110,3 +110,29 @@ func TestClaudeReviewAgentRecoveryClearsTransientMetadata(t *testing.T) { t.Fatal(out.String()) } } + +// The internal 2.1.312 producer keys Workflow entries by type:index. This +// reduced sequence models its queued/start/done shapes; it is not a newly +// recorded live 2.1.312 run. +func TestClaudeReviewLateAgentIDUsesOneIndexedRow(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"read","phaseTitle":"Read"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","state":"start","label":"read","phaseTitle":"Read"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"read","phaseTitle":"Read"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "— running") != 1 || strings.Count(out.String(), "— completed") != 1 || len(r.taskProgressSeen) != 1 { + t.Fatal("late ID split agent row: " + out.String()) + } + for _, row := range r.taskProgressSeen { + if row.event.AgentID != "a1" || row.event.State != TaskCompleted || row.event.AgentIndex != 1 { + t.Fatalf("lost agent identity or completion: %+v", row.event) + } + } + if !strings.Contains(out.String(), "a1") { + t.Fatal("known agent ID missing from completion display") + } +} diff --git a/internal/runtime/claude_status_progress.go b/internal/runtime/claude_status_progress.go index 6e48a1296b..e50fc988c9 100644 --- a/internal/runtime/claude_status_progress.go +++ b/internal/runtime/claude_status_progress.go @@ -56,6 +56,9 @@ func decodeClaudeStatusProgress(line []byte, subtype string) (StatusProgressEven } } case "task_summary": + // Undocumented internal Claude Code message from the inspected 2.1.312 + // embedded schema, not a public Agent SDK contract. It may change or + // disappear in any patch release; unknown display shapes are ignored. var wire struct { Detail *string `json:"detail"` Summary *string `json:"summary"` diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go index b242b13f9a..62510c5d5a 100644 --- a/internal/runtime/claude_task_progress.go +++ b/internal/runtime/claude_task_progress.go @@ -8,16 +8,19 @@ import ( // Optional snapshots remain raw so malformed entries cannot discard a useful // lifecycle event. Prompt/result bodies and terminal summaries are not decoded. type claudeTaskProgress struct { - TaskID string `json:"task_id"` - RunID string `json:"run_id"` - Description string `json:"description"` - Status string `json:"status"` - LastToolName string `json:"last_tool_name"` - Summary json.RawMessage `json:"summary"` - Reason string `json:"reason"` - Ambient bool `json:"ambient"` - SkipTranscript bool `json:"skip_transcript"` - Patch json.RawMessage `json:"patch"` + TaskID string `json:"task_id"` + RunID string `json:"run_id"` + Description string `json:"description"` + Status string `json:"status"` + LastToolName string `json:"last_tool_name"` + Summary json.RawMessage `json:"summary"` + Reason string `json:"reason"` + Ambient bool `json:"ambient"` + SkipTranscript bool `json:"skip_transcript"` + Patch json.RawMessage `json:"patch"` + // WorkflowProgress is an undocumented internal Claude Code payload, not + // a public Agent SDK contract. It may change or disappear without notice + // in any patch release; decoding is best-effort and raw capture is retained. WorkflowProgress json.RawMessage `json:"workflow_progress"` } diff --git a/internal/runtime/event.go b/internal/runtime/event.go index 4c3d1e465c..0b96bd93a0 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -177,9 +177,13 @@ const ( ) // TaskProgressEvent carries live background task or Workflow agent metadata. -// An empty AgentID and zero AgentIndex describe the task itself. Phase is -// agent attribution, never an inventory of declared phases. Progress does not -// update token/cost accounting and carries no prompts or tool result bodies. +// An empty AgentID and zero AgentIndex describe the task itself. A positive +// AgentIndex is the stable Workflow row identity within a task/run; AgentID +// is optional display attribution and is the identity fallback only when +// index is absent. Learning an ID alone is not a new display transition. +// Phase is agent attribution, never an inventory of declared phases. +// Progress does not update token/cost accounting and carries no prompts or +// tool result bodies. // Consumers receive repeated snapshots and partial patches, not reconciled // transitions. EventRenderer merges and deduplicates after caller-specific // credential redaction; custom OnEvent consumers must reconcile their own diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index f5cefaf24e..7da1559542 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -17,8 +17,8 @@ type taskProgressKey struct { } type taskProgressDisplay struct { - event TaskProgressEvent - message string + event TaskProgressEvent + fingerprint [sha256.Size]byte } func (r *EventRenderer) taskProgress(e TaskProgressEvent) { @@ -83,11 +83,32 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { r.taskProgressSeen[key] = taskProgressDisplay{event: e} return } + msg := taskProgressMessage(e) + comparison := msg + if e.AgentIndex > 0 { + // An ID arriving late is attribution, not a second progress transition. + indexed := e + indexed.AgentID = "" + comparison = taskProgressMessage(indexed) + } + fingerprint := sha256.Sum256([]byte(comparison)) + r.taskProgressSeen[key] = taskProgressDisplay{event: e, fingerprint: fingerprint} + if previous.fingerprint == fingerprint { + return + } + r.printProgress(msg) +} + +// taskProgressMessage formats only already-redacted, bounded display fields. +func taskProgressMessage(e TaskProgressEvent) string { msg := "Task " + e.TaskID - if e.AgentID != "" { - msg += " / agent " + e.AgentID - } else if e.AgentIndex > 0 { + if e.AgentIndex > 0 { msg += fmt.Sprintf(" / agent #%d", e.AgentIndex) + if e.AgentID != "" { + msg += " (" + e.AgentID + ")" + } + } else if e.AgentID != "" { + msg += " / agent " + e.AgentID } if e.Phase != "" { msg += " [" + e.Phase + "]" @@ -119,12 +140,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { if e.Detail != "" { msg += " — " + e.Detail } - msg = sanitizeOutput(msg) - r.taskProgressSeen[key] = taskProgressDisplay{event: e, message: msg} - if previous.message == msg { - return - } - r.printProgress(msg) + return sanitizeOutput(msg) } // Resolve optional run IDs without splitting a task when its first run ID @@ -179,7 +195,15 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK } } } - return taskProgressKey{task: task, run: run, agent: sha256.Sum256([]byte(e.AgentID)), index: e.AgentIndex} + // Workflow entries are keyed by type:index in the producer. agentId is + // absent while queued and can also be omitted in subsequent snapshots. + agent := sha256.Sum256(nil) + index := e.AgentIndex + if index <= 0 { + index = 0 + agent = sha256.Sum256([]byte(e.AgentID)) + } + return taskProgressKey{task: task, run: run, agent: agent, index: index} } // mergeAgentProgress retains already-sanitized optional metadata when a @@ -187,6 +211,9 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK // Error/blocked/cached metadata is state-relative: a transition drops omitted // transient values instead of describing a recovered agent as still blocked. func mergeAgentProgress(e *TaskProgressEvent, old TaskProgressEvent) { + if e.AgentID == "" { + e.AgentID = old.AgentID + } if !e.PhaseSet && e.Phase == "" { e.Phase = old.Phase } diff --git a/internal/runtime/task_progress_test.go b/internal/runtime/task_progress_test.go index 75d5cb66c1..a19be7dbee 100644 --- a/internal/runtime/task_progress_test.go +++ b/internal/runtime/task_progress_test.go @@ -145,3 +145,30 @@ func TestTaskProgressHiddenAgentCannotReplaceParent(t *testing.T) { t.Fatal(out.String()) } } + +func TestTaskProgressIndexIdentityScopesAndIDFallback(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "first", AgentIndex: 1, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "first", AgentIndex: 2, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "two", RunID: "first", AgentIndex: 1, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentIndex: 1, AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentID: "shared", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentID: "fallback-a", Label: "Work", State: TaskRunning}, + {TaskID: "one", RunID: "second", AgentID: "fallback-b", Label: "Work", State: TaskRunning}, + } { + r.Handle(e) + } + if len(r.taskProgressSeen) != 7 || strings.Count(out.String(), "— running") != 7 { + t.Fatal("distinct slots/tasks/runs/fallback IDs collapsed: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "first", AgentIndex: 1, AgentID: "learned", Label: "Work", State: TaskRunning}) + if len(r.taskProgressSeen) != 7 || strings.Count(out.String(), "— running") != 7 { + t.Fatal("ID-only indexed change created another row") + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "first", AgentIndex: 1, Label: "Work", State: TaskCompleted}) + if !strings.Contains(out.String(), "agent #1 (learned): Work — completed") { + t.Fatal("known display ID was lost: " + out.String()) + } +} From d7f048d3b1de1376d7bc3edb40cdf7b47c042167 Mon Sep 17 00:00:00 2001 From: jctanner Date: Fri, 30 Oct 2026 10:07:57 -0400 Subject: [PATCH 04/16] fix(#8908): derive Workflow agent status from producer metadata Derive queued, retrying, and skipped agent status from timestamps, attempts, retry reasons, and flags in the four-state Claude producer. Display attempt metadata, accept genuine retries after failed attempts, and ignore stale snapshots without reopening completed workflows. Replace schema-invalid fixtures and move the detailed progress docs to the Claude runtime page as requested in review. Signed-off-by: jctanner --- docs/cli/run.md | 72 +--------- docs/runtimes/claude.md | 83 ++++++++++- internal/runtime/claude_pr_review_test.go | 12 +- internal/runtime/claude_task_progress.go | 81 ++++++++--- internal/runtime/claude_task_updates_test.go | 4 +- .../runtime/claude_workflow_progress_test.go | 6 +- .../runtime/claude_workflow_state_test.go | 129 ++++++++++++++++++ internal/runtime/event.go | 10 ++ internal/runtime/task_progress.go | 79 ++++++++++- 9 files changed, 371 insertions(+), 105 deletions(-) create mode 100644 internal/runtime/claude_workflow_state_test.go diff --git a/docs/cli/run.md b/docs/cli/run.md index cdf64185f4..f24422d02a 100644 --- a/docs/cli/run.md +++ b/docs/cli/run.md @@ -111,75 +111,11 @@ cases fail earlier: See [pi § Per-persona model configuration](../runtimes/pi.md#per-persona-model-configuration). -## Live Claude Workflow progress +## Live progress -When Claude Code emits background task and Workflow progress, `fullsend run` -prints task identity, agent labels, attributed phases, state changes, and -available tool names/context. For example: - -```console - ⚙ Task wf-example / agent #1 (reader) [Read]: read input — running - ⚙ Task wf-example / agent #1 (reader) [Read]: read input — completed - ⚙ Task wf-example / agent #2 (creator) [Create]: strategy-create — running (tool: Bash: python3 create.py) -``` - -Unchanged snapshots and counter-only updates do not repeat the same display -line. Text is sanitized, credential-redacted, and bounded before display or -retention in the bounded display cache. Concurrent tasks and agents retain -separate identities. Partial lifecycle patches retain known task labels and -state; explicit starts can reset an identity. Late running snapshots do not -reopen a known terminal task or agent. Sparse agent snapshots retain known -labels, phases and tool context. Error, blocked and cached metadata persists -within a state; state changes clear omitted transient metadata. Explicit -empty strings and false flags also clear their corresponding fields. -Visibility belongs to each run: promoting its first late run ID preserves -its hidden classification, while a distinct named run does not inherit an -older run's visibility. Hook names and event attribution survive sparse -progress/completion messages for the same hook ID. - -The display handles these structured Claude events when the runtime emits -them. Task progress shapes were checked against Claude Code 2.1.296 capture -and the embedded 2.1.312 emitter/schema; this is version-bound compatibility, -not a promise of a stable public protocol. In particular, `workflow_progress` -(including `workflow_agent` metadata) and `system/task_summary` are -**undocumented internal Claude Code extensions**, not public Agent SDK -contracts in the inspected version. They may change or disappear without -notice in any Claude patch release. Support is best-effort; unsupported -shapes are ignored for display and raw events remain available for diagnosis. -A newly recorded live 2.1.312 Workflow stream has not been qualified here. - -Workflow agents use their positive index as stable identity within a task/run. -A late `agentId` is retained as display attribution, and learning it alone -does not add another progress line. If the index is absent, the agent ID is -the identity fallback. - -| Event | Console behavior | -| --- | --- | -| `task_started` | Task identity and description; ambient/hidden starts suppress subsequent progress while tracked. | -| `task_progress` | Task description, last tool and progress summary; best-effort decoding of the undocumented internal `workflow_progress` agent metadata. | -| `task_updated` | Pending, running, paused, completed, failed and killed states; description-only patches and bounded errors. | -| `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | -| `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | -| `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | -| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. | -| `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | -| `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | -| `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | -| `rate_limit_event` | Warnings, rejection, supplied reset time and subsequent recovery; routine initial allowed status suppressed. | - -Declared `workflow_phase` records do not prove live advancement and are not -rendered as phase starts. Internal `workflow_log` entries are filtered out -of SDK progress by the inspected Claude 2.1.312 producer; Fullsend cannot -display records absent from its input stream. This is not a stream of full -nested tool stdout/stderr, prompts, result bodies or hook output. Unknown -message kinds/states and malformed records are ignored for display; raw -events remain in `output.jsonl` for diagnosis and future compatibility work. - -Task completion and session idle are distinct from the run's validated -business result. Progress counters do not add to token/cost totals. The -periodic `Agent running (...)` heartbeat still reports elapsed time rather -than proving progress. The display is advisory, not a durable task registry; -very large sessions can evict cached identity and deduplication state. +Progress display depends on the selected runtime. See +[Claude Workflow progress](../runtimes/claude.md#live-claude-workflow-progress) +for Claude background tasks, agent lifecycle metadata and display limits. ## Output artifacts diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index bd8307a5b1..a7f9903e7c 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -12,7 +12,7 @@ config keys live there too. Background Workflow phase/agent changes and runtime lifecycle/status notices are displayed from Claude's structured event stream. See -[live Workflow progress](../cli/run.md#live-claude-workflow-progress) +[live Workflow progress](#live-claude-workflow-progress) for the display behavior and its limits; it does not include full nested tool stdout/stderr. @@ -330,6 +330,87 @@ These are the places Claude Code differs from pi — useful when comparing a run hook wiring is passed explicitly with `--settings` so it loads regardless, but repo-supplied hooks are a separate exposure to be aware of. +## Live Claude Workflow progress + +When Claude Code emits background task and Workflow progress, `fullsend run` +prints task identity, agent labels, attributed phases, state changes, and +available tool names/context. For example: + +```console + ⚙ Task wf-example / agent #1 (reader) [Read]: read input — running (attempt 1) + ⚙ Task wf-example / agent #1 (reader) [Read]: read input — completed (attempt 1) + ⚙ Task wf-example / agent #2 (creator) [Create]: strategy-create — running (tool: Bash: python3 create.py) (attempt 1) +``` + +Unchanged snapshots and counter-only updates do not repeat the same display +line. Text is sanitized, credential-redacted, and bounded before display or +retention in the bounded display cache. Concurrent tasks and agents retain +separate identities. Partial lifecycle patches retain known task labels and +state; explicit starts can reset an identity. Late running snapshots do not +reopen a known terminal task or agent. Sparse agent snapshots retain known +labels, phases and tool context. Error, blocked and cached metadata persists +within a state; state changes clear omitted transient metadata. Explicit +empty strings and false flags also clear their corresponding fields. +Visibility belongs to each run: promoting its first late run ID preserves +its hidden classification, while a distinct named run does not inherit an +older run's visibility. Hook names and event attribution survive sparse +progress/completion messages for the same hook ID. + +Workflow agent wire states are only `start`, `progress`, `done` and `error`. +A `start` record with `queuedAt` and no `startedAt` is queued; a record with +`startedAt` is executing. Started agents display their one-based `attempt` +when supplied. A retry start has an `attempt` greater than one; its display +includes `attempt` and the supplied `lastAttemptReason` +(`stalled`, `throttled` or `user-retry`). Later progress is running, with the +attempt retained, and each new attempt is visible even when its label and +tool are unchanged. `error` plus `skipped: true` is skipped, not failed. +Older records without timing metadata retain the best-effort running display. +These derived statuses do not assume extra values in the agent wire enum. + +The display handles these structured Claude events when the runtime emits +them. Task progress shapes were checked against Claude Code 2.1.296 capture +and the embedded 2.1.312 emitter/schema; this is version-bound compatibility, +not a promise of a stable public protocol. In particular, `workflow_progress` +(including `workflow_agent` metadata) and `system/task_summary` are +**undocumented internal Claude Code extensions**, not public Agent SDK +contracts in the inspected version. They may change or disappear without +notice in any Claude patch release. Support is best-effort; unsupported +shapes are ignored for display and raw events remain available for diagnosis. +A newly recorded live 2.1.312 Workflow stream has not been qualified here. + +Workflow agents use their positive index as stable identity within a task/run. +A late `agentId` is retained as display attribution, and learning it alone +does not add another progress line. If the index is absent, the agent ID is +the identity fallback. + +| Event | Console behavior | +| --- | --- | +| `task_started` | Task identity and description; ambient/hidden starts suppress subsequent progress while tracked. | +| `task_progress` | Task description, last tool and progress summary; best-effort decoding of the undocumented internal `workflow_progress` agent metadata. | +| `task_updated` | Pending, running, paused, completed, failed and killed states; description-only patches and bounded errors. | +| `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | +| `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | +| `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | +| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. | +| `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | +| `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | +| `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | +| `rate_limit_event` | Warnings, rejection, supplied reset time and subsequent recovery; routine initial allowed status suppressed. | + +Declared `workflow_phase` records do not prove live advancement and are not +rendered as phase starts. Internal `workflow_log` entries are filtered out +of SDK progress by the inspected Claude 2.1.312 producer; Fullsend cannot +display records absent from its input stream. This is not a stream of full +nested tool stdout/stderr, prompts, result bodies or hook output. Unknown +message kinds/states and malformed records are ignored for display; raw +events remain in `output.jsonl` for diagnosis and future compatibility work. + +Task completion and session idle are distinct from the run's validated +business result. Progress counters do not add to token/cost totals. The +periodic `Agent running (...)` heartbeat still reports elapsed time rather +than proving progress. The display is advisory, not a durable task registry; +very large sessions can evict cached identity and deduplication state. + ## Troubleshooting **The model is not what you asked for.** Check `metrics.json`: `requested_model` is what was handed diff --git a/internal/runtime/claude_pr_review_test.go b/internal/runtime/claude_pr_review_test.go index 2562061741..5310e7c34d 100644 --- a/internal/runtime/claude_pr_review_test.go +++ b/internal/runtime/claude_pr_review_test.go @@ -92,9 +92,9 @@ func TestClaudeReviewHookIdentityExplicitClear(t *testing.T) { } func TestClaudeReviewAgentRecoveryClearsTransientMetadata(t *testing.T) { - stream := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"retrying","label":"Create","error":"rate limited","blocked":true,"cached":true}]} -{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"Create","lastToolName":"Bash"}]} -{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"Create"}]} + stream := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","startedAt":100,"attempt":2,"lastAttemptReason":"throttled","label":"Create","error":"rate limited","blocked":true,"cached":true}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"progress","startedAt":100,"attempt":2,"label":"Create","lastToolName":"Bash"}]} +{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","startedAt":100,"attempt":2,"label":"Create"}]} ` var out bytes.Buffer r := newTestRenderer(&out) @@ -115,9 +115,9 @@ func TestClaudeReviewAgentRecoveryClearsTransientMetadata(t *testing.T) { // reduced sequence models its queued/start/done shapes; it is not a newly // recorded live 2.1.312 run. func TestClaudeReviewLateAgentIDUsesOneIndexedRow(t *testing.T) { - stream := `{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","label":"read","phaseTitle":"Read"}]} -{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","state":"start","label":"read","phaseTitle":"Read"}]} -{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"read","phaseTitle":"Read"}]} + stream := `{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","queuedAt":100,"label":"read","phaseTitle":"Read"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","state":"start","queuedAt":100,"startedAt":101,"attempt":1,"label":"read","phaseTitle":"Read"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","run_id":"run","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","queuedAt":100,"startedAt":101,"attempt":1,"label":"read","phaseTitle":"Read"}]} ` var out bytes.Buffer r := newTestRenderer(&out) diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go index 62510c5d5a..c4b40d605f 100644 --- a/internal/runtime/claude_task_progress.go +++ b/internal/runtime/claude_task_progress.go @@ -25,17 +25,22 @@ type claudeTaskProgress struct { } type claudeWorkflowAgentProgress struct { - Type string `json:"type"` - Index int `json:"index"` - AgentID string `json:"agentId"` - Label *string `json:"label"` - PhaseTitle *string `json:"phaseTitle"` - State string `json:"state"` - LastToolName *string `json:"lastToolName"` - LastToolSummary *string `json:"lastToolSummary"` - Error *string `json:"error"` - Blocked *bool `json:"blocked"` - Cached *bool `json:"cached"` + Type string `json:"type"` + Index int `json:"index"` + AgentID string `json:"agentId"` + Label *string `json:"label"` + PhaseTitle *string `json:"phaseTitle"` + State string `json:"state"` + LastToolName *string `json:"lastToolName"` + LastToolSummary *string `json:"lastToolSummary"` + Error *string `json:"error"` + Blocked *bool `json:"blocked"` + Cached *bool `json:"cached"` + QueuedAt *float64 `json:"queuedAt"` + StartedAt *float64 `json:"startedAt"` + Attempt *int `json:"attempt"` + LastAttemptReason *string `json:"lastAttemptReason"` + Skipped *bool `json:"skipped"` } func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { @@ -105,11 +110,30 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { if json.Unmarshal(entry, &agent) != nil || agent.Type != "workflow_agent" || (agent.AgentID == "" && agent.Index <= 0) { continue } - state := claudeTaskState(agent.State) + state := claudeWorkflowAgentState(agent) if state == "" { continue } event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, State: state} + if agent.QueuedAt != nil && *agent.QueuedAt >= 0 { + event.QueuedAt = *agent.QueuedAt + event.QueuedAtSet = true + } + if agent.StartedAt != nil && *agent.StartedAt >= 0 { + event.StartedAt = *agent.StartedAt + event.StartedAtSet = true + } + if agent.Attempt != nil && *agent.Attempt > 0 { + event.Attempt = *agent.Attempt + event.AttemptSet = true + } + if agent.LastAttemptReason != nil { + event.LastAttemptReasonSet = true + switch *agent.LastAttemptReason { + case "stalled", "throttled", "user-retry": + event.LastAttemptReason = *agent.LastAttemptReason + } + } if agent.Label != nil { event.Label = *agent.Label event.LabelSet = true @@ -143,6 +167,33 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { return events } +// claudeWorkflowAgentState follows the internal four-value producer enum. +// Queue/retry/skip are metadata, not additional workflow_agent.state values. +func claudeWorkflowAgentState(agent claudeWorkflowAgentProgress) TaskState { + switch agent.State { + case "start": + if agent.QueuedAt != nil && *agent.QueuedAt >= 0 && agent.StartedAt == nil { + return TaskQueued + } + if agent.StartedAt != nil && *agent.StartedAt >= 0 && agent.Attempt != nil && *agent.Attempt > 1 { + return TaskRetrying + } + return TaskRunning + case "progress": + return TaskRunning + case "done": + return TaskCompleted + case "error": + if agent.Skipped != nil && *agent.Skipped { + return TaskSkipped + } + return TaskFailed + default: + return "" + } +} + +// claudeTaskState maps task lifecycle statuses, not workflow_agent states. func claudeTaskState(state string) TaskState { switch state { case "start", "started", "progress", "running": @@ -153,16 +204,10 @@ func claudeTaskState(state string) TaskState { return TaskFailed case "killed", "stopped", "cancelled", "canceled": return TaskStopped - case "queued": - return TaskQueued case "pending": return TaskPending case "paused": return TaskPaused - case "retrying": - return TaskRetrying - case "skipped": - return TaskSkipped default: return "" } diff --git a/internal/runtime/claude_task_updates_test.go b/internal/runtime/claude_task_updates_test.go index d25f62d8a7..2175a1afc1 100644 --- a/internal/runtime/claude_task_updates_test.go +++ b/internal/runtime/claude_task_updates_test.go @@ -44,13 +44,13 @@ func TestClaudeTaskPartialUpdatesAndResume(t *testing.T) { } func TestClaudeWorkflowAgentDetails(t *testing.T) { - line := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","blocked":true,"error":"schema refused","label":"Create"},{"type":"workflow_agent","index":2,"state":"done","cached":true,"label":"Read","resultPreview":"PRIVATE"},{"type":"workflow_agent","index":3,"state":"paused","label":"Review"}]}` + line := `{"type":"system","subtype":"task_progress","task_id":"one","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","blocked":true,"error":"schema refused","label":"Create"},{"type":"workflow_agent","index":2,"state":"done","cached":true,"label":"Read","resultPreview":"PRIVATE"},{"type":"workflow_agent","index":3,"state":"start","queuedAt":1,"label":"Review"}]}` var out bytes.Buffer r := newTestRenderer(&out) if err := parseClaudeStream(strings.NewReader(line+"\n"), r.Handle); err != nil { t.Fatal(err) } - for _, want := range []string{"failed (blocked)", "schema refused", "completed (cached)", "Review — paused"} { + for _, want := range []string{"failed (blocked)", "schema refused", "completed (cached)", "Review — queued"} { if !strings.Contains(out.String(), want) { t.Errorf("missing %q: %s", want, out.String()) } diff --git a/internal/runtime/claude_workflow_progress_test.go b/internal/runtime/claude_workflow_progress_test.go index 5c4647043e..0281ac64cd 100644 --- a/internal/runtime/claude_workflow_progress_test.go +++ b/internal/runtime/claude_workflow_progress_test.go @@ -95,11 +95,11 @@ func TestClaudeTaskLifecycle(t *testing.T) { } func TestClaudeWorkflowProgressToleratesMalformedEntries(t *testing.T) { - line := `{"type":"system","subtype":"task_progress","task_id":"task-one","run_id":"run-one","workflow_progress":[null,42,{"type":"workflow_phase","title":"Not started"},{"type":"workflow_agent","state":"start"},{"type":"workflow_agent","index":4,"state":"future-state"},{"type":"workflow_agent","index":3,"state":"done","label":"first","phaseTitle":"Read","lastToolName":"Read","lastToolSummary":"input.json"},{"type":"workflow_agent","agentId":"child","state":"queued","label":"second"}]}` + line := `{"type":"system","subtype":"task_progress","task_id":"task-one","run_id":"run-one","workflow_progress":[null,42,{"type":"workflow_phase","title":"Not started"},{"type":"workflow_agent","state":"start"},{"type":"workflow_agent","index":4,"state":"future-state"},{"type":"workflow_agent","index":3,"state":"done","label":"first","phaseTitle":"Read","lastToolName":"Read","lastToolSummary":"input.json"},{"type":"workflow_agent","agentId":"child","state":"start","queuedAt":1,"label":"second"}]}` got := decodeClaudeTaskProgress([]byte(line), "task_progress") want := []TaskProgressEvent{ {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json", LabelSet: true, PhaseSet: true, ToolNameSet: true, ToolSummarySet: true}, - {TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "second", State: TaskQueued, LabelSet: true}, + {TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "second", State: TaskQueued, LabelSet: true, QueuedAt: 1, QueuedAtSet: true}, } if !reflect.DeepEqual(got, want) { t.Fatalf("got %+v, want %+v", got, want) @@ -121,7 +121,7 @@ func TestClaudeTaskStates(t *testing.T) { {"start", TaskRunning}, {"started", TaskRunning}, {"progress", TaskRunning}, {"running", TaskRunning}, {"done", TaskCompleted}, {"completed", TaskCompleted}, {"error", TaskFailed}, {"failed", TaskFailed}, {"killed", TaskStopped}, {"stopped", TaskStopped}, {"cancelled", TaskStopped}, {"canceled", TaskStopped}, - {"queued", TaskQueued}, {"retrying", TaskRetrying}, {"skipped", TaskSkipped}, {"unknown", ""}, + {"queued", ""}, {"retrying", ""}, {"skipped", ""}, {"unknown", ""}, } { if got := claudeTaskState(pair.wire); got != pair.want { t.Errorf("%s = %s, want %s", pair.wire, got, pair.want) diff --git a/internal/runtime/claude_workflow_state_test.go b/internal/runtime/claude_workflow_state_test.go new file mode 100644 index 0000000000..daaa32faf8 --- /dev/null +++ b/internal/runtime/claude_workflow_state_test.go @@ -0,0 +1,129 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +// Reduced from the inspected Claude Code 2.1.312 bundled schema/emitter, +// not a newly recorded live run. The wire state enum has only four values. +func TestClaudeWorkflowAgentProducerStates(t *testing.T) { + cases := []struct { + name, agent string + want TaskState + }{ + {"queued", `"state":"start","queuedAt":0`, TaskQueued}, + {"started", `"state":"start","queuedAt":0,"startedAt":0,"attempt":1`, TaskRunning}, + {"retry start", `"state":"start","startedAt":20,"attempt":2,"lastAttemptReason":"stalled"`, TaskRetrying}, + {"retry progress", `"state":"progress","startedAt":20,"attempt":2,"lastAttemptReason":"stalled"`, TaskRunning}, + {"completed", `"state":"done","attempt":2`, TaskCompleted}, + {"skipped", `"state":"error","skipped":true,"error":"skipped by user"`, TaskSkipped}, + {"failed", `"state":"error","skipped":false`, TaskFailed}, + {"blocked", `"state":"error","blocked":true`, TaskFailed}, + {"older start without times", `"state":"start"`, TaskRunning}, + {"not an agent queued enum", `"state":"queued"`, ""}, + {"not an agent retry enum", `"state":"retrying"`, ""}, + {"not an agent skip enum", `"state":"skipped"`, ""}, + {"not an agent pause enum", `"state":"paused"`, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"label":"read",%s}]}`, tc.agent) + events := decodeClaudeTaskProgress([]byte(raw), "task_progress") + if tc.want == "" { + if len(events) != 0 { + t.Fatalf("unsupported agent enum accepted: %+v", events) + } + return + } + if len(events) != 1 || events[0].State != tc.want { + t.Fatalf("got %+v, want state %s", events, tc.want) + } + }) + } +} + +func TestClaudeWorkflowAgentRetriesAndSkipsRender(t *testing.T) { + stream := `{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"label":"Read","state":"start","queuedAt":100}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","label":"Read","state":"start","queuedAt":100,"startedAt":101,"attempt":1}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a1","label":"Read","state":"error","queuedAt":100,"startedAt":101,"attempt":1,"error":"stalled"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a2","label":"Read","state":"start","queuedAt":100,"startedAt":201,"attempt":2,"lastAttemptReason":"stalled"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a2","label":"Read","state":"start","queuedAt":100,"startedAt":201,"attempt":2,"lastAttemptReason":"stalled","tokens":200}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a2","label":"Read","state":"error","queuedAt":100,"startedAt":201,"attempt":2,"lastAttemptReason":"stalled","error":"retry requested"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a3","label":"Read","state":"start","queuedAt":100,"startedAt":301,"attempt":3,"lastAttemptReason":"user-retry"}]} +{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"agentId":"a3","label":"Read","state":"done","queuedAt":100,"startedAt":301,"attempt":3,"lastAttemptReason":"user-retry"},{"type":"workflow_agent","index":2,"label":"Other","state":"error","skipped":true,"error":"skipped by user"}]} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "— queued") != 1 || strings.Count(out.String(), "— retrying") != 2 { + t.Fatal("missing queue/retry transitions: " + out.String()) + } + for _, want := range []string{"attempt 2; retry: stalled", "attempt 3; retry: user-retry", "Other — skipped"} { + if !strings.Contains(out.String(), want) { + t.Fatalf("missing %s: %s", want, out.String()) + } + } + if strings.Contains(out.String(), "Other — failed") { + t.Fatal("skip reported as failure") + } +} + +func TestClaudeWorkflowAgentQuotaWaitAndStaleSnapshots(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, fields := range []string{ + `"state":"start","queuedAt":10,"startedAt":100,"attempt":1`, + `"state":"start","queuedAt":10`, // stale initial queue + `"state":"error","queuedAt":10,"startedAt":100,"attempt":1,"error":"quota"`, + `"state":"start","queuedAt":200`, // quota wait has no attempt/startedAt + `"state":"start","queuedAt":10,"startedAt":100,"attempt":1`, // stale running during wait + `"state":"start","queuedAt":10`, // stale queue during wait + `"state":"error","queuedAt":200,"error":"quota wait failed"`, + `"state":"start","queuedAt":10,"startedAt":100,"attempt":1`, // stale after wait failure + `"state":"error","queuedAt":10,"startedAt":100,"attempt":1`, // stale failure + `"state":"start","queuedAt":200,"startedAt":300,"attempt":1`, + `"state":"error","queuedAt":200,"startedAt":300,"attempt":1`, + `"state":"start","queuedAt":200,"attempt":2,"lastAttemptReason":"throttled"`, + `"state":"start","queuedAt":200,"startedAt":400,"attempt":2,"lastAttemptReason":"throttled"`, + `"state":"done","queuedAt":200,"startedAt":300,"attempt":1`, // stale completion + `"state":"done","queuedAt":200,"startedAt":400,"attempt":2`, + } { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"label":"Read",%s}]}`+"\n", fields) + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + } + if strings.Count(out.String(), "— queued") != 2 || strings.Count(out.String(), "— completed") != 1 || !strings.Contains(out.String(), "attempt 2; retry: throttled") { + t.Fatal(out.String()) + } + for _, row := range r.taskProgressSeen { + if row.event.State != TaskCompleted || row.event.Attempt != 2 { + t.Fatalf("stale attempt changed final state: %+v", row.event) + } + } +} + +func TestClaudeWorkflowAgentRetryDoesNotReopenClosedWork(t *testing.T) { + for _, parent := range []bool{false, true} { + t.Run(fmt.Sprint("parent=", parent), func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "wf", AgentIndex: 1, State: TaskFailed, Attempt: 1, AttemptSet: true}) + if parent { + r.Handle(TaskProgressEvent{TaskID: "wf", State: TaskCompleted}) + } else { + r.Handle(TaskProgressEvent{TaskID: "wf", AgentIndex: 1, State: TaskCompleted, Attempt: 1, AttemptSet: true}) + } + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "wf", AgentIndex: 1, State: TaskRetrying, Attempt: 2, AttemptSet: true}) + if out.String() != before { + t.Fatal("retry reopened closed work: " + out.String()) + } + }) + } +} diff --git a/internal/runtime/event.go b/internal/runtime/event.go index 0b96bd93a0..3e43cdd352 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -205,6 +205,16 @@ type TaskProgressEvent struct { Detail string Blocked bool Cached bool + // Workflow attempts are one-based. Timestamps are producer epoch-ms + // metadata used only for lifecycle reconciliation, never usage accounting. + Attempt int + LastAttemptReason string + QueuedAt float64 + StartedAt float64 + AttemptSet bool + LastAttemptReasonSet bool + QueuedAtSet bool + StartedAtSet bool // Update is a task lifecycle patch; it retains prior tool context. // LabelSet/DetailSet apply to task and agent metadata; Phase/Tool/Blocked/ // Cached Set flags apply only to agent snapshots. Started is task-level. diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index 7da1559542..c081b98052 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -31,7 +31,12 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { previous := r.taskProgressSeen[key] parentKey := taskProgressKey{task: taskHash, run: runHash, agent: sha256.Sum256(nil)} parent := r.taskProgressSeen[parentKey].event - if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || terminalTaskState(previous.event.State)))) { + isAgent := e.AgentID != "" || e.AgentIndex > 0 + if isAgent && staleAgentSnapshot(e, previous.event) { + return + } + resumable := isAgent && previous.event.State == TaskFailed && agentExecutionAdvanced(e, previous.event) + if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || (terminalTaskState(previous.event.State) && !resumable)))) { return } // Sanitize before retaining metadata, not just before printing it. This @@ -45,6 +50,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { e.ToolSummary = r.progressText(e.ToolSummary, 160) e.Summary = r.progressText(e.Summary, 200) e.Detail = r.progressText(e.Detail, 200) + e.LastAttemptReason = r.progressText(e.LastAttemptReason, 60) e.State = TaskState(r.progressText(string(e.State), 40)) if !e.Started { old := previous.event @@ -134,6 +140,19 @@ func taskProgressMessage(e TaskProgressEvent) string { } msg += ")" } + if e.Attempt > 0 || e.LastAttemptReason != "" { + msg += " (" + if e.Attempt > 0 { + msg += fmt.Sprintf("attempt %d", e.Attempt) + } + if e.LastAttemptReason != "" { + if e.Attempt > 0 { + msg += "; " + } + msg += "retry: " + e.LastAttemptReason + } + msg += ")" + } if e.Summary != "" { msg += " — " + e.Summary } @@ -211,29 +230,75 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK // Error/blocked/cached metadata is state-relative: a transition drops omitted // transient values instead of describing a recovered agent as still blocked. func mergeAgentProgress(e *TaskProgressEvent, old TaskProgressEvent) { - if e.AgentID == "" { + advanced := agentExecutionAdvanced(*e, old) + if !e.AttemptSet { + e.Attempt = old.Attempt + e.AttemptSet = old.AttemptSet + } + if !e.LastAttemptReasonSet && !advanced { + e.LastAttemptReason = old.LastAttemptReason + } + if !e.QueuedAtSet && !advanced { + e.QueuedAt = old.QueuedAt + e.QueuedAtSet = old.QueuedAtSet + } + if !e.StartedAtSet && e.State != TaskQueued && !advanced { + e.StartedAt = old.StartedAt + e.StartedAtSet = old.StartedAtSet + } + if e.AgentID == "" && !advanced { e.AgentID = old.AgentID } if !e.PhaseSet && e.Phase == "" { e.Phase = old.Phase } - if !e.ToolNameSet && e.ToolName == "" { + if !e.ToolNameSet && e.ToolName == "" && !advanced { e.ToolName = old.ToolName } - if !e.ToolSummarySet && e.ToolSummary == "" && e.ToolName == old.ToolName { + if !e.ToolSummarySet && e.ToolSummary == "" && e.ToolName == old.ToolName && !advanced { e.ToolSummary = old.ToolSummary } - if !e.DetailSet && e.Detail == "" && e.State == old.State { + sameState := e.State == old.State && !advanced + if !e.DetailSet && e.Detail == "" && sameState { e.Detail = old.Detail } - if !e.BlockedSet && !e.Blocked && e.State == old.State { + if !e.BlockedSet && !e.Blocked && sameState { e.Blocked = old.Blocked } - if !e.CachedSet && !e.Cached && e.State == old.State { + if !e.CachedSet && !e.Cached && sameState { e.Cached = old.Cached } } +// agentExecutionAdvanced permits an intermediate failed attempt to resume, +// while completed/skipped tasks and terminal parent workflows remain closed. +// The producer can also emit a fresh queue while waiting out a quota limit. +func agentExecutionAdvanced(e, old TaskProgressEvent) bool { + if e.AttemptSet && e.Attempt > 1 && e.Attempt > old.Attempt { + return true + } + if e.StartedAtSet && (old.StartedAtSet && e.StartedAt > old.StartedAt || !old.StartedAtSet && old.State == TaskFailed) { + return true + } + return e.State == TaskQueued && e.QueuedAtSet && old.QueuedAtSet && e.QueuedAt > old.QueuedAt && (!old.StartedAtSet || e.QueuedAt > old.StartedAt) +} + +// staleAgentSnapshot rejects prior-attempt deliveries and a queued snapshot +// that predates the known execution. An index stays stable across attempts. +func staleAgentSnapshot(e, old TaskProgressEvent) bool { + if e.AttemptSet && old.AttemptSet && e.Attempt < old.Attempt { + return true + } + higherAttempt := e.AttemptSet && e.Attempt > old.Attempt + if old.QueuedAtSet && !old.StartedAtSet && !higherAttempt && ((e.QueuedAtSet && e.QueuedAt < old.QueuedAt) || (e.StartedAtSet && e.StartedAt < old.QueuedAt)) { + return true + } + if e.State == TaskQueued && e.QueuedAtSet && old.StartedAtSet && e.QueuedAt <= old.StartedAt && !higherAttempt { + return true + } + return e.StartedAtSet && old.StartedAtSet && e.StartedAt < old.StartedAt && !(e.AttemptSet && e.Attempt > old.Attempt) +} + func terminalTaskState(state TaskState) bool { return state == TaskCompleted || state == TaskFailed || state == TaskStopped || state == TaskSkipped } From a5dbc8de09a515a014d316cfd58481b24f6b7bb2 Mon Sep 17 00:00:00 2001 From: jctanner Date: Fri, 30 Oct 2026 11:04:22 -0400 Subject: [PATCH 05/16] fix(#8908): preserve sparse agent state and bound cache allocations Retain the producer state and optional skip metadata so display states are derived after sparse timing and attempt fields are reconciled. Preserve queued, retrying and skipped snapshots without inventing transitions, and accept fresh quota queues after sparse retry failures. Clone final normalized progress strings so short cached fields cannot retain oversized sanitizer buffers. Cover sparse transitions, closed workflows and retained heap with regressions. Signed-off-by: jctanner --- .../runtime/claude_sparse_lifecycle_test.go | 100 ++++++++++++++++++ internal/runtime/claude_task_progress.go | 6 +- .../runtime/claude_workflow_progress_test.go | 4 +- internal/runtime/event.go | 22 ++-- internal/runtime/progress_allocation_test.go | 45 ++++++++ internal/runtime/task_progress.go | 76 ++++++++++--- 6 files changed, 226 insertions(+), 27 deletions(-) create mode 100644 internal/runtime/claude_sparse_lifecycle_test.go create mode 100644 internal/runtime/progress_allocation_test.go diff --git a/internal/runtime/claude_sparse_lifecycle_test.go b/internal/runtime/claude_sparse_lifecycle_test.go new file mode 100644 index 0000000000..f2bb6155a0 --- /dev/null +++ b/internal/runtime/claude_sparse_lifecycle_test.go @@ -0,0 +1,100 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestClaudeWorkflowSparseLifecycle(t *testing.T) { + for _, tc := range []struct { + name, first, sparse string + want TaskState + }{ + {"queued", `"state":"start","queuedAt":100`, `"state":"start","tokens":20`, TaskQueued}, + {"retry", `"state":"start","startedAt":200,"attempt":2,"lastAttemptReason":"stalled"`, `"state":"start","tokens":20`, TaskRetrying}, + {"skipped", `"state":"error","skipped":true`, `"state":"error","tokens":20`, TaskSkipped}, + {"legacy fallback", `"state":"start"`, `"state":"start","tokens":20`, TaskRunning}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, fields := range []string{tc.first, tc.sparse, tc.sparse} { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,%s}]}`+"\n", fields) + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + } + if strings.Count(out.String(), "Task wf") != 1 { + t.Fatalf("sparse snapshot fabricated transition: %s", out.String()) + } + for _, row := range r.taskProgressSeen { + if row.event.State != tc.want { + t.Fatalf("state %s, want %s", row.event.State, tc.want) + } + } + }) + } +} + +func TestClaudeWorkflowSparseLifecycleTransitions(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, step := range []struct { + fields string + want TaskState + }{ + {`"state":"start","queuedAt":100`, TaskQueued}, + {`"state":"start","queuedAt":100,"tokens":20`, TaskQueued}, + {`"state":"start","startedAt":200,"attempt":1`, TaskRunning}, + {`"state":"progress","tokens":30`, TaskRunning}, + {`"state":"error","skipped":true`, TaskSkipped}, + {`"state":"error","tokens":40`, TaskSkipped}, + {`"state":"error","skipped":false`, TaskFailed}, + {`"state":"start","startedAt":300,"attempt":2,"lastAttemptReason":"throttled"`, TaskRetrying}, + {`"state":"start","tokens":50`, TaskRetrying}, + {`"state":"progress","tokens":60`, TaskRunning}, + {`"state":"error"`, TaskFailed}, // previous skipped flag must not leak + {`"state":"start","queuedAt":400`, TaskQueued}, // fresh quota queue drops old startedAt + {`"state":"start","tokens":70`, TaskQueued}, + {`"state":"start","startedAt":500,"attempt":2,"lastAttemptReason":""`, TaskRetrying}, + {`"state":"done"`, TaskCompleted}, + } { + raw := fmt.Sprintf(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,%s}]}`+"\n", step.fields) + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + for _, row := range r.taskProgressSeen { + if row.event.State != step.want { + t.Fatalf("%s: state %s, want %s; output: %s", step.fields, row.event.State, step.want, out.String()) + } + } + } +} + +func TestClaudeWorkflowSparseLifecycleClosedGuards(t *testing.T) { + for _, tc := range []struct{ name, terminal string }{ + {"parent", `{"type":"system","subtype":"task_notification","task_id":"wf","status":"completed"}`}, + {"completed agent", `{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done"}]}`}, + {"skipped agent", `{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"error","skipped":true}]}`}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + parse := func(raw string) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + parse(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","startedAt":100,"attempt":1}]}`) + parse(tc.terminal) + before := out.String() + parse(`{"type":"system","subtype":"task_progress","task_id":"wf","workflow_progress":[{"type":"workflow_agent","index":1,"state":"start","startedAt":200,"attempt":2}]}`) + if out.String() != before { + t.Fatalf("reopened closed work: %s", out.String()) + } + }) + } +} diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go index c4b40d605f..1b75eb0535 100644 --- a/internal/runtime/claude_task_progress.go +++ b/internal/runtime/claude_task_progress.go @@ -114,7 +114,7 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { if state == "" { continue } - event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, State: state} + event := TaskProgressEvent{TaskID: task.TaskID, RunID: task.RunID, AgentID: agent.AgentID, AgentIndex: agent.Index, State: state, AgentState: agent.State} if agent.QueuedAt != nil && *agent.QueuedAt >= 0 { event.QueuedAt = *agent.QueuedAt event.QueuedAtSet = true @@ -134,6 +134,10 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { event.LastAttemptReason = *agent.LastAttemptReason } } + if agent.Skipped != nil { + event.Skipped = *agent.Skipped + event.SkippedSet = true + } if agent.Label != nil { event.Label = *agent.Label event.LabelSet = true diff --git a/internal/runtime/claude_workflow_progress_test.go b/internal/runtime/claude_workflow_progress_test.go index 0281ac64cd..a383013043 100644 --- a/internal/runtime/claude_workflow_progress_test.go +++ b/internal/runtime/claude_workflow_progress_test.go @@ -98,8 +98,8 @@ func TestClaudeWorkflowProgressToleratesMalformedEntries(t *testing.T) { line := `{"type":"system","subtype":"task_progress","task_id":"task-one","run_id":"run-one","workflow_progress":[null,42,{"type":"workflow_phase","title":"Not started"},{"type":"workflow_agent","state":"start"},{"type":"workflow_agent","index":4,"state":"future-state"},{"type":"workflow_agent","index":3,"state":"done","label":"first","phaseTitle":"Read","lastToolName":"Read","lastToolSummary":"input.json"},{"type":"workflow_agent","agentId":"child","state":"start","queuedAt":1,"label":"second"}]}` got := decodeClaudeTaskProgress([]byte(line), "task_progress") want := []TaskProgressEvent{ - {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json", LabelSet: true, PhaseSet: true, ToolNameSet: true, ToolSummarySet: true}, - {TaskID: "task-one", RunID: "run-one", AgentID: "child", Label: "second", State: TaskQueued, LabelSet: true, QueuedAt: 1, QueuedAtSet: true}, + {TaskID: "task-one", RunID: "run-one", AgentIndex: 3, AgentState: "done", Label: "first", Phase: "Read", State: TaskCompleted, ToolName: "Read", ToolSummary: "input.json", LabelSet: true, PhaseSet: true, ToolNameSet: true, ToolSummarySet: true}, + {TaskID: "task-one", RunID: "run-one", AgentID: "child", AgentState: "start", Label: "second", State: TaskQueued, LabelSet: true, QueuedAt: 1, QueuedAtSet: true}, } if !reflect.DeepEqual(got, want) { t.Fatalf("got %+v, want %+v", got, want) diff --git a/internal/runtime/event.go b/internal/runtime/event.go index 3e43cdd352..a6771e8836 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -192,13 +192,19 @@ const ( // error/blocked/cached fields are state-relative: omitted values survive // repeated snapshots of the same state, but not a state transition. type TaskProgressEvent struct { - TaskID string - RunID string - AgentID string - AgentIndex int - Label string - Phase string - State TaskState + TaskID string + RunID string + AgentID string + AgentIndex int + Label string + Phase string + State TaskState + // AgentState preserves the Workflow producer's four-value lifecycle + // (start/progress/done/error). State is a per-snapshot approximation; + // renderers reconcile optional metadata before deriving display state. + AgentState string + Skipped bool + SkippedSet bool ToolName string ToolSummary string Summary string @@ -217,7 +223,7 @@ type TaskProgressEvent struct { StartedAtSet bool // Update is a task lifecycle patch; it retains prior tool context. // LabelSet/DetailSet apply to task and agent metadata; Phase/Tool/Blocked/ - // Cached Set flags apply only to agent snapshots. Started is task-level. + // Cached/Skipped Set flags apply only to agent snapshots. Started is task-level. Update bool LabelSet bool DetailSet bool diff --git a/internal/runtime/progress_allocation_test.go b/internal/runtime/progress_allocation_test.go new file mode 100644 index 0000000000..d7bb742c02 --- /dev/null +++ b/internal/runtime/progress_allocation_test.go @@ -0,0 +1,45 @@ +package runtime + +import ( + "bytes" + "fmt" + "runtime" + "strings" + "testing" +) + +func TestProgressCacheOwnsNormalizedStrings(t *testing.T) { + padded := strings.Repeat(" ", 1<<20) + "x" + runtime.GC() + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + check := func(s string) { + t.Helper() + if s != "x" { + t.Fatalf("unexpected normalized value %q", s) + } + } + check(taskProgressText(padded, 80)) + var out bytes.Buffer + r := newTestRenderer(&out) + for i := range 32 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), Label: padded, State: TaskRunning}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: fmt.Sprint(i), Label: "Hook", Subject: padded, Context: padded}) + } + for _, row := range r.taskProgressSeen { + check(row.event.Label) + } + for _, row := range r.statusProgressSeen { + check(row.subject) + check(row.context) + } + runtime.GC() + runtime.ReadMemStats(&after) + runtime.KeepAlive(r) + runtime.KeepAlive(padded) + // 32 rows retain 96 one-byte values. Allow ample GC/runtime noise but + // reject the roughly 96 MiB retained by padded backing allocations. + if after.HeapAlloc > before.HeapAlloc+(8<<20) { + t.Fatalf("tiny cached fields retained %d bytes", after.HeapAlloc-before.HeapAlloc) + } +} diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index c081b98052..4a289f049c 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -35,6 +35,9 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { if isAgent && staleAgentSnapshot(e, previous.event) { return } + if isAgent && e.AgentState != "" { + reconcileAgentLifecycle(&e, previous.event) + } resumable := isAgent && previous.event.State == TaskFailed && agentExecutionAdvanced(e, previous.event) if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || (terminalTaskState(previous.event.State) && !resumable)))) { return @@ -52,6 +55,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { e.Detail = r.progressText(e.Detail, 200) e.LastAttemptReason = r.progressText(e.LastAttemptReason, 60) e.State = TaskState(r.progressText(string(e.State), 40)) + e.AgentState = r.progressText(e.AgentState, 40) if !e.Started { old := previous.event if e.Label == "" && !e.LabelSet { @@ -231,20 +235,8 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK // transient values instead of describing a recovered agent as still blocked. func mergeAgentProgress(e *TaskProgressEvent, old TaskProgressEvent) { advanced := agentExecutionAdvanced(*e, old) - if !e.AttemptSet { - e.Attempt = old.Attempt - e.AttemptSet = old.AttemptSet - } - if !e.LastAttemptReasonSet && !advanced { - e.LastAttemptReason = old.LastAttemptReason - } - if !e.QueuedAtSet && !advanced { - e.QueuedAt = old.QueuedAt - e.QueuedAtSet = old.QueuedAtSet - } - if !e.StartedAtSet && e.State != TaskQueued && !advanced { - e.StartedAt = old.StartedAt - e.StartedAtSet = old.StartedAtSet + if e.AgentState == "" { + mergeAgentLifecycle(e, old, advanced) } if e.AgentID == "" && !advanced { e.AgentID = old.AgentID @@ -270,6 +262,56 @@ func mergeAgentProgress(e *TaskProgressEvent, old TaskProgressEvent) { } } +// reconcileAgentLifecycle merges presence-aware lifecycle metadata before +// deriving display state. Fresh executions do not inherit prior-attempt data. +func reconcileAgentLifecycle(e *TaskProgressEvent, old TaskProgressEvent) { + advanced := agentExecutionAdvanced(*e, old) + mergeAgentLifecycle(e, old, advanced) + if !e.SkippedSet && !advanced && e.AgentState == old.AgentState { + e.Skipped = old.Skipped + } + switch e.AgentState { + case "start": + switch { + case e.QueuedAtSet && !e.StartedAtSet: + e.State = TaskQueued + case e.StartedAtSet && e.Attempt > 1: + e.State = TaskRetrying + default: + e.State = TaskRunning + } + case "progress": + e.State = TaskRunning + case "done": + e.State = TaskCompleted + case "error": + e.State = TaskFailed + if e.Skipped { + e.State = TaskSkipped + } + } +} + +// mergeAgentLifecycle retains optional numeric/retry metadata within one +// execution; callers determine advancement before filling omitted fields. +func mergeAgentLifecycle(e *TaskProgressEvent, old TaskProgressEvent, advanced bool) { + if !e.AttemptSet { + e.Attempt = old.Attempt + e.AttemptSet = old.AttemptSet + } + if !e.LastAttemptReasonSet && !advanced { + e.LastAttemptReason = old.LastAttemptReason + } + if !e.QueuedAtSet && !advanced { + e.QueuedAt = old.QueuedAt + e.QueuedAtSet = old.QueuedAtSet + } + if !e.StartedAtSet && e.State != TaskQueued && !advanced { + e.StartedAt = old.StartedAt + e.StartedAtSet = old.StartedAtSet + } +} + // agentExecutionAdvanced permits an intermediate failed attempt to resume, // while completed/skipped tasks and terminal parent workflows remain closed. // The producer can also emit a fresh queue while waiting out a quota limit. @@ -280,7 +322,7 @@ func agentExecutionAdvanced(e, old TaskProgressEvent) bool { if e.StartedAtSet && (old.StartedAtSet && e.StartedAt > old.StartedAt || !old.StartedAtSet && old.State == TaskFailed) { return true } - return e.State == TaskQueued && e.QueuedAtSet && old.QueuedAtSet && e.QueuedAt > old.QueuedAt && (!old.StartedAtSet || e.QueuedAt > old.StartedAt) + return e.State == TaskQueued && e.QueuedAtSet && (!old.QueuedAtSet || e.QueuedAt > old.QueuedAt) && (!old.StartedAtSet || e.QueuedAt > old.StartedAt) } // staleAgentSnapshot rejects prior-attempt deliveries and a queued snapshot @@ -320,5 +362,7 @@ func taskProgressText(s string, limit int) string { if utf8.RuneCountInString(s) > limit { s = string([]rune(s)[:limit]) + "…" } - return s + // strings.Fields/Join can return a short slice of the sanitizer's large + // allocation. Cache only storage proportional to the bounded final value. + return strings.Clone(s) } From b0066f61e96701aa29525b8960d9c3ffbeef9f62 Mon Sep 17 00:00:00 2001 From: jctanner Date: Fri, 30 Oct 2026 11:51:38 -0400 Subject: [PATCH 06/16] fix(#8908): redact secrets reconstructed by progress cleanup Apply caller credential redaction to both raw and normalized progress fields before truncation and cache retention. ANSI removal and whitespace cleanup can otherwise reconstruct an opaque secret after its only literal redaction pass. Preserve raw literal masking and bounded owned allocations. Cover console output, CI notices, task fields and hook attribution caches with ANSI/OSC, whitespace, encoded-newline and long-secret regressions. Match normalized credential aliases in the progress-only CLI redactor, and suppress a field when raw and normalized passes mask different spans. Keep the original literal-only behavior for non-progress feedback. Signed-off-by: jctanner --- internal/cli/progress_redaction_test.go | 53 ++++++++++++++++ internal/cli/run.go | 27 ++++++-- internal/runtime/progress_redaction_test.go | 69 +++++++++++++++++++++ internal/runtime/renderer.go | 4 +- internal/runtime/task_progress.go | 41 +++++++++--- 5 files changed, 182 insertions(+), 12 deletions(-) create mode 100644 internal/cli/progress_redaction_test.go create mode 100644 internal/runtime/progress_redaction_test.go diff --git a/internal/cli/progress_redaction_test.go b/internal/cli/progress_redaction_test.go new file mode 100644 index 0000000000..52e0c5b4fc --- /dev/null +++ b/internal/cli/progress_redaction_test.go @@ -0,0 +1,53 @@ +package cli + +import ( + "bytes" + "strings" + "testing" + + agentruntime "github.com/fullsend-ai/fullsend/internal/runtime" + "github.com/fullsend-ai/fullsend/internal/security" + "github.com/fullsend-ai/fullsend/internal/ui" +) + +func TestRedactProgressSecretLiterals(t *testing.T) { + for _, tc := range []struct{ name, secret, input string }{ + {"split tab", "opaque\trunner credential", "opaque\trun\x1b[31mner credential"}, + {"split markers", "opaque::runner%0Acredential", "opaque:\x1b[31m:runner%0Acredential"}, + {"short normalized value", "opaque\x1b[31m", "opaque"}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + r := agentruntime.NewEventRenderer(ui.New(&out)) + r.RedactProgress = func(s string) string { return redactProgressSecretLiterals(s, map[string]string{"X_TOKEN": tc.secret}) } + r.Handle(agentruntime.TaskProgressEvent{TaskID: "wf", State: agentruntime.TaskRunning, Label: tc.input}) + if strings.Contains(out.String(), "opaque") || !strings.Contains(out.String(), "[REDACTED") { + t.Fatalf("normalized credential escaped: %q", out.String()) + } + }) + } + const longer = "opaque-prefix-shortsecret-tail" + env := map[string]string{"LONG_TOKEN": longer, "SHORT_TOKEN": "shortsecret", "EMPTY_TOKEN": "\x1b[31m\x1b[0m"} + var out bytes.Buffer + r := agentruntime.NewEventRenderer(ui.New(&out)) + r.RedactProgress = func(s string) string { return redactProgressSecretLiterals(s, env) } + r.Handle(agentruntime.TaskProgressEvent{TaskID: "wf", State: agentruntime.TaskRunning, Label: "opaque-prefix-\x1b[31mshortsecret-tail"}) + if strings.Contains(out.String(), "opaque") || strings.Contains(out.String(), "-tail") { + t.Fatalf("nested literal leaked: %q", out.String()) + } + // Empty normalized literals must not inject replacements everywhere. + if got := redactProgressSecretLiterals("ordinary", env); got != "ordinary" { + t.Fatalf("empty normalization matched text: %q", got) + } + t.Setenv("GH_WORKFLOW_TOKEN", "provider\tcredential-for-test") + if got := redactProgressSecretLiterals("provider credential-for-test", nil); strings.Contains(got, "provider") { + t.Fatalf("provider alias unredacted: %q", got) + } + const registered = "registered\tcredential-for-progress-test" + if !security.RegisterRuntimeSecret(registered) { + t.Fatal("register fake runtime secret") + } + if got := redactProgressSecretLiterals("registered credential-for-progress-test", nil); got != "***" { + t.Fatalf("registered alias unredacted: %q", got) + } +} diff --git a/internal/cli/run.go b/internal/cli/run.go index d66c617872..2c5334a737 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -2770,7 +2770,7 @@ func runAgent(ctx context.Context, agentName, fullsendDir, outputBase, targetRep toolSpans.runnerEnv = h.RunnerEnv renderer := agentruntime.NewEventRenderer(printer) renderer.RedactProgress = func(text string) string { - return redactSecretLiterals(text, h.RunnerEnv) + return redactProgressSecretLiterals(text, h.RunnerEnv) } var metrics agentruntime.RunMetrics hooksSettings := "" @@ -4312,6 +4312,15 @@ func preScriptLogResult(res prescript.Result, runnerEnv map[string]string) presc // (runner secrets among them). Unlike redactFeedback it runs no pattern // scan, so text that merely looks like a secret is left alone. func redactSecretLiterals(feedback string, runnerEnv map[string]string) string { + return redactSecretLiteralsWithNormalizer(feedback, runnerEnv, nil) +} + +// Progress cleanup can alter a secret itself, so mask both literal forms. +func redactProgressSecretLiterals(feedback string, runnerEnv map[string]string) string { + return redactSecretLiteralsWithNormalizer(feedback, runnerEnv, agentruntime.NormalizeProgressText) +} + +func redactSecretLiteralsWithNormalizer(feedback string, runnerEnv map[string]string, normalize func(string) string) string { // All exact literals are replaced in one pass, longest first, so a // value that is a substring of another never leaves part of the longer // one visible, whichever source each came from. envLiterals covers @@ -4322,9 +4331,19 @@ func redactSecretLiterals(feedback string, runnerEnv map[string]string) string { var literals []literal seen := map[string]bool{} add := func(value, mask string) { - if len(value) >= minRedactableSecretLen && !seen[value] { - seen[value] = true - literals = append(literals, literal{value, mask}) + if len(value) < minRedactableSecretLen { + return + } + values := []string{value} + if normalize != nil { + values = append(values, normalize(value)) + } + for _, value := range values { + // An eligible original may normalize to a short sensitive value. + if value != "" && !seen[value] { + seen[value] = true + literals = append(literals, literal{value, mask}) + } } } for _, l := range envLiterals(runnerEnv) { diff --git a/internal/runtime/progress_redaction_test.go b/internal/runtime/progress_redaction_test.go new file mode 100644 index 0000000000..0883d21f12 --- /dev/null +++ b/internal/runtime/progress_redaction_test.go @@ -0,0 +1,69 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestProgressCallerRedactionAfterCleanup(t *testing.T) { + for _, tc := range []struct{ name, secret, input string }{ + {"ANSI split", "opaque-runner-credential-for-test", "opaque-runner-\x1b[31mcredential-for-test"}, + {"OSC split", "opaque-runner-credential-for-test", "opaque-runner-\x1b]0;hidden\x07credential-for-test"}, + {"whitespace", "opaque runner credential for test", "opaque\t runner\n credential for test"}, + {"encoded whitespace", "opaque runner credential for test", "opaque%0Arunner%0Dcredential for test"}, + {"raw whitespace literal", "opaque\trunner credential for test", "opaque\trunner credential for test"}, + {"split whitespace literal", "opaque\trunner credential for test", "opaque\trun\x1b[31mner credential for test"}, + {"split rewritten markers", "opaque::runner%0Acredential", "opaque:\x1b[31m:runner%0Acredential"}, + {"before truncation", "opaque-" + strings.Repeat("long-credential", 30), "opaque-\x1b[31m" + strings.Repeat("long-credential", 30)}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + r.RedactProgress = func(s string) string { + return strings.ReplaceAll(strings.ReplaceAll(s, tc.secret, "[REDACTED]"), NormalizeProgressText(tc.secret), "[REDACTED]") + } + stderr := captureStderr(t, func() { + r.Handle(TaskProgressEvent{TaskID: "task", AgentIndex: 1, AgentID: tc.input, Label: tc.input, Phase: tc.input, State: TaskRunning, ToolName: tc.input, ToolSummary: tc.input, Summary: tc.input, Detail: tc.input, LastAttemptReason: tc.input}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "id", Label: tc.input, State: tc.input, Detail: tc.input, Subject: tc.input, Context: tc.input}) + }) + check := func(where, s string) { + t.Helper() + if strings.Contains(s, "opaque") || strings.Contains(s, "long-credential") { + t.Fatalf("secret exposed in %s: %q", where, s) + } + } + check("console", out.String()) + check("CI", stderr) + if !strings.Contains(out.String(), "[REDACTED]") || !strings.Contains(stderr, "[REDACTED]") { + t.Fatal("missing redaction marker") + } + for _, row := range r.taskProgressSeen { + check("task cache", fmt.Sprintf("%+v", row.event)) + } + for _, row := range r.statusProgressSeen { + check("status cache", fmt.Sprintf("%+v", row)) + } + }) + } +} + +func TestProgressCallerRedactionDifferentSpans(t *testing.T) { + const longer = "opaque-prefix-shortsecret-tail" + const shorter = "shortsecret" + redact := func(s string) string { return strings.NewReplacer(longer, "[LONG]", shorter, "[SHORT]").Replace(s) } + r := newTestRenderer(&bytes.Buffer{}) + r.RedactProgress = redact + // The raw pass masks the inner secret, the independent normalized pass + // sees the outer secret. Do not print the remnants of either candidate. + if got := r.progressText("context opaque-prefix-\x1b[31mshortsecret-tail", 160); got != "[REDACTED]" { + t.Fatalf("conflicting redaction left residual text: %q", got) + } + // A raw-only match must still protect a literal that cleanup would alter. + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "opaque\tcredential", "[REDACTED]") } + if got := r.progressText("opaque\tcredential", 160); got != "[REDACTED]" { + t.Fatalf("lost raw-only masking: %q", got) + } +} diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index b0a491be13..bd8598db08 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -14,7 +14,9 @@ import ( // types produce clean output boundaries. type EventRenderer struct { // RedactProgress removes caller-owned credential literals from progress - // metadata before normalization/truncation. Pattern and registered + // metadata before and after normalization, before truncation. The callback + // must match original and NormalizeProgressText-normalized literals and + // use display-safe replacement markers. Pattern and registered // runtime-secret redaction apply even when this callback is nil. RedactProgress func(string) string diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index 4a289f049c..ed8a19cb26 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -346,16 +346,36 @@ func terminalTaskState(state TaskState) bool { } func (r *EventRenderer) progressText(s string, limit int) string { - if r.RedactProgress != nil { - s = r.RedactProgress(s) - } - return taskProgressText(s, limit) + return redactProgressText(s, limit, r.RedactProgress) } -// Sanitize and redact complete fields before truncation, so an escape, CI -// command, or credential cannot be exposed by chopping off its suffix first. func taskProgressText(s string, limit int) string { - s = strings.Join(strings.Fields(sanitizeOutput(s)), " ") + return redactProgressText(s, limit, nil) +} + +// Redact complete raw literals before cleanup, then repeat after cleanup: +// removing ANSI and normalizing whitespace can reconstruct an opaque secret. +// Both passes precede truncation and cache retention. The caller's redactor +// uses display-safe replacement markers, such as [REDACTED] or ***. +func redactProgressText(s string, limit int, redact func(string) string) string { + normalized := NormalizeProgressText(s) + if redact != nil { + raw := redact(s) + cleanedRaw := NormalizeProgressText(raw) + cleaned := redact(normalized) + switch { + case raw != s && cleaned != normalized && cleanedRaw != cleaned: + // Different passes masked different spans (for example nested secrets). + // Neither candidate proves the other one's residual text is safe. + s = "[REDACTED]" + case cleaned != normalized: + s = cleaned + default: + s = cleanedRaw + } + } else { + s = normalized + } if result := progressRedactor.Scan(s); !result.Safe { s = result.Sanitized } @@ -366,3 +386,10 @@ func taskProgressText(s string, limit int) string { // allocation. Cache only storage proportional to the bounded final value. return strings.Clone(s) } + +// NormalizeProgressText applies the same cleanup to display text and caller +// credential literals. Redactors must match both original and normalized +// values, because cleanup can rewrite whitespace, escapes and CI markers. +func NormalizeProgressText(s string) string { + return strings.Join(strings.Fields(sanitizeOutput(s)), " ") +} From 528416da026b2def8fff134d505b6b4815f55b4d Mon Sep 17 00:00:00 2001 From: jctanner Date: Fri, 30 Oct 2026 17:31:04 -0400 Subject: [PATCH 07/16] fix(#8908): reject progress from superseded task runs Compare safely retained bounded run IDs in SDK opening order before mutating renderer identity or display state. Preserve the named watermark through anonymous restarts, promote only newer names, and keep late starts from exposing hidden generations or stealing run-less updates. Retain UTF-16 lexical ordering, hashed raw identity and bounded redacted metadata. Cover unseen/known late terminal and progress frames, anonymous promotion, late starts, Unicode order and unsafe ordering metadata. Signed-off-by: jctanner --- docs/runtimes/claude.md | 2 + internal/runtime/claude_pr_review_test.go | 8 +- .../runtime/claude_progress_review_test.go | 8 +- internal/runtime/claude_run_order_test.go | 133 ++++++++++++++++++ internal/runtime/renderer.go | 2 +- internal/runtime/task_progress.go | 114 +++++++++------ internal/runtime/task_progress_test.go | 6 +- 7 files changed, 221 insertions(+), 52 deletions(-) create mode 100644 internal/runtime/claude_run_order_test.go diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index a7f9903e7c..12721e4dd8 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -351,6 +351,8 @@ reopen a known terminal task or agent. Sparse agent snapshots retain known labels, phases and tool context. Error, blocked and cached metadata persists within a state; state changes clear omitted transient metadata. Explicit empty strings and false flags also clear their corresponding fields. +Run IDs follow the Agent SDK opening order; late frames from superseded +runs are ignored, so they cannot steal later updates without a run ID. Visibility belongs to each run: promoting its first late run ID preserves its hidden classification, while a distinct named run does not inherit an older run's visibility. Hook names and event attribution survive sparse diff --git a/internal/runtime/claude_pr_review_test.go b/internal/runtime/claude_pr_review_test.go index 5310e7c34d..fd1b5821f9 100644 --- a/internal/runtime/claude_pr_review_test.go +++ b/internal/runtime/claude_pr_review_test.go @@ -47,10 +47,10 @@ func TestClaudeReviewAgentCounterSnapshotRetainsContext(t *testing.T) { } func TestClaudeReviewDistinctRunDoesNotInheritHiddenParent(t *testing.T) { - stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"old","ambient":true,"description":"PRIVATE"} -{"type":"system","subtype":"task_progress","task_id":"one","run_id":"new","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"New worker"}]} -{"type":"system","subtype":"task_progress","task_id":"one","run_id":"new","description":"Visible new run"} -{"type":"system","subtype":"task_progress","task_id":"one","run_id":"old","description":"PRIVATE"} + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"r1","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r2","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"New worker"}]} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r2","description":"Visible new run"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r1","description":"PRIVATE"} ` var out bytes.Buffer r := newTestRenderer(&out) diff --git a/internal/runtime/claude_progress_review_test.go b/internal/runtime/claude_progress_review_test.go index 7010c02de6..0a80e41e10 100644 --- a/internal/runtime/claude_progress_review_test.go +++ b/internal/runtime/claude_progress_review_test.go @@ -109,10 +109,10 @@ func TestWorkflowReviewRunIDPromotionPreservesHiddenAndTerminal(t *testing.T) { func TestWorkflowReviewNewRunWithoutStartReceivesOptionalCompletion(t *testing.T) { var out bytes.Buffer r := newTestRenderer(&out) - stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"old","description":"Old"} -{"type":"system","subtype":"task_notification","task_id":"one","run_id":"old","status":"completed"} -{"type":"system","subtype":"task_progress","task_id":"one","run_id":"new","description":"New"} -{"type":"system","subtype":"task_progress","task_id":"one","run_id":"old","description":"LATE OLD"} + stream := `{"type":"system","subtype":"task_started","task_id":"one","run_id":"r1","description":"Old"} +{"type":"system","subtype":"task_notification","task_id":"one","run_id":"r1","status":"completed"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r2","description":"New"} +{"type":"system","subtype":"task_progress","task_id":"one","run_id":"r1","description":"LATE OLD"} {"type":"system","subtype":"task_notification","task_id":"one","status":"completed"} ` if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { diff --git a/internal/runtime/claude_run_order_test.go b/internal/runtime/claude_run_order_test.go new file mode 100644 index 0000000000..6ec9cded36 --- /dev/null +++ b/internal/runtime/claude_run_order_test.go @@ -0,0 +1,133 @@ +package runtime + +import ( + "bytes" + "strings" + "testing" +) + +func TestClaudeTaskLateUnseenRunCannotBecomeCurrent(t *testing.T) { + for _, late := range []string{ + `{"type":"system","subtype":"task_notification","task_id":"t1","run_id":"r1","status":"completed"}`, + `{"type":"system","subtype":"task_progress","task_id":"t1","run_id":"r1","description":"STALE"}`, + `{"type":"system","subtype":"task_updated","task_id":"t1","run_id":"r1","patch":{"description":"STALE","status":"failed"}}`, + `{"type":"system","subtype":"task_progress","task_id":"t1","run_id":"r1","workflow_progress":[{"type":"workflow_agent","index":1,"state":"done","label":"STALE"}]}`, + } { + t.Run(late, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + stream := `{"type":"system","subtype":"task_started","task_id":"t1","run_id":"r2","description":"Current"}` + "\n" + late + "\n" + `{"type":"system","subtype":"task_updated","task_id":"t1","patch":{"status":"failed"}}` + "\n" + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "completed") || strings.Contains(out.String(), "STALE") || !strings.HasSuffix(out.String(), "Task t1: Current — failed\n") || strings.Count(out.String(), "Task t1") != 2 { + t.Fatal("late run hijacked display: " + out.String()) + } + }) + } +} + +func TestTaskRunOrderForwardAndAnonymousWatermark(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r2", Started: true, State: TaskRunning, Label: "Prior"}) + r.Handle(TaskProgressEvent{TaskID: "one", Started: true, State: TaskRunning, Label: "Anonymous"}) + before := out.String() + for _, e := range []TaskProgressEvent{ + {TaskID: "one", RunID: "r1", State: TaskCompleted}, + {TaskID: "one", RunID: "r2", State: TaskCompleted}, + {TaskID: "one", RunID: "r1", Started: true, State: TaskRunning, Label: "STALE"}, + {TaskID: "one", RunID: "r2", Started: true, State: TaskRunning, Label: "STALE"}, + } { + r.Handle(e) + } + if out.String() != before { + t.Fatal("older run took anonymous generation: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r3", State: TaskRunning, ToolName: "Bash"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskCompleted, Update: true}) + if !strings.HasSuffix(out.String(), "Anonymous — completed (tool: Bash)\n") { + t.Fatal("newer name lost current context: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r4", State: TaskRunning, Label: "Forward"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Forward — failed\n") { + t.Fatal("newer unseen name not adopted: " + out.String()) + } +} + +func TestTaskRunOrderPlainStringAndKnownOldRuns(t *testing.T) { + for _, tc := range []struct{ old, current string }{ + {"r1", "r2"}, {"r10", "r2"}, {"r", "r1"}, {"\U00010000", "\ue000"}, + } { + t.Run(tc.current, func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.old, Started: true, State: TaskRunning, Label: "Old"}) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.current, Started: true, State: TaskRunning, Label: "Current"}) + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.old, State: TaskCompleted}) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: tc.old, State: TaskRunning, Label: "STALE"}) + if out.String() != before { + t.Fatal("known superseded run rendered: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Current — failed\n") { + t.Fatal(out.String()) + } + }) + } +} + +func TestTaskRunOrderUnsafeIDsNeedExplicitStart(t *testing.T) { + for _, id := range []string{"opaque-run-order-secret-for-test", strings.Repeat("z", maxTaskRunOrderBytes+1), "bad\nrun", string([]byte{0xff})} { + t.Run(id[:min(len(id), 24)], func(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "opaque-run-order-secret-for-test", "[REDACTED]") } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r2", Started: true, State: TaskRunning, Label: "Current"}) + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, State: TaskCompleted}) + if out.String() != before { + t.Fatal("unorderable unseen frame replaced current: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "Explicit"}) + for _, run := range r.taskProgressRuns { + if run.order != "" { + t.Fatalf("retained unsafe order text: %q", run.order) + } + } + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "r3", State: TaskCompleted}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Explicit — failed\n") { + t.Fatal("unorderable state stole implicit updates: " + out.String()) + } + r.Handle(TaskProgressEvent{TaskID: "one", Started: true, Hidden: true, State: TaskRunning, Label: "PRIVATE"}) + before = out.String() + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "STALE"}) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "PRIVATE"}) + if out.String() != before { + t.Fatal("unorderable prior name exposed anonymous generation: " + out.String()) + } + + }) + } +} + +func TestClaudeTaskLateStartCannotExposeAnonymousRestart(t *testing.T) { + stream := `{"type":"system","subtype":"task_started","task_id":"t1","run_id":"r2","description":"Visible prior"} +{"type":"system","subtype":"task_started","task_id":"t1","ambient":true,"description":"PRIVATE"} +{"type":"system","subtype":"task_started","task_id":"t1","run_id":"r2","description":"STALE"} +{"type":"system","subtype":"task_progress","task_id":"t1","description":"PRIVATE"} +{"type":"system","subtype":"task_progress","task_id":"t1","run_id":"r3","description":"PRIVATE"} +{"type":"system","subtype":"task_notification","task_id":"t1","status":"completed"} +` + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Contains(out.String(), "STALE") || strings.Contains(out.String(), "PRIVATE") || strings.Count(out.String(), "Task t1") != 1 { + t.Fatal("old start exposed anonymous run: " + out.String()) + } +} diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index bd8598db08..5eacbbf236 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -26,7 +26,7 @@ type EventRenderer struct { inThinking bool seenInit bool taskProgressSeen map[taskProgressKey]taskProgressDisplay - taskProgressRuns map[[sha256.Size]byte][sha256.Size]byte + taskProgressRuns map[[sha256.Size]byte]taskProgressRun statusProgressSeen map[[sha256.Size]byte]statusProgressDisplay } diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index ed8a19cb26..6467f4c5f5 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -3,7 +3,9 @@ package runtime import ( "crypto/sha256" "fmt" + "slices" "strings" + "unicode/utf16" "unicode/utf8" ) @@ -11,6 +13,17 @@ import ( // Hashing IDs also avoids retaining arbitrarily large sandbox strings as keys. const maxTaskProgressEntries = 1024 +// Retain ordering text only when bounded and unchanged by sanitization and +// credential redaction. Non-comparable IDs cannot implicitly replace a run. +const maxTaskRunOrderBytes = 1024 + +type taskProgressRun struct { + watermark [sha256.Size]byte + hash [sha256.Size]byte + order string + named bool +} + type taskProgressKey struct { task, run, agent [sha256.Size]byte index int @@ -25,7 +38,10 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { if e.TaskID == "" || (e.State == "" && !e.Update) { return } - key := r.taskProgressIdentity(&e) + key, accepted := r.taskProgressIdentity(&e) + if !accepted { + return + } taskHash := key.task runHash := key.run previous := r.taskProgressSeen[key] @@ -82,13 +98,6 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { if e.State != "" && e.State != TaskRunning { e.Summary = "" } - if len(r.taskProgressSeen) >= maxTaskProgressEntries { - clear(r.taskProgressSeen) - clear(r.taskProgressRuns) - } - if _, exists := r.taskProgressRuns[taskHash]; !exists { - r.taskProgressRuns[taskHash] = runHash - } if e.Hidden { r.taskProgressSeen[key] = taskProgressDisplay{event: e} return @@ -166,58 +175,67 @@ func taskProgressMessage(e TaskProgressEvent) string { return sanitizeOutput(msg) } -// Resolve optional run IDs without splitting a task when its first run ID -// arrives late. An explicit new start resets its run's agent rows too. Known -// older runs remain addressable, but cannot steal later run-less updates. -func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressKey { +// Resolve optional run IDs. SDK 0.3.314 orders a task's run IDs by plain +// JavaScript string comparison. Reject superseded frames before changing any +// identity, visibility or dedup state. Anonymous restarts retain the previous +// named watermark until a newer name adopts the anonymous generation's rows. +func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgressKey, bool) { if r.taskProgressSeen == nil { r.taskProgressSeen = make(map[taskProgressKey]taskProgressDisplay) - r.taskProgressRuns = make(map[[sha256.Size]byte][sha256.Size]byte) + r.taskProgressRuns = make(map[[sha256.Size]byte]taskProgressRun) + } + if len(r.taskProgressSeen) >= maxTaskProgressEntries { + clear(r.taskProgressSeen) + clear(r.taskProgressRuns) } task := sha256.Sum256([]byte(e.TaskID)) - run := r.taskProgressRuns[task] + current := r.taskProgressRuns[task] + run := current.hash zero := [sha256.Size]byte{} + order := "" if e.RunID != "" { run = sha256.Sum256([]byte(e.RunID)) + // Even an unorderable name cannot reclaim a newer anonymous run when + // its hash identifies the prior named generation exactly. + if current.named && current.hash == zero && run == current.watermark { + return taskProgressKey{}, false + } + order = r.taskRunOrder(e.RunID) + if current.named && run != current.hash { + comparable := order != "" && current.order != "" + comparison := compareTaskRunIDs(order, current.order) + if (!e.Started && (!comparable || comparison <= 0)) || + (e.Started && comparable && (comparison < 0 || (current.hash == zero && comparison == 0))) { + return taskProgressKey{}, false + } + } } if e.Started { if e.RunID == "" { run = zero + current.hash = zero + } else { + current = taskProgressRun{hash: run, watermark: run, order: order, named: true} } for key := range r.taskProgressSeen { if key.task == task && key.run == run { delete(r.taskProgressSeen, key) } } - r.taskProgressRuns[task] = run - } else if e.RunID != "" { - current := r.taskProgressRuns[task] - if current != run { - known := false - for key := range r.taskProgressSeen { - if key.task == task && key.run == run { - known = true - break - } - } - if !known { - if current == zero { - // Keep old named runs when an anonymous restart is active. Only a - // genuinely unseen run may adopt the anonymous generation's rows. - for key, display := range r.taskProgressSeen { - if key.task == task && key.run == zero { - delete(r.taskProgressSeen, key) - key.run = run - r.taskProgressSeen[key] = display - } - } + } else if e.RunID != "" && current.hash != run { + if current.hash == zero { + // The first late ID promotes only this anonymous generation's rows. + for key, display := range r.taskProgressSeen { + if key.task == task && key.run == zero { + delete(r.taskProgressSeen, key) + key.run = run + r.taskProgressSeen[key] = display } - // Distinct named runs have independent visibility. Only promotion of - // anonymous rows above carries visibility within the same generation. - r.taskProgressRuns[task] = run } } + current = taskProgressRun{hash: run, watermark: run, order: order, named: true} } + r.taskProgressRuns[task] = current // Workflow entries are keyed by type:index in the producer. agentId is // absent while queued and can also be omitted in subsequent snapshots. agent := sha256.Sum256(nil) @@ -226,7 +244,23 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) taskProgressK index = 0 agent = sha256.Sum256([]byte(e.AgentID)) } - return taskProgressKey{task: task, run: run, agent: agent, index: index} + return taskProgressKey{task: task, run: run, agent: agent, index: index}, true +} + +func (r *EventRenderer) taskRunOrder(id string) string { + if len(id) > maxTaskRunOrderBytes || !utf8.ValidString(id) { + return "" + } + clean := r.progressText(id, maxTaskRunOrderBytes) + if clean != id { + return "" + } + return clean +} + +func compareTaskRunIDs(a, b string) int { + // Go compares UTF-8 bytes; the SDK's producer uses UTF-16 code units. + return slices.Compare(utf16.Encode([]rune(a)), utf16.Encode([]rune(b))) } // mergeAgentProgress retains already-sanitized optional metadata when a diff --git a/internal/runtime/task_progress_test.go b/internal/runtime/task_progress_test.go index a19be7dbee..63a4e8d99b 100644 --- a/internal/runtime/task_progress_test.go +++ b/internal/runtime/task_progress_test.go @@ -39,7 +39,7 @@ func TestTaskProgressRendererIdentityAndLifecycle(t *testing.T) { {TaskID: "one", AgentID: "different", Label: "review", State: TaskRunning}, {TaskID: "one", AgentIndex: 1, Label: "review", State: TaskQueued}, {TaskID: "one", AgentIndex: 2, Label: "review", State: TaskQueued}, - {TaskID: "one", AgentID: "worker", RunID: "another-run", Label: "review", State: TaskRunning}, + {TaskID: "one", AgentID: "worker", RunID: "second-run", Label: "review", State: TaskRunning}, {TaskID: "one", State: TaskFailed}, {TaskID: "two", State: TaskStopped}, } { @@ -163,11 +163,11 @@ func TestTaskProgressIndexIdentityScopesAndIDFallback(t *testing.T) { if len(r.taskProgressSeen) != 7 || strings.Count(out.String(), "— running") != 7 { t.Fatal("distinct slots/tasks/runs/fallback IDs collapsed: " + out.String()) } - r.Handle(TaskProgressEvent{TaskID: "one", RunID: "first", AgentIndex: 1, AgentID: "learned", Label: "Work", State: TaskRunning}) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, AgentID: "learned", Label: "Work", State: TaskRunning}) if len(r.taskProgressSeen) != 7 || strings.Count(out.String(), "— running") != 7 { t.Fatal("ID-only indexed change created another row") } - r.Handle(TaskProgressEvent{TaskID: "one", RunID: "first", AgentIndex: 1, Label: "Work", State: TaskCompleted}) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, Label: "Work", State: TaskCompleted}) if !strings.Contains(out.String(), "agent #1 (learned): Work — completed") { t.Fatal("known display ID was lost: " + out.String()) } From acf12545c3269a5072cc00c444a5f9393808f3ee Mon Sep 17 00:00:00 2001 From: jctanner Date: Fri, 30 Oct 2026 19:39:46 -0400 Subject: [PATCH 08/16] fix(#8908): retain workflow controls and sparse task metadata Replace clear-all display cache eviction with bounded row admission, retiring superseded and terminal agent rows while preserving task visibility, terminal state and run watermarks outside row storage. Large unchanged snapshots no longer flood console or CI annotations. Retain omitted task tool and summary fields with explicit presence flags; empty strings clear them. Preserve summaries across pause/resume without displaying them while paused, and discard them on terminal/new runs. Cover large snapshots, limits, lifecycle cleanup and sparse metadata. Signed-off-by: jctanner --- docs/runtimes/claude.md | 19 +++- internal/runtime/claude_task_cache_test.go | 111 +++++++++++++++++++ internal/runtime/claude_task_progress.go | 18 ++- internal/runtime/event.go | 6 +- internal/runtime/task_progress.go | 71 ++++++++---- internal/runtime/task_progress_cache.go | 42 +++++++ internal/runtime/task_progress_cache_test.go | 92 +++++++++++++++ internal/runtime/task_progress_test.go | 10 +- 8 files changed, 331 insertions(+), 38 deletions(-) create mode 100644 internal/runtime/claude_task_cache_test.go create mode 100644 internal/runtime/task_progress_cache.go create mode 100644 internal/runtime/task_progress_cache_test.go diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index 12721e4dd8..5f7bc660b6 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -345,12 +345,25 @@ available tool names/context. For example: Unchanged snapshots and counter-only updates do not repeat the same display line. Text is sanitized, credential-redacted, and bounded before display or retention in the bounded display cache. Concurrent tasks and agents retain -separate identities. Partial lifecycle patches retain known task labels and -state; explicit starts can reset an identity. Late running snapshots do not -reopen a known terminal task or agent. Sparse agent snapshots retain known +separate identities. Task tool/status fields retain omitted values; +explicit empty strings clear them. Pausing hides the last summary until the +task resumes; a terminal state or new run clears it. Partial lifecycle +patches retain known task labels and state; explicit starts can reset an +identity. Late running snapshots do not reopen known terminal tasks or +agents. Sparse agent snapshots retain known labels, phases and tool context. Error, blocked and cached metadata persists within a state; state changes clear omitted transient metadata. Explicit empty strings and false flags also clear their corresponding fields. + +Task visibility, terminal state and run watermarks are retained separately +from agent display rows. New runs and terminal task states retire old agent +rows. Tracking admits up to 1,024 task identities and 1,024 agents per task, +with a shared 16,384-row threshold for admitting new agent rows. At a limit, +new identities or agent rows are suppressed; tracked rows and task guards +remain. +Agent-row capacity becomes available when tasks finish or open new runs. +Task-identity slots stay reserved for the renderer's lifetime. + Run IDs follow the Agent SDK opening order; late frames from superseded runs are ignored, so they cannot steal later updates without a run ID. Visibility belongs to each run: promoting its first late run ID preserves diff --git a/internal/runtime/claude_task_cache_test.go b/internal/runtime/claude_task_cache_test.go new file mode 100644 index 0000000000..1184463923 --- /dev/null +++ b/internal/runtime/claude_task_cache_test.go @@ -0,0 +1,111 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" + "testing" +) + +func TestClaudeTaskSparseToolAndSummary(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for _, fields := range []string{ + `"description":"Build","last_tool_name":"Bash","summary":"Running tests"`, + `"description":"Build","usage":{"total_tokens":20,"tool_uses":1}`, + `"usage":{"total_tokens":30,"tool_uses":1}`, + `"description":"Build","last_tool_name":null,"summary":null`, + } { + raw := `{"type":"system","subtype":"task_progress","task_id":"one",` + fields + "}\n" + if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { + t.Fatal(err) + } + } + if strings.Count(out.String(), "Task one") != 1 || !strings.Contains(out.String(), "tool: Bash") || !strings.Contains(out.String(), "Running tests") { + t.Fatal("sparse task erased progress: " + out.String()) + } + for _, row := range r.taskProgressSeen { + if row.event.ToolName != "Bash" || row.event.Summary != "Running tests" { + t.Fatalf("sparse cache erased metadata: %+v", row.event) + } + } +} + +func TestClaudeWorkflowLargeSnapshotsDoNotReprint(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + parse := func(raw string) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + frame := func(task string, count int) string { + entries := make([]map[string]any, count) + for i := range entries { + entries[i] = map[string]any{"type": "workflow_agent", "index": i + 1, "state": "progress", "label": "Worker"} + } + raw, err := json.Marshal(map[string]any{"type": "system", "subtype": "task_progress", "task_id": task, "run_id": "r2", "workflow_progress": entries}) + if err != nil { + t.Fatal(err) + } + return string(raw) + } + a, b := frame("one", 1000), frame("two", 500) + stderr := captureStderr(t, func() { + parse(`{"type":"system","subtype":"task_started","task_id":"hidden","ambient":true,"description":"PRIVATE"}`) + for _, task := range []string{"one", "two"} { + parse(fmt.Sprintf(`{"type":"system","subtype":"task_started","task_id":%q,"run_id":"r2","description":%q}`, task, task)) + } + for range 20 { + parse(a) + parse(b) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"hidden","description":"PRIVATE"}`) + parse(`{"type":"system","subtype":"task_notification","task_id":"one","run_id":"r1","status":"completed"}`) + }) + if got := strings.Count(out.String(), " / agent #"); got != 1500 { + t.Fatalf("unchanged snapshots printed %d agent lines, want1500", got) + } + if strings.Count(stderr, "::notice::") != 1502 || strings.Contains(out.String(), "PRIVATE") || strings.Contains(out.String(), "completed") { + t.Fatal("cache pressure lost dedup/hidden/run guards") + } +} + +func TestClaudeTaskExplicitClearsAndPauseResume(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + parse := func(raw string) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + parse(`{"type":"system","subtype":"task_progress","task_id":"one","description":"Build","last_tool_name":"Bash","summary":"Running tests"}`) + parse(`{"type":"system","subtype":"task_progress","task_id":"one","description":"Renamed","last_tool_name":{},"summary":42}`) + if !strings.HasSuffix(out.String(), "Renamed — running (tool: Bash) — Running tests\n") { + t.Fatal("malformed optional fields erased context: " + out.String()) + } + parse(`{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"paused"}}`) + if !strings.HasSuffix(out.String(), "Renamed — paused (tool: Bash)\n") { + t.Fatal("paused task displayed active summary") + } + parse(`{"type":"system","subtype":"task_updated","task_id":"one","patch":{"status":"running"}}`) + if !strings.HasSuffix(out.String(), "Renamed — running (tool: Bash) — Running tests\n") { + t.Fatal("resume lost once-per-change status") + } + parse(`{"type":"system","subtype":"task_progress","task_id":"one","summary":""}`) + parse(`{"type":"system","subtype":"task_progress","task_id":"one","last_tool_name":""}`) + before := out.String() + parse(`{"type":"system","subtype":"task_progress","task_id":"one","description":"Renamed","usage":{"total_tokens":30}}`) + if out.String() != before || !strings.HasSuffix(before, "Renamed — running\n") { + t.Fatal("empty fields not retained across sparse snapshot: " + out.String()) + } + parse(`{"type":"system","subtype":"task_notification","task_id":"one","status":"completed","summary":"PRIVATE result"}`) + parse(`{"type":"system","subtype":"task_started","task_id":"one","run_id":"r2","description":"Fresh"}`) + if strings.Contains(out.String(), "PRIVATE") || !strings.HasSuffix(out.String(), "Fresh — running\n") { + t.Fatal("new generation inherited old context/result: " + out.String()) + } +} diff --git a/internal/runtime/claude_task_progress.go b/internal/runtime/claude_task_progress.go index 1b75eb0535..2df621bc1b 100644 --- a/internal/runtime/claude_task_progress.go +++ b/internal/runtime/claude_task_progress.go @@ -12,7 +12,7 @@ type claudeTaskProgress struct { RunID string `json:"run_id"` Description string `json:"description"` Status string `json:"status"` - LastToolName string `json:"last_tool_name"` + LastToolName json.RawMessage `json:"last_tool_name"` Summary json.RawMessage `json:"summary"` Reason string `json:"reason"` Ambient bool `json:"ambient"` @@ -56,8 +56,8 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { event.Hidden = task.Ambient || task.SkipTranscript case "task_progress": event.State = TaskRunning - event.ToolName = task.LastToolName - _ = json.Unmarshal(task.Summary, &event.Summary) + event.ToolName, event.ToolNameSet = claudeProgressString(task.LastToolName) + event.Summary, event.SummarySet = claudeProgressString(task.Summary) case "task_updated": var patch struct { Status *string `json:"status"` @@ -94,7 +94,7 @@ func decodeClaudeTaskProgress(line []byte, subtype string) []TaskProgressEvent { return nil } var events []TaskProgressEvent - useful := event.LabelSet || event.DetailSet || event.Detail != "" || event.ToolName != "" || event.Summary != "" + useful := event.ToolNameSet || event.SummarySet || event.LabelSet || event.DetailSet || event.Detail != "" || event.ToolName != "" || event.Summary != "" if (event.State != "" || useful) && (subtype != "task_progress" || task.Description != "" || useful) { events = append(events, event) } @@ -216,3 +216,13 @@ func claudeTaskState(state string) TaskState { return "" } } + +// claudeProgressString treats null/malformed metadata as absent; empty strings +// clear prior progress without discarding the rest of a valid snapshot. +func claudeProgressString(raw json.RawMessage) (string, bool) { + var value *string + if json.Unmarshal(raw, &value) != nil || value == nil { + return "", false + } + return *value, true +} diff --git a/internal/runtime/event.go b/internal/runtime/event.go index a6771e8836..1e0a7d9bce 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -222,13 +222,15 @@ type TaskProgressEvent struct { QueuedAtSet bool StartedAtSet bool // Update is a task lifecycle patch; it retains prior tool context. - // LabelSet/DetailSet apply to task and agent metadata; Phase/Tool/Blocked/ - // Cached/Skipped Set flags apply only to agent snapshots. Started is task-level. + // Label/Detail/ToolName/ToolSummary Set flags apply to task and agent + // metadata; SummarySet applies to task snapshots. Phase/Blocked/Cached/ + // Skipped Set flags apply only to agents. Started is task-level. Update bool LabelSet bool DetailSet bool PhaseSet bool ToolNameSet bool + SummarySet bool ToolSummarySet bool BlockedSet bool CachedSet bool diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress.go index 6467f4c5f5..214eacc0bd 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress.go @@ -13,6 +13,11 @@ import ( // Hashing IDs also avoids retaining arbitrarily large sandbox strings as keys. const maxTaskProgressEntries = 1024 +// Task controls outlive row retention. Overflow rows/tasks are not admitted; +// already tracked state is never flushed by an oversized snapshot. +const maxTaskProgressAgentsPerTask = 1024 +const maxTaskProgressRows = 16 * 1024 + // Retain ordering text only when bounded and unchanged by sanitization and // credential redaction. Non-comparable IDs cannot implicitly replace a run. const maxTaskRunOrderBytes = 1024 @@ -22,6 +27,8 @@ type taskProgressRun struct { hash [sha256.Size]byte order string named bool + agents int + parent taskProgressDisplay } type taskProgressKey struct { @@ -43,11 +50,17 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { return } taskHash := key.task - runHash := key.run + current := r.taskProgressRuns[taskHash] previous := r.taskProgressSeen[key] - parentKey := taskProgressKey{task: taskHash, run: runHash, agent: sha256.Sum256(nil)} - parent := r.taskProgressSeen[parentKey].event + parent := current.parent.event isAgent := e.AgentID != "" || e.AgentIndex > 0 + if !isAgent { + previous = current.parent + } + // Parent lifecycle/visibility lives outside the agent dedup row budget. + if isAgent && terminalTaskState(parent.State) { + return + } if isAgent && staleAgentSnapshot(e, previous.event) { return } @@ -58,6 +71,15 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || (terminalTaskState(previous.event.State) && !resumable)))) { return } + if isAgent { + if _, exists := r.taskProgressSeen[key]; !exists { + if current.agents >= maxTaskProgressAgentsPerTask || len(r.taskProgressSeen) >= maxTaskProgressRows { + return + } + current.agents++ + r.taskProgressRuns[taskHash] = current + } + } // Sanitize before retaining metadata, not just before printing it. This // cache contains bounded display fields and hashed raw identities only. e.TaskID = r.progressText(e.TaskID, 80) @@ -80,26 +102,23 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { if e.State == "" { e.State = old.State } - if e.Update { - e.ToolName = old.ToolName - e.ToolSummary = old.ToolSummary - e.Summary = old.Summary - if !e.DetailSet { - e.Detail = old.Detail - } + if e.Update && !e.DetailSet { + e.Detail = old.Detail } if e.AgentID != "" || e.AgentIndex > 0 { mergeAgentProgress(&e, old) + } else { + mergeTaskProgress(&e, old) } if e.RunID == "" { e.RunID = old.RunID } } - if e.State != "" && e.State != TaskRunning { + if terminalTaskState(e.State) || (isAgent && e.State != "" && e.State != TaskRunning) { e.Summary = "" } if e.Hidden { - r.taskProgressSeen[key] = taskProgressDisplay{event: e} + r.storeTaskProgress(key, taskProgressDisplay{event: e}, isAgent) return } msg := taskProgressMessage(e) @@ -111,7 +130,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { comparison = taskProgressMessage(indexed) } fingerprint := sha256.Sum256([]byte(comparison)) - r.taskProgressSeen[key] = taskProgressDisplay{event: e, fingerprint: fingerprint} + r.storeTaskProgress(key, taskProgressDisplay{event: e, fingerprint: fingerprint}, isAgent) if previous.fingerprint == fingerprint { return } @@ -166,7 +185,7 @@ func taskProgressMessage(e TaskProgressEvent) string { } msg += ")" } - if e.Summary != "" { + if e.Summary != "" && e.State == TaskRunning { msg += " — " + e.Summary } if e.Detail != "" { @@ -184,11 +203,10 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgress r.taskProgressSeen = make(map[taskProgressKey]taskProgressDisplay) r.taskProgressRuns = make(map[[sha256.Size]byte]taskProgressRun) } - if len(r.taskProgressSeen) >= maxTaskProgressEntries { - clear(r.taskProgressSeen) - clear(r.taskProgressRuns) - } task := sha256.Sum256([]byte(e.TaskID)) + if _, exists := r.taskProgressRuns[task]; !exists && len(r.taskProgressRuns) >= maxTaskProgressEntries { + return taskProgressKey{}, false + } current := r.taskProgressRuns[task] run := current.hash zero := [sha256.Size]byte{} @@ -211,17 +229,15 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgress } } if e.Started { + r.retireTaskProgressRows(task, false) + current.parent = taskProgressDisplay{} + current.agents = 0 if e.RunID == "" { run = zero current.hash = zero } else { current = taskProgressRun{hash: run, watermark: run, order: order, named: true} } - for key := range r.taskProgressSeen { - if key.task == task && key.run == run { - delete(r.taskProgressSeen, key) - } - } } else if e.RunID != "" && current.hash != run { if current.hash == zero { // The first late ID promotes only this anonymous generation's rows. @@ -232,8 +248,15 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgress r.taskProgressSeen[key] = display } } + } else { + r.retireTaskProgressRows(task, false) + current.parent = taskProgressDisplay{} + current.agents = 0 } - current = taskProgressRun{hash: run, watermark: run, order: order, named: true} + current.hash = run + current.watermark = run + current.order = order + current.named = true } r.taskProgressRuns[task] = current // Workflow entries are keyed by type:index in the producer. agentId is diff --git a/internal/runtime/task_progress_cache.go b/internal/runtime/task_progress_cache.go new file mode 100644 index 0000000000..9b9df67e3f --- /dev/null +++ b/internal/runtime/task_progress_cache.go @@ -0,0 +1,42 @@ +package runtime + +import "crypto/sha256" + +// retireTaskProgressRows removes rows without discarding authoritative run and +// visibility control. A completed task needs no agent rows: all subsequent +// agent frames are blocked by its retained terminal parent state. +func (r *EventRenderer) retireTaskProgressRows(task [sha256.Size]byte, agentsOnly bool) { + parentAgent := sha256.Sum256(nil) + for key := range r.taskProgressSeen { + if key.task == task && (!agentsOnly || key.index > 0 || key.agent != parentAgent) { + delete(r.taskProgressSeen, key) + } + } +} + +func (r *EventRenderer) storeTaskProgress(key taskProgressKey, display taskProgressDisplay, isAgent bool) { + if !isAgent { + control := r.taskProgressRuns[key.task] + control.parent = display + if terminalTaskState(display.event.State) && control.agents > 0 { + r.retireTaskProgressRows(key.task, true) + control.agents = 0 + } + r.taskProgressRuns[key.task] = control + } + r.taskProgressSeen[key] = display +} + +// mergeTaskProgress retains status emitted only on change (not on every usage +// snapshot). Empty supplied fields clear; omitted or malformed fields retain. +func mergeTaskProgress(e *TaskProgressEvent, old TaskProgressEvent) { + if !e.ToolNameSet && e.ToolName == "" { + e.ToolName = old.ToolName + } + if !e.ToolSummarySet && e.ToolSummary == "" && e.ToolName == old.ToolName { + e.ToolSummary = old.ToolSummary + } + if !e.SummarySet && e.Summary == "" { + e.Summary = old.Summary + } +} diff --git a/internal/runtime/task_progress_cache_test.go b/internal/runtime/task_progress_cache_test.go new file mode 100644 index 0000000000..a24e40e1ee --- /dev/null +++ b/internal/runtime/task_progress_cache_test.go @@ -0,0 +1,92 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" +) + +func TestTaskProgressCacheAdmissionRetainsGuardsAndDedup(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "hidden", Started: true, Hidden: true, State: TaskRunning, Label: "PRIVATE"}) + r.Handle(TaskProgressEvent{TaskID: "anchor", RunID: "r2", Started: true, State: TaskRunning, Label: "Anchor"}) + for task := range 17 { + id := fmt.Sprintf("task-%d", task) + r.Handle(TaskProgressEvent{TaskID: id, RunID: "r2", Started: true, State: TaskRunning, Label: id}) + for index := range maxTaskProgressAgentsPerTask + 10 { + r.Handle(TaskProgressEvent{TaskID: id, RunID: "r2", AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) + } + } + if len(r.taskProgressSeen) > maxTaskProgressRows+maxTaskProgressEntries || len(r.taskProgressRuns) > maxTaskProgressEntries { + t.Fatal("unbounded cache/control state") + } + before := out.String() + for _, row := range r.taskProgressSeen { + if row.event.AgentIndex > 0 { + r.Handle(row.event) + } + } + r.Handle(TaskProgressEvent{TaskID: "hidden", State: TaskRunning, Label: "PRIVATE"}) + r.Handle(TaskProgressEvent{TaskID: "anchor", RunID: "r1", State: TaskCompleted}) + if out.String() != before { + t.Fatal("row admission pressure erased dedup/visibility/run controls") + } + r.Handle(TaskProgressEvent{TaskID: "anchor", State: TaskFailed, Update: true}) + if !strings.HasSuffix(out.String(), "Anchor — failed\n") { + t.Fatal("runless update lost label") + } + // Terminal parents release agents, keep their guards, and free admission + // for an existing task whose agents could not fit previously. + r.Handle(TaskProgressEvent{TaskID: "task-0", State: TaskCompleted, Update: true}) + before = out.String() + for range 100 { + r.Handle(TaskProgressEvent{TaskID: "task-0", State: TaskCompleted, Update: true}) + } + r.Handle(TaskProgressEvent{TaskID: "task-0", AgentIndex: 1, State: TaskCompleted, Label: "STALE"}) + r.Handle(TaskProgressEvent{TaskID: "task-0", AgentIndex: 2, State: TaskRunning, Label: "STALE"}) + if out.String() != before { + t.Fatal("terminal cleanup admitted late agents") + } + r.Handle(TaskProgressEvent{TaskID: "task-16", AgentIndex: 1, State: TaskRunning, Label: "Admitted"}) + if !strings.HasSuffix(out.String(), "Admitted — running\n") { + t.Fatal("terminal rows did not free capacity") + } +} + +func TestTaskProgressRelaunchRetiresSupersededRows(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + for run := 1; run <= 4; run++ { + id := fmt.Sprintf("r%d", run) + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "Current"}) + if len(r.taskProgressSeen) != 1 { + t.Fatal("new generation retained superseded rows") + } + for index := range 1000 { + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) + } + before := out.String() + for index := range 1000 { + r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) + } + if out.String() != before || len(r.taskProgressSeen) != 1001 { + t.Fatal("relaunched workflow lost dedup") + } + } +} + +func TestTaskControlAdmissionNeverFlushesExistingTasks(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "hidden", Started: true, Hidden: true, State: TaskRunning, Label: "PRIVATE"}) + for index := range maxTaskProgressEntries + 10 { + r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(index), State: TaskRunning}) + } + before := out.String() + r.Handle(TaskProgressEvent{TaskID: "hidden", State: TaskRunning, Label: "PRIVATE"}) + if out.String() != before || len(r.taskProgressRuns) != maxTaskProgressEntries { + t.Fatal("task admission evicted hidden control") + } +} diff --git a/internal/runtime/task_progress_test.go b/internal/runtime/task_progress_test.go index 63a4e8d99b..2c801b164a 100644 --- a/internal/runtime/task_progress_test.go +++ b/internal/runtime/task_progress_test.go @@ -67,8 +67,8 @@ func TestTaskProgressRendererBoundedState(t *testing.T) { for i := range maxTaskProgressEntries + 1 { r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), State: TaskRunning}) } - if len(r.taskProgressSeen) > maxTaskProgressEntries { - t.Fatalf("unbounded dedup state: %d", len(r.taskProgressSeen)) + if len(r.taskProgressSeen) > maxTaskProgressEntries || len(r.taskProgressRuns) > maxTaskProgressEntries { + t.Fatalf("unbounded task/parent state: %d rows, %d controls", len(r.taskProgressSeen), len(r.taskProgressRuns)) } } @@ -160,11 +160,11 @@ func TestTaskProgressIndexIdentityScopesAndIDFallback(t *testing.T) { } { r.Handle(e) } - if len(r.taskProgressSeen) != 7 || strings.Count(out.String(), "— running") != 7 { - t.Fatal("distinct slots/tasks/runs/fallback IDs collapsed: " + out.String()) + if len(r.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { + t.Fatal("distinct active slots/tasks/fallback IDs collapsed: " + out.String()) } r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, AgentID: "learned", Label: "Work", State: TaskRunning}) - if len(r.taskProgressSeen) != 7 || strings.Count(out.String(), "— running") != 7 { + if len(r.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { t.Fatal("ID-only indexed change created another row") } r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, Label: "Work", State: TaskCompleted}) From 55dde5e0f32f7c66e0e4579a366425b985d9de0e Mon Sep 17 00:00:00 2001 From: jctanner Date: Sat, 31 Oct 2026 10:59:00 -0400 Subject: [PATCH 09/16] fix(#8908): sanitize Unicode progress in a dedicated reconciler Strip bidi, invisible and compatibility obfuscation consistently from progress text and caller credential aliases. Scan raw and normalized inputs for literal and pattern secrets before truncation and retention so Unicode composition cannot bypass token-pattern detection. Preserve full registered-literal matches when trimming scanner-only padding. Extract bounded task, run and status reconciliation from renderer I/O. Keep raw parser callbacks, captured streams and usage accounting intact. Cover Unicode display/CI/cache safety, redaction and callback parity. Signed-off-by: jctanner --- docs/runtimes/claude.md | 10 +- internal/cli/progress_redaction_test.go | 2 + internal/runtime/claude_pr_review_test.go | 4 +- internal/runtime/claude_progress.go | 4 - internal/runtime/claude_run_order_test.go | 2 +- .../runtime/claude_sparse_lifecycle_test.go | 4 +- internal/runtime/claude_task_cache_test.go | 2 +- .../runtime/claude_workflow_state_test.go | 2 +- internal/runtime/event.go | 2 +- internal/runtime/progress_allocation_test.go | 4 +- internal/runtime/progress_pattern_test.go | 81 +++++++++ internal/runtime/progress_reconciler.go | 12 ++ internal/runtime/progress_redaction_test.go | 11 +- internal/runtime/progress_text.go | 99 +++++++++++ internal/runtime/progress_unicode_test.go | 78 +++++++++ internal/runtime/renderer.go | 23 +-- internal/runtime/status_progress.go | 24 +-- internal/runtime/status_progress_test.go | 4 +- internal/runtime/task_progress_cache.go | 4 +- internal/runtime/task_progress_cache_test.go | 10 +- internal/runtime/task_progress_message.go | 60 +++++++ ...rogress.go => task_progress_reconciler.go} | 162 +++--------------- internal/runtime/task_progress_test.go | 8 +- 23 files changed, 422 insertions(+), 190 deletions(-) create mode 100644 internal/runtime/progress_pattern_test.go create mode 100644 internal/runtime/progress_reconciler.go create mode 100644 internal/runtime/progress_text.go create mode 100644 internal/runtime/progress_unicode_test.go create mode 100644 internal/runtime/task_progress_message.go rename internal/runtime/{task_progress.go => task_progress_reconciler.go} (72%) diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index 5f7bc660b6..78ceec73d0 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -344,7 +344,15 @@ available tool names/context. For example: Unchanged snapshots and counter-only updates do not repeat the same display line. Text is sanitized, credential-redacted, and bounded before display or -retention in the bounded display cache. Concurrent tasks and agents retain +retention in the bounded display cache. Progress text uses Unicode cleanup: +bidirectional overrides, invisible format characters and Unicode tags are +removed, and compatibility characters are normalized. The CLI applies the +same cleanup to credential literals before matching. +A dedicated reconciler owns lifecycle and deduplication; the renderer prints +its safe messages. Parser/`OnEvent` callbacks and captured stream bytes keep +their original snapshot content. + +Concurrent tasks and agents retain separate identities. Task tool/status fields retain omitted values; explicit empty strings clear them. Pausing hides the last summary until the task resumes; a terminal state or new run clears it. Partial lifecycle diff --git a/internal/cli/progress_redaction_test.go b/internal/cli/progress_redaction_test.go index 52e0c5b4fc..e7de43e623 100644 --- a/internal/cli/progress_redaction_test.go +++ b/internal/cli/progress_redaction_test.go @@ -14,6 +14,8 @@ func TestRedactProgressSecretLiterals(t *testing.T) { for _, tc := range []struct{ name, secret, input string }{ {"split tab", "opaque\trunner credential", "opaque\trun\x1b[31mner credential"}, {"split markers", "opaque::runner%0Acredential", "opaque:\x1b[31m:runner%0Acredential"}, + {"Unicode literal", "opaque-\u200bcredential", "opaque-\u200bcred\u2066ential"}, + {"compatibility literal", "opaque-credential", "opaque-cred\u202eential"}, {"short normalized value", "opaque\x1b[31m", "opaque"}, } { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/runtime/claude_pr_review_test.go b/internal/runtime/claude_pr_review_test.go index fd1b5821f9..7e544ef8d8 100644 --- a/internal/runtime/claude_pr_review_test.go +++ b/internal/runtime/claude_pr_review_test.go @@ -124,10 +124,10 @@ func TestClaudeReviewLateAgentIDUsesOneIndexedRow(t *testing.T) { if err := parseClaudeStream(strings.NewReader(stream), r.Handle); err != nil { t.Fatal(err) } - if strings.Count(out.String(), "— running") != 1 || strings.Count(out.String(), "— completed") != 1 || len(r.taskProgressSeen) != 1 { + if strings.Count(out.String(), "— running") != 1 || strings.Count(out.String(), "— completed") != 1 || len(r.progress.taskProgressSeen) != 1 { t.Fatal("late ID split agent row: " + out.String()) } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { if row.event.AgentID != "a1" || row.event.State != TaskCompleted || row.event.AgentIndex != 1 { t.Fatalf("lost agent identity or completion: %+v", row.event) } diff --git a/internal/runtime/claude_progress.go b/internal/runtime/claude_progress.go index 72c5a94882..3570c37e6f 100644 --- a/internal/runtime/claude_progress.go +++ b/internal/runtime/claude_progress.go @@ -9,7 +9,6 @@ import ( "strings" "unicode/utf8" - "github.com/fullsend-ai/fullsend/internal/security" "github.com/fullsend-ai/fullsend/internal/ui" ) @@ -704,9 +703,6 @@ func recordClaudeMetrics(metrics *RunMetrics, evt AgentEvent) { } } -// progressRedactor scrubs secrets from tool context strings before display. -var progressRedactor = security.NewSecretRedactor() - // extractSafeContext returns a safe, non-secret string for progress display. // The result is run through SecretRedactor to scrub tokens, keys, and // credentials before anything reaches the terminal or CI annotations. diff --git a/internal/runtime/claude_run_order_test.go b/internal/runtime/claude_run_order_test.go index 6ec9cded36..346ea845f8 100644 --- a/internal/runtime/claude_run_order_test.go +++ b/internal/runtime/claude_run_order_test.go @@ -92,7 +92,7 @@ func TestTaskRunOrderUnsafeIDsNeedExplicitStart(t *testing.T) { t.Fatal("unorderable unseen frame replaced current: " + out.String()) } r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "Explicit"}) - for _, run := range r.taskProgressRuns { + for _, run := range r.progress.taskProgressRuns { if run.order != "" { t.Fatalf("retained unsafe order text: %q", run.order) } diff --git a/internal/runtime/claude_sparse_lifecycle_test.go b/internal/runtime/claude_sparse_lifecycle_test.go index f2bb6155a0..70c9f17608 100644 --- a/internal/runtime/claude_sparse_lifecycle_test.go +++ b/internal/runtime/claude_sparse_lifecycle_test.go @@ -29,7 +29,7 @@ func TestClaudeWorkflowSparseLifecycle(t *testing.T) { if strings.Count(out.String(), "Task wf") != 1 { t.Fatalf("sparse snapshot fabricated transition: %s", out.String()) } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { if row.event.State != tc.want { t.Fatalf("state %s, want %s", row.event.State, tc.want) } @@ -65,7 +65,7 @@ func TestClaudeWorkflowSparseLifecycleTransitions(t *testing.T) { if err := parseClaudeStream(strings.NewReader(raw), r.Handle); err != nil { t.Fatal(err) } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { if row.event.State != step.want { t.Fatalf("%s: state %s, want %s; output: %s", step.fields, row.event.State, step.want, out.String()) } diff --git a/internal/runtime/claude_task_cache_test.go b/internal/runtime/claude_task_cache_test.go index 1184463923..4029c39522 100644 --- a/internal/runtime/claude_task_cache_test.go +++ b/internal/runtime/claude_task_cache_test.go @@ -25,7 +25,7 @@ func TestClaudeTaskSparseToolAndSummary(t *testing.T) { if strings.Count(out.String(), "Task one") != 1 || !strings.Contains(out.String(), "tool: Bash") || !strings.Contains(out.String(), "Running tests") { t.Fatal("sparse task erased progress: " + out.String()) } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { if row.event.ToolName != "Bash" || row.event.Summary != "Running tests" { t.Fatalf("sparse cache erased metadata: %+v", row.event) } diff --git a/internal/runtime/claude_workflow_state_test.go b/internal/runtime/claude_workflow_state_test.go index daaa32faf8..1fa8ea0dd5 100644 --- a/internal/runtime/claude_workflow_state_test.go +++ b/internal/runtime/claude_workflow_state_test.go @@ -101,7 +101,7 @@ func TestClaudeWorkflowAgentQuotaWaitAndStaleSnapshots(t *testing.T) { if strings.Count(out.String(), "— queued") != 2 || strings.Count(out.String(), "— completed") != 1 || !strings.Contains(out.String(), "attempt 2; retry: throttled") { t.Fatal(out.String()) } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { if row.event.State != TaskCompleted || row.event.Attempt != 2 { t.Fatalf("stale attempt changed final state: %+v", row.event) } diff --git a/internal/runtime/event.go b/internal/runtime/event.go index 1e0a7d9bce..aec8cb087b 100644 --- a/internal/runtime/event.go +++ b/internal/runtime/event.go @@ -185,7 +185,7 @@ const ( // Progress does not update token/cost accounting and carries no prompts or // tool result bodies. // Consumers receive repeated snapshots and partial patches, not reconciled -// transitions. EventRenderer merges and deduplicates after caller-specific +// transitions. A display reconciler merges snapshots after caller-specific // credential redaction; custom OnEvent consumers must reconcile their own // state. Nonempty values are supplied values; the Set flags distinguish an // explicitly empty string/false flag from absent optional metadata. Agent diff --git a/internal/runtime/progress_allocation_test.go b/internal/runtime/progress_allocation_test.go index d7bb742c02..99dd481ff9 100644 --- a/internal/runtime/progress_allocation_test.go +++ b/internal/runtime/progress_allocation_test.go @@ -26,10 +26,10 @@ func TestProgressCacheOwnsNormalizedStrings(t *testing.T) { r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), Label: padded, State: TaskRunning}) r.Handle(StatusProgressEvent{Kind: "hook", ID: fmt.Sprint(i), Label: "Hook", Subject: padded, Context: padded}) } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { check(row.event.Label) } - for _, row := range r.statusProgressSeen { + for _, row := range r.progress.statusProgressSeen { check(row.subject) check(row.context) } diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go new file mode 100644 index 0000000000..37495fd736 --- /dev/null +++ b/internal/runtime/progress_pattern_test.go @@ -0,0 +1,81 @@ +package runtime + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +func TestProgressPatternRedactionBeforeUnicodeComposition(t *testing.T) { + // Repetitive synthetic fixtures exercise patterns; never authenticate. + tokens := []string{strings.Join([]string{"gh", "p_"}, "") + strings.Repeat("a", 35) + "e", strings.Join([]string{"AK", "IA"}, "") + strings.Repeat("A", 15) + "E"} + for index, token := range tokens { + for _, withCallback := range []bool{false, true} { + t.Run(fmt.Sprintf("pattern%d/callback=%t", index, withCallback), func(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + var out bytes.Buffer + r := newTestRenderer(&out) + if withCallback { + r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "caller-owned-placeholder", "[REDACTED]") } + } + stderr := captureStderr(t, func() { + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: " \t" + token + "\u0301 \n"}) + r.Handle(StatusProgressEvent{Kind: "notice", ID: "one", Label: "Notice", Detail: " \t" + token + "\u0301 \n"}) + }) + check := func(where, s string) { + t.Helper() + if strings.Contains(s, token[:len(token)-1]) { + t.Fatalf("pattern credential prefix exposed in %s", where) + } + } + check("console", out.String()) + check("CI", stderr) + for _, row := range r.progress.taskProgressSeen { + check("task cache", fmt.Sprintf("%+v", row.event)) + } + for _, row := range r.progress.statusProgressSeen { + check("status cache", fmt.Sprintf("%+v", row)) + } + }) + } + } +} + +func TestProgressRegisteredUnicodeLiteralWithoutCallback(t *testing.T) { + const secret = "opaque-\u202eruntime-progress-for-test" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: secret}) + if strings.Contains(out.String(), "opaque-") || !strings.Contains(out.String(), "***") { + t.Fatal("registered literal escaped normalization") + } +} + +func TestProgressPatternPaddingKeepsExactRegisteredMatches(t *testing.T) { + const secret = "\t opaque-padded-runtime-progress-only \n" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic padded literal") + } + if got := scanProgressSecrets(secret); strings.Contains(got, "opaque-padded") { + t.Fatal("padding optimization lost exact registered match") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "padded", State: TaskRunning, Label: secret}) + if strings.Contains(out.String(), "opaque-padded") || !strings.Contains(out.String(), "***") { + t.Fatal("nil-callback padded registered literal escaped") + } + const ordinary = " \tordinary status \n" + if got := scanProgressSecrets(ordinary); got != ordinary { + t.Fatal("nonsecret raw text changed before normalization") + } + if got := scanProgressSecrets(" \t \n"); got != " \t \n" { + t.Fatal("empty scanner candidate changed raw text") + } +} diff --git a/internal/runtime/progress_reconciler.go b/internal/runtime/progress_reconciler.go new file mode 100644 index 0000000000..55c161f76c --- /dev/null +++ b/internal/runtime/progress_reconciler.go @@ -0,0 +1,12 @@ +package runtime + +import "crypto/sha256" + +// progressReconciler owns bounded lifecycle, visibility, run-order and dedup +// state independently of printer/CI output. Callers supply credential redaction +// before any retained display metadata. Parser callbacks remain raw snapshots. +type progressReconciler struct { + taskProgressSeen map[taskProgressKey]taskProgressDisplay + taskProgressRuns map[[sha256.Size]byte]taskProgressRun + statusProgressSeen map[[sha256.Size]byte]statusProgressDisplay +} diff --git a/internal/runtime/progress_redaction_test.go b/internal/runtime/progress_redaction_test.go index 0883d21f12..8c98e1c732 100644 --- a/internal/runtime/progress_redaction_test.go +++ b/internal/runtime/progress_redaction_test.go @@ -16,6 +16,9 @@ func TestProgressCallerRedactionAfterCleanup(t *testing.T) { {"raw whitespace literal", "opaque\trunner credential for test", "opaque\trunner credential for test"}, {"split whitespace literal", "opaque\trunner credential for test", "opaque\trun\x1b[31mner credential for test"}, {"split rewritten markers", "opaque::runner%0Acredential", "opaque:\x1b[31m:runner%0Acredential"}, + {"Unicode split", "opaque-runner-credential-for-test", "opaque-runner-\u202ecredential-for-test"}, + {"Unicode literal", "opaque-\u200bcredential", "opaque-\u200bcred\u2066ential"}, + {"compatibility split", "opaque-runner-credential-for-test", "opaque-runner-credential-for-test"}, {"before truncation", "opaque-" + strings.Repeat("long-credential", 30), "opaque-\x1b[31m" + strings.Repeat("long-credential", 30)}, } { t.Run(tc.name, func(t *testing.T) { @@ -40,10 +43,10 @@ func TestProgressCallerRedactionAfterCleanup(t *testing.T) { if !strings.Contains(out.String(), "[REDACTED]") || !strings.Contains(stderr, "[REDACTED]") { t.Fatal("missing redaction marker") } - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { check("task cache", fmt.Sprintf("%+v", row.event)) } - for _, row := range r.statusProgressSeen { + for _, row := range r.progress.statusProgressSeen { check("status cache", fmt.Sprintf("%+v", row)) } }) @@ -58,12 +61,12 @@ func TestProgressCallerRedactionDifferentSpans(t *testing.T) { r.RedactProgress = redact // The raw pass masks the inner secret, the independent normalized pass // sees the outer secret. Do not print the remnants of either candidate. - if got := r.progressText("context opaque-prefix-\x1b[31mshortsecret-tail", 160); got != "[REDACTED]" { + if got := redactProgressText("context opaque-prefix-\x1b[31mshortsecret-tail", 160, r.RedactProgress); got != "[REDACTED]" { t.Fatalf("conflicting redaction left residual text: %q", got) } // A raw-only match must still protect a literal that cleanup would alter. r.RedactProgress = func(s string) string { return strings.ReplaceAll(s, "opaque\tcredential", "[REDACTED]") } - if got := r.progressText("opaque\tcredential", 160); got != "[REDACTED]" { + if got := redactProgressText("opaque\tcredential", 160, r.RedactProgress); got != "[REDACTED]" { t.Fatalf("lost raw-only masking: %q", got) } } diff --git a/internal/runtime/progress_text.go b/internal/runtime/progress_text.go new file mode 100644 index 0000000000..3a5c596b06 --- /dev/null +++ b/internal/runtime/progress_text.go @@ -0,0 +1,99 @@ +package runtime + +import ( + "strings" + "unicode/utf8" + + "github.com/fullsend-ai/fullsend/internal/security" +) + +var progressRedactor = security.NewSecretRedactor() +var progressUnicodeNormalizer = security.NewUnicodeNormalizer() + +func taskProgressText(s string, limit int) string { + return redactProgressText(s, limit, nil) +} + +// Redact complete raw literals before cleanup, then repeat after cleanup: +// removing ANSI and normalizing whitespace can reconstruct an opaque secret. +// Both passes precede truncation and cache retention. The caller's redactor +// uses display-safe replacement markers, such as [REDACTED] or ***. +func redactProgressText(s string, limit int, redact func(string) string) string { + // Pattern and registered-secret matching must also see the raw text: + // Unicode composition can otherwise destroy a recognizable token prefix. + pass := func(text string) string { + if redact != nil { + text = redact(text) + } + return scanProgressSecrets(text) + } + normalized := NormalizeProgressText(s) + raw := pass(s) + cleanedRaw := NormalizeProgressText(raw) + cleaned := raw + if normalized != s { + cleaned = pass(normalized) + } + switch { + case raw != s && cleaned != normalized && cleanedRaw != cleaned: + // Different passes masked different spans; suppress residual text. + s = "[REDACTED]" + case cleaned != normalized: + s = cleaned + default: + s = cleanedRaw + } + s = scanProgressSecrets(s) + if utf8.RuneCountInString(s) > limit { + s = string([]rune(s)[:limit]) + "…" + } + // strings.Fields/Join can return a short slice of the sanitizer's large + // allocation. Cache only storage proportional to the bounded final value. + return strings.Clone(s) +} + +// scanProgressSecrets applies pattern and registered-literal protection. +// Empty fields cannot match either class and need no scanner allocation. +func scanProgressSecrets(s string) string { + if s == "" { + return "" + } + // Token patterns do not need outer padding, but exact registered values + // may contain it. Preserve their full-input match before shortening the + // scanner input; return the original text when no redaction occurred. + candidate := s + if trimmed := strings.TrimSpace(s); len(trimmed) != len(s) { + registered := false + for _, secret := range security.RuntimeSecrets() { + if strings.Contains(s, secret) { + registered = true + break + } + } + if !registered { + candidate = trimmed + } + } + if candidate == "" { + return s + } + if result := progressRedactor.Scan(candidate); !result.Safe { + return result.Sanitized + } + return s +} + +// NormalizeProgressText applies the same cleanup to display text and caller +// credential literals. Redactors must match both original and normalized +// values, because cleanup can rewrite whitespace, escapes and CI markers. +func NormalizeProgressText(s string) string { + // Plain ASCII cannot contain Unicode format/compatibility characters. + // NUL and ESC still need the normalizer's stronger terminal cleanup. + for i := 0; i < len(s); i++ { + if s[i] >= utf8.RuneSelf || s[i] == 0 || s[i] == 0x1b { + s = progressUnicodeNormalizer.Scan(s).Sanitized + break + } + } + return strings.Join(strings.Fields(sanitizeOutput(s)), " ") +} diff --git a/internal/runtime/progress_unicode_test.go b/internal/runtime/progress_unicode_test.go new file mode 100644 index 0000000000..77c111e3bd --- /dev/null +++ b/internal/runtime/progress_unicode_test.go @@ -0,0 +1,78 @@ +package runtime + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "strings" + "testing" +) + +func TestProgressUnicodeControlsRemovedFromDisplayAndCaches(t *testing.T) { + t.Setenv("GITHUB_ACTIONS", "true") + controls := "\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\u200b\ufeff\U000e0061" + label := "Visible" + controls + " café 漢字 العربية" + var out bytes.Buffer + r := newTestRenderer(&out) + stderr := captureStderr(t, func() { + r.Handle(TaskProgressEvent{TaskID: "task", RunID: "r1", AgentIndex: 1, AgentID: "worker" + controls, Label: label, Phase: label, State: TaskRunning, ToolName: label, ToolSummary: label, Summary: label, Detail: label, LastAttemptReason: label}) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: label, Subject: label, Context: label, State: label, Detail: label}) + }) + check := func(where, text string) { + t.Helper() + if strings.ContainsAny(text, controls) { + t.Fatalf("unsafe Unicode in %s", where) + } + } + check("console", out.String()) + check("CI", stderr) + for _, row := range r.progress.taskProgressSeen { + check("task cache", fmt.Sprintf("%+v", row.event)) + } + for _, row := range r.progress.statusProgressSeen { + check("status cache", fmt.Sprintf("%+v", row)) + } + if !strings.Contains(out.String(), "café 漢字 العربية") { + t.Fatal("ordinary Unicode content changed") + } + if got := NormalizeProgressText("::error:: injected"); strings.Contains(got, "::") { + t.Fatal("compatibility normalization recreated CI command") + } +} + +func TestClaudeProgressCallbacksStayRawWhileDisplayReconciles(t *testing.T) { + label := "Working\u202e" + raw, err := json.Marshal(map[string]any{"type": "system", "subtype": "task_progress", "task_id": "task", "description": label}) + if err != nil { + t.Fatal(err) + } + stream := strings.Repeat(string(raw)+"\n", 3) + `{"type":"result","num_turns":3,"total_cost_usd":0.25}` + "\n" + var console, capture bytes.Buffer + r := newTestRenderer(&console) + var labels []string + var metrics RunMetrics + if err := parseClaudeStream(io.TeeReader(strings.NewReader(stream), &capture), func(e AgentEvent) { + recordClaudeMetrics(&metrics, e) + r.Handle(e) + if task, ok := e.(TaskProgressEvent); ok { + labels = append(labels, task.Label) + } + }); err != nil { + t.Fatal(err) + } + if capture.String() != stream || len(labels) != 3 { + t.Fatal("raw stream/event contract changed") + } + for _, got := range labels { + if got != label { + t.Fatal("renderer changed caller event") + } + } + if strings.Count(console.String(), "Task task") != 1 || strings.Contains(console.String(), "\u202e") { + t.Fatal("display did not reconcile/sanitize independently") + } + if metrics.NumTurns != 3 || metrics.TotalCostUSD != 0.25 { + t.Fatal("progress changed accounting") + } +} diff --git a/internal/runtime/renderer.go b/internal/runtime/renderer.go index 5eacbbf236..db1235d7d5 100644 --- a/internal/runtime/renderer.go +++ b/internal/runtime/renderer.go @@ -1,7 +1,6 @@ package runtime import ( - "crypto/sha256" "fmt" "os" @@ -20,14 +19,12 @@ type EventRenderer struct { // runtime-secret redaction apply even when this callback is nil. RedactProgress func(string) string - printer *ui.Printer - isCI bool - inText bool - inThinking bool - seenInit bool - taskProgressSeen map[taskProgressKey]taskProgressDisplay - taskProgressRuns map[[sha256.Size]byte]taskProgressRun - statusProgressSeen map[[sha256.Size]byte]statusProgressDisplay + printer *ui.Printer + isCI bool + inText bool + inThinking bool + seenInit bool + progress progressReconciler } // NewEventRenderer creates a renderer that writes to the given printer. @@ -46,9 +43,13 @@ var ( func (r *EventRenderer) Handle(evt AgentEvent) { switch e := evt.(type) { case StatusProgressEvent: - r.statusProgress(e) + if msg, show := r.progress.status(e, r.RedactProgress); show { + r.printProgress(msg) + } case TaskProgressEvent: - r.taskProgress(e) + if msg, show := r.progress.task(e, r.RedactProgress); show { + r.printProgress(msg) + } case InitEvent: if r.seenInit { return diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go index ecd79c93bc..4e00d41fc7 100644 --- a/internal/runtime/status_progress.go +++ b/internal/runtime/status_progress.go @@ -8,25 +8,25 @@ type statusProgressDisplay struct { context string } -func (r *EventRenderer) statusProgress(e StatusProgressEvent) { +func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) string) (string, bool) { if e.Kind == "" { - return + return "", false } key := sha256.Sum256([]byte(e.Kind + "\x00" + e.ID)) previous := r.statusProgressSeen[key] if e.Clear { delete(r.statusProgressSeen, key) - return + return "", false } if e.Recovery && previous.message == "" { - return + return "", false } - msg := r.progressText(e.Label, 120) + msg := redactProgressText(e.Label, 120, redact) if msg == "" { - return + return "", false } - subject := r.progressText(e.Subject, 120) - context := r.progressText(e.Context, 80) + subject := redactProgressText(e.Subject, 120, redact) + context := redactProgressText(e.Context, 80, redact) if subject == "" && !e.SubjectSet { subject = previous.subject } @@ -39,15 +39,15 @@ func (r *EventRenderer) statusProgress(e StatusProgressEvent) { if context != "" { msg += " [" + context + "]" } - if state := r.progressText(e.State, 60); state != "" { + if state := redactProgressText(e.State, 60, redact); state != "" { msg += " — " + state } - if detail := r.progressText(e.Detail, 240); detail != "" { + if detail := redactProgressText(e.Detail, 240, redact); detail != "" { msg += ": " + detail } msg = sanitizeOutput(msg) if !e.Occurrence && previous.message == msg { - return + return "", false } if !e.Occurrence { if r.statusProgressSeen == nil { @@ -58,5 +58,5 @@ func (r *EventRenderer) statusProgress(e StatusProgressEvent) { } r.statusProgressSeen[key] = statusProgressDisplay{message: msg, subject: subject, context: context} } - r.printProgress(msg) + return msg, true } diff --git a/internal/runtime/status_progress_test.go b/internal/runtime/status_progress_test.go index 575d9a97e3..7b073531c2 100644 --- a/internal/runtime/status_progress_test.go +++ b/internal/runtime/status_progress_test.go @@ -30,7 +30,7 @@ func TestStatusProgressRendererSafetyAndBounds(t *testing.T) { for i := range maxTaskProgressEntries + 1 { r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row"}) } - if len(r.statusProgressSeen) > maxTaskProgressEntries { + if len(r.progress.statusProgressSeen) > maxTaskProgressEntries { t.Fatal("unbounded status cache") } } @@ -58,7 +58,7 @@ func TestStatusProgressAttributionRedactedBeforeRetention(t *testing.T) { if strings.Contains(out.String(), secret) || strings.Contains(stderr, secret) || strings.Contains(stderr, "::error::") || strings.Count(stderr, "::notice::") != 2 { t.Fatal("unsafe hook attribution") } - for _, display := range r.statusProgressSeen { + for _, display := range r.progress.statusProgressSeen { if strings.Contains(display.subject+display.context+display.message, secret) || len([]rune(display.subject)) > 121 || len([]rune(display.context)) > 81 { t.Fatal("unsafe or unbounded cached attribution") } diff --git a/internal/runtime/task_progress_cache.go b/internal/runtime/task_progress_cache.go index 9b9df67e3f..db79fdd84c 100644 --- a/internal/runtime/task_progress_cache.go +++ b/internal/runtime/task_progress_cache.go @@ -5,7 +5,7 @@ import "crypto/sha256" // retireTaskProgressRows removes rows without discarding authoritative run and // visibility control. A completed task needs no agent rows: all subsequent // agent frames are blocked by its retained terminal parent state. -func (r *EventRenderer) retireTaskProgressRows(task [sha256.Size]byte, agentsOnly bool) { +func (r *progressReconciler) retireTaskProgressRows(task [sha256.Size]byte, agentsOnly bool) { parentAgent := sha256.Sum256(nil) for key := range r.taskProgressSeen { if key.task == task && (!agentsOnly || key.index > 0 || key.agent != parentAgent) { @@ -14,7 +14,7 @@ func (r *EventRenderer) retireTaskProgressRows(task [sha256.Size]byte, agentsOnl } } -func (r *EventRenderer) storeTaskProgress(key taskProgressKey, display taskProgressDisplay, isAgent bool) { +func (r *progressReconciler) storeTaskProgress(key taskProgressKey, display taskProgressDisplay, isAgent bool) { if !isAgent { control := r.taskProgressRuns[key.task] control.parent = display diff --git a/internal/runtime/task_progress_cache_test.go b/internal/runtime/task_progress_cache_test.go index a24e40e1ee..ba0284c1a7 100644 --- a/internal/runtime/task_progress_cache_test.go +++ b/internal/runtime/task_progress_cache_test.go @@ -19,11 +19,11 @@ func TestTaskProgressCacheAdmissionRetainsGuardsAndDedup(t *testing.T) { r.Handle(TaskProgressEvent{TaskID: id, RunID: "r2", AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) } } - if len(r.taskProgressSeen) > maxTaskProgressRows+maxTaskProgressEntries || len(r.taskProgressRuns) > maxTaskProgressEntries { + if len(r.progress.taskProgressSeen) > maxTaskProgressRows+maxTaskProgressEntries || len(r.progress.taskProgressRuns) > maxTaskProgressEntries { t.Fatal("unbounded cache/control state") } before := out.String() - for _, row := range r.taskProgressSeen { + for _, row := range r.progress.taskProgressSeen { if row.event.AgentIndex > 0 { r.Handle(row.event) } @@ -61,7 +61,7 @@ func TestTaskProgressRelaunchRetiresSupersededRows(t *testing.T) { for run := 1; run <= 4; run++ { id := fmt.Sprintf("r%d", run) r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, Started: true, State: TaskRunning, Label: "Current"}) - if len(r.taskProgressSeen) != 1 { + if len(r.progress.taskProgressSeen) != 1 { t.Fatal("new generation retained superseded rows") } for index := range 1000 { @@ -71,7 +71,7 @@ func TestTaskProgressRelaunchRetiresSupersededRows(t *testing.T) { for index := range 1000 { r.Handle(TaskProgressEvent{TaskID: "one", RunID: id, AgentIndex: index + 1, State: TaskRunning, Label: "Worker"}) } - if out.String() != before || len(r.taskProgressSeen) != 1001 { + if out.String() != before || len(r.progress.taskProgressSeen) != 1001 { t.Fatal("relaunched workflow lost dedup") } } @@ -86,7 +86,7 @@ func TestTaskControlAdmissionNeverFlushesExistingTasks(t *testing.T) { } before := out.String() r.Handle(TaskProgressEvent{TaskID: "hidden", State: TaskRunning, Label: "PRIVATE"}) - if out.String() != before || len(r.taskProgressRuns) != maxTaskProgressEntries { + if out.String() != before || len(r.progress.taskProgressRuns) != maxTaskProgressEntries { t.Fatal("task admission evicted hidden control") } } diff --git a/internal/runtime/task_progress_message.go b/internal/runtime/task_progress_message.go new file mode 100644 index 0000000000..dcd55b8bab --- /dev/null +++ b/internal/runtime/task_progress_message.go @@ -0,0 +1,60 @@ +package runtime + +import "fmt" + +// taskProgressMessage formats only already-redacted, bounded display fields. +func taskProgressMessage(e TaskProgressEvent) string { + msg := "Task " + e.TaskID + if e.AgentIndex > 0 { + msg += fmt.Sprintf(" / agent #%d", e.AgentIndex) + if e.AgentID != "" { + msg += " (" + e.AgentID + ")" + } + } else if e.AgentID != "" { + msg += " / agent " + e.AgentID + } + if e.Phase != "" { + msg += " [" + e.Phase + "]" + } + if e.Label != "" { + msg += ": " + e.Label + } + if e.State != "" { + msg += " — " + string(e.State) + } else { + msg += " — updated" + } + if e.Blocked { + msg += " (blocked)" + } + if e.Cached { + msg += " (cached)" + } + if e.ToolName != "" { + msg += " (tool: " + e.ToolName + if e.ToolSummary != "" { + msg += ": " + e.ToolSummary + } + msg += ")" + } + if e.Attempt > 0 || e.LastAttemptReason != "" { + msg += " (" + if e.Attempt > 0 { + msg += fmt.Sprintf("attempt %d", e.Attempt) + } + if e.LastAttemptReason != "" { + if e.Attempt > 0 { + msg += "; " + } + msg += "retry: " + e.LastAttemptReason + } + msg += ")" + } + if e.Summary != "" && e.State == TaskRunning { + msg += " — " + e.Summary + } + if e.Detail != "" { + msg += " — " + e.Detail + } + return sanitizeOutput(msg) +} diff --git a/internal/runtime/task_progress.go b/internal/runtime/task_progress_reconciler.go similarity index 72% rename from internal/runtime/task_progress.go rename to internal/runtime/task_progress_reconciler.go index 214eacc0bd..b5fd421695 100644 --- a/internal/runtime/task_progress.go +++ b/internal/runtime/task_progress_reconciler.go @@ -2,9 +2,7 @@ package runtime import ( "crypto/sha256" - "fmt" "slices" - "strings" "unicode/utf16" "unicode/utf8" ) @@ -41,13 +39,13 @@ type taskProgressDisplay struct { fingerprint [sha256.Size]byte } -func (r *EventRenderer) taskProgress(e TaskProgressEvent) { +func (r *progressReconciler) task(e TaskProgressEvent, redact func(string) string) (string, bool) { if e.TaskID == "" || (e.State == "" && !e.Update) { - return + return "", false } - key, accepted := r.taskProgressIdentity(&e) + key, accepted := r.taskProgressIdentity(&e, redact) if !accepted { - return + return "", false } taskHash := key.task current := r.taskProgressRuns[taskHash] @@ -59,22 +57,22 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { } // Parent lifecycle/visibility lives outside the agent dedup row budget. if isAgent && terminalTaskState(parent.State) { - return + return "", false } if isAgent && staleAgentSnapshot(e, previous.event) { - return + return "", false } if isAgent && e.AgentState != "" { reconcileAgentLifecycle(&e, previous.event) } resumable := isAgent && previous.event.State == TaskFailed && agentExecutionAdvanced(e, previous.event) if !e.Started && (parent.Hidden || previous.event.Hidden || (e.State != "" && !terminalTaskState(e.State) && (terminalTaskState(parent.State) || (terminalTaskState(previous.event.State) && !resumable)))) { - return + return "", false } if isAgent { if _, exists := r.taskProgressSeen[key]; !exists { if current.agents >= maxTaskProgressAgentsPerTask || len(r.taskProgressSeen) >= maxTaskProgressRows { - return + return "", false } current.agents++ r.taskProgressRuns[taskHash] = current @@ -82,18 +80,18 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { } // Sanitize before retaining metadata, not just before printing it. This // cache contains bounded display fields and hashed raw identities only. - e.TaskID = r.progressText(e.TaskID, 80) - e.RunID = r.progressText(e.RunID, 80) - e.AgentID = r.progressText(e.AgentID, 80) - e.Label = r.progressText(e.Label, 160) - e.Phase = r.progressText(e.Phase, 80) - e.ToolName = r.progressText(e.ToolName, 50) - e.ToolSummary = r.progressText(e.ToolSummary, 160) - e.Summary = r.progressText(e.Summary, 200) - e.Detail = r.progressText(e.Detail, 200) - e.LastAttemptReason = r.progressText(e.LastAttemptReason, 60) - e.State = TaskState(r.progressText(string(e.State), 40)) - e.AgentState = r.progressText(e.AgentState, 40) + e.TaskID = redactProgressText(e.TaskID, 80, redact) + e.RunID = redactProgressText(e.RunID, 80, redact) + e.AgentID = redactProgressText(e.AgentID, 80, redact) + e.Label = redactProgressText(e.Label, 160, redact) + e.Phase = redactProgressText(e.Phase, 80, redact) + e.ToolName = redactProgressText(e.ToolName, 50, redact) + e.ToolSummary = redactProgressText(e.ToolSummary, 160, redact) + e.Summary = redactProgressText(e.Summary, 200, redact) + e.Detail = redactProgressText(e.Detail, 200, redact) + e.LastAttemptReason = redactProgressText(e.LastAttemptReason, 60, redact) + e.State = TaskState(redactProgressText(string(e.State), 40, redact)) + e.AgentState = redactProgressText(e.AgentState, 40, redact) if !e.Started { old := previous.event if e.Label == "" && !e.LabelSet { @@ -119,7 +117,7 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { } if e.Hidden { r.storeTaskProgress(key, taskProgressDisplay{event: e}, isAgent) - return + return "", false } msg := taskProgressMessage(e) comparison := msg @@ -132,73 +130,16 @@ func (r *EventRenderer) taskProgress(e TaskProgressEvent) { fingerprint := sha256.Sum256([]byte(comparison)) r.storeTaskProgress(key, taskProgressDisplay{event: e, fingerprint: fingerprint}, isAgent) if previous.fingerprint == fingerprint { - return + return "", false } - r.printProgress(msg) -} - -// taskProgressMessage formats only already-redacted, bounded display fields. -func taskProgressMessage(e TaskProgressEvent) string { - msg := "Task " + e.TaskID - if e.AgentIndex > 0 { - msg += fmt.Sprintf(" / agent #%d", e.AgentIndex) - if e.AgentID != "" { - msg += " (" + e.AgentID + ")" - } - } else if e.AgentID != "" { - msg += " / agent " + e.AgentID - } - if e.Phase != "" { - msg += " [" + e.Phase + "]" - } - if e.Label != "" { - msg += ": " + e.Label - } - if e.State != "" { - msg += " — " + string(e.State) - } else { - msg += " — updated" - } - if e.Blocked { - msg += " (blocked)" - } - if e.Cached { - msg += " (cached)" - } - if e.ToolName != "" { - msg += " (tool: " + e.ToolName - if e.ToolSummary != "" { - msg += ": " + e.ToolSummary - } - msg += ")" - } - if e.Attempt > 0 || e.LastAttemptReason != "" { - msg += " (" - if e.Attempt > 0 { - msg += fmt.Sprintf("attempt %d", e.Attempt) - } - if e.LastAttemptReason != "" { - if e.Attempt > 0 { - msg += "; " - } - msg += "retry: " + e.LastAttemptReason - } - msg += ")" - } - if e.Summary != "" && e.State == TaskRunning { - msg += " — " + e.Summary - } - if e.Detail != "" { - msg += " — " + e.Detail - } - return sanitizeOutput(msg) + return msg, true } // Resolve optional run IDs. SDK 0.3.314 orders a task's run IDs by plain // JavaScript string comparison. Reject superseded frames before changing any // identity, visibility or dedup state. Anonymous restarts retain the previous // named watermark until a newer name adopts the anonymous generation's rows. -func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgressKey, bool) { +func (r *progressReconciler) taskProgressIdentity(e *TaskProgressEvent, redact func(string) string) (taskProgressKey, bool) { if r.taskProgressSeen == nil { r.taskProgressSeen = make(map[taskProgressKey]taskProgressDisplay) r.taskProgressRuns = make(map[[sha256.Size]byte]taskProgressRun) @@ -218,7 +159,7 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgress if current.named && current.hash == zero && run == current.watermark { return taskProgressKey{}, false } - order = r.taskRunOrder(e.RunID) + order = r.taskRunOrder(e.RunID, redact) if current.named && run != current.hash { comparable := order != "" && current.order != "" comparison := compareTaskRunIDs(order, current.order) @@ -270,11 +211,11 @@ func (r *EventRenderer) taskProgressIdentity(e *TaskProgressEvent) (taskProgress return taskProgressKey{task: task, run: run, agent: agent, index: index}, true } -func (r *EventRenderer) taskRunOrder(id string) string { +func (r *progressReconciler) taskRunOrder(id string, redact func(string) string) string { if len(id) > maxTaskRunOrderBytes || !utf8.ValidString(id) { return "" } - clean := r.progressText(id, maxTaskRunOrderBytes) + clean := redactProgressText(id, maxTaskRunOrderBytes, redact) if clean != id { return "" } @@ -401,52 +342,3 @@ func staleAgentSnapshot(e, old TaskProgressEvent) bool { func terminalTaskState(state TaskState) bool { return state == TaskCompleted || state == TaskFailed || state == TaskStopped || state == TaskSkipped } - -func (r *EventRenderer) progressText(s string, limit int) string { - return redactProgressText(s, limit, r.RedactProgress) -} - -func taskProgressText(s string, limit int) string { - return redactProgressText(s, limit, nil) -} - -// Redact complete raw literals before cleanup, then repeat after cleanup: -// removing ANSI and normalizing whitespace can reconstruct an opaque secret. -// Both passes precede truncation and cache retention. The caller's redactor -// uses display-safe replacement markers, such as [REDACTED] or ***. -func redactProgressText(s string, limit int, redact func(string) string) string { - normalized := NormalizeProgressText(s) - if redact != nil { - raw := redact(s) - cleanedRaw := NormalizeProgressText(raw) - cleaned := redact(normalized) - switch { - case raw != s && cleaned != normalized && cleanedRaw != cleaned: - // Different passes masked different spans (for example nested secrets). - // Neither candidate proves the other one's residual text is safe. - s = "[REDACTED]" - case cleaned != normalized: - s = cleaned - default: - s = cleanedRaw - } - } else { - s = normalized - } - if result := progressRedactor.Scan(s); !result.Safe { - s = result.Sanitized - } - if utf8.RuneCountInString(s) > limit { - s = string([]rune(s)[:limit]) + "…" - } - // strings.Fields/Join can return a short slice of the sanitizer's large - // allocation. Cache only storage proportional to the bounded final value. - return strings.Clone(s) -} - -// NormalizeProgressText applies the same cleanup to display text and caller -// credential literals. Redactors must match both original and normalized -// values, because cleanup can rewrite whitespace, escapes and CI markers. -func NormalizeProgressText(s string) string { - return strings.Join(strings.Fields(sanitizeOutput(s)), " ") -} diff --git a/internal/runtime/task_progress_test.go b/internal/runtime/task_progress_test.go index 2c801b164a..cffae5f1a6 100644 --- a/internal/runtime/task_progress_test.go +++ b/internal/runtime/task_progress_test.go @@ -67,8 +67,8 @@ func TestTaskProgressRendererBoundedState(t *testing.T) { for i := range maxTaskProgressEntries + 1 { r.Handle(TaskProgressEvent{TaskID: fmt.Sprint(i), State: TaskRunning}) } - if len(r.taskProgressSeen) > maxTaskProgressEntries || len(r.taskProgressRuns) > maxTaskProgressEntries { - t.Fatalf("unbounded task/parent state: %d rows, %d controls", len(r.taskProgressSeen), len(r.taskProgressRuns)) + if len(r.progress.taskProgressSeen) > maxTaskProgressEntries || len(r.progress.taskProgressRuns) > maxTaskProgressEntries { + t.Fatalf("unbounded task/parent state: %d rows, %d controls", len(r.progress.taskProgressSeen), len(r.progress.taskProgressRuns)) } } @@ -160,11 +160,11 @@ func TestTaskProgressIndexIdentityScopesAndIDFallback(t *testing.T) { } { r.Handle(e) } - if len(r.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { + if len(r.progress.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { t.Fatal("distinct active slots/tasks/fallback IDs collapsed: " + out.String()) } r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, AgentID: "learned", Label: "Work", State: TaskRunning}) - if len(r.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { + if len(r.progress.taskProgressSeen) != 5 || strings.Count(out.String(), "— running") != 7 { t.Fatal("ID-only indexed change created another row") } r.Handle(TaskProgressEvent{TaskID: "one", RunID: "second", AgentIndex: 1, Label: "Work", State: TaskCompleted}) From a9174e8f2730371066666abf460927a77536ea20 Mon Sep 17 00:00:00 2001 From: jctanner Date: Tue, 3 Nov 2026 09:08:39 -0500 Subject: [PATCH 10/16] fix(#8908): keep status history when updating an existing key at capacity The capacity guard in progressReconciler.status ran before every non-occurrence write, so once maxTaskProgressEntries distinct status keys existed, the next update to any existing key cleared the entire cache: sparse hook completions lost the subject and context retained from previous, and unchanged snapshots printed again because their previous message was gone. Only a new key needs a free slot, so the clear now runs only when the key is not already present. Adds a regression test covering existing-key updates at capacity, retained-subject merging across the update, and dedup after it. Signed-off-by: jctanner --- internal/runtime/status_progress.go | 4 +++- internal/runtime/status_progress_test.go | 29 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go index 4e00d41fc7..25d700713f 100644 --- a/internal/runtime/status_progress.go +++ b/internal/runtime/status_progress.go @@ -53,7 +53,9 @@ func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) s if r.statusProgressSeen == nil { r.statusProgressSeen = make(map[[sha256.Size]byte]statusProgressDisplay) } - if len(r.statusProgressSeen) >= maxTaskProgressEntries { + // Only a new key needs a free slot: updating an existing key at + // capacity must not discard the retained state of every other key. + if _, exists := r.statusProgressSeen[key]; !exists && len(r.statusProgressSeen) >= maxTaskProgressEntries { clear(r.statusProgressSeen) } r.statusProgressSeen[key] = statusProgressDisplay{message: msg, subject: subject, context: context} diff --git a/internal/runtime/status_progress_test.go b/internal/runtime/status_progress_test.go index 7b073531c2..6aa30b65b5 100644 --- a/internal/runtime/status_progress_test.go +++ b/internal/runtime/status_progress_test.go @@ -67,3 +67,32 @@ func TestStatusProgressAttributionRedactedBeforeRetention(t *testing.T) { t.Fatal("sparse completion lost redacted attribution: " + out.String()) } } + +func TestStatusProgressCapacityUpdateKeepsExistingEntries(t *testing.T) { + var out bytes.Buffer + r := newTestRenderer(&out) + // Fill the status cache to capacity with distinct keys carrying subjects. + for i := range maxTaskProgressEntries { + r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row " + fmt.Sprint(i), Subject: "subject " + fmt.Sprint(i), SubjectSet: true}) + } + if len(r.progress.statusProgressSeen) != maxTaskProgressEntries { + t.Fatalf("setup: want %d entries, got %d", maxTaskProgressEntries, len(r.progress.statusProgressSeen)) + } + // Updating an existing key at capacity must not wipe the cache. + r.Handle(StatusProgressEvent{Kind: "row", ID: "0", Label: "row 0 updated"}) + if len(r.progress.statusProgressSeen) != maxTaskProgressEntries { + t.Fatalf("existing-key update at capacity wiped the cache: %d entries remain", len(r.progress.statusProgressSeen)) + } + // Retained state of other keys must survive: a sparse update to a + // different key still merges its retained subject, and dedup still + // suppresses an identical resend. + r.Handle(StatusProgressEvent{Kind: "row", ID: "1", Label: "row 1"}) + if msg := out.String(); !strings.Contains(msg, "row 1 subject 1") { + t.Fatalf("retained subject lost after capacity update: %q", msg) + } + out.Reset() + r.Handle(StatusProgressEvent{Kind: "row", ID: "1", Label: "row 1"}) + if out.String() != "" { + t.Fatalf("dedup broken after capacity update: %q", out.String()) + } +} From b29ac36b48cba28947d62c1ebfd1f727080f823b Mon Sep 17 00:00:00 2001 From: jctanner Date: Tue, 3 Nov 2026 18:57:08 -0500 Subject: [PATCH 11/16] fix(#8908): redact normalized runtime secrets in the fallback pass The renderer nil-callback fallback matched registered runtime secrets by exact literal only. A credential that cleanup rewrites (an ANSI-split or tab-containing value normalizes to different text than the registered literal) therefore escaped the fallback: the reconstructed secret was displayed and retained. The CLI callback redacts normalized literals itself (redactProgressSecretLiterals), so only the fallback was affected. The fallback now also masks the normalized form of each registered secret, skipping forms below the registration length floor so a short normalized remnant cannot blank ordinary output. Adds a regression test with a tab-containing registered credential and no callback, covering both the scanner and full rendering. Signed-off-by: jctanner --- internal/runtime/progress_pattern_test.go | 24 ++++++++++++++++++ internal/runtime/progress_text.go | 31 ++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go index 37495fd736..65428c3c32 100644 --- a/internal/runtime/progress_pattern_test.go +++ b/internal/runtime/progress_pattern_test.go @@ -79,3 +79,27 @@ func TestProgressPatternPaddingKeepsExactRegisteredMatches(t *testing.T) { t.Fatal("empty scanner candidate changed raw text") } } + +func TestProgressFallbackRedactsNormalizedRuntimeSecret(t *testing.T) { + // A registered credential containing whitespace variants (here a tab) + // normalizes to different text than the registered literal. Without a + // RedactProgress callback the fallback must still mask the normalized + // literal, or the reconstructed credential is displayed and retained. + const secret = "opaque-runtime-secret \twith-tab-for-test" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + cleaned := NormalizeProgressText(secret) + if cleaned == secret || !strings.Contains(cleaned, "with-tab-for-test") { + t.Fatalf("setup: secret did not normalize differently: %q", cleaned) + } + if got := scanProgressSecrets("progress " + cleaned + " done"); strings.Contains(got, "opaque-runtime-secret") || !strings.Contains(got, "***") { + t.Fatalf("normalized registered literal escaped the fallback: %q", got) + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "progress " + cleaned + " done"}) + if strings.Contains(out.String(), "opaque-runtime-secret") || !strings.Contains(out.String(), "***") { + t.Fatalf("normalized registered literal escaped rendering: %q", out.String()) + } +} diff --git a/internal/runtime/progress_text.go b/internal/runtime/progress_text.go index 3a5c596b06..9f39c7c0f6 100644 --- a/internal/runtime/progress_text.go +++ b/internal/runtime/progress_text.go @@ -77,8 +77,37 @@ func scanProgressSecrets(s string) string { if candidate == "" { return s } + text := s if result := progressRedactor.Scan(candidate); !result.Safe { - return result.Sanitized + text = result.Sanitized + } + if masked := redactNormalizedRuntimeSecrets(text); masked != text { + return masked + } + return text +} + +// minNormalizedSecretLen mirrors the security package registration floor: +// a short normalized remnant of a registered secret must never blank out +// ordinary output. +const minNormalizedSecretLen = 8 + +// redactNormalizedRuntimeSecrets masks registered runtime secrets in the +// forms cleanup rewrites them into: an ANSI-split or tab-containing +// credential normalizes to different text than the registered literal, so +// exact-literal matching alone can let a reconstructed secret through. The +// CLI callback redacts normalized literals itself (redactProgressSecret- +// Literals); the renderer nil-callback fallback must match them too, or +// the reconstructed credential is displayed and retained. +func redactNormalizedRuntimeSecrets(s string) string { + for _, secret := range security.RuntimeSecrets() { + normalized := NormalizeProgressText(secret) + if len(normalized) < minNormalizedSecretLen || normalized == secret { + continue + } + if strings.Contains(s, normalized) { + s = strings.ReplaceAll(s, normalized, "***") + } } return s } From 9a20f47c1f1c9693a4ca7ceac05b27f064286c30 Mon Sep 17 00:00:00 2001 From: jctanner Date: Wed, 4 Nov 2026 09:08:55 -0500 Subject: [PATCH 12/16] fix(#8908): address review findings on progress redaction and naming - The normalized-secret fallback masks every non-empty normalized form of a registered credential: the original literal passed the registration length floor, so short normalized derivatives remain authenticated secrets. This mirrors redactSecretLiteralsWithNormalizer in the CLI, which applies its floor to the original value only. - redactProgressText and redactProgressSecretLiterals doc comments now start with the function name. - The status display cache cap gets its own constant, maxStatusProgressEntries, instead of reusing the task-specific maxTaskProgressEntries. Adds a nil-callback regression test for a registered credential whose normalized form is shorter than the registration floor. Signed-off-by: jctanner --- internal/cli/run.go | 3 ++- internal/runtime/progress_pattern_test.go | 25 +++++++++++++++++++++++ internal/runtime/progress_text.go | 20 +++++++++--------- internal/runtime/status_progress.go | 6 +++++- internal/runtime/status_progress_test.go | 6 +++--- 5 files changed, 45 insertions(+), 15 deletions(-) diff --git a/internal/cli/run.go b/internal/cli/run.go index 2c5334a737..22c1e8b92f 100644 --- a/internal/cli/run.go +++ b/internal/cli/run.go @@ -4315,7 +4315,8 @@ func redactSecretLiterals(feedback string, runnerEnv map[string]string) string { return redactSecretLiteralsWithNormalizer(feedback, runnerEnv, nil) } -// Progress cleanup can alter a secret itself, so mask both literal forms. +// redactProgressSecretLiterals masks both literal forms because progress +// cleanup can alter a secret itself. func redactProgressSecretLiterals(feedback string, runnerEnv map[string]string) string { return redactSecretLiteralsWithNormalizer(feedback, runnerEnv, agentruntime.NormalizeProgressText) } diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go index 65428c3c32..408034c3c1 100644 --- a/internal/runtime/progress_pattern_test.go +++ b/internal/runtime/progress_pattern_test.go @@ -103,3 +103,28 @@ func TestProgressFallbackRedactsNormalizedRuntimeSecret(t *testing.T) { t.Fatalf("normalized registered literal escaped rendering: %q", out.String()) } } + +// A registered credential whose normalized form is shorter than the +// registration floor must still be masked: the original literal passed the +// floor at registration, so every non-empty normalized derivative stays an +// authenticated secret. No RedactProgress callback is set, exercising the +// renderer fallback. +func TestProgressFallbackRedactsShortNormalizedRuntimeSecret(t *testing.T) { + const secret = "zz\x1b[32m\x1b[0mtok" // raw length 14; normalizes to "zztok" (5) + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + cleaned := NormalizeProgressText(secret) + if cleaned != "zztok" { + t.Fatalf("setup: unexpected normalized form %q", cleaned) + } + if got := scanProgressSecrets("status " + cleaned + " done"); strings.Contains(got, "zztok") || !strings.Contains(got, "***") { + t.Fatalf("short normalized registered literal escaped the fallback: %q", got) + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "status " + cleaned + " done"}) + if strings.Contains(out.String(), "zztok") || !strings.Contains(out.String(), "***") { + t.Fatalf("short normalized registered literal escaped rendering: %q", out.String()) + } +} diff --git a/internal/runtime/progress_text.go b/internal/runtime/progress_text.go index 9f39c7c0f6..c279209649 100644 --- a/internal/runtime/progress_text.go +++ b/internal/runtime/progress_text.go @@ -14,10 +14,11 @@ func taskProgressText(s string, limit int) string { return redactProgressText(s, limit, nil) } -// Redact complete raw literals before cleanup, then repeat after cleanup: -// removing ANSI and normalizing whitespace can reconstruct an opaque secret. -// Both passes precede truncation and cache retention. The caller's redactor -// uses display-safe replacement markers, such as [REDACTED] or ***. +// redactProgressText redacts complete raw literals before cleanup, then +// repeats after cleanup: removing ANSI and normalizing whitespace can +// reconstruct an opaque secret. Both passes precede truncation and cache +// retention. The caller's redactor uses display-safe replacement markers, +// such as [REDACTED] or ***. func redactProgressText(s string, limit int, redact func(string) string) string { // Pattern and registered-secret matching must also see the raw text: // Unicode composition can otherwise destroy a recognizable token prefix. @@ -87,11 +88,6 @@ func scanProgressSecrets(s string) string { return text } -// minNormalizedSecretLen mirrors the security package registration floor: -// a short normalized remnant of a registered secret must never blank out -// ordinary output. -const minNormalizedSecretLen = 8 - // redactNormalizedRuntimeSecrets masks registered runtime secrets in the // forms cleanup rewrites them into: an ANSI-split or tab-containing // credential normalizes to different text than the registered literal, so @@ -101,8 +97,12 @@ const minNormalizedSecretLen = 8 // the reconstructed credential is displayed and retained. func redactNormalizedRuntimeSecrets(s string) string { for _, secret := range security.RuntimeSecrets() { + // The original literal passed the registration length floor, so + // every non-empty normalized form is a derivative of an + // authenticated credential and is masked, mirroring + // redactSecretLiteralsWithNormalizer in the CLI. normalized := NormalizeProgressText(secret) - if len(normalized) < minNormalizedSecretLen || normalized == secret { + if normalized == "" || normalized == secret { continue } if strings.Contains(s, normalized) { diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go index 25d700713f..0ab67a51f8 100644 --- a/internal/runtime/status_progress.go +++ b/internal/runtime/status_progress.go @@ -8,6 +8,10 @@ type statusProgressDisplay struct { context string } +// maxStatusProgressEntries bounds the status-event display cache. It shares +// the task-progress scale because both caches retain one row per active key. +const maxStatusProgressEntries = maxTaskProgressEntries + func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) string) (string, bool) { if e.Kind == "" { return "", false @@ -55,7 +59,7 @@ func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) s } // Only a new key needs a free slot: updating an existing key at // capacity must not discard the retained state of every other key. - if _, exists := r.statusProgressSeen[key]; !exists && len(r.statusProgressSeen) >= maxTaskProgressEntries { + if _, exists := r.statusProgressSeen[key]; !exists && len(r.statusProgressSeen) >= maxStatusProgressEntries { clear(r.statusProgressSeen) } r.statusProgressSeen[key] = statusProgressDisplay{message: msg, subject: subject, context: context} diff --git a/internal/runtime/status_progress_test.go b/internal/runtime/status_progress_test.go index 6aa30b65b5..70b4034a58 100644 --- a/internal/runtime/status_progress_test.go +++ b/internal/runtime/status_progress_test.go @@ -72,15 +72,15 @@ func TestStatusProgressCapacityUpdateKeepsExistingEntries(t *testing.T) { var out bytes.Buffer r := newTestRenderer(&out) // Fill the status cache to capacity with distinct keys carrying subjects. - for i := range maxTaskProgressEntries { + for i := range maxStatusProgressEntries { r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row " + fmt.Sprint(i), Subject: "subject " + fmt.Sprint(i), SubjectSet: true}) } - if len(r.progress.statusProgressSeen) != maxTaskProgressEntries { + if len(r.progress.statusProgressSeen) != maxStatusProgressEntries { t.Fatalf("setup: want %d entries, got %d", maxTaskProgressEntries, len(r.progress.statusProgressSeen)) } // Updating an existing key at capacity must not wipe the cache. r.Handle(StatusProgressEvent{Kind: "row", ID: "0", Label: "row 0 updated"}) - if len(r.progress.statusProgressSeen) != maxTaskProgressEntries { + if len(r.progress.statusProgressSeen) != maxStatusProgressEntries { t.Fatalf("existing-key update at capacity wiped the cache: %d entries remain", len(r.progress.statusProgressSeen)) } // Retained state of other keys must survive: a sparse update to a From f4920d3ef29b1fe81c60ec9f6e1aaca52fbe167e Mon Sep 17 00:00:00 2001 From: jctanner Date: Wed, 4 Nov 2026 14:04:16 -0500 Subject: [PATCH 13/16] docs(#8908): qualify hook-event rendering against the launch configuration Fullsend launches Claude with --print --verbose --output-format stream-json and no --include-hook-events. The SDK emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the docs table now says so, and the hook decoder fixtures use SessionStart to match the producer configuration instead of documenting PreToolUse behaviour fullsend never receives. The decoder itself still accepts any hook_event value if a future launch enables hook events. Signed-off-by: jctanner --- docs/runtimes/claude.md | 2 +- internal/runtime/claude_status_progress_test.go | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index 78ceec73d0..d8c2aaff08 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -414,7 +414,7 @@ the identity fallback. | `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | | `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | | `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | -| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. | +| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. Fullsend launches Claude without `--include-hook-events`, and the SDK emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the decoder still renders other hook events if a future launch enables them. | | `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | | `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | | `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | diff --git a/internal/runtime/claude_status_progress_test.go b/internal/runtime/claude_status_progress_test.go index e3a8d74c1c..abd1779e3e 100644 --- a/internal/runtime/claude_status_progress_test.go +++ b/internal/runtime/claude_status_progress_test.go @@ -9,9 +9,13 @@ import ( // Shapes below are reduced from the embedded SDK schemas/emitter in Claude // 2.1.312. Raw output/prompt/result fields are included to prove exclusion. +// Fullsend launches Claude without --include-hook-events, and the SDK emits +// only SessionStart and Setup hook events in that mode, so the hook fixtures +// use SessionStart to match the producer configuration real runs use; the +// decoder itself accepts any hook_event value. func TestClaudeStatusProgressShapes(t *testing.T) { cases := []struct{ name, line, want string }{ - {"hook start", `{"type":"system","subtype":"hook_started","hook_id":"h1","hook_name":"guard","hook_event":"PreToolUse"}`, "Hook guard [PreToolUse] — running"}, + {"hook start", `{"type":"system","subtype":"hook_started","hook_id":"h1","hook_name":"guard","hook_event":"SessionStart"}`, "Hook guard [SessionStart] — running"}, {"hook progress", `{"type":"system","subtype":"hook_progress","hook_id":"h1","hook_name":"guard","stdout":"PRIVATE","stderr":"PRIVATE","output":"PRIVATE"}`, "Hook guard — running"}, {"hook success", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"success","exit_code":0,"output":"PRIVATE"}`, "completed: exit 0"}, {"hook failed", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"error","exit_code":2}`, "failed: exit 2"}, From 798c51fde875b0963d40b88cc288fedf11e74f26 Mon Sep 17 00:00:00 2001 From: jctanner Date: Wed, 4 Nov 2026 15:27:06 -0500 Subject: [PATCH 14/16] fix(#8908): mask overlapping credentials longest-first and settle tool row churn Redaction: registered runtime secrets and their normalized forms are now masked in one pass ordered by each literal own length, before pattern redaction. The registry orders by raw length, but normalization can reverse that order, so a shorter normalized form masked first could destroy a longer overlapping credential match and leave its suffix displayed and retained. The joined status row is also masked after its label/subject/context joins, which can reconstruct a tab-containing credential from fields redacted individually. Task rows: a parent-task tool swap no longer prints a second row per subagent tool call (the SDK already emits those tools as ToolUseEvents). The dedup comparison is tool-name-insensitive but tool-presence- sensitive, so a tool appearing or disappearing still prints while a swap does not; the retained event keeps the latest tool name. The status cache capacity guard reuses the entry lookup, and tests were repaired to assert retention through changed output rather than assertions that pass regardless of the fix. Also restores a non-SessionStart hook fixture and cites the inspected SDK version in the hook docs row. Signed-off-by: jctanner --- docs/runtimes/claude.md | 2 +- .../runtime/claude_status_progress_test.go | 1 + internal/runtime/progress_pattern_test.go | 36 +++++++++++++ internal/runtime/progress_text.go | 51 +++++++++++-------- internal/runtime/status_progress.go | 9 +++- internal/runtime/status_progress_test.go | 41 +++++++++++---- internal/runtime/task_progress_reconciler.go | 12 +++++ 7 files changed, 117 insertions(+), 35 deletions(-) diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index d8c2aaff08..d1003af00d 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -414,7 +414,7 @@ the identity fallback. | `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | | `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | | `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | -| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. Fullsend launches Claude without `--include-hook-events`, and the SDK emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the decoder still renders other hook events if a future launch enables them. | +| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. Fullsend launches Claude without `--include-hook-events`, and the SDK (inspected Claude 2.1.312) emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the decoder still renders other hook events if a future launch enables them. | | `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | | `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | | `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | diff --git a/internal/runtime/claude_status_progress_test.go b/internal/runtime/claude_status_progress_test.go index abd1779e3e..5836493375 100644 --- a/internal/runtime/claude_status_progress_test.go +++ b/internal/runtime/claude_status_progress_test.go @@ -16,6 +16,7 @@ import ( func TestClaudeStatusProgressShapes(t *testing.T) { cases := []struct{ name, line, want string }{ {"hook start", `{"type":"system","subtype":"hook_started","hook_id":"h1","hook_name":"guard","hook_event":"SessionStart"}`, "Hook guard [SessionStart] — running"}, + {"hook start other events", `{"type":"system","subtype":"hook_started","hook_id":"h2","hook_name":"guard","hook_event":"PreToolUse"}`, "Hook guard [PreToolUse] — running"}, {"hook progress", `{"type":"system","subtype":"hook_progress","hook_id":"h1","hook_name":"guard","stdout":"PRIVATE","stderr":"PRIVATE","output":"PRIVATE"}`, "Hook guard — running"}, {"hook success", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"success","exit_code":0,"output":"PRIVATE"}`, "completed: exit 0"}, {"hook failed", `{"type":"system","subtype":"hook_response","hook_id":"h1","hook_name":"guard","outcome":"error","exit_code":2}`, "failed: exit 2"}, diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go index 408034c3c1..3e838ebe5b 100644 --- a/internal/runtime/progress_pattern_test.go +++ b/internal/runtime/progress_pattern_test.go @@ -128,3 +128,39 @@ func TestProgressFallbackRedactsShortNormalizedRuntimeSecret(t *testing.T) { t.Fatalf("short normalized registered literal escaped rendering: %q", out.String()) } } + +func TestProgressFallbackMaskingOrderKeepsOverlappingCredentials(t *testing.T) { + // A secret with a longer raw value can normalize shorter than another + // secret's normalized form. Masking in registry (raw-length) order + // would replace the shorter literal first and leave the longer + // overlapping credential's suffix visible. No callback is set. + long := "abc\x1b[32m\x1b[0mdef" // raw 14, normalizes to "abcdef" + short := "abcdefghi\tj" // raw 10, normalizes to "abcdefghi j" + if !security.RegisterRuntimeSecret(long) || !security.RegisterRuntimeSecret(short) { + t.Fatal("register synthetic literals") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "status abcdefghi j done"}) + if strings.Contains(out.String(), "ghi j") || !strings.Contains(out.String(), "***") { + t.Fatalf("overlapping normalized credential leaked: %q", out.String()) + } +} + +func TestTaskProgressToolOnlyFramesDoNotPrint(t *testing.T) { + // Subagent tool calls already arrive as ToolUseEvents; a task_progress + // frame that only changes last_tool_name must not print a second line. + lines := `{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Subagent work","last_tool_name":"Read"}` + "\n" + + `{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Subagent work","last_tool_name":"Bash"}` + "\n" + var out bytes.Buffer + r := newTestRenderer(&out) + if err := parseClaudeStream(strings.NewReader(lines), r.Handle); err != nil { + t.Fatal(err) + } + if strings.Count(out.String(), "Task sub1") != 1 { + t.Fatalf("tool-only task_progress printed more than once: %q", out.String()) + } + if strings.Contains(out.String(), "tool: Bash") { + t.Fatalf("tool-only change printed a second row: %q", out.String()) + } +} diff --git a/internal/runtime/progress_text.go b/internal/runtime/progress_text.go index c279209649..b84cbf5cbe 100644 --- a/internal/runtime/progress_text.go +++ b/internal/runtime/progress_text.go @@ -1,6 +1,8 @@ package runtime import ( + "cmp" + "slices" "strings" "unicode/utf8" @@ -78,35 +80,40 @@ func scanProgressSecrets(s string) string { if candidate == "" { return s } - text := s - if result := progressRedactor.Scan(candidate); !result.Safe { + masked := maskRuntimeSecretLiterals(candidate) + text := masked + if result := progressRedactor.Scan(masked); !result.Safe { text = result.Sanitized } - if masked := redactNormalizedRuntimeSecrets(text); masked != text { - return masked + if text != candidate { + return text } - return text + return s } -// redactNormalizedRuntimeSecrets masks registered runtime secrets in the -// forms cleanup rewrites them into: an ANSI-split or tab-containing -// credential normalizes to different text than the registered literal, so -// exact-literal matching alone can let a reconstructed secret through. The -// CLI callback redacts normalized literals itself (redactProgressSecret- -// Literals); the renderer nil-callback fallback must match them too, or -// the reconstructed credential is displayed and retained. -func redactNormalizedRuntimeSecrets(s string) string { +// maskRuntimeSecretLiterals masks registered runtime secrets and their +// normalized forms in one longest-first pass. The registry is ordered by +// raw length, but normalization can reverse that order: a secret with a +// longer raw value can normalize shorter than another secret's normalized +// form. Masking in registry order would then replace the shorter literal +// first and destroy the longer overlapping credential's match, leaving its +// suffix visible. Pattern redaction runs after the literal pass for the +// same reason. The original literal passed the registration length floor, +// so every non-empty normalized form is a derivative of an authenticated +// credential and is masked, mirroring redactSecretLiteralsWithNormalizer +// in the CLI. +func maskRuntimeSecretLiterals(s string) string { + var literals []string for _, secret := range security.RuntimeSecrets() { - // The original literal passed the registration length floor, so - // every non-empty normalized form is a derivative of an - // authenticated credential and is masked, mirroring - // redactSecretLiteralsWithNormalizer in the CLI. - normalized := NormalizeProgressText(secret) - if normalized == "" || normalized == secret { - continue + literals = append(literals, secret) + if normalized := NormalizeProgressText(secret); normalized != "" && normalized != secret { + literals = append(literals, normalized) } - if strings.Contains(s, normalized) { - s = strings.ReplaceAll(s, normalized, "***") + } + slices.SortStableFunc(literals, func(a, b string) int { return cmp.Compare(len(b), len(a)) }) + for _, literal := range literals { + if strings.Contains(s, literal) { + s = strings.ReplaceAll(s, literal, "***") } } return s diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go index 0ab67a51f8..8e12061acb 100644 --- a/internal/runtime/status_progress.go +++ b/internal/runtime/status_progress.go @@ -17,7 +17,7 @@ func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) s return "", false } key := sha256.Sum256([]byte(e.Kind + "\x00" + e.ID)) - previous := r.statusProgressSeen[key] + previous, keyPresent := r.statusProgressSeen[key] if e.Clear { delete(r.statusProgressSeen, key) return "", false @@ -50,6 +50,11 @@ func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) s msg += ": " + detail } msg = sanitizeOutput(msg) + // Fields are redacted individually; the joins can reconstruct a + // credential (a tab-containing secret normalizes to the exact text a + // label/subject join produces). Mask the joined row before dedup + // comparison, retention and display. + msg = scanProgressSecrets(msg) if !e.Occurrence && previous.message == msg { return "", false } @@ -59,7 +64,7 @@ func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) s } // Only a new key needs a free slot: updating an existing key at // capacity must not discard the retained state of every other key. - if _, exists := r.statusProgressSeen[key]; !exists && len(r.statusProgressSeen) >= maxStatusProgressEntries { + if !keyPresent && len(r.statusProgressSeen) >= maxStatusProgressEntries { clear(r.statusProgressSeen) } r.statusProgressSeen[key] = statusProgressDisplay{message: msg, subject: subject, context: context} diff --git a/internal/runtime/status_progress_test.go b/internal/runtime/status_progress_test.go index 70b4034a58..8c682e36c6 100644 --- a/internal/runtime/status_progress_test.go +++ b/internal/runtime/status_progress_test.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" "testing" + + "github.com/fullsend-ai/fullsend/internal/security" ) func TestStatusProgressRendererSafetyAndBounds(t *testing.T) { @@ -76,23 +78,42 @@ func TestStatusProgressCapacityUpdateKeepsExistingEntries(t *testing.T) { r.Handle(StatusProgressEvent{Kind: "row", ID: fmt.Sprint(i), Label: "row " + fmt.Sprint(i), Subject: "subject " + fmt.Sprint(i), SubjectSet: true}) } if len(r.progress.statusProgressSeen) != maxStatusProgressEntries { - t.Fatalf("setup: want %d entries, got %d", maxTaskProgressEntries, len(r.progress.statusProgressSeen)) + t.Fatalf("setup: want %d entries, got %d", maxStatusProgressEntries, len(r.progress.statusProgressSeen)) } + out.Reset() // Updating an existing key at capacity must not wipe the cache. r.Handle(StatusProgressEvent{Kind: "row", ID: "0", Label: "row 0 updated"}) if len(r.progress.statusProgressSeen) != maxStatusProgressEntries { t.Fatalf("existing-key update at capacity wiped the cache: %d entries remain", len(r.progress.statusProgressSeen)) } - // Retained state of other keys must survive: a sparse update to a - // different key still merges its retained subject, and dedup still - // suppresses an identical resend. - r.Handle(StatusProgressEvent{Kind: "row", ID: "1", Label: "row 1"}) - if msg := out.String(); !strings.Contains(msg, "row 1 subject 1") { + // Retained state of other keys must survive: a changed label on another + // key still merges its retained subject, printing the new row exactly + // once. (An unchanged resend is deduplicated and proves nothing: it + // prints nothing whether or not the cache was wiped.) + r.Handle(StatusProgressEvent{Kind: "row", ID: "1", Label: "row 1 changed"}) + if msg := out.String(); !strings.Contains(msg, "row 1 changed subject 1") { t.Fatalf("retained subject lost after capacity update: %q", msg) } - out.Reset() - r.Handle(StatusProgressEvent{Kind: "row", ID: "1", Label: "row 1"}) - if out.String() != "" { - t.Fatalf("dedup broken after capacity update: %q", out.String()) + if strings.Count(out.String(), "row 1 changed subject 1") != 1 { + t.Fatalf("capacity update row printed more than once: %q", out.String()) + } +} + +func TestStatusProgressJoinCannotReconstructCredential(t *testing.T) { + // A tab-containing credential normalizes to the exact text a + // label/subject join can produce when the credential is split across + // fields. The joined row must be masked before display and retention. + const secret = "opaque-join-runtime-secret \tfor-test" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + if NormalizeProgressText(secret) != "opaque-join-runtime-secret for-test" { + t.Fatalf("setup: unexpected normalized form %q", NormalizeProgressText(secret)) + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(StatusProgressEvent{Kind: "hook", ID: "one", Label: "opaque-join-runtime-secret", Subject: "for-test", SubjectSet: true}) + if strings.Contains(out.String(), "for-test") || strings.Contains(out.String(), "opaque-join-runtime-secret") { + t.Fatalf("joined credential leaked: %q", out.String()) } } diff --git a/internal/runtime/task_progress_reconciler.go b/internal/runtime/task_progress_reconciler.go index b5fd421695..f9949a3ecb 100644 --- a/internal/runtime/task_progress_reconciler.go +++ b/internal/runtime/task_progress_reconciler.go @@ -126,6 +126,18 @@ func (r *progressReconciler) task(e TaskProgressEvent, redact func(string) strin indexed := e indexed.AgentID = "" comparison = taskProgressMessage(indexed) + } else if e.AgentID == "" { + // A parent-task tool swap is attribution, not a progress + // transition: subagent tool calls already print as ToolUseEvents, + // so the row must not churn once per tool. Compare on tool + // presence rather than name; the retained event keeps the latest + // tool name for the next row that prints for a real reason. + toolless := e + toolless.ToolSummary = "" + if toolless.ToolName != "" { + toolless.ToolName = "tool" + } + comparison = taskProgressMessage(toolless) } fingerprint := sha256.Sum256([]byte(comparison)) r.storeTaskProgress(key, taskProgressDisplay{event: e, fingerprint: fingerprint}, isAgent) From 81af21d9d767edbe9f1cb2eb32ca28f99f3678c5 Mon Sep 17 00:00:00 2001 From: jctanner Date: Wed, 4 Nov 2026 15:50:10 -0500 Subject: [PATCH 15/16] fix(#8908): merge literal match spans and mask the joined row with the caller callback Cross-model review of the longest-first masking found that no sequential replacement order survives crossing overlaps: one secret end overlapping another secret start leaves a fragment visible whichever is replaced first, and a self-overlapping literal re-matches its own replacement. Literal match ranges are now collected against the original text and their union is masked in one rewrite. The joined status row also runs the caller redaction callback before the fallback scanner, so environment-derived credentials split across fields are masked too. Test literals were made distinctive so registered normalized forms cannot mask unrelated later tests, and the tool-churn tests now cover appearance, explicit clears, retained names on real transitions, and usage-bearing frames. Signed-off-by: jctanner --- docs/runtimes/claude.md | 2 +- internal/runtime/progress_pattern_test.go | 61 +++++++++++++++++++++-- internal/runtime/progress_text.go | 58 ++++++++++++++++----- internal/runtime/status_progress.go | 11 +++- 4 files changed, 111 insertions(+), 21 deletions(-) diff --git a/docs/runtimes/claude.md b/docs/runtimes/claude.md index d1003af00d..a8c60eb31d 100644 --- a/docs/runtimes/claude.md +++ b/docs/runtimes/claude.md @@ -414,7 +414,7 @@ the identity fallback. | `task_notification` | Completion, failure or stop, including a worker-restart cause when supplied; full result summary excluded. | | `task_summary` | Undocumented internal mid-turn summary; best-effort display, with null/empty values clearing deduplication silently. | | `background_tasks_changed` | Count of reported non-ambient background tasks; membership is not execution or completion evidence. | -| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. Fullsend launches Claude without `--include-hook-events`, and the SDK (inspected Claude 2.1.312) emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the decoder still renders other hook events if a future launch enables them. | +| `hook_started`, `hook_progress`, `hook_response` | Hook name/event, running/outcome and exit code; stdout/stderr/output excluded. Fullsend launches Claude without `--include-hook-events`, and the inspected Claude 2.1.312 producer emits only SessionStart and Setup hook events in that mode, so those are the only hook rows real runs produce; the decoder still renders other hook events if a future launch enables them. | | `permission_denied` | Tool/agent identity and bounded decision reason; tool-result body excluded. | | `status`, `session_state_changed` | Compaction, session state and action-required transitions; per-request status chatter excluded. | | `informational`, `notification` | Salient notices, suggestions, warnings and text notifications; unkeyed occurrences repeat, transcript-only info excluded. | diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go index 3e838ebe5b..5e8b61508e 100644 --- a/internal/runtime/progress_pattern_test.go +++ b/internal/runtime/progress_pattern_test.go @@ -110,7 +110,7 @@ func TestProgressFallbackRedactsNormalizedRuntimeSecret(t *testing.T) { // authenticated secret. No RedactProgress callback is set, exercising the // renderer fallback. func TestProgressFallbackRedactsShortNormalizedRuntimeSecret(t *testing.T) { - const secret = "zz\x1b[32m\x1b[0mtok" // raw length 14; normalizes to "zztok" (5) + const secret = "zz\x1b[32m\x1b[0mtok" // raw length 14 bytes; normalizes to "zztok" (5) if !security.RegisterRuntimeSecret(secret) { t.Fatal("register synthetic literal") } @@ -134,19 +134,38 @@ func TestProgressFallbackMaskingOrderKeepsOverlappingCredentials(t *testing.T) { // secret's normalized form. Masking in registry (raw-length) order // would replace the shorter literal first and leave the longer // overlapping credential's suffix visible. No callback is set. - long := "abc\x1b[32m\x1b[0mdef" // raw 14, normalizes to "abcdef" - short := "abcdefghi\tj" // raw 10, normalizes to "abcdefghi j" + long := "containment-long\x1b[32m\x1b[0m" // raw 25 bytes, normalizes to "containment-long" + short := "containment-long-suffix" // raw 23 bytes, normalizes to itself if !security.RegisterRuntimeSecret(long) || !security.RegisterRuntimeSecret(short) { t.Fatal("register synthetic literals") } var out bytes.Buffer r := newTestRenderer(&out) - r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "status abcdefghi j done"}) - if strings.Contains(out.String(), "ghi j") || !strings.Contains(out.String(), "***") { + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "status containment-long-suffix done"}) + if strings.Contains(out.String(), "containment-long") || !strings.Contains(out.String(), "***") { t.Fatalf("overlapping normalized credential leaked: %q", out.String()) } } +func TestProgressFallbackMergesCrossingOverlaps(t *testing.T) { + // One secret's end overlapping another's start defeats every + // sequential replacement order; the merged span must be masked whole. + a := "crossing-alpha-start" + b := "start-crossing-beta" + if !security.RegisterRuntimeSecret(a) || !security.RegisterRuntimeSecret(b) { + t.Fatal("register synthetic literals") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "one", State: TaskRunning, Label: "prefix crossing-alpha-start-crossing-beta suffix"}) + if strings.Contains(out.String(), "crossing-alpha") || strings.Contains(out.String(), "crossing-beta") { + t.Fatalf("crossing overlap leaked a fragment: %q", out.String()) + } + if !strings.Contains(out.String(), "***") { + t.Fatalf("crossing overlap was not masked: %q", out.String()) + } +} + func TestTaskProgressToolOnlyFramesDoNotPrint(t *testing.T) { // Subagent tool calls already arrive as ToolUseEvents; a task_progress // frame that only changes last_tool_name must not print a second line. @@ -164,3 +183,35 @@ func TestTaskProgressToolOnlyFramesDoNotPrint(t *testing.T) { t.Fatalf("tool-only change printed a second row: %q", out.String()) } } + +func TestTaskProgressToolLifecyclePrintsRealTransitions(t *testing.T) { + // Tool swaps are attribution churn and do not print, but a tool + // appearing or disappearing changes the row, and a later real + // transition prints the latest retained tool name. Frames carry + // usage counters like real SDK snapshots to prove they do not churn. + parse := func(raw string, r *EventRenderer) { + t.Helper() + if err := parseClaudeStream(strings.NewReader(raw+"\n"), r.Handle); err != nil { + t.Fatal(err) + } + } + var out bytes.Buffer + r := newTestRenderer(&out) + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","usage":{"total_tokens":10,"tool_uses":1}}`, r) + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","last_tool_name":"Read","usage":{"total_tokens":20,"tool_uses":2}}`, r) + if !strings.Contains(out.String(), "tool: Read") { + t.Fatalf("tool appearance did not print: %q", out.String()) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","last_tool_name":"Bash","usage":{"total_tokens":30,"tool_uses":3}}`, r) + if strings.Contains(out.String(), "tool: Bash") { + t.Fatalf("tool swap printed a row: %q", out.String()) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","summary":"Halfway","last_tool_name":"Bash","usage":{"total_tokens":40,"tool_uses":4}}`, r) + if !strings.Contains(out.String(), "tool: Bash") || !strings.Contains(out.String(), "Halfway") { + t.Fatalf("real transition lost the retained tool name: %q", out.String()) + } + parse(`{"type":"system","subtype":"task_progress","task_id":"sub1","description":"Work","last_tool_name":"","summary":""}`, r) + if !strings.HasSuffix(strings.TrimRight(out.String(), "\n"), "— running") { + t.Fatalf("explicit tool and summary clear did not print: %q", out.String()) + } +} diff --git a/internal/runtime/progress_text.go b/internal/runtime/progress_text.go index b84cbf5cbe..33ca569939 100644 --- a/internal/runtime/progress_text.go +++ b/internal/runtime/progress_text.go @@ -1,7 +1,6 @@ package runtime import ( - "cmp" "slices" "strings" "unicode/utf8" @@ -92,14 +91,16 @@ func scanProgressSecrets(s string) string { } // maskRuntimeSecretLiterals masks registered runtime secrets and their -// normalized forms in one longest-first pass. The registry is ordered by -// raw length, but normalization can reverse that order: a secret with a -// longer raw value can normalize shorter than another secret's normalized -// form. Masking in registry order would then replace the shorter literal -// first and destroy the longer overlapping credential's match, leaving its -// suffix visible. Pattern redaction runs after the literal pass for the -// same reason. The original literal passed the registration length floor, -// so every non-empty normalized form is a derivative of an authenticated +// normalized forms in one rewrite. Match ranges for every literal are +// collected against the original text and their union is masked, because +// no sequential replacement order survives crossing overlaps: one +// secret's end overlapping another's start leaves a fragment of one +// visible whichever is replaced first, and a self-overlapping literal +// must not re-match its own replacement. The registry orders by raw +// length, but normalization can reverse that order, so ordering alone +// was never sufficient. Pattern redaction runs after the literal pass. +// The original literal passed the registration length floor, so every +// non-empty normalized form is a derivative of an authenticated // credential and is masked, mirroring redactSecretLiteralsWithNormalizer // in the CLI. func maskRuntimeSecretLiterals(s string) string { @@ -110,13 +111,44 @@ func maskRuntimeSecretLiterals(s string) string { literals = append(literals, normalized) } } - slices.SortStableFunc(literals, func(a, b string) int { return cmp.Compare(len(b), len(a)) }) + if len(literals) == 0 { + return s + } + covered := make([]bool, len(s)) for _, literal := range literals { - if strings.Contains(s, literal) { - s = strings.ReplaceAll(s, literal, "***") + if literal == "" { + continue + } + // Advance one byte past each match so overlapping occurrences of + // the same literal are all collected. + for offset := 0; offset+len(literal) <= len(s); { + i := strings.Index(s[offset:], literal) + if i < 0 { + break + } + start := offset + i + for j := start; j < start+len(literal); j++ { + covered[j] = true + } + offset = start + 1 } } - return s + if !slices.Contains(covered, true) { + return s + } + var b strings.Builder + for i := 0; i < len(s); { + if covered[i] { + b.WriteString("***") + for i < len(s) && covered[i] { + i++ + } + continue + } + b.WriteByte(s[i]) + i++ + } + return b.String() } // NormalizeProgressText applies the same cleanup to display text and caller diff --git a/internal/runtime/status_progress.go b/internal/runtime/status_progress.go index 8e12061acb..8171a4990b 100644 --- a/internal/runtime/status_progress.go +++ b/internal/runtime/status_progress.go @@ -52,8 +52,15 @@ func (r *progressReconciler) status(e StatusProgressEvent, redact func(string) s msg = sanitizeOutput(msg) // Fields are redacted individually; the joins can reconstruct a // credential (a tab-containing secret normalizes to the exact text a - // label/subject join produces). Mask the joined row before dedup - // comparison, retention and display. + // label/subject join produces). The caller's callback runs first: it + // owns literals the fallback scanner cannot know, such as + // environment-derived credentials. Mask the joined row before dedup + // comparison, retention and display. Retained subject/context stay + // per-field masked; fragments appearing across separate rows are the + // same exposure as printing the pieces separately and are accepted. + if redact != nil { + msg = redact(msg) + } msg = scanProgressSecrets(msg) if !e.Occurrence && previous.message == msg { return "", false From d667f9323c55532eb1d8de871776fb1e6c5ba8cb Mon Sep 17 00:00:00 2001 From: jctanner Date: Wed, 4 Nov 2026 17:23:35 -0500 Subject: [PATCH 16/16] fix(#8908): mask the assembled task row against split credentials Task rows redact each field individually but the assembled message joins them, so a registered credential split across fields (for example TaskID and Label around the colon separator) reconstructed in the displayed row. The caller callback and the fallback scanner now run on the joined text before the fingerprint and display, mirroring the status rows. Adds a join reconstruction regression test. Signed-off-by: jctanner --- internal/runtime/progress_pattern_test.go | 18 ++++++++++++++++++ internal/runtime/task_progress_reconciler.go | 10 ++++++++++ 2 files changed, 28 insertions(+) diff --git a/internal/runtime/progress_pattern_test.go b/internal/runtime/progress_pattern_test.go index 5e8b61508e..d75f93f7c4 100644 --- a/internal/runtime/progress_pattern_test.go +++ b/internal/runtime/progress_pattern_test.go @@ -215,3 +215,21 @@ func TestTaskProgressToolLifecyclePrintsRealTransitions(t *testing.T) { t.Fatalf("explicit tool and summary clear did not print: %q", out.String()) } } + +func TestTaskProgressJoinCannotReconstructCredential(t *testing.T) { + // A credential split across TaskID and Label reconstructs in the + // assembled row; the joined message must be masked before display. + const secret = "taskrow-split: cred" + if !security.RegisterRuntimeSecret(secret) { + t.Fatal("register synthetic literal") + } + var out bytes.Buffer + r := newTestRenderer(&out) + r.Handle(TaskProgressEvent{TaskID: "taskrow-split", Label: "cred", State: TaskRunning}) + if strings.Contains(out.String(), "cred") || strings.Contains(out.String(), "taskrow-split: cred") { + t.Fatalf("joined task-row credential leaked: %q", out.String()) + } + if !strings.Contains(out.String(), "***") { + t.Fatalf("joined task-row credential was not masked: %q", out.String()) + } +} diff --git a/internal/runtime/task_progress_reconciler.go b/internal/runtime/task_progress_reconciler.go index f9949a3ecb..d3c2fc0e16 100644 --- a/internal/runtime/task_progress_reconciler.go +++ b/internal/runtime/task_progress_reconciler.go @@ -139,6 +139,16 @@ func (r *progressReconciler) task(e TaskProgressEvent, redact func(string) strin } comparison = taskProgressMessage(toolless) } + // The assembled row can reconstruct a credential split across fields + // (fields are redacted individually; the joins are not), so the caller + // callback and the fallback scanner run on the joined text before the + // fingerprint and display, mirroring the status rows. + if redact != nil { + msg = redact(msg) + comparison = redact(comparison) + } + msg = scanProgressSecrets(msg) + comparison = scanProgressSecrets(comparison) fingerprint := sha256.Sum256([]byte(comparison)) r.storeTaskProgress(key, taskProgressDisplay{event: e, fingerprint: fingerprint}, isAgent) if previous.fingerprint == fingerprint {