返回 DeepSeek-Reasonix
goal_diagnostics.go
根目录 / internal / control / goal_diagnostics.go
1 package control
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "maps"
11 "runtime/debug"
12 "strings"
13 "time"
14
15 goaldomain "reasonix/internal/goal"
16 "reasonix/internal/secrets"
17 "reasonix/internal/session"
18 )
19
20 // GoalDiagnosticMetadata is supplied by the host so a user-exported artifact
21 // identifies the exact build and negotiated feature surface that produced it.
22 type GoalDiagnosticMetadata struct {
23 ApplicationVersion string `json:"applicationVersion,omitempty"`
24 BuildCommit string `json:"buildCommit,omitempty"`
25 ProtocolVersion int `json:"protocolVersion,omitempty"`
26 Capabilities []string `json:"capabilities"`
27 }
28
29 type goalDiagnosticTransition struct {
30 Sequence uint64 `json:"sequence"`
31 OperationID string `json:"operationId"`
32 GoalID string `json:"goalId,omitempty"`
33 Revision uint64 `json:"revision,omitempty"`
34 Phase goaldomain.Phase `json:"phase,omitempty"`
35 Activation goaldomain.Activation `json:"activation"`
36 RoundsStarted uint64 `json:"roundsStarted,omitempty"`
37 Inferred bool `json:"inferred"`
38 }
39
40 // ExportGoalDiagnostics is the compatibility in-memory form. Production hosts
41 // use WriteGoalDiagnostics so diagnostic size is not a memory or RPC limit.
42 func (c *Controller) ExportGoalDiagnostics(ctx context.Context, metadata GoalDiagnosticMetadata) ([]byte, error) {
43 var output bytes.Buffer
44 if err := c.WriteGoalDiagnostics(ctx, &output, metadata); err != nil {
45 return nil, err
46 }
47 return output.Bytes(), nil
48 }
49
50 // WriteGoalDiagnostics streams the authoritative accepted event prefix after
51 // attempting a Flush checkpoint. A failed Flush is exported as evidence, and
52 // credential-like material is redacted one commit at a time.
53 func (c *Controller) WriteGoalDiagnostics(ctx context.Context, dst io.Writer, metadata GoalDiagnosticMetadata) error {
54 return c.WriteSessionDiagnostics(ctx, dst, metadata, nil)
55 }
56
57 // WriteSessionDiagnostics preserves the goal schema while adding host observations.
58 func (c *Controller) WriteSessionDiagnostics(ctx context.Context, dst io.Writer, metadata GoalDiagnosticMetadata, extra map[string]any) error {
59 if c == nil {
60 return session.ErrSessionNotRunning
61 }
62 _, runtime, exclusive := c.v3Binding()
63 if !exclusive || runtime == nil {
64 return errors.New("goal diagnostics require a canonical session")
65 }
66 cut := runtime.Session().EventSequence()
67 var exportSnapshot session.ExportSnapshot
68 if value, ok := extra["exportSnapshot"]; ok {
69 raw, err := json.Marshal(value)
70 if err != nil {
71 return err
72 }
73 if err = json.Unmarshal(raw, &exportSnapshot); err != nil {
74 return err
75 }
76 if exportSnapshot.Ref != runtime.Ref() || exportSnapshot.SnapshotSequence > cut {
77 return errors.New("diagnostic export source changed")
78 }
79 cut = exportSnapshot.SnapshotSequence
80 }
81 _, flushErr := runtime.Session().FlushThrough(ctx, cut)
82 if metadata.Capabilities == nil {
83 metadata.Capabilities = []string{}
84 }
85 fillGoalDiagnosticBuildMetadata(&metadata)
86 state := runtime.StateSnapshot()
87 state.Session.PersistenceError = secrets.RedactCredentials(state.Session.PersistenceError)
88 observation := c.RuntimeStateSnapshot()
89 observation.PersistenceErr = secrets.RedactCredentials(observation.PersistenceErr)
90 unavailable := []string{
91 "activation transitions are inferred from recorded Goal events; process-local activation history before export is unavailable",
92 }
93 if flushErr != nil {
94 unavailable = append(unavailable, "durability checkpoint failed: "+secrets.RedactError(flushErr))
95 }
96 if _, err := io.WriteString(dst, "{\n"); err != nil {
97 return err
98 }
99 fields := []struct {
100 name string
101 value any
102 }{
103 {"schemaVersion", 1},
104 {"exportedAt", time.Now().UTC()},
105 {"metadata", metadata},
106 {"runtime", state},
107 {"observation", observation},
108 {"submissionDiagnostics", map[string]uint64{"reused": c.submissions.reused.Load(), "conflicts": c.submissions.conflicts.Load(), "unknown": c.submissions.unknown.Load()}},
109 {"shellDiagnostics", c.persistentShell.Diagnostics()},
110 {"lifecycleDiagnostics", c.lifecycleDiagnosticSnapshot()},
111 {"providerDiagnostics", c.providerDiagnosticSnapshot()},
112 {"acceptedThrough", cut},
113 {"runtimeObservedAt", time.Now().UTC()},
114 {"runtimeObservedThrough", state.Session.EventSequence},
115 {"durableThrough", state.Session.DurableSequence},
116 {"persistenceStatus", state.Session.PersistenceStatus},
117 {"persistenceError", state.Session.PersistenceError},
118 }
119 if exportSnapshot.Ref.SessionID != "" {
120 exportSnapshot.DurableThrough = state.Session.DurableSequence
121 extra = cloneDiagnosticExtras(extra)
122 extra["exportSnapshot"] = exportSnapshot
123 }
124 for name, value := range extra {
125 fields = append(fields, struct {
126 name string
127 value any
128 }{name, value})
129 }
130 for _, field := range fields {
131 if err := writeGoalDiagnosticField(dst, field.name, field.value, true); err != nil {
132 return err
133 }
134 }
135 if _, err := io.WriteString(dst, " \"commits\": ["); err != nil {
136 return err
137 }
138 return writeSessionDiagnosticCommits(ctx, dst, runtime.Session(), cut, unavailable)
139 }
140
141 func writeSessionDiagnosticCommits(ctx context.Context, dst io.Writer, store *session.Session, cut uint64, unavailable []string) error {
142 first := true
143 var destinationError error
144 changes := []goalDiagnosticTransition{}
145 activation := goaldomain.ActivationDisarmed
146 err := visitAcceptedGoalDiagnosticCommits(ctx, store, cut, func(commit session.Commit) error {
147 encoded, err := marshalDiagnosticCommit(commit)
148 if err != nil {
149 return err
150 }
151 separator := "\n "
152 if !first {
153 separator = ",\n "
154 }
155 if _, err := io.WriteString(dst, separator); err != nil {
156 destinationError = err
157 return err
158 }
159 if _, err := dst.Write(encoded); err != nil {
160 destinationError = err
161 return err
162 }
163 first = false
164 changes = append(changes, goalActivationChangesForCommit(commit, &activation)...)
165 return nil
166 })
167 if destinationError != nil {
168 return destinationError
169 }
170 if ctx.Err() != nil {
171 return ctx.Err()
172 }
173 if err != nil {
174 unavailable = append(unavailable, "accepted event traversal failed: "+secrets.RedactError(err))
175 }
176 if !first {
177 if _, err := io.WriteString(dst, "\n "); err != nil {
178 return err
179 }
180 }
181 if _, err := io.WriteString(dst, "],\n"); err != nil {
182 return err
183 }
184 if err := writeGoalDiagnosticField(dst, "activationChanges", changes, true); err != nil {
185 return err
186 }
187 if err := writeGoalDiagnosticField(dst, "unavailable", unavailable, false); err != nil {
188 return err
189 }
190 _, err = io.WriteString(dst, "}\n")
191 return err
192 }
193
194 func visitAcceptedGoalDiagnosticCommits(ctx context.Context, store *session.Session, through uint64, visit func(session.Commit) error) error {
195 offset := uint64(0)
196 for {
197 page, err := store.AcceptedPage(ctx, offset, 1000)
198 if err != nil {
199 return err
200 }
201 for _, commit := range page.Commits {
202 if commit.LastSequence() > through {
203 return nil
204 }
205 if err := visit(commit); err != nil {
206 return err
207 }
208 }
209 if !page.Truncated {
210 return nil
211 }
212 if page.Next <= offset {
213 return errors.New("goal diagnostics accepted-page cursor did not advance")
214 }
215 offset = page.Next
216 }
217 }
218
219 func writeGoalDiagnosticField(dst io.Writer, name string, value any, comma bool) error {
220 encoded, err := json.Marshal(value)
221 if err != nil {
222 return err
223 }
224 encoded, err = secrets.RedactJSON(encoded)
225 if err != nil {
226 return err
227 }
228 var formatted bytes.Buffer
229 if err := json.Indent(&formatted, encoded, " ", " "); err != nil {
230 return err
231 }
232 encoded = formatted.Bytes()
233 if _, err := fmt.Fprintf(dst, " %q: ", name); err != nil {
234 return err
235 }
236 if _, err := dst.Write(encoded); err != nil {
237 return err
238 }
239 if comma {
240 _, err = io.WriteString(dst, ",")
241 if err != nil {
242 return err
243 }
244 }
245 _, err = io.WriteString(dst, "\n")
246 return err
247 }
248
249 func fillGoalDiagnosticBuildMetadata(metadata *GoalDiagnosticMetadata) {
250 if metadata == nil {
251 return
252 }
253 info, ok := debug.ReadBuildInfo()
254 if !ok {
255 return
256 }
257 if metadata.ApplicationVersion == "" && info.Main.Version != "" && info.Main.Version != "(devel)" {
258 metadata.ApplicationVersion = info.Main.Version
259 }
260 if metadata.BuildCommit != "" {
261 return
262 }
263 for _, setting := range info.Settings {
264 if setting.Key == "vcs.revision" {
265 metadata.BuildCommit = setting.Value
266 return
267 }
268 }
269 }
270
271 func goalActivationChangesForCommit(commit session.Commit, activation *goaldomain.Activation) []goalDiagnosticTransition {
272 changes := []goalDiagnosticTransition{}
273 hasTurnStart := false
274 for _, item := range commit.Events {
275 hasTurnStart = hasTurnStart || item.Kind == "turn/start"
276 }
277 for _, item := range commit.Events {
278 if item.Kind != "goal/state" {
279 continue
280 }
281 var document struct {
282 Current *goaldomain.Snapshot `json:"current"`
283 }
284 if json.Unmarshal(item.Payload, &document) != nil {
285 continue
286 }
287 transition := goalDiagnosticTransition{Sequence: item.Sequence, OperationID: commit.OperationID, Activation: goaldomain.ActivationDisarmed, Inferred: true}
288 if document.Current != nil {
289 transition.GoalID = document.Current.ID
290 transition.Revision = document.Current.Revision
291 transition.Phase = document.Current.Phase
292 transition.RoundsStarted = document.Current.RoundsStarted
293 if document.Current.Phase == goaldomain.PhaseActive {
294 op := strings.ToLower(commit.OperationID)
295 if hasTurnStart || strings.Contains(op, ":create") || strings.Contains(op, ":resume") || strings.Contains(op, "goal-control:set") {
296 *activation = goaldomain.ActivationArmed
297 }
298 } else {
299 *activation = goaldomain.ActivationDisarmed
300 }
301 transition.Activation = *activation
302 } else {
303 *activation = goaldomain.ActivationDisarmed
304 }
305 changes = append(changes, transition)
306 }
307 return changes
308 }
309
310 func cloneDiagnosticExtras(input map[string]any) map[string]any {
311 out := make(map[string]any, len(input))
312 maps.Copy(out, input)
313 return out
314 }
315
315 lines GO