返回 DeepSeek-Reasonix
domain.go
根目录 / internal / goal / domain.go
1 package goal
2
3 import (
4 "crypto/rand"
5 "encoding/hex"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "strings"
10 "sync"
11 "time"
12 )
13
14 const StateVersion = 1
15
16 type Phase string
17
18 const (
19 PhaseActive Phase = "active"
20 PhasePaused Phase = "paused"
21 PhaseBlocked Phase = "blocked"
22 PhaseComplete Phase = "complete"
23 )
24
25 type Activation string
26
27 const (
28 ActivationArmed Activation = "armed"
29 ActivationDisarmed Activation = "disarmed"
30 )
31
32 type ErrorCode string
33
34 const (
35 ErrNotFound ErrorCode = "GOAL_NOT_FOUND"
36 ErrAlreadyExists ErrorCode = "GOAL_ALREADY_EXISTS"
37 ErrStaleRevision ErrorCode = "GOAL_STALE_REVISION"
38 ErrInvalidObjective ErrorCode = "GOAL_INVALID_OBJECTIVE"
39 ErrInvalidRoundLimit ErrorCode = "GOAL_INVALID_MAX_ROUNDS"
40 ErrInvalidBlockReason ErrorCode = "GOAL_INVALID_BLOCK_REASON"
41 ErrInvalidEdit ErrorCode = "GOAL_INVALID_EDIT"
42 ErrInvalidTransition ErrorCode = "GOAL_INVALID_TRANSITION"
43 ErrRoundLimit ErrorCode = "GOAL_ROUND_LIMIT"
44 ErrBlockedTooEarly ErrorCode = "GOAL_BLOCKED_TOO_EARLY"
45 ErrUserAuthorityRequired ErrorCode = "GOAL_USER_AUTHORITY_REQUIRED"
46 ErrUnsupportedVersion ErrorCode = "GOAL_UNSUPPORTED_VERSION"
47 )
48
49 type Error struct {
50 Code ErrorCode
51 Message string
52 }
53
54 func (e *Error) Error() string { return e.Message }
55
56 func ErrorCodeOf(err error) ErrorCode {
57 var target *Error
58 if errors.As(err, &target) {
59 return target.Code
60 }
61 return ""
62 }
63
64 func goalError(code ErrorCode, format string, args ...any) error {
65 return &Error{Code: code, Message: fmt.Sprintf(format, args...)}
66 }
67
68 type Ref struct {
69 ID string `json:"id"`
70 Revision uint64 `json:"revision"`
71 }
72
73 type BlockReason struct {
74 Code string `json:"code"`
75 Message string `json:"message"`
76 }
77
78 type Snapshot struct {
79 ID string `json:"id"`
80 Revision uint64 `json:"revision"`
81 Objective string `json:"objective"`
82 Phase Phase `json:"phase"`
83 MaxGoalRounds *uint64 `json:"maxGoalRounds"`
84 RoundsStarted uint64 `json:"roundsStarted"`
85 WorkDurationMs int64 `json:"workDurationMs,omitempty"`
86 BlockedReason *BlockReason `json:"blockedReason,omitempty"`
87 CreatedAt time.Time `json:"createdAt"`
88 UpdatedAt time.Time `json:"updatedAt"`
89 }
90
91 func (s Snapshot) Ref() Ref { return Ref{ID: s.ID, Revision: s.Revision} }
92
93 type View struct {
94 Snapshot
95 Activation Activation `json:"activation"`
96 StopReason string `json:"stopReason,omitempty"`
97 }
98
99 func (v View) Ref() Ref { return v.Snapshot.Ref() }
100
101 type CreateRequest struct {
102 Objective string
103 MaxGoalRounds *uint64
104 }
105
106 // RoundLimitChange distinguishes an omitted edit from explicitly removing a
107 // limit. Set=false leaves the existing limit unchanged; Set=true with a nil
108 // Value selects unlimited rounds.
109 type RoundLimitChange struct {
110 Set bool
111 Value *uint64
112 }
113
114 type EditRequest struct {
115 Objective *string
116 MaxGoalRounds RoundLimitChange
117 }
118
119 type stateDocument struct {
120 Version int `json:"version"`
121 Current *Snapshot `json:"current"`
122 Cleared *Ref `json:"cleared,omitempty"`
123 ClearedAt *time.Time `json:"clearedAt,omitempty"`
124 Extra map[string]json.RawMessage `json:"-"`
125 }
126
127 type Machine struct {
128 mu sync.Mutex
129 now func() time.Time
130 newID func() string
131 current *Snapshot
132 activation Activation
133 stopReason string
134 cleared *Ref
135 clearedAt *time.Time
136 extra map[string]json.RawMessage
137 }
138
139 func NewMachine(now func() time.Time, newID func() string) *Machine {
140 if now == nil {
141 now = time.Now
142 }
143 if newID == nil {
144 newID = randomID
145 }
146 return &Machine{now: now, newID: newID, activation: ActivationDisarmed}
147 }
148
149 func randomID() string {
150 var value [16]byte
151 if _, err := rand.Read(value[:]); err != nil {
152 return fmt.Sprintf("goal-%d", time.Now().UnixNano())
153 }
154 return hex.EncodeToString(value[:])
155 }
156
157 func (m *Machine) Get() *View {
158 m.mu.Lock()
159 defer m.mu.Unlock()
160 return m.viewLocked()
161 }
162
163 // Clone returns an independent candidate with the same durable and live state.
164 // Hosts use it to prepare a mutation before the corresponding session event is
165 // accepted, then publish the candidate atomically after Append succeeds.
166 func (m *Machine) Clone() *Machine {
167 if m == nil {
168 return NewMachine(nil, nil)
169 }
170 m.mu.Lock()
171 defer m.mu.Unlock()
172 extra := make(map[string]json.RawMessage, len(m.extra))
173 for key, value := range m.extra {
174 extra[key] = append(json.RawMessage(nil), value...)
175 }
176 return &Machine{
177 now: m.now,
178 newID: m.newID,
179 current: cloneSnapshot(m.current),
180 activation: m.activation,
181 stopReason: m.stopReason,
182 cleared: cloneRef(m.cleared),
183 clearedAt: cloneTime(m.clearedAt),
184 extra: extra,
185 }
186 }
187
188 // InheritRuntimeFrom copies only process-local activation state when both
189 // machines describe the exact same durable goal version. It never changes the
190 // persisted snapshot or lifecycle revision.
191 func (m *Machine) InheritRuntimeFrom(previous *Machine) error {
192 if m == nil || previous == nil {
193 return nil
194 }
195 prior := previous.Get()
196 m.mu.Lock()
197 defer m.mu.Unlock()
198 if prior == nil && m.current == nil {
199 return nil
200 }
201 if prior == nil || m.current == nil || prior.ID != m.current.ID || prior.Revision != m.current.Revision || prior.RoundsStarted != m.current.RoundsStarted || prior.Phase != m.current.Phase {
202 return goalError(ErrStaleRevision, "cannot inherit activation across different goal snapshots")
203 }
204 m.activation = prior.Activation
205 m.stopReason = prior.StopReason
206 return nil
207 }
208
209 func (m *Machine) Create(request CreateRequest) (View, error) {
210 m.mu.Lock()
211 defer m.mu.Unlock()
212 if m.current != nil && m.current.Phase != PhaseComplete {
213 return View{}, goalError(ErrAlreadyExists, "an unfinished goal already exists")
214 }
215 objective, err := validObjective(request.Objective)
216 if err != nil {
217 return View{}, err
218 }
219 if err := validLimit(request.MaxGoalRounds, 0); err != nil {
220 return View{}, err
221 }
222 now := m.now().UTC()
223 m.current = &Snapshot{
224 ID: m.newID(),
225 Revision: 1,
226 Objective: objective,
227 Phase: PhaseActive,
228 MaxGoalRounds: cloneLimit(request.MaxGoalRounds),
229 CreatedAt: now,
230 UpdatedAt: now,
231 }
232 m.activation = ActivationArmed
233 m.stopReason = ""
234 m.cleared, m.clearedAt = nil, nil
235 return *m.viewLocked(), nil
236 }
237
238 // Replace is the explicit host/UI operation for installing a new goal while
239 // preserving the replaced goal reference as a clear tombstone in the same
240 // versioned snapshot. Model create_goal intentionally cannot invoke it.
241 func (m *Machine) Replace(request CreateRequest) (View, error) {
242 m.mu.Lock()
243 defer m.mu.Unlock()
244 objective, err := validObjective(request.Objective)
245 if err != nil {
246 return View{}, err
247 }
248 if err := validLimit(request.MaxGoalRounds, 0); err != nil {
249 return View{}, err
250 }
251 now := m.now().UTC()
252 if m.current != nil {
253 ref := m.current.Ref()
254 m.cleared = &ref
255 m.clearedAt = &now
256 }
257 m.current = &Snapshot{
258 ID: m.newID(), Revision: 1, Objective: objective, Phase: PhaseActive,
259 MaxGoalRounds: cloneLimit(request.MaxGoalRounds), CreatedAt: now, UpdatedAt: now,
260 }
261 m.activation = ActivationArmed
262 m.stopReason = ""
263 return *m.viewLocked(), nil
264 }
265
266 func (m *Machine) Edit(ref Ref, request EditRequest) (View, error) {
267 m.mu.Lock()
268 defer m.mu.Unlock()
269 current, err := m.exactLocked(ref)
270 if err != nil {
271 return View{}, err
272 }
273 if request.Objective == nil && !request.MaxGoalRounds.Set {
274 return View{}, goalError(ErrInvalidEdit, "goal edit requires objective and/or max_goal_rounds")
275 }
276 if request.Objective != nil {
277 objective, validateErr := validObjective(*request.Objective)
278 if validateErr != nil {
279 return View{}, validateErr
280 }
281 current.Objective = objective
282 }
283 if request.MaxGoalRounds.Set {
284 if validateErr := validLimit(request.MaxGoalRounds.Value, current.RoundsStarted); validateErr != nil {
285 return View{}, validateErr
286 }
287 current.MaxGoalRounds = cloneLimit(request.MaxGoalRounds.Value)
288 }
289 m.bumpLocked(current)
290 return *m.viewLocked(), nil
291 }
292
293 func (m *Machine) Pause(ref Ref) (View, error) {
294 m.mu.Lock()
295 defer m.mu.Unlock()
296 current, err := m.exactLocked(ref)
297 if err != nil {
298 return View{}, err
299 }
300 if current.Phase != PhaseActive {
301 return View{}, goalError(ErrInvalidTransition, "only an active goal can be paused")
302 }
303 current.Phase = PhasePaused
304 current.BlockedReason = nil
305 m.activation = ActivationDisarmed
306 m.stopReason = "user-paused"
307 m.bumpLocked(current)
308 return *m.viewLocked(), nil
309 }
310
311 func (m *Machine) Resume(ref Ref, directUser bool) (View, error) {
312 m.mu.Lock()
313 defer m.mu.Unlock()
314 current, err := m.exactLocked(ref)
315 if err != nil {
316 return View{}, err
317 }
318 if !directUser {
319 return View{}, goalError(ErrUserAuthorityRequired, "resuming a goal requires current direct user authority")
320 }
321 if current.Phase == PhaseComplete || (current.Phase == PhaseActive && m.activation == ActivationArmed) {
322 return View{}, goalError(ErrInvalidTransition, "goal cannot be resumed from %s/%s", current.Phase, m.activation)
323 }
324 if current.MaxGoalRounds != nil && current.RoundsStarted >= *current.MaxGoalRounds {
325 return View{}, goalError(ErrRoundLimit, "goal exhausted its configured round limit")
326 }
327 current.Phase = PhaseActive
328 current.BlockedReason = nil
329 m.activation = ActivationArmed
330 m.stopReason = ""
331 m.bumpLocked(current)
332 return *m.viewLocked(), nil
333 }
334
335 func (m *Machine) Complete(ref Ref) (View, error) {
336 m.mu.Lock()
337 defer m.mu.Unlock()
338 current, err := m.exactLocked(ref)
339 if err != nil {
340 return View{}, err
341 }
342 if current.Phase != PhaseActive {
343 return View{}, goalError(ErrInvalidTransition, "only an active goal can complete")
344 }
345 current.Phase = PhaseComplete
346 current.BlockedReason = nil
347 m.activation = ActivationDisarmed
348 m.stopReason = "complete"
349 m.bumpLocked(current)
350 return *m.viewLocked(), nil
351 }
352
353 func (m *Machine) Block(ref Ref, reason BlockReason, directUser bool, minimumAutomaticRounds uint64) (View, error) {
354 m.mu.Lock()
355 defer m.mu.Unlock()
356 current, err := m.exactLocked(ref)
357 if err != nil {
358 return View{}, err
359 }
360 if current.Phase != PhaseActive {
361 return View{}, goalError(ErrInvalidTransition, "only an active goal can be blocked")
362 }
363 reason.Code = strings.TrimSpace(reason.Code)
364 reason.Message = strings.TrimSpace(reason.Message)
365 if reason.Code == "" || reason.Message == "" {
366 return View{}, goalError(ErrInvalidBlockReason, "blocked goal requires a code and message")
367 }
368 if !directUser && current.RoundsStarted < minimumAutomaticRounds {
369 return View{}, goalError(ErrBlockedTooEarly, "automatic blocking requires at least %d admitted rounds", minimumAutomaticRounds)
370 }
371 current.Phase = PhaseBlocked
372 current.BlockedReason = &reason
373 m.activation = ActivationDisarmed
374 m.stopReason = reason.Code
375 m.bumpLocked(current)
376 return *m.viewLocked(), nil
377 }
378
379 func (m *Machine) AdmitRound(ref Ref) (View, error) {
380 m.mu.Lock()
381 defer m.mu.Unlock()
382 current, err := m.exactLocked(ref)
383 if err != nil {
384 return View{}, err
385 }
386 if current.Phase != PhaseActive || m.activation != ActivationArmed {
387 return View{}, goalError(ErrInvalidTransition, "goal is not armed for automatic continuation")
388 }
389 if current.MaxGoalRounds != nil && current.RoundsStarted >= *current.MaxGoalRounds {
390 return View{}, goalError(ErrRoundLimit, "goal exhausted its configured round limit")
391 }
392 current.RoundsStarted++
393 return *m.viewLocked(), nil
394 }
395
396 func (m *Machine) Disarm(reason string) *View {
397 m.mu.Lock()
398 defer m.mu.Unlock()
399 if m.current == nil {
400 return nil
401 }
402 if m.current.Phase != PhaseActive {
403 return m.viewLocked()
404 }
405 m.activation = ActivationDisarmed
406 m.stopReason = strings.TrimSpace(reason)
407 return m.viewLocked()
408 }
409
410 func (m *Machine) Clear(ref Ref) error {
411 m.mu.Lock()
412 defer m.mu.Unlock()
413 current, err := m.exactLocked(ref)
414 if err != nil {
415 return err
416 }
417 cleared := current.Ref()
418 clearedAt := m.now().UTC()
419 m.current = nil
420 m.activation = ActivationDisarmed
421 m.stopReason = "cleared"
422 m.cleared = &cleared
423 m.clearedAt = &clearedAt
424 return nil
425 }
426
427 func (m *Machine) Encode() ([]byte, error) {
428 m.mu.Lock()
429 defer m.mu.Unlock()
430 doc := map[string]any{"version": StateVersion, "current": m.current}
431 if m.cleared != nil {
432 doc["cleared"] = m.cleared
433 doc["clearedAt"] = m.clearedAt
434 }
435 for key, value := range m.extra {
436 if _, reserved := doc[key]; !reserved {
437 doc[key] = json.RawMessage(append([]byte(nil), value...))
438 }
439 }
440 return json.Marshal(doc)
441 }
442
443 func (m *Machine) Restore(data []byte) (*View, error) {
444 var raw map[string]json.RawMessage
445 if err := json.Unmarshal(data, &raw); err != nil {
446 return nil, goalError(ErrUnsupportedVersion, "decode goal state: %v", err)
447 }
448 var doc stateDocument
449 if err := json.Unmarshal(data, &doc); err != nil {
450 return nil, goalError(ErrUnsupportedVersion, "decode goal state: %v", err)
451 }
452 if doc.Version != StateVersion {
453 return nil, goalError(ErrUnsupportedVersion, "unsupported goal state version %d", doc.Version)
454 }
455 if doc.Current != nil {
456 if err := validateSnapshot(*doc.Current); err != nil {
457 return nil, err
458 }
459 }
460 delete(raw, "version")
461 delete(raw, "current")
462 delete(raw, "cleared")
463 delete(raw, "clearedAt")
464 m.mu.Lock()
465 defer m.mu.Unlock()
466 m.current = cloneSnapshot(doc.Current)
467 m.cleared = cloneRef(doc.Cleared)
468 m.clearedAt = cloneTime(doc.ClearedAt)
469 m.extra = raw
470 m.activation = ActivationDisarmed
471 m.stopReason = "cold-restore"
472 return m.viewLocked(), nil
473 }
474
475 func (m *Machine) exactLocked(ref Ref) (*Snapshot, error) {
476 if m.current == nil {
477 return nil, goalError(ErrNotFound, "no current goal")
478 }
479 if ref.ID != m.current.ID || ref.Revision != m.current.Revision {
480 return nil, goalError(ErrStaleRevision, "goal reference is stale")
481 }
482 return m.current, nil
483 }
484
485 func (m *Machine) bumpLocked(current *Snapshot) {
486 current.Revision++
487 current.UpdatedAt = m.now().UTC()
488 }
489
490 func (m *Machine) viewLocked() *View {
491 if m.current == nil {
492 return nil
493 }
494 return &View{Snapshot: *cloneSnapshot(m.current), Activation: m.activation, StopReason: m.stopReason}
495 }
496
497 func validObjective(value string) (string, error) {
498 value = strings.TrimSpace(value)
499 if value == "" {
500 return "", goalError(ErrInvalidObjective, "goal objective must not be empty")
501 }
502 return value, nil
503 }
504
505 func validLimit(limit *uint64, roundsStarted uint64) error {
506 if limit != nil && (*limit == 0 || *limit < roundsStarted) {
507 return goalError(ErrInvalidRoundLimit, "max goal rounds must be positive and not below admitted rounds")
508 }
509 return nil
510 }
511
512 func validateSnapshot(snapshot Snapshot) error {
513 if snapshot.WorkDurationMs < 0 {
514 return goalError(ErrUnsupportedVersion, "goal state has negative work duration")
515 }
516 if snapshot.ID == "" || snapshot.Revision == 0 {
517 return goalError(ErrUnsupportedVersion, "goal state has invalid identity")
518 }
519 if _, err := validObjective(snapshot.Objective); err != nil {
520 return err
521 }
522 if err := validLimit(snapshot.MaxGoalRounds, snapshot.RoundsStarted); err != nil {
523 return err
524 }
525 switch snapshot.Phase {
526 case PhaseActive, PhasePaused, PhaseComplete:
527 if snapshot.BlockedReason != nil {
528 return goalError(ErrUnsupportedVersion, "non-blocked goal contains blockedReason")
529 }
530 case PhaseBlocked:
531 if snapshot.BlockedReason == nil || strings.TrimSpace(snapshot.BlockedReason.Code) == "" || strings.TrimSpace(snapshot.BlockedReason.Message) == "" {
532 return goalError(ErrInvalidBlockReason, "blocked goal requires a code and message")
533 }
534 default:
535 return goalError(ErrUnsupportedVersion, "unsupported goal phase %q", snapshot.Phase)
536 }
537 if snapshot.CreatedAt.IsZero() || snapshot.UpdatedAt.Before(snapshot.CreatedAt) {
538 return goalError(ErrUnsupportedVersion, "goal state has invalid timestamps")
539 }
540 return nil
541 }
542
543 func cloneLimit(value *uint64) *uint64 {
544 if value == nil {
545 return nil
546 }
547 copy := *value
548 return &copy
549 }
550
551 func cloneSnapshot(value *Snapshot) *Snapshot {
552 if value == nil {
553 return nil
554 }
555 copy := *value
556 copy.MaxGoalRounds = cloneLimit(value.MaxGoalRounds)
557 if value.BlockedReason != nil {
558 reason := *value.BlockedReason
559 copy.BlockedReason = &reason
560 }
561 return &copy
562 }
563
564 func cloneRef(value *Ref) *Ref {
565 if value == nil {
566 return nil
567 }
568 copy := *value
569 return &copy
570 }
571
572 func cloneTime(value *time.Time) *time.Time {
573 if value == nil {
574 return nil
575 }
576 copy := *value
577 return &copy
578 }
579
579 lines GO