forked from lovyou-ai/work
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstore.go
More file actions
2518 lines (2384 loc) · 82.2 KB
/
Copy pathstore.go
File metadata and controls
2518 lines (2384 loc) · 82.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package work
import (
"errors"
"fmt"
"sort"
"strings"
"time"
"unicode"
v39 "github.com/transpara-ai/eventgraph/go/pkg/darkfactory/v39"
"github.com/transpara-ai/eventgraph/go/pkg/event"
"github.com/transpara-ai/eventgraph/go/pkg/store"
"github.com/transpara-ai/eventgraph/go/pkg/types"
"github.com/transpara-ai/work/pkg/worklifecycle"
)
// ErrArtifactRequired is returned by Complete when the task has neither an
// artifact nor an artifact waiver. Callers can check with errors.Is.
var ErrArtifactRequired = errors.New("task has no artifacts; attach an artifact or waive the requirement")
// ErrInvalidLifecycleTransition is returned when a requested v3.9 task state
// transition is not allowed from the current replayed state.
var ErrInvalidLifecycleTransition = errors.New("invalid task lifecycle transition")
// TaskStatus represents the canonical Dark Factory v3.9 lifecycle state of a task.
type TaskStatus string
const (
// StatusCreated means the task record exists and has not entered scheduling.
StatusCreated TaskStatus = "created"
// StatusReady means the task is unblocked and has enough Work evidence to be scheduled.
StatusReady TaskStatus = "ready"
// StatusRunning means runtime or human production work is in progress.
StatusRunning TaskStatus = "running"
// StatusBlocked means dependency or evidence prerequisites block the task.
StatusBlocked TaskStatus = "blocked"
// StatusFailed means task verification or execution failed.
StatusFailed TaskStatus = "failed"
// StatusRepairRequired means a failure needs an explicit repair attempt.
StatusRepairRequired TaskStatus = "repair_required"
// StatusRepairRunning means a repair attempt is active.
StatusRepairRunning TaskStatus = "repair_running"
// StatusRepaired means repair output exists and is ready for verification.
StatusRepaired TaskStatus = "repaired"
// StatusVerificationRunning means verification evidence is being gathered.
StatusVerificationRunning TaskStatus = "verification_running"
// StatusVerified means verification passed.
StatusVerified TaskStatus = "verified"
// StatusCertified means the task has terminal certification evidence.
StatusCertified TaskStatus = "certified"
// StatusRejected means the task was explicitly rejected.
StatusRejected TaskStatus = "rejected"
// StatusSuperseded means the task was replaced by another canonical task record.
StatusSuperseded TaskStatus = "superseded"
// StatusPolicyBlocked means policy denied or paused the task.
StatusPolicyBlocked TaskStatus = "policy_blocked"
)
// LegacyTaskStatus is the compatibility-only projection for pre-v3.9 Work
// events. These names are not canonical v3.9 TaskStatus values.
type LegacyTaskStatus string
const (
LegacyStatusPending LegacyTaskStatus = "pending"
LegacyStatusAssigned LegacyTaskStatus = "assigned"
LegacyStatusCompleted LegacyTaskStatus = "completed"
LegacyStatusBlocked LegacyTaskStatus = "blocked"
LegacyStatusReady LegacyTaskStatus = "ready"
)
// Task represents a work item derived from a work.task.created event.
type Task struct {
ID types.EventID
Title string
Description string
CreatedBy types.ActorID
Priority TaskPriority
Workspace string
CanonicalTaskID string
FactoryOrderID string
RequirementIDs []string
AcceptanceCriterionIDs []string
Cell string
RiskClass string
ExpectedOutputs []string
CreatedAt time.Time // timestamp of the work.task.created event
}
// TaskSummary extends Task with computed state fields for efficient list views.
// Status, Assignee, Blocked, ArtifactCount, and Waived are populated by
// ListSummaries using batch store scans.
type TaskSummary struct {
Task
Status TaskStatus
LegacyStatus LegacyTaskStatus
Assignee types.ActorID // zero value if unassigned
Blocked bool
ArtifactCount int
Waived bool
Ready bool
MissingGates []string
MissingFacts []string
Canonical *worklifecycle.CanonicalWorkState `json:"canonical,omitempty"`
CanonicalError string `json:"canonical_error,omitempty"`
}
// TaskCreateOptions carries v3.9 Tier 0 lineage and scheduling metadata for a task.
type TaskCreateOptions struct {
Title string
Description string
Workspace string
Priority TaskPriority
CanonicalTaskID string
FactoryOrderID string
RequirementIDs []string
AcceptanceCriterionIDs []string
Cell string
RiskClass string
ExpectedOutputs []string
}
// TaskLinkage is the replayed FactoryOrder -> Requirement -> AcceptanceCriterion -> Task linkage.
type TaskLinkage struct {
CanonicalTaskID string
FactoryOrderID string
RequirementIDs []string
AcceptanceCriterionIDs []string
}
// VerificationEvidence is the replayed verification evidence attached to a task.
type VerificationEvidence struct {
TestCaseIDs []string
TestRunIDs []string
GateResultIDs []string
WaiverIDs []string
}
// FailureRepairReferences is the replayed failure/repair evidence attached to a task.
type FailureRepairReferences struct {
FailureIDs []string
RepairAttemptIDs []string
WaiverIDs []string
}
// TaskProjection is the v3.9 replayed operational view of a Work task.
type TaskProjection struct {
Task
Status TaskStatus
Assignee types.ActorID
Blocked bool
Ready bool
Linkage TaskLinkage
SourceIssueRecords []FactoryOrderSourceIssueRecord
ModelOverrides []FactoryOrderModelOverride
Verification VerificationEvidence
FailureRepair FailureRepairReferences
SupersededBy string
LastTransitionEvent types.EventID
Canonical *worklifecycle.CanonicalWorkState `json:"canonical,omitempty"`
CanonicalError string `json:"canonical_error,omitempty"`
}
// LegacyTaskProjection replays historical Work events without promoting
// pending/assigned/completed into the canonical v3.9 lifecycle.
type LegacyTaskProjection struct {
TaskID types.EventID
Status LegacyTaskStatus
Assignee types.ActorID
Blocked bool
Ready bool
}
// ArtifactEvent holds the data from a work.task.artifact event.
type ArtifactEvent struct {
ID types.EventID
TaskID types.EventID
Label string
MediaType string
Body string
CreatedBy types.ActorID
Timestamp time.Time
}
// CommentEvent holds the data from a work.task.comment event.
type CommentEvent struct {
ID types.EventID
TaskID types.EventID
Body string
AuthorID types.ActorID
Timestamp time.Time
}
// ReopenEvent holds the data from a work.task.reopened event.
type ReopenEvent struct {
ID types.EventID
TaskID types.EventID
ReopenedBy types.ActorID
Reason string
Issues []string
Timestamp time.Time
}
// ChildTask records a direct task dependency edge where Task depends on ParentID.
// In the Work graph this means Task is a child/subtask of ParentID.
type ChildTask struct {
Task
ParentID types.EventID
DependencyEventID types.EventID
DependencyAddedBy types.ActorID
DependencyTimestamp time.Time
}
// SupersededTask records a duplicate child task that was closed in favor of
// an earlier canonical child under the same parent.
type SupersededTask struct {
TaskID types.EventID
TaskTitle string
CanonicalID types.EventID
}
// TaskReadiness is the replayed readiness gate state for a task.
type TaskReadiness struct {
TaskID types.EventID
Ready bool
PresentGates []string
MissingGates []string
PresentFacts []string
MissingFacts []string
}
// FactRequirement is a task readiness prerequisite satisfied by an existing
// EventGraph fact of the required type, optionally pinned to an exact event ID.
type FactRequirement struct {
ID types.EventID
TaskID types.EventID
RequiredEventType types.EventType
RequiredEventID types.EventID
Reason string
RequiredBy types.ActorID
Timestamp time.Time
Satisfied bool
}
// TaskStore creates and queries tasks as auditable events on the shared graph.
type TaskStore struct {
store store.Store
factory *event.EventFactory
signer event.Signer
// fold is the head-keyed fold-generation memo used by
// ListSummariesCached (store_fold_cache.go). Once set, its own internals
// (mutex + singleflight.Group) are safe for concurrent use. It is always
// set by NewTaskStore, the only constructor in this codebase — the
// nil-check fallback in ListSummariesCached exists purely so a
// zero-value TaskStore{} (constructed outside NewTaskStore, e.g. in a
// future test) fails safe with a working fold cache rather than a nil
// dereference; that fallback path is NOT itself safe for concurrent
// first-use across goroutines (ordinary Go nil-check-then-assign race),
// so callers must go through NewTaskStore for any concurrent use, which
// this codebase always does.
fold *foldCache
}
// NewTaskStore creates a new TaskStore backed by the given event store.
func NewTaskStore(s store.Store, factory *event.EventFactory, signer event.Signer) *TaskStore {
return &TaskStore{store: s, factory: factory, signer: signer, fold: newFoldCache()}
}
// Create records a work.task.created event on the graph and returns the task.
// The caller must supply at least one cause (typically the current chain head).
// An optional priority may be passed as the last argument; defaults to PriorityMedium.
func (ts *TaskStore) Create(
source types.ActorID,
title, description string,
causes []types.EventID,
convID types.ConversationID,
priority ...TaskPriority,
) (Task, error) {
return ts.create(source, TaskCreateOptions{
Title: title,
Description: description,
Priority: firstPriority(priority),
}, causes, convID)
}
// CreateV39 records a Work task with v3.9 Tier 0 lineage references.
func (ts *TaskStore) CreateV39(
source types.ActorID,
opts TaskCreateOptions,
causes []types.EventID,
convID types.ConversationID,
) (Task, error) {
return ts.create(source, opts, causes, convID)
}
func (ts *TaskStore) create(
source types.ActorID,
opts TaskCreateOptions,
causes []types.EventID,
convID types.ConversationID,
) (Task, error) {
title := opts.Title
if title == "" {
return Task{}, fmt.Errorf("title is required")
}
if err := validateTaskCreateOptions(opts); err != nil {
return Task{}, err
}
p := opts.Priority
if p == "" {
p = DefaultPriority
}
content := TaskCreatedContent{
Title: title,
Description: opts.Description,
CreatedBy: source,
Priority: p,
Workspace: opts.Workspace,
CanonicalTaskID: opts.CanonicalTaskID,
FactoryOrderID: opts.FactoryOrderID,
RequirementIDs: cloneStrings(opts.RequirementIDs),
AcceptanceCriterionIDs: cloneStrings(opts.AcceptanceCriterionIDs),
Cell: opts.Cell,
RiskClass: opts.RiskClass,
ExpectedOutputs: cloneStrings(opts.ExpectedOutputs),
}
ev, err := ts.factory.Create(EventTypeTaskCreated, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return Task{}, fmt.Errorf("create task event: %w", err)
}
stored, err := ts.store.Append(ev)
if err != nil {
return Task{}, fmt.Errorf("append task event: %w", err)
}
return Task{
ID: stored.ID(),
Title: title,
Description: opts.Description,
CreatedBy: source,
Priority: p,
Workspace: opts.Workspace,
CanonicalTaskID: opts.CanonicalTaskID,
FactoryOrderID: opts.FactoryOrderID,
RequirementIDs: cloneStrings(opts.RequirementIDs),
AcceptanceCriterionIDs: cloneStrings(opts.AcceptanceCriterionIDs),
Cell: opts.Cell,
RiskClass: opts.RiskClass,
ExpectedOutputs: cloneStrings(opts.ExpectedOutputs),
}, nil
}
// List returns up to limit work.task.created events as Tasks.
// Linkage fields (FactoryOrderID, CanonicalTaskID, RequirementIDs,
// AcceptanceCriterionIDs) are reconciled against the newest work.task.linked
// event per task so that tasks linked after creation return current values.
func (ts *TaskStore) List(limit int) ([]Task, error) {
if limit <= 0 {
limit = 20
}
page, err := ts.store.ByType(EventTypeTaskCreated, limit, types.None[types.Cursor]())
if err != nil {
return nil, fmt.Errorf("list tasks: %w", err)
}
// Build a map of the newest TaskLinkedContent per task ID (ByType returns
// newest-first, so the first entry seen per task is the most recent).
// Pages to exhaustion (D1b): this is a full-domain overlay scan (unlike
// the EventTypeTaskCreated read above, which is intentionally bounded by
// the caller's requested limit) — a link event beyond one page must not
// be silently missed.
// newestLink is keyed by the task's creation-event ID. TaskLinkedContent.TaskID
// stores the creation-event ID (same convention projectLinkage relies on), so the
// later newestLink[t.ID] lookup — where t.ID is ev.ID() of the created event — matches.
newestLink := make(map[types.EventID]TaskLinkedContent)
if err := ts.pageAllByType(EventTypeTaskLinked, func(ev event.Event) {
c, ok := ev.Content().(TaskLinkedContent)
if !ok {
return
}
if _, seen := newestLink[c.TaskID]; !seen {
newestLink[c.TaskID] = c
}
}); err != nil {
return nil, fmt.Errorf("list tasks: fetch link events: %w", err)
}
tasks := make([]Task, 0, len(page.Items()))
for _, ev := range page.Items() {
c, ok := ev.Content().(TaskCreatedContent)
if !ok {
continue
}
p := c.Priority
if p == "" {
p = DefaultPriority
}
t := Task{
ID: ev.ID(),
Title: c.Title,
Description: c.Description,
CreatedBy: c.CreatedBy,
Priority: p,
Workspace: c.Workspace,
CanonicalTaskID: c.CanonicalTaskID,
FactoryOrderID: c.FactoryOrderID,
RequirementIDs: cloneStrings(c.RequirementIDs),
AcceptanceCriterionIDs: cloneStrings(c.AcceptanceCriterionIDs),
Cell: c.Cell,
RiskClass: c.RiskClass,
ExpectedOutputs: cloneStrings(c.ExpectedOutputs),
CreatedAt: ev.Timestamp().Value(),
}
// Override linkage fields with the newest TaskLinkedContent, mirroring
// the projectLinkage semantics: only override when the linked value is
// non-empty so a partial re-link does not erase existing values.
if lc, ok := newestLink[t.ID]; ok {
if lc.CanonicalTaskID != "" {
t.CanonicalTaskID = lc.CanonicalTaskID
}
if lc.FactoryOrderID != "" {
t.FactoryOrderID = lc.FactoryOrderID
}
if len(lc.RequirementIDs) > 0 {
t.RequirementIDs = cloneStrings(lc.RequirementIDs)
}
if len(lc.AcceptanceCriterionIDs) > 0 {
t.AcceptanceCriterionIDs = cloneStrings(lc.AcceptanceCriterionIDs)
}
}
tasks = append(tasks, t)
}
return tasks, nil
}
// CreateInWorkspace records a work.task.created event with a workspace label.
// The caller must supply at least one cause (typically the current chain head).
// An optional priority may be passed as the last argument; defaults to PriorityMedium.
func (ts *TaskStore) CreateInWorkspace(
source types.ActorID,
title, description, workspace string,
causes []types.EventID,
convID types.ConversationID,
priority ...TaskPriority,
) (Task, error) {
return ts.create(source, TaskCreateOptions{
Title: title,
Description: description,
Workspace: workspace,
Priority: firstPriority(priority),
}, causes, convID)
}
// ListByWorkspace returns up to limit tasks whose Workspace field matches the given workspace.
func (ts *TaskStore) ListByWorkspace(workspace string, limit int) ([]Task, error) {
if limit <= 0 {
limit = 20
}
// Fetch a broad page; filter in-process since ByType has no predicate support.
page, err := ts.store.ByType(EventTypeTaskCreated, 1000, types.None[types.Cursor]())
if err != nil {
return nil, fmt.Errorf("list tasks by workspace: %w", err)
}
tasks := make([]Task, 0)
for _, ev := range page.Items() {
c, ok := ev.Content().(TaskCreatedContent)
if !ok || c.Workspace != workspace {
continue
}
p := c.Priority
if p == "" {
p = DefaultPriority
}
tasks = append(tasks, Task{
ID: ev.ID(),
Title: c.Title,
Description: c.Description,
CreatedBy: c.CreatedBy,
Priority: p,
Workspace: c.Workspace,
CanonicalTaskID: c.CanonicalTaskID,
FactoryOrderID: c.FactoryOrderID,
RequirementIDs: cloneStrings(c.RequirementIDs),
AcceptanceCriterionIDs: cloneStrings(c.AcceptanceCriterionIDs),
Cell: c.Cell,
RiskClass: c.RiskClass,
ExpectedOutputs: cloneStrings(c.ExpectedOutputs),
})
if len(tasks) >= limit {
break
}
}
return tasks, nil
}
// ListSummariesByWorkspace returns up to limit workspace-scoped tasks with Status,
// Assignee, and Blocked populated via batch store scans.
func (ts *TaskStore) ListSummariesByWorkspace(workspace string, limit int) ([]TaskSummary, error) {
tasks, err := ts.ListByWorkspace(workspace, limit)
if err != nil {
return nil, err
}
return ts.batchStatus(tasks)
}
// Assign records a work.task.assigned event on the graph.
// source is the actor performing the assignment (may equal assignee for self-assignment).
func (ts *TaskStore) Assign(
source types.ActorID,
taskID types.EventID,
assignee types.ActorID,
causes []types.EventID,
convID types.ConversationID,
) error {
content := TaskAssignedContent{
TaskID: taskID,
AssignedTo: assignee,
AssignedBy: source,
}
ev, err := ts.factory.Create(EventTypeTaskAssigned, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create assign event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append assign event: %w", err)
}
return nil
}
// Complete records a work.task.completed event on the graph.
// source is the actor completing the task (typically the assignee).
//
// The artifact gate requires at least one work.task.artifact or
// work.task.artifact.waived event for the task. If neither exists,
// Complete returns ErrArtifactRequired.
func (ts *TaskStore) Complete(
source types.ActorID,
taskID types.EventID,
summary string,
causes []types.EventID,
convID types.ConversationID,
) error {
// --- Artifact gate (captures the event ID for ArtifactRef) ---
artifactRef, hasArtifact, err := ts.findEventForTask(EventTypeTaskArtifact, taskID)
if err != nil {
return fmt.Errorf("check artifacts: %w", err)
}
if !hasArtifact {
waiverRef, hasWaiver, err := ts.findEventForTask(EventTypeTaskArtifactWaived, taskID)
if err != nil {
return fmt.Errorf("check waivers: %w", err)
}
if !hasWaiver {
return ErrArtifactRequired
}
artifactRef = waiverRef
}
content := TaskCompletedContent{
TaskID: taskID,
CompletedBy: source,
Summary: summary,
ArtifactRef: artifactRef,
}
ev, err := ts.factory.Create(EventTypeTaskCompleted, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create complete event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append complete event: %w", err)
}
return nil
}
// Reopen records a work.task.reopened event, returning a completed task to the
// open state — the review→fix return edge (run findings v12-F1). The event
// references every live completion for the task, so the supersede fold is pure
// set algebra over explicit CompletionRefs: no event-order comparison anywhere
// (ByType page order differs across store backends), duplicate reopens are
// structurally idempotent, and a re-completion is live again by construction.
//
// Fail-closed: an unreadable completion state refuses (it cannot be proven the
// task is completed), and a task with no live completion refuses (only
// completed work can be reopened — reopening open work would let a reopen
// masquerade as a no-op and desync callers that emit feedback alongside it).
// Reason is required: a reopen exists to carry actionable feedback to the
// producer's next Operate instruction.
func (ts *TaskStore) Reopen(
source types.ActorID,
taskID types.EventID,
reason string,
issues []string,
causes []types.EventID,
convID types.ConversationID,
) error {
if strings.TrimSpace(reason) == "" {
return fmt.Errorf("reopen reason is required")
}
live, err := ts.liveCompletionsByTask()
if err != nil {
return fmt.Errorf("reopen %s: %w", taskID.Value(), err)
}
refs := live[taskID]
if len(refs) == 0 {
return fmt.Errorf("reopen %s: no live completion — only a completed task can be reopened", taskID.Value())
}
content := TaskReopenedContent{
TaskID: taskID,
ReopenedBy: source,
Reason: reason,
Issues: issues,
CompletionRefs: refs,
}
ev, err := ts.factory.Create(EventTypeTaskReopened, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create reopen event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append reopen event: %w", err)
}
return nil
}
// TransitionTask records a v3.9 lifecycle transition after validating it
// against the current replayed Work projection.
func (ts *TaskStore) TransitionTask(
source types.ActorID,
taskID types.EventID,
to TaskStatus,
reason string,
evidenceRefs []string,
causes []types.EventID,
convID types.ConversationID,
) error {
return ts.transitionTask(source, taskID, "", to, reason, evidenceRefs, "", causes, convID)
}
// RejectTask records a terminal rejected lifecycle state.
func (ts *TaskStore) RejectTask(
source types.ActorID,
taskID types.EventID,
reason string,
evidenceRefs []string,
causes []types.EventID,
convID types.ConversationID,
) error {
if strings.TrimSpace(reason) == "" {
return fmt.Errorf("rejection reason is required")
}
return ts.transitionTask(source, taskID, "", StatusRejected, reason, evidenceRefs, "", causes, convID)
}
// SupersedeTask records a terminal superseded lifecycle state and the canonical replacement.
func (ts *TaskStore) SupersedeTask(
source types.ActorID,
taskID types.EventID,
supersededBy string,
reason string,
evidenceRefs []string,
causes []types.EventID,
convID types.ConversationID,
) error {
if strings.TrimSpace(supersededBy) == "" {
return fmt.Errorf("superseded_by is required")
}
if strings.TrimSpace(reason) == "" {
return fmt.Errorf("supersession reason is required")
}
return ts.transitionTask(source, taskID, "", StatusSuperseded, reason, evidenceRefs, supersededBy, causes, convID)
}
func (ts *TaskStore) transitionTask(
source types.ActorID,
taskID types.EventID,
from TaskStatus,
to TaskStatus,
reason string,
evidenceRefs []string,
supersededBy string,
causes []types.EventID,
convID types.ConversationID,
) error {
if !isKnownTaskStatus(to) {
return fmt.Errorf("%w: unknown target state %q", ErrInvalidLifecycleTransition, to)
}
current, err := ts.GetStatus(taskID)
if err != nil {
return err
}
if from != "" && from != current {
return fmt.Errorf("%w: current state %q does not match requested from_state %q", ErrInvalidLifecycleTransition, current, from)
}
if !canTransitionTask(current, to) {
return fmt.Errorf("%w: %s -> %s", ErrInvalidLifecycleTransition, current, to)
}
content := TaskLifecycleTransitionContent{
TaskID: taskID,
FromState: current,
ToState: to,
Reason: strings.TrimSpace(reason),
EvidenceRefs: cloneStrings(evidenceRefs),
SupersededBy: strings.TrimSpace(supersededBy),
ChangedBy: source,
}
ev, err := ts.factory.Create(EventTypeTaskLifecycleTransitioned, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create lifecycle transition event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append lifecycle transition event: %w", err)
}
return nil
}
// LinkTask attaches FactoryOrder, Requirement, AcceptanceCriterion, and
// canonical Task record references to an existing Work task.
func (ts *TaskStore) LinkTask(
source types.ActorID,
taskID types.EventID,
linkage TaskLinkage,
causes []types.EventID,
convID types.ConversationID,
) error {
if err := validateTaskLinkage(linkage); err != nil {
return err
}
content := TaskLinkedContent{
TaskID: taskID,
CanonicalTaskID: strings.TrimSpace(linkage.CanonicalTaskID),
FactoryOrderID: strings.TrimSpace(linkage.FactoryOrderID),
RequirementIDs: cloneStrings(linkage.RequirementIDs),
AcceptanceCriterionIDs: cloneStrings(linkage.AcceptanceCriterionIDs),
LinkedBy: source,
}
ev, err := ts.factory.Create(EventTypeTaskLinked, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create task link event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append task link event: %w", err)
}
return nil
}
// AttachVerificationEvidence attaches TestCase, TestRun, GateResult, and Waiver refs.
func (ts *TaskStore) AttachVerificationEvidence(
source types.ActorID,
taskID types.EventID,
evidence VerificationEvidence,
summary string,
causes []types.EventID,
convID types.ConversationID,
) error {
if len(evidence.TestCaseIDs) == 0 && len(evidence.TestRunIDs) == 0 && len(evidence.GateResultIDs) == 0 && len(evidence.WaiverIDs) == 0 {
return fmt.Errorf("at least one verification evidence reference is required")
}
if err := validateVerificationEvidence(evidence); err != nil {
return err
}
content := TaskVerificationAttachedContent{
TaskID: taskID,
TestCaseIDs: cloneStrings(evidence.TestCaseIDs),
TestRunIDs: cloneStrings(evidence.TestRunIDs),
GateResultIDs: cloneStrings(evidence.GateResultIDs),
WaiverIDs: cloneStrings(evidence.WaiverIDs),
Summary: strings.TrimSpace(summary),
AttachedBy: source,
}
ev, err := ts.factory.Create(EventTypeTaskVerificationAttached, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create verification evidence event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append verification evidence event: %w", err)
}
return nil
}
// AttachFailureRepairReferences attaches Failure, RepairAttempt, and Waiver refs.
func (ts *TaskStore) AttachFailureRepairReferences(
source types.ActorID,
taskID types.EventID,
refs FailureRepairReferences,
summary string,
causes []types.EventID,
convID types.ConversationID,
) error {
if len(refs.FailureIDs) == 0 && len(refs.RepairAttemptIDs) == 0 && len(refs.WaiverIDs) == 0 {
return fmt.Errorf("at least one failure, repair, or waiver reference is required")
}
if err := validateFailureRepairReferences(refs); err != nil {
return err
}
content := TaskFailureRepairAttachedContent{
TaskID: taskID,
FailureIDs: cloneStrings(refs.FailureIDs),
RepairAttemptIDs: cloneStrings(refs.RepairAttemptIDs),
WaiverIDs: cloneStrings(refs.WaiverIDs),
Summary: strings.TrimSpace(summary),
AttachedBy: source,
}
ev, err := ts.factory.Create(EventTypeTaskFailureRepairAttached, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create failure repair event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append failure repair event: %w", err)
}
return nil
}
// GetStatus reconstructs the current canonical v3.9 status of a task by
// scanning explicit lifecycle events. Legacy Work events are exposed through
// ProjectLegacyTask and GetCompatibilityStatus instead of being promoted into
// canonical v3.9 lifecycle state.
func (ts *TaskStore) GetStatus(taskID types.EventID) (TaskStatus, error) {
after := types.None[types.Cursor]()
for {
transitionPage, err := ts.store.ByType(EventTypeTaskLifecycleTransitioned, 1000, after)
if err != nil {
return StatusCreated, fmt.Errorf("fetch lifecycle transition events: %w", err)
}
for _, ev := range transitionPage.Items() {
c, ok := ev.Content().(TaskLifecycleTransitionContent)
if ok && c.TaskID == taskID {
return c.ToState, nil
}
}
if !transitionPage.HasMore() {
return StatusCreated, nil
}
after = transitionPage.Cursor()
}
}
// GetCompatibilityStatus returns the legacy Work task status projection for
// callers that still depend on pending/assigned/completed operational flow.
func (ts *TaskStore) GetCompatibilityStatus(taskID types.EventID) (LegacyTaskStatus, error) {
projection, err := ts.ProjectLegacyTask(taskID)
if err != nil {
return "", err
}
return projection.Status, nil
}
// ProjectLegacyTask reconstructs pre-v3.9 Work task state without changing the
// canonical v3.9 lifecycle. It keeps old created/assigned/completed events
// replayable as an operational compatibility view.
func (ts *TaskStore) ProjectLegacyTask(taskID types.EventID) (LegacyTaskProjection, error) {
assignee, err := ts.projectAssignee(taskID)
if err != nil {
return LegacyTaskProjection{}, err
}
readiness, err := ts.Readiness(taskID)
if err != nil {
return LegacyTaskProjection{}, err
}
completedIDs, err := ts.liveCompletedIDs()
if err != nil {
return LegacyTaskProjection{}, err
}
if completedIDs[taskID] {
return LegacyTaskProjection{
TaskID: taskID,
Status: LegacyStatusCompleted,
Assignee: assignee,
Ready: readiness.Ready,
}, nil
}
blocked, err := ts.IsBlocked(taskID)
if err != nil {
return LegacyTaskProjection{}, err
}
if blocked {
return LegacyTaskProjection{
TaskID: taskID,
Status: LegacyStatusBlocked,
Assignee: assignee,
Blocked: true,
Ready: readiness.Ready,
}, nil
}
if !assignee.IsZero() {
return LegacyTaskProjection{
TaskID: taskID,
Status: LegacyStatusAssigned,
Assignee: assignee,
Ready: readiness.Ready,
}, nil
}
if readiness.Ready {
return LegacyTaskProjection{
TaskID: taskID,
Status: LegacyStatusReady,
Ready: true,
}, nil
}
return LegacyTaskProjection{
TaskID: taskID,
Status: LegacyStatusPending,
}, nil
}
// AddDependency records a work.task.dependency.added event, declaring that taskID
// depends on dependsOnID — taskID is blocked until dependsOnID completes.
func (ts *TaskStore) AddDependency(
source types.ActorID,
taskID, dependsOnID types.EventID,
causes []types.EventID,
convID types.ConversationID,
) error {
if taskID == dependsOnID {
return fmt.Errorf("task %s cannot depend on itself", taskID.Value())
}
content := TaskDependencyContent{
TaskID: taskID,
DependsOnID: dependsOnID,
AddedBy: source,
}
ev, err := ts.factory.Create(EventTypeTaskDependencyAdded, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return fmt.Errorf("create dependency event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return fmt.Errorf("append dependency event: %w", err)
}
return nil
}
// GetDependencies returns all task IDs that the given taskID depends on.
// It folds EVERY dependency event, paging until exhaustion: this read is
// load-bearing for the reverse-edge deadlock guard (run findings v11-F1,
// hive#153), and a bounded read under a safety guard is a fail-open — an edge
// older than the newest page would become invisible to the guard.
func (ts *TaskStore) GetDependencies(taskID types.EventID) ([]types.EventID, error) {
var deps []types.EventID
after := types.None[types.Cursor]()
for {
page, err := ts.store.ByType(EventTypeTaskDependencyAdded, 1000, after)
if err != nil {
return nil, fmt.Errorf("fetch dependency events: %w", err)
}
for _, ev := range page.Items() {
c, ok := ev.Content().(TaskDependencyContent)
if ok && c.TaskID == taskID {
deps = append(deps, c.DependsOnID)
}
}
if !page.HasMore() {
return deps, nil
}
after = page.Cursor()
}
}
// DirectChildren returns tasks that directly depend on parentID, sorted by the
// dependency event timestamp from oldest to newest. The oldest child is treated
// as canonical when duplicate child titles are discovered.
func (ts *TaskStore) DirectChildren(parentID types.EventID) ([]ChildTask, error) {
page, err := ts.store.ByType(EventTypeTaskDependencyAdded, 1000, types.None[types.Cursor]())
if err != nil {
return nil, fmt.Errorf("fetch dependency events: %w", err)
}
children := make([]ChildTask, 0)
seenChildren := make(map[types.EventID]bool)
for _, ev := range page.Items() {
c, ok := ev.Content().(TaskDependencyContent)
if !ok || c.DependsOnID != parentID {
continue
}
if seenChildren[c.TaskID] {
continue
}
seenChildren[c.TaskID] = true
created, err := ts.store.Get(c.TaskID)
if err != nil {
continue
}
cc, ok := created.Content().(TaskCreatedContent)
if !ok {
continue
}
p := cc.Priority
if p == "" {
p = DefaultPriority
}
children = append(children, ChildTask{
Task: Task{
ID: created.ID(),
Title: cc.Title,
Description: cc.Description,
CreatedBy: cc.CreatedBy,
Priority: p,
Workspace: cc.Workspace,
CanonicalTaskID: cc.CanonicalTaskID,
FactoryOrderID: cc.FactoryOrderID,