返回 DeepSeek-Reasonix
event.go
根目录 / internal / event / event.go
1 // Package event defines the typed event stream the agent emits as it runs a
2 // turn, and the Sink it emits to. It decouples "what happened" (the model
3 // produced reasoning, a tool was dispatched, a turn used N tokens) from "how to
4 // show it" (ANSI scrollback in a terminal, a card in a webview).
5 //
6 // The agent depends only on Sink; each frontend implements one. The chat TUI
7 // renders events to its scrollback; a headless run renders them to plain ANSI
8 // on stdout; a future GUI/serve transport forwards them to a webview or
9 // websocket. This replaces the old io.Writer contract, where the agent wrote
10 // pre-formatted ANSI and the consumer had to re-derive structure by matching
11 // line prefixes — fragile, and lossy for any frontend richer than a terminal.
12 package event
13
14 import (
15 "encoding/json"
16
17 "reasonix/internal/billing"
18 "reasonix/internal/evidence"
19 "reasonix/internal/nilutil"
20 "reasonix/internal/provider"
21 )
22
23 // Kind tags an Event. Read the field(s) documented for that kind.
24 type Kind int
25
26 const (
27 // TurnStarted marks the start of one top-level Run (one user turn). Sinks
28 // reset any per-turn rendering state on it. Carries no payload.
29 TurnStarted Kind = iota
30 // Reasoning is a thinking-mode reasoning delta (Text). Streamed before the
31 // visible answer; sinks typically render it muted under a "thinking" header.
32 Reasoning
33 // Text is an answer-text delta (Text).
34 Text
35 // Message marks the assistant turn's text as complete: Text holds the full
36 // answer and Reasoning the full chain-of-thought (both already streamed via
37 // the deltas above). A sink may use it to re-render the streamed raw text as
38 // styled markdown; a plain sink can ignore it.
39 Message
40 // ToolDispatch announces a tool call is about to run (Tool: ID/Name/Args/ReadOnly).
41 ToolDispatch
42 // ToolResult reports a finished tool call (Tool: Output/Err/Truncated set).
43 ToolResult
44 // Usage carries per-turn token telemetry (Usage; Pricing optional, for cost).
45 Usage
46 // Notice is an out-of-band message — a warning, truncation, block, or
47 // compaction notice (Level + Text).
48 Notice
49 // Phase marks a coordinator boundary, e.g. planner→executor handoff (Text =
50 // label such as "deepseek · planning").
51 Phase
52 // ApprovalRequest asks the frontend to approve a pending tool call
53 // (Approval: ID/Tool/Subject). The run blocks until the controller's
54 // Approve(ID, …) resolves it; a frontend shows a prompt and answers.
55 ApprovalRequest
56 // AskRequest asks the frontend to put one or more structured multiple-choice
57 // questions to the user (Ask: ID + Questions). The run blocks until the
58 // controller's AnswerQuestion(ID, …) resolves it. Powers the `ask` tool.
59 AskRequest
60 // TurnDone marks the end of one top-level Run (Err non-nil on failure;
61 // nil also for a user cancellation, which is not an error). Always the
62 // last event of a turn.
63 TurnDone
64 // CompactionStarted marks the start of a context-compaction pass (Compaction
65 // payload: Trigger). A frontend shows a "compacting…" placeholder while the
66 // summarizer runs; CompactionDone replaces it. Mirrors ToolDispatch/ToolResult.
67 CompactionStarted
68 // CompactionDone reports a finished compaction pass (Compaction payload:
69 // Trigger/Messages/Summary/Archive). An aborted pass emits this with an empty
70 // Summary so the placeholder still resolves. Replaces the older plain Notice
71 // so a sink can render a distinct, expandable card.
72 CompactionDone
73 // ToolProgress streams a chunk of a still-running tool's combined output
74 // (Tool: ID + Output = the new chunk). Emitted between ToolDispatch and
75 // ToolResult for long tools like bash so a frontend can show live progress.
76 // Appended last to keep the Kind values before it wire-stable.
77 ToolProgress
78 // MCPSurfaceReady fires once per server when its background-loaded surface
79 // (prompts or resources) finishes after startup. Lets UIs refresh /mcp
80 // status without polling. Text carries "<server>: <surface> ready (<count>
81 // items)". Appended last to keep the Kind values before it wire-stable.
82 MCPSurfaceReady
83 // Retrying fires before each backoff sleep while the provider re-attempts the
84 // connection+header phase after a transient failure (RetryAttempt of RetryMax).
85 // A frontend shows a transient "retrying (n/m)" indicator that the next stream
86 // event — or TurnDone — clears. Appended last to keep the Kind values before
87 // it wire-stable.
88 Retrying
89 // Steer fires when a mid-turn steer message is consumed from the queue and
90 // injected as a user message. Text carries the raw steer content (without the
91 // wrapper prefix), so a frontend can display it to the user as confirmation.
92 // Frontends use Steer to know a queued message has been delivered.
93 Steer
94 // GuardianAssessment reports the outcome of a guardian sub-agent safety review.
95 // Carries GuardianResult payload (Outcome, RiskLevel, Rationale, etc.).
96 GuardianAssessment
97 // ExtensionSurface carries a structured UI surface published by an extension
98 // sidecar (Extension payload with one of the Card/Form/Notification
99 // sub-structs set). Appended last to keep the Kind values before it
100 // wire-stable.
101 ExtensionSurface
102 // ExtensionStatus carries a one-line status contribution published by an
103 // extension sidecar (Extension payload with Status set). Appended last to
104 // keep the Kind values before it wire-stable.
105 ExtensionStatus
106 // StreamAttempt marks the local lifecycle of one sampling attempt within a
107 // model round (StreamAttempt payload: begin | discard | commit). IDs are
108 // local transcript identities — persisted in the event ledger, never sent
109 // to the model. Appended last to
110 // keep earlier Kind values wire-stable; older clients ignore unknown kinds.
111 StreamAttempt
112 // ContextMaintenance reports a free tool-result maintenance or a durable
113 // blocked/noop outcome. It is separate from CompactionStarted/Done so UIs do
114 // not render a paid-summary card for a cache-preserving view update.
115 ContextMaintenanceEvent
116 // WorkspaceChanged reports a debounced host-side workspace mutation.
117 WorkspaceChanged
118 // TurnPhase reports a host-side work phase for the active turn (working |
119 // checking | verifying | reviewing). Content-free; Text holds the phase.
120 TurnPhase
121 // CompletionSummary reports a content-free end-of-turn quality summary for
122 // role-setting strategies (preset, verdict, check counts, review status).
123 CompletionSummary
124 // ToolResultPreview reports that a tool has finished locally before its
125 // provider-ordered ToolResult can be emitted. Upsert-capable frontends may
126 // render the successful state early; append-only consumers should ignore it.
127 // The later ToolResult remains the call's only terminal event.
128 ToolResultPreview
129 // TurnStatusChanged is a content-free lifecycle transition such as
130 // waiting_user, cancelling, or returning to in_progress after an answer.
131 TurnStatusChanged
132 // PromptAnswered records that a durable Ask/approval item was answered and the same turn resumed; ItemID carries the stable prompt id and answer content remains in its purpose-built decision receipt.
133 PromptAnswered
134 // MCPInteractionRequest carries a server-initiated MCP elicitation (form
135 // or URL) for the frontend to answer via the MCP interaction resolve call.
136 // Appended last to keep the Kind values before it wire-stable.
137 MCPInteractionRequest
138 // SessionChanged is a content-free Serve routing barrier for all-session clients.
139 SessionChanged
140 // ReadStatus upserts one logical read's delivery state instead of per page.
141 ReadStatus
142 ToolStarted // Persisted after policy/validation and before execution.
143 // UserMessage binds an admitted user bubble to its persisted message ID.
144 // Text is display text; provider-only framing must never be emitted here.
145 UserMessage
146 // SessionOperation is a controller-owned, provider-excluded maintenance
147 // lifecycle. One stable operation id is upserted from running through its
148 // terminal state without inventing a user turn.
149 SessionOperation
150 // KindCount is a sentinel one past the last real Kind. New event kinds must
151 // be inserted above it so completeness tests cover them automatically.
152 KindCount
153 )
154
155 // TurnPhaseName is the machine-readable phase on TurnPhase events.
156 type TurnPhaseName string
157
158 const (
159 TurnPhaseWorking TurnPhaseName = "working"
160 TurnPhaseChecking TurnPhaseName = "checking"
161 TurnPhaseVerifying TurnPhaseName = "verifying"
162 TurnPhaseReviewing TurnPhaseName = "reviewing"
163 )
164
165 // CompletionSummaryInfo is the content-free quality summary on CompletionSummary
166 // events. It never carries user prompts, file contents, command args, or
167 // reviewer reasoning.
168 type CompletionSummaryInfo struct {
169 Preset string // deprecated wire-compat label; pinned to "balanced"
170 Verdict string // complete | partial | blocked | continue
171 Mutations int
172 ChangedFiles int
173 ChecksPassed int
174 ChecksFailed int
175 ChecksSuppressed int
176 Review string // none | passed | warned | failed | unavailable
177 GapKinds []string
178 ConstraintDegraded bool
179 Floor string // standard | delivery; empty on legacy events
180 Attention bool // authoritative when Floor is non-empty
181 }
182
183 // Level classifies a Notice so sinks can style or filter it.
184 type Level int
185
186 const (
187 LevelInfo Level = iota
188 LevelWarn
189 )
190
191 // NoticeAudience separates a notice's recipient from its severity. The empty
192 // default preserves the existing contract: ordinary notices are eligible for
193 // every frontend. Operator notices describe local runtime maintenance and must
194 // not be forwarded as end-user chat messages. Local frontends and diagnostics
195 // remain free to surface or quietly record them under their own policy.
196 type NoticeAudience string
197
198 const (
199 NoticeAudienceDefault NoticeAudience = ""
200 NoticeAudienceOperator NoticeAudience = "operator"
201 )
202
203 // Profile carries the subagent model/effort resolved for this call.
204 type Profile struct {
205 Model string
206 Effort string
207 }
208
209 // Tool describes a tool call for ToolDispatch / ToolResult events. On dispatch
210 // ID/Name/Args/ReadOnly and optional preview metadata are set; on result
211 // Output/Err/Truncated are filled in. Args is the raw JSON arguments — a sink
212 // compacts it for display.
213 type Tool struct {
214 RunState provider.ToolRunState
215 Diagnostic json.RawMessage `json:"diagnostic,omitempty"`
216 // Verifying is emitted only once an authorized check actually enters execution.
217 Verifying bool
218 ID string
219 Name string
220 Args string
221 // Todos is the complete semantic todo replacement committed with a
222 // successful todo_write result. TodoWritten distinguishes an empty list
223 // from an older event with no semantic payload.
224 Todos []Todo
225 TodoWritten bool
226 // ResolvedName/CapabilityID describe the real target behind a stable proxy
227 // while Name/Args remain the provider-visible call. They are optional local
228 // display metadata and never enter provider requests.
229 ResolvedName string
230 CapabilityID string
231 Output string // ToolResult: the result text fed to the model
232 Err string // ToolResult: non-empty when the call failed or was blocked
233 PresentedFiles []provider.PresentedFile
234 ReadOnly bool
235 Truncated bool // ToolResult: Output was head+tailed before display/model
236 DurationMs int64 // ToolResult: wall-clock execution time in milliseconds
237 // StartedAt/EndedAt are unix-millisecond execution bounds (ToolResult).
238 // Zero when the call never ran (dependency-skipped, cancelled, synthetic).
239 StartedAt int64
240 EndedAt int64
241 // Partial marks an early ToolDispatch emitted when a call begins (ID/Name set,
242 // Args still streaming) so a frontend can show the card immediately; a second,
243 // full ToolDispatch (Partial false, Args set) follows when the call completes.
244 Partial bool
245 // ArgChars is the cumulative argument characters received so far for a
246 // Partial dispatch — a liveness signal while a large payload streams. Zero
247 // on the initial start dispatch and on full dispatches.
248 ArgChars int
249 // Refreshed marks a repeated full ToolDispatch for the same ID whose file
250 // preview or resolved proxy metadata changed after the initial dispatch.
251 // Frontends that can upsert by ID should replace the existing card;
252 // append-only sinks should ignore it to avoid duplicate tool cards.
253 Refreshed bool
254 // ParentID, when set, is the ID of the tool call that spawned this one — a
255 // sub-agent's calls carry the parent `task` call's ID so a frontend can nest
256 // them under it. Empty for top-level calls.
257 ParentID string
258 // AttemptID is the host-local stream_attempt id that produced a speculative
259 // partial ToolDispatch. Empty for committed/full dispatches and for nested
260 // sub-agent tools. Frontends must only journal partial events whose
261 // AttemptID matches the active stream_attempt begin.
262 AttemptID string
263 FileDiff
264 Profile *Profile // ToolDispatch: subagent model/effort (set for task/skill calls)
265 // Subagent outcome metadata is host/UI-only and never enters provider requests.
266 SubagentRef string
267 SubagentStatus string
268 SubagentErrorCode string
269 SubagentRetryable bool
270 // Execution is optional local shell metadata (ToolResult). Never sent to
271 // model providers; omitempty keeps old wire readers compatible.
272 Execution *ShellExecution
273 // Workspace mutation metadata is host-only and is omitted from eventwire.
274 WorkspaceMutation bool
275 WorkspacePaths []string
276 WorkspaceAllPaths bool
277 }
278
279 // ShellExecution mirrors tool.ShellExecution for event sinks without importing
280 // the tool package (event is a lower-level dependency of tool consumers).
281 type ShellExecution struct {
282 Kind string `json:"kind,omitempty"`
283 Shell string `json:"shell,omitempty"`
284 ShellVersion string `json:"shellVersion,omitempty"`
285 Platform string `json:"platform,omitempty"`
286 SupportsAndAnd bool `json:"supportsAndAnd"`
287 State string `json:"state,omitempty"`
288 FailurePhase string `json:"failurePhase,omitempty"`
289 ExitCode *int `json:"exitCode,omitempty"`
290 OutputTail string `json:"outputTail,omitempty"`
291 MutationRisk string `json:"mutationRisk,omitempty"`
292 Verification string `json:"verification,omitempty"`
293 DurationMs int64 `json:"durationMs,omitempty"`
294 }
295
296 // FileDiff is a previewed change carried on a writer tool's full ToolDispatch
297 // and on its ApprovalRequest, so a frontend can render +/- lines before the
298 // call runs. Diff is the unified diff (empty for read-only tools, binary files,
299 // or no-op changes); Added/Removed are its line tallies.
300 type FileDiff struct {
301 Diff string
302 Added int
303 Removed int
304 }
305
306 // AskOption is one choice the user can pick for an AskQuestion.
307 type AskOption struct {
308 Label string
309 Description string // optional one-line explanation shown under the label
310 }
311
312 // AskQuestion is one structured question the `ask` tool puts to the user.
313 type AskQuestion struct {
314 ID string // stable per-question id, so answers correlate back
315 Header string // short label (the tab title)
316 Prompt string // the question text
317 Options []AskOption
318 Multi bool // allow selecting more than one option
319 }
320
321 // Ask carries an AskRequest: a batch of questions and the ID that correlates the
322 // controller's AnswerQuestion(ID, …) reply.
323 type Ask struct {
324 ID string
325 Questions []AskQuestion
326 TurnID string
327 }
328
329 // MCPInteraction carries one MCPInteractionRequest: a server-initiated
330 // elicitation the frontend must answer with accept/decline/cancel. Mode is
331 // "form" (RequestedSchema is a flat primitive JSON schema) or "url" (URL is a
332 // credential-free HTTP(S) target the user opens explicitly).
333 type MCPInteraction struct {
334 ID string
335 Server string
336 Mode string
337 Message string
338 RequestedSchema json.RawMessage
339 URL string
340 ElicitationID string
341 TurnID string
342 }
343
344 // Compaction carries a context-compaction pass for the CompactionStarted /
345 // CompactionDone events. On CompactionStarted only Trigger is set. On
346 // CompactionDone, Messages/Summary/Archive are filled in (an aborted pass leaves
347 // Summary empty). Trigger is "auto" (the prompt reached the window threshold) or
348 // "manual" (the user ran /compact).
349 type Compaction struct {
350 Trigger string // "auto" | "manual"
351 Messages int // Done: how many messages were folded into the summary
352 Summary string // Done: the briefing the agent keeps relying on
353 Archive string // Done: path the dropped originals were archived to ("" if none)
354 }
355
356 // ContextMaintenance is the typed wire-safe receipt for snip/prune/noop/
357 // blocked operations. Transcript bytes are represented by hashes and counts.
358 type ContextMaintenance struct {
359 Status string `json:"status,omitempty"`
360 Action string `json:"action,omitempty"`
361 Trigger string `json:"trigger,omitempty"`
362 OperationID string `json:"operationId,omitempty"`
363 InputTokens int `json:"inputTokens,omitempty"`
364 ResultTokens int `json:"resultTokens,omitempty"`
365 SavedTokens int `json:"savedTokens,omitempty"`
366 AffectedToolResults int `json:"affectedToolResults,omitempty"`
367 ProjectionVersion uint64 `json:"projectionVersion,omitempty"`
368 CacheBreak bool `json:"cacheBreak,omitempty"`
369 Reason string `json:"reason,omitempty"`
370 }
371
372 // GuardianResult carries the outcome of a guardian sub-agent safety review.
373 // Emitted with Kind=GuardianAssessment after each review completes.
374 type GuardianResult struct {
375 ID string // unique review id
376 Tool string // tool being reviewed (e.g. "bash")
377 Subject string // call subject (e.g. "rm -rf /tmp/build")
378 Outcome string // "allow" | "deny"
379 RiskLevel string // "low" | "medium" | "high" | "critical"
380 UserAuthorization string // "unknown" | "low" | "medium" | "high"
381 Rationale string // one-sentence reason
382 DurationMs int64 // wall-clock review time
383 Usage *provider.Usage // guardian review token telemetry
384 Pricing *provider.Pricing // for cost display (nil = omit cost)
385 }
386
387 // AskAnswer is the user's reply to one AskQuestion: the chosen option label(s)
388 // (a free-typed answer is carried as a single Selected entry).
389 type AskAnswer struct {
390 QuestionID string
391 Selected []string
392 }
393
394 // FinalReadiness carries machine-readable recovery requirements on TurnDone.
395 // Missing values are stable category ids; user-facing detail stays localized in
396 // the frontend instead of scraping the diagnostic error string.
397 type FinalReadiness struct {
398 Attempts int `json:"attempts,omitempty"`
399 Missing []string `json:"missing,omitempty"`
400 }
401
402 const (
403 UsageSourceExecutor = "executor"
404 UsageSourcePlanner = "planner"
405 UsageSourceSubagent = "subagent"
406 UsageSourceCompaction = "compaction"
407 UsageSourceClassifier = "classifier"
408 UsageSourceTitle = "title"
409 UsageSourceCapabilityRouter = "capability-router"
410 UsageSourceRecoveryReviewer = "recovery-reviewer"
411 UsageSourceGoalEvaluator = "goal-evaluator"
412 )
413
414 // Event is one increment in a turn's event stream. Read the field(s) documented
415 // for Kind; the others are zero.
416 type Event struct {
417 Kind Kind
418 MessageID string // local identity shared by streaming and persisted messages
419 AttemptID string // owning sampling attempt; never provider-visible
420 SessionID string // durable display routing, stamped after append
421 RuntimeEpoch string // originating controller incarnation
422 SubmissionID string // exact optimistic submit correlation
423 PromptKind string // interactive prompt kind for lifecycle events
424 Replayed bool // pending prompt re-emitted for a frontend rebuilding its card; not a new request
425 InteractionState string // PromptAnswered: answered | rejected | cancelled | unavailable
426 DomainKind string // host-internal state event committed atomically with this lifecycle event
427 DomainPayload json.RawMessage // host-internal payload for DomainKind
428 TurnID string // stable id of the owning top-level turn
429 Sequence uint64 // monotonic session-local event sequence
430 Status TurnStatus // lifecycle state after this event
431 Text string // Reasoning / Text / Message / Notice / Phase
432 ModelRef string // Usage: canonical "provider/model" ref that produced this usage
433 Detail string // Notice: optional diagnostic text for expandable details
434 Code string // Notice: stable id for frontend localization; empty = unmapped
435 Reasoning string // Message: the full reasoning chain
436 MemoryCitations []provider.MemoryCitation // Message: local memory references displayed by rich frontends
437 Tool Tool // ToolDispatch / ToolResult
438 Usage *provider.Usage // Usage
439 Pricing *provider.Pricing // Usage: rate card for quote middleware (nil = omit cost)
440 CostQuote *billing.CostQuote // Usage: host-side quote; sinks must not reprice
441 Source string // optional display/event source (executor, planner, subagent, ...)
442 UsageSource string // Usage: billable call source; empty means executor for compatibility
443 CacheDiagnostics *CacheDiagnostics // Usage: cache-churn attribution (nil = N/A)
444 // SessionHit/SessionMiss carry cumulative cache tokens across the whole
445 // session (Usage events only), so a frontend can show the aggregate hit-rate
446 // — which doesn't crater on a short turn or after compaction — alongside
447 // Usage's single-turn numbers.
448 SessionHit int // Usage: cumulative cache-hit prompt tokens this session
449 SessionMiss int // Usage: cumulative cache-miss prompt tokens this session
450 Level Level // Notice
451 Audience NoticeAudience // Notice: empty = ordinary frontend delivery; operator = no end-user chat forwarding
452 Approval Approval // ApprovalRequest
453 Ask Ask // AskRequest
454 MCPInteraction MCPInteraction // MCPInteractionRequest
455 Extension *ExtensionSurfacePayload // ExtensionSurface / ExtensionStatus (nil for every other kind)
456 Err error // TurnDone: non-nil on failure
457 Cancelled bool // TurnDone: Cancel was requested while the turn was active
458 Outcome string // TurnDone: optional machine-readable recoverable outcome
459 Readiness *FinalReadiness // TurnDone: structured final-readiness recovery state
460 ProtocolRecovery *provider.ProtocolRecoveryAction
461 Diagnostic *provider.FailureDiagnostic
462 RecoveryCheckpoint bool // local durable recovery checkpoint, not a notice
463 Receipt *CompletionReceipt // TurnDone: what the host verified, and what it could not
464 CheckpointTurn *int // TurnDone: authoritative checkpoint for this turn's visible user message
465 Compaction Compaction // Compaction
466 Maintenance *ContextMaintenance // ContextMaintenanceEvent
467 SessionOperation *SessionOperationInfo // SessionOperation
468 Guardian GuardianResult
469 DecisionReceipt *provider.DecisionReceipt // Notice: durable user decision receipt
470 WriteIntent bool // local write-ahead checkpoint, not a user notice
471 Recovery *RecoveryStatus // optional local recovery details
472 RetryAttempt int // Retrying: 1-based attempt about to be made
473 RetryMax int // Retrying: total attempts before giving up
474 RetryScope RetryScope // Retrying: optional "headers" | "stream"; empty for older emitters
475 StreamAttempt StreamAttemptInfo // StreamAttempt lifecycle
476 ReadStatus *ReadStatusPayload // ReadStatus: one logical read's delivery state
477 ReadPause *provider.ReadPause // TurnDone: durable display-only pause receipt
478 ReadCompletion *provider.ReadCompletion // TurnDone: accepted partial coverage, display-only
479 ItemID string // correlates durable inbox events
480 SessionPath string // routes Serve frames
481 SessionReset bool // SessionChanged came from /new or /clear, not resume/recovery
482 Workspace *WorkspaceChangedPayload // WorkspaceChanged (host-local)
483 // PhaseName is set on TurnPhase events (working|checking|verifying|reviewing).
484 PhaseName TurnPhaseName
485 // Completion is set on CompletionSummary events.
486 Completion *CompletionSummaryInfo
487 // CommittedMessage is the exact provider transcript record paired with a
488 // terminal tool result. It is host-internal and omitted from frontend wire
489 // payloads; the session event store commits it atomically with tool/result
490 // and any todo/write state transition.
491 CommittedMessage *provider.Message
492 }
493
494 type WorkspaceWatchState string
495
496 const (
497 WorkspaceWatchActive WorkspaceWatchState = "active"
498 WorkspaceWatchDegraded WorkspaceWatchState = "degraded"
499 WorkspaceWatchUnavailable WorkspaceWatchState = "unavailable"
500 )
501
502 type WorkspaceRevision struct {
503 Content uint64 `json:"content"`
504 Tree uint64 `json:"tree"`
505 WorkingTree uint64 `json:"workingTree"`
506 GitMeta uint64 `json:"gitMeta"`
507 Session uint64 `json:"session"`
508 }
509
510 type WorkspacePathChange struct {
511 Path string `json:"path"`
512 OldPath string `json:"oldPath,omitempty"`
513 Op string `json:"op"`
514 }
515
516 type WorkspaceChangedPayload struct {
517 Revisions WorkspaceRevision
518 Changes []WorkspacePathChange
519 AllPaths bool
520 Source string
521 WatchState WorkspaceWatchState
522 }
523
524 // ReadinessAuditSink is an optional sink capability. Sinks that do not care
525 // about readiness audit receipts can implement only Sink and will ignore them.
526 type ReadinessAuditSink interface {
527 RecordReadinessAudit(evidence.ReadinessAudit)
528 }
529
530 // AnchorSafetyAudit is a content-free shadow decision for an anchor-based
531 // writer. It contains only bounded enums/counts; paths, anchors, source text,
532 // and digests never leave the host-side observation ledger.
533 type AnchorSafetyAudit struct {
534 Mode string
535 TaskMode string
536 RangeLines int
537 ObservationAge int
538 LegacyAllowed bool
539 ShadowAllowed bool
540 Reason string
541 SameBatchReadRejected bool
542 }
543
544 type AnchorSafetyAuditSink interface {
545 RecordAnchorSafetyAudit(AnchorSafetyAudit)
546 }
547
548 func RecordAnchorSafetyAudit(s Sink, a AnchorSafetyAudit) {
549 if nilutil.IsNil(s) {
550 return
551 }
552 if as, ok := s.(AnchorSafetyAuditSink); ok {
553 as.RecordAnchorSafetyAudit(a)
554 }
555 }
556
557 // TurnCompletionSink is an optional sink capability for synchronous controller
558 // entry points that do not publish a TurnDone UI event. It keeps accounting
559 // independent from frontend event lifecycles without synthesizing an event that
560 // transports may mistake for an interactive completion.
561 type TurnCompletionSink interface {
562 RecordTurnCompletion()
563 }
564
565 // RecordTurnCompletion records one successfully admitted top-level controller
566 // run on sinks that opt into completion accounting.
567 func RecordTurnCompletion(s Sink) {
568 if nilutil.IsNil(s) {
569 return
570 }
571 if ts, ok := s.(TurnCompletionSink); ok {
572 ts.RecordTurnCompletion()
573 }
574 }
575
576 // RecordReadinessAudit forwards a readiness audit receipt to sinks that opt in.
577 func RecordReadinessAudit(s Sink, a evidence.ReadinessAudit) {
578 if nilutil.IsNil(s) {
579 return
580 }
581 if rs, ok := s.(ReadinessAuditSink); ok {
582 rs.RecordReadinessAudit(a)
583 }
584 }
585
586 // ProtocolRecoveryKind is a content-free internal observation about a provider
587 // protocol repair. It is deliberately separate from Event/Notice so recovery
588 // stays invisible in chat transcripts and frontends do not need to understand
589 // provider implementation details.
590 type ProtocolRecoveryKind string
591
592 const (
593 ProtocolRecoveryMissingReasoningDetected ProtocolRecoveryKind = "missing_reasoning_detected"
594 ProtocolRecoveryMissingReasoningRetryAttempted ProtocolRecoveryKind = "missing_reasoning_retry_attempted"
595 ProtocolRecoveryMissingReasoningRetryRecovered ProtocolRecoveryKind = "missing_reasoning_retry_recovered"
596 ProtocolRecoveryMissingReasoningRetryReplaced ProtocolRecoveryKind = "missing_reasoning_retry_replaced_response"
597 ProtocolRecoveryMissingReasoningRetrySuppressed ProtocolRecoveryKind = "missing_reasoning_retry_suppressed"
598 ProtocolRecoveryMissingReasoningFallback ProtocolRecoveryKind = "missing_reasoning_fallback_used"
599 ProtocolRecoveryReasoningOverflowDetected ProtocolRecoveryKind = "reasoning_overflow_detected"
600 ProtocolRecoveryClientToolRejected ProtocolRecoveryKind = "client_tool_rejected_unreplayable_reasoning"
601 ProtocolRecoveryServerSearchSalvaged ProtocolRecoveryKind = "server_search_history_salvaged"
602 ProtocolRecoveryHistoryRepaired ProtocolRecoveryKind = "unreplayable_history_repaired"
603 ProtocolRecoveryReasoningReplay400Detected ProtocolRecoveryKind = "reasoning_replay_400_detected"
604 ProtocolRecoveryReasoningReplay400Recovered ProtocolRecoveryKind = "reasoning_replay_400_recovered"
605 )
606
607 type ProtocolRecoveryAudit struct {
608 Kind ProtocolRecoveryKind
609 }
610
611 // ContractShadowAudit is the shadow task-contract's end-of-turn summary:
612 // counts and enums only, never requirement text. Shadow means observed, not
613 // enforced — the old control logic still decides behavior.
614 type ContractShadowAudit struct {
615 Intent string
616 Requirements int
617 RequirementsSatisfied int
618 Checks int
619 ChecksSatisfied int
620 Epoch uint64
621 Verdict string
622 Complete bool
623 ReadyToFinalize bool
624 }
625
626 // ContractShadowAuditSink is an optional sink capability; implementations
627 // must keep it content-free, like every other audit channel.
628 type ContractShadowAuditSink interface {
629 RecordContractShadow(ContractShadowAudit)
630 }
631
632 // RecordContractShadow forwards the shadow contract summary only to sinks
633 // that explicitly opt in. Ordinary UI sinks receive nothing.
634 func RecordContractShadow(s Sink, a ContractShadowAudit) {
635 if nilutil.IsNil(s) {
636 return
637 }
638 if cs, ok := s.(ContractShadowAuditSink); ok {
639 cs.RecordContractShadow(a)
640 }
641 }
642
643 // CompletionReportAudit is the host-authored completion report's end-of-turn
644 // summary: counts, enums, and gap kinds only, never paths or command text.
645 // The gap counters carry the point — what the turn left unproven.
646 type CompletionReportAudit struct {
647 Verdict string
648 Risk string
649 Criteria int
650 CriteriaSatisfied int
651 Changes int
652 ChangesUnreviewed int
653 Verifications int
654 VerificationsFailed int
655 VerificationsStale int
656 Gaps int
657 GapKinds []string
658 // ClaimsVerified counts the turn's own asserted verifications;
659 // ClaimsUnbacked is how many of them the ledger did not support.
660 ClaimsVerified int
661 ClaimsUnbacked int
662 }
663
664 // CompletionReportAuditSink is an optional sink capability; implementations
665 // must keep it content-free, like every other audit channel.
666 type CompletionReportAuditSink interface {
667 RecordCompletionReport(CompletionReportAudit)
668 }
669
670 // RecordCompletionReport forwards the completion summary only to sinks that
671 // explicitly opt in. Ordinary UI sinks receive nothing.
672 func RecordCompletionReport(s Sink, a CompletionReportAudit) {
673 if nilutil.IsNil(s) {
674 return
675 }
676 if cs, ok := s.(CompletionReportAuditSink); ok {
677 cs.RecordCompletionReport(a)
678 }
679 }
680
681 // MemoryRecallAudit summarizes one automatic-recall decision: identifiers,
682 // scores, and budget numbers only — never the query or fact text.
683 type MemoryRecallAudit struct {
684 Hits []MemoryRecallHit
685 UsedChars int
686 Omitted int
687 Suppressed string // reason recall stayed silent; "" when hits were injected
688 // Shadow is the Retrieval V2 ranking (telemetry only, never served).
689 Shadow []MemoryRecallHit
690 }
691
692 // MemoryRecallHit is one recalled fact's content-free fingerprint.
693 type MemoryRecallHit struct {
694 ID string
695 Revision int
696 Scope string
697 Type string
698 Freshness string
699 Score float64
700 }
701
702 // MemoryRecallSink is an optional sink capability; implementations must keep
703 // it content-free, like every other audit channel.
704 type MemoryRecallSink interface {
705 RecordMemoryRecall(MemoryRecallAudit)
706 }
707
708 // RecordMemoryRecall forwards a recall decision only to sinks that explicitly
709 // opt in. Ordinary UI sinks receive nothing.
710 func RecordMemoryRecall(s Sink, a MemoryRecallAudit) {
711 if nilutil.IsNil(s) {
712 return
713 }
714 if mr, ok := s.(MemoryRecallSink); ok {
715 mr.RecordMemoryRecall(a)
716 }
717 }
718
719 // DelegationAdmissionAudit is the shadow admission verdict for one expensive
720 // delegation call: tool name and enums only, never the query or prompt text.
721 // Shadow means observed, not enforced — no call is blocked.
722 type DelegationAdmissionAudit struct {
723 Tool string
724 Verdict string // "allow" | "deny"
725 Reason string // e.g. "local_fix_no_external_need"
726 Intent string // compatibility field; no longer classified from prompt text
727 }
728
729 // DelegationAdmissionSink is an optional sink capability; implementations
730 // must keep it content-free, like every other audit channel.
731 type DelegationAdmissionSink interface {
732 RecordDelegationAdmission(DelegationAdmissionAudit)
733 }
734
735 // RecordDelegationAdmission forwards a shadow admission verdict only to sinks
736 // that explicitly opt in. Ordinary UI sinks receive nothing.
737 func RecordDelegationAdmission(s Sink, a DelegationAdmissionAudit) {
738 if nilutil.IsNil(s) {
739 return
740 }
741 if da, ok := s.(DelegationAdmissionSink); ok {
742 da.RecordDelegationAdmission(a)
743 }
744 }
745
746 // OutcomeProgressSink is an optional sink capability for the shadow outcome
747 // scorer's per-round samples: counts only, never paths or commands. Shadow
748 // means observed, not enforced — the novelty guard still decides behavior.
749 type OutcomeProgressSink interface {
750 RecordOutcomeProgress(evidence.OutcomeSample)
751 }
752
753 // RecordOutcomeProgress forwards a shadow outcome sample only to sinks that
754 // explicitly opt in. Ordinary UI sinks receive nothing.
755 func RecordOutcomeProgress(s Sink, sample evidence.OutcomeSample) {
756 if nilutil.IsNil(s) {
757 return
758 }
759 if op, ok := s.(OutcomeProgressSink); ok {
760 op.RecordOutcomeProgress(sample)
761 }
762 }
763
764 // ProtocolRecoveryAuditSink is an optional sink capability. Implementations
765 // must keep it content-free; prompts, responses, endpoints, model names, and
766 // tool arguments do not belong in this audit channel.
767 type ProtocolRecoveryAuditSink interface {
768 RecordProtocolRecovery(ProtocolRecoveryAudit)
769 }
770
771 // RecordProtocolRecovery forwards a content-free recovery observation only to
772 // sinks that explicitly opt in. Ordinary UI sinks receive nothing.
773 func RecordProtocolRecovery(s Sink, a ProtocolRecoveryAudit) {
774 if nilutil.IsNil(s) {
775 return
776 }
777 if rs, ok := s.(ProtocolRecoveryAuditSink); ok {
778 rs.RecordProtocolRecovery(a)
779 }
780 }
781
781 lines GO