forked from lovyou-ai/work
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathissue_scan.go
More file actions
1059 lines (1001 loc) · 36.3 KB
/
Copy pathissue_scan.go
File metadata and controls
1059 lines (1001 loc) · 36.3 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 (
"crypto/sha256"
"encoding/json"
"fmt"
"strconv"
"strings"
"unicode"
"github.com/transpara-ai/eventgraph/go/pkg/types"
)
const (
// IssueScanWorkspace is the stable Work workspace for Civilization
// autonomous issue-scan stage tasks.
IssueScanWorkspace = "civilization.issue_scan"
// IssueScanMarkerSchemaVersion is the stable schema version for Work-owned
// source-issue marker reference packets.
IssueScanMarkerSchemaVersion = "1"
// IssueScanMarkerProjectionKind identifies Work source-issue marker refs for
// Hive, EventGraph, Site, and fixture consumers.
IssueScanMarkerProjectionKind = "work.issue_scan.source_marker_ref"
defaultIssueScanCell = "cell_civilization_issue_scan"
defaultIssueScanRiskClass = "high"
)
// IssueScanStageID is the canonical stage key for the autonomous issue-scan
// pipeline. The values are part of the Work/EventGraph contract.
type IssueScanStageID string
const (
IssueScanStageResearch IssueScanStageID = "research_issue_and_repo_context"
IssueScanStageDebate IssueScanStageID = "debate_with_correct_civic_roles"
IssueScanStageSelectApproach IssueScanStageID = "select_and_design_approach"
IssueScanStageImplement IssueScanStageID = "implement_on_branch"
IssueScanStageAdversarialReview IssueScanStageID = "run_adversarial_review"
IssueScanStageDriveBlockersToZero IssueScanStageID = "drive_blockers_to_zero"
IssueScanStageSurfaceHumanReadyPR IssueScanStageID = "surface_ready_for_human_result_pr"
)
type issueScanStageDefinition struct {
Number int
Title string
Gate string
ExpectedOutputs []string
}
var issueScanStageDefinitions = map[IssueScanStageID]issueScanStageDefinition{
IssueScanStageResearch: {
Number: 1,
Title: "Research issue and repo context",
Gate: "research_packet_posted",
ExpectedOutputs: []string{
"bounded issue and repository context",
"current target state",
"protected-action boundary",
},
},
IssueScanStageDebate: {
Number: 2,
Title: "Debate with correct civic roles",
Gate: "role_debate_complete",
ExpectedOutputs: []string{
"role debate summary",
"risk and authority assessment",
},
},
IssueScanStageSelectApproach: {
Number: 3,
Title: "Select and design approach",
Gate: "implementation_plan_selected",
ExpectedOutputs: []string{
"selected approach",
"acceptance test plan",
},
},
IssueScanStageImplement: {
Number: 4,
Title: "Implement on branch",
Gate: "branch_patch_ready",
ExpectedOutputs: []string{
"scoped branch changes",
"local validation evidence",
},
},
IssueScanStageAdversarialReview: {
Number: 5,
Title: "Run adversarial review",
Gate: "adversarial_review_result_recorded",
ExpectedOutputs: []string{
"exact-head adversarial review artifact",
"finding disposition",
},
},
IssueScanStageDriveBlockersToZero: {
Number: 6,
Title: "Drive blockers to zero",
Gate: "blockers_zero_or_human_parked",
ExpectedOutputs: []string{
"resolved blocker list",
"revalidation evidence",
},
},
IssueScanStageSurfaceHumanReadyPR: {
Number: 7,
Title: "Surface ready-for-Human result PR",
Gate: "human_action_state_clear",
ExpectedOutputs: []string{
"draft PR URL",
"human action summary",
"merge/re-enable recommendation boundary",
},
},
}
// IssueScanStageIDs returns the canonical stage order for issue-scan DAGs.
func IssueScanStageIDs() []IssueScanStageID {
return []IssueScanStageID{
IssueScanStageResearch,
IssueScanStageDebate,
IssueScanStageSelectApproach,
IssueScanStageImplement,
IssueScanStageAdversarialReview,
IssueScanStageDriveBlockersToZero,
IssueScanStageSurfaceHumanReadyPR,
}
}
// IssueScanTarget identifies the GitHub issue being processed.
type IssueScanTarget struct {
Repository string
IssueNumber int
}
// Ref returns the human-readable repository issue reference.
func (t IssueScanTarget) Ref() string {
return fmt.Sprintf("%s#%d", strings.TrimSpace(t.Repository), t.IssueNumber)
}
// IssueScanStageOptions configures one deterministic issue-scan stage task.
type IssueScanStageOptions struct {
RunID string
Target IssueScanTarget
Stage IssueScanStageID
Title string
Description string
Workspace string
Priority TaskPriority
CanonicalTaskID string
FactoryOrderID string
RequirementIDs []string
AcceptanceCriterionIDs []string
Cell string
RiskClass string
ExpectedOutputs []string
}
// IssueScanDAGOptions configures the canonical stage DAG for one target issue.
type IssueScanDAGOptions struct {
RunID string
Target IssueScanTarget
Stages []IssueScanStageID
Workspace string
Priority TaskPriority
Cell string
RiskClass string
}
// IssueScanStageRef is the stable reference callers pass when recording typed
// issue-scan stage state.
type IssueScanStageRef struct {
TaskID types.EventID
RunID string
Target IssueScanTarget
Stage IssueScanStageID
}
// IssueScanStageRecord is returned by idempotent stage creation.
type IssueScanStageRecord struct {
IssueScanStageRef
Task Task
StageNumber int
Gate string
Created bool
DuplicateOf types.EventID
CanonicalTaskID string
FactoryOrderID string
}
// IssueScanDAGResult is returned by EnsureIssueScanDAG.
type IssueScanDAGResult struct {
Stages []IssueScanStageRecord
CreatedTasks int
CreatedDependencies int
}
// IssueScanBlockerReason is the typed reason a scan stage parked.
type IssueScanBlockerReason string
const (
IssueScanBlockerNeedsHumanScope IssueScanBlockerReason = "needs_human_scope"
IssueScanBlockerProtectedAction IssueScanBlockerReason = "protected_action"
IssueScanBlockerStaleTarget IssueScanBlockerReason = "stale_target"
IssueScanBlockerDuplicateChain IssueScanBlockerReason = "duplicate_chain"
IssueScanBlockerMissingGateEvidence IssueScanBlockerReason = "missing_gate_evidence"
)
// IssueScanBlocker carries the structured blocker state for a parked stage.
type IssueScanBlocker struct {
Reason IssueScanBlockerReason
Detail string
EvidenceRefs []string
}
// IssueScanStageBlockResult reports whether a new blocker event was appended.
type IssueScanStageBlockResult struct {
Created bool
Status TaskStatus
}
// IssueScanStageGateResult reports whether a new gate-satisfied event was appended.
type IssueScanStageGateResult struct {
Created bool
Status TaskStatus
}
// IssueScanMarkerWorkRef is the stable Work-owned reference packet that Hive,
// EventGraph, and Site can cite when projecting source GitHub issue marker
// state. It is derived from replayed Work events; callers must not derive it
// from GitHub marker comments or labels.
type IssueScanMarkerWorkRef struct {
SchemaVersion string `json:"schema_version"`
ProjectionKind string `json:"projection_kind"`
CanonicalSource string `json:"canonical_source"`
ProjectionOnly bool `json:"projection_only"`
RunID string `json:"run_id"`
Target IssueScanMarkerTargetRef `json:"target"`
Stage IssueScanStageID `json:"stage"`
StageNumber int `json:"stage_number"`
Gate string `json:"gate"`
TaskID string `json:"task_id"`
CanonicalTaskID string `json:"canonical_task_id"`
FactoryOrderID string `json:"factory_order_id"`
RequirementIDs []string `json:"requirement_ids,omitempty"`
AcceptanceCriterionIDs []string `json:"acceptance_criterion_ids,omitempty"`
LifecycleState TaskStatus `json:"lifecycle_state"`
Blocked bool `json:"blocked"`
Ready bool `json:"ready"`
MissingGates []string `json:"missing_gates,omitempty"`
MissingFacts []string `json:"missing_facts,omitempty"`
SupersededBy string `json:"superseded_by,omitempty"`
LastTransitionEvent string `json:"last_transition_event,omitempty"`
LatestBlocker *IssueScanMarkerBlockerRef `json:"latest_blocker,omitempty"`
LatestGate *IssueScanMarkerGateRef `json:"latest_gate,omitempty"`
VerificationRefs IssueScanMarkerEvidenceRefs `json:"verification_refs"`
FailureRepairRefs IssueScanMarkerEvidenceRefs `json:"failure_repair_refs"`
SourceIssueRefs []string `json:"source_issue_refs,omitempty"`
AuthorityExclusions []string `json:"authority_exclusions"`
}
// IssueScanMarkerTargetRef is the marker-packet JSON shape for a GitHub issue
// target. It is separate from IssueScanTarget so persisted event content is not
// affected by marker JSON field names.
type IssueScanMarkerTargetRef struct {
Repository string `json:"repository"`
IssueNumber int `json:"issue_number"`
}
// Ref returns the compact repository issue reference.
func (t IssueScanMarkerTargetRef) Ref() string {
return fmt.Sprintf("%s#%d", strings.TrimSpace(t.Repository), t.IssueNumber)
}
// IssueScanMarkerBlockerRef is the latest typed blocker Work knows for a stage.
type IssueScanMarkerBlockerRef struct {
Reason IssueScanBlockerReason `json:"reason"`
Detail string `json:"detail,omitempty"`
EvidenceRefs []string `json:"evidence_refs,omitempty"`
}
// IssueScanMarkerGateRef is the latest typed gate completion Work knows for a stage.
type IssueScanMarkerGateRef struct {
Gate string `json:"gate"`
EvidenceRefs []string `json:"evidence_refs,omitempty"`
}
// IssueScanMarkerEvidenceRefs carries stable Work evidence references for
// marker consumers without asking them to parse Work comments.
type IssueScanMarkerEvidenceRefs struct {
TestCaseIDs []string `json:"test_case_ids,omitempty"`
TestRunIDs []string `json:"test_run_ids,omitempty"`
GateResultIDs []string `json:"gate_result_ids,omitempty"`
FailureIDs []string `json:"failure_ids,omitempty"`
RepairAttemptIDs []string `json:"repair_attempt_ids,omitempty"`
WaiverIDs []string `json:"waiver_ids,omitempty"`
}
func (r IssueScanStageRecord) Ref() IssueScanStageRef {
return IssueScanStageRef{
TaskID: r.Task.ID,
RunID: r.RunID,
Target: r.Target,
Stage: r.Stage,
}
}
// ProjectIssueScanMarkerWorkRef returns the Work-owned source-issue marker
// reference for an issue-scan stage. The packet is projection output only:
// Work remains the canonical source for lifecycle/readiness/blocking state,
// and GitHub comments/labels remain derived human-visible markers.
func (ts *TaskStore) ProjectIssueScanMarkerWorkRef(ref IssueScanStageRef) (IssueScanMarkerWorkRef, error) {
if err := ts.validateIssueScanStageRef(ref); err != nil {
return IssueScanMarkerWorkRef{}, err
}
projection, err := ts.ProjectTask(ref.TaskID)
if err != nil {
return IssueScanMarkerWorkRef{}, err
}
readiness, err := ts.Readiness(ref.TaskID)
if err != nil {
return IssueScanMarkerWorkRef{}, err
}
def, ok := issueScanStageDefinitions[ref.Stage]
if !ok {
return IssueScanMarkerWorkRef{}, fmt.Errorf("unknown issue-scan stage %q", ref.Stage)
}
out := IssueScanMarkerWorkRef{
SchemaVersion: IssueScanMarkerSchemaVersion,
ProjectionKind: IssueScanMarkerProjectionKind,
CanonicalSource: "work",
ProjectionOnly: true,
RunID: strings.TrimSpace(ref.RunID),
Target: IssueScanMarkerTargetRef{Repository: strings.TrimSpace(ref.Target.Repository), IssueNumber: ref.Target.IssueNumber},
Stage: ref.Stage,
StageNumber: def.Number,
Gate: def.Gate,
TaskID: projection.Task.ID.Value(),
CanonicalTaskID: projection.Linkage.CanonicalTaskID,
FactoryOrderID: projection.Linkage.FactoryOrderID,
RequirementIDs: cloneStrings(projection.Linkage.RequirementIDs),
AcceptanceCriterionIDs: cloneStrings(projection.Linkage.AcceptanceCriterionIDs),
LifecycleState: projection.Status,
Blocked: projection.Blocked,
Ready: projection.Ready,
MissingGates: cloneStrings(readiness.MissingGates),
MissingFacts: cloneStrings(readiness.MissingFacts),
SupersededBy: projection.SupersededBy,
VerificationRefs: IssueScanMarkerEvidenceRefs{
TestCaseIDs: cloneStrings(projection.Verification.TestCaseIDs),
TestRunIDs: cloneStrings(projection.Verification.TestRunIDs),
GateResultIDs: cloneStrings(projection.Verification.GateResultIDs),
WaiverIDs: cloneStrings(projection.Verification.WaiverIDs),
},
FailureRepairRefs: IssueScanMarkerEvidenceRefs{
FailureIDs: cloneStrings(projection.FailureRepair.FailureIDs),
RepairAttemptIDs: cloneStrings(projection.FailureRepair.RepairAttemptIDs),
WaiverIDs: cloneStrings(projection.FailureRepair.WaiverIDs),
},
SourceIssueRefs: sourceIssueRefs(projection.SourceIssueRecords),
AuthorityExclusions: issueScanMarkerAuthorityExclusions(),
}
if projection.LastTransitionEvent != (types.EventID{}) {
out.LastTransitionEvent = projection.LastTransitionEvent.Value()
}
if latest, ok, err := ts.latestIssueScanBlocker(ref.TaskID); err != nil {
return IssueScanMarkerWorkRef{}, err
} else if ok {
out.LatestBlocker = &IssueScanMarkerBlockerRef{
Reason: latest.BlockerReason,
Detail: strings.TrimSpace(latest.Detail),
EvidenceRefs: cloneStrings(latest.EvidenceRefs),
}
}
if latest, ok, err := ts.latestIssueScanGate(ref.TaskID); err != nil {
return IssueScanMarkerWorkRef{}, err
} else if ok {
out.LatestGate = &IssueScanMarkerGateRef{
Gate: latest.Gate,
EvidenceRefs: cloneStrings(latest.EvidenceRefs),
}
}
return out, nil
}
// ProjectIssueScanMarkerWorkRefJSON serializes ProjectIssueScanMarkerWorkRef
// for consumers that need to embed the Work ref packet in an artifact or test
// fixture.
func (ts *TaskStore) ProjectIssueScanMarkerWorkRefJSON(ref IssueScanStageRef) (string, error) {
packet, err := ts.ProjectIssueScanMarkerWorkRef(ref)
if err != nil {
return "", err
}
encoded, err := json.MarshalIndent(packet, "", " ")
if err != nil {
return "", fmt.Errorf("marshal issue-scan marker Work ref: %w", err)
}
return string(encoded), nil
}
// FindTaskByCanonicalTaskID returns the oldest task with the supplied canonical
// v3.9 task ID. If bad callers appended duplicates directly, the oldest event
// remains the canonical Work task for deterministic issue-scan replay.
func (ts *TaskStore) FindTaskByCanonicalTaskID(canonicalTaskID string) (Task, bool, error) {
canonicalTaskID = strings.TrimSpace(canonicalTaskID)
if canonicalTaskID == "" {
return Task{}, false, fmt.Errorf("canonical_task_id is required")
}
var found Task
hasFound := false
after := types.None[types.Cursor]()
for {
page, err := ts.store.ByType(EventTypeTaskCreated, 1000, after)
if err != nil {
return Task{}, false, fmt.Errorf("find canonical task: %w", err)
}
for _, ev := range page.Items() {
c, ok := ev.Content().(TaskCreatedContent)
if !ok || strings.TrimSpace(c.CanonicalTaskID) != canonicalTaskID {
continue
}
found = taskFromCreatedContent(ev.ID(), c)
hasFound = true
}
if !page.HasMore() {
return found, hasFound, nil
}
after = page.Cursor()
}
}
// EnsureIssueScanStage creates or returns the deterministic task for one
// issue-scan stage. Repeated calls for the same run, target, and stage do not
// append duplicate task events.
func (ts *TaskStore) EnsureIssueScanStage(
source types.ActorID,
opts IssueScanStageOptions,
causes []types.EventID,
convID types.ConversationID,
) (IssueScanStageRecord, error) {
normalized, def, err := normalizeIssueScanStageOptions(opts)
if err != nil {
return IssueScanStageRecord{}, err
}
if existing, ok, err := ts.FindTaskByCanonicalTaskID(normalized.CanonicalTaskID); err != nil {
return IssueScanStageRecord{}, err
} else if ok {
return issueScanStageRecord(existing, normalized, def, false, existing.ID), nil
}
task, err := ts.CreateV39(source, TaskCreateOptions{
Title: normalized.Title,
Description: normalized.Description,
Workspace: normalized.Workspace,
Priority: normalized.Priority,
CanonicalTaskID: normalized.CanonicalTaskID,
FactoryOrderID: normalized.FactoryOrderID,
RequirementIDs: normalized.RequirementIDs,
AcceptanceCriterionIDs: normalized.AcceptanceCriterionIDs,
Cell: normalized.Cell,
RiskClass: normalized.RiskClass,
ExpectedOutputs: normalized.ExpectedOutputs,
}, causes, convID)
if err != nil {
return IssueScanStageRecord{}, err
}
return issueScanStageRecord(task, normalized, def, true, types.EventID{}), nil
}
// EnsureIssueScanDAG creates the canonical stage tasks and linear dependencies
// for one target issue. Replaying the same run is idempotent for both task nodes
// and dependency edges.
func (ts *TaskStore) EnsureIssueScanDAG(
source types.ActorID,
opts IssueScanDAGOptions,
causes []types.EventID,
convID types.ConversationID,
) (IssueScanDAGResult, error) {
stages := opts.Stages
if len(stages) == 0 {
stages = IssueScanStageIDs()
}
result := IssueScanDAGResult{Stages: make([]IssueScanStageRecord, 0, len(stages))}
var previous IssueScanStageRecord
for i, stage := range stages {
record, err := ts.EnsureIssueScanStage(source, IssueScanStageOptions{
RunID: opts.RunID,
Target: opts.Target,
Stage: stage,
Workspace: opts.Workspace,
Priority: opts.Priority,
Cell: opts.Cell,
RiskClass: opts.RiskClass,
}, causes, convID)
if err != nil {
return result, err
}
if record.Created {
result.CreatedTasks++
}
if i > 0 {
created, err := ts.EnsureDependency(source, record.Task.ID, previous.Task.ID, causes, convID)
if err != nil {
return result, err
}
if created {
result.CreatedDependencies++
}
}
result.Stages = append(result.Stages, record)
previous = record
}
return result, nil
}
// EnsureDependency records taskID -> dependsOnID only if that edge is absent.
func (ts *TaskStore) EnsureDependency(
source types.ActorID,
taskID, dependsOnID types.EventID,
causes []types.EventID,
convID types.ConversationID,
) (bool, error) {
deps, err := ts.GetDependencies(taskID)
if err != nil {
return false, err
}
for _, dep := range deps {
if dep == dependsOnID {
return false, nil
}
}
if err := ts.AddDependency(source, taskID, dependsOnID, causes, convID); err != nil {
return false, err
}
return true, nil
}
// StartIssueScanStage moves an unblocked stage deterministically to running.
// Parked stages require an external repair/unblock transition before restart.
func (ts *TaskStore) StartIssueScanStage(
source types.ActorID,
ref IssueScanStageRef,
reason string,
causes []types.EventID,
convID types.ConversationID,
) (TaskStatus, error) {
if err := ts.validateIssueScanStageRef(ref); err != nil {
return "", err
}
current, err := ts.GetStatus(ref.TaskID)
if err != nil {
return "", err
}
if current == StatusBlocked || current == StatusPolicyBlocked {
return "", fmt.Errorf("%w: issue-scan stage %s is parked in %s", ErrInvalidLifecycleTransition, ref.TaskID.Value(), current)
}
blocked, err := ts.IsBlocked(ref.TaskID)
if err != nil {
return "", err
}
if blocked {
return "", fmt.Errorf("%w: issue-scan stage %s is blocked by an incomplete predecessor", ErrInvalidLifecycleTransition, ref.TaskID.Value())
}
if strings.TrimSpace(reason) == "" {
reason = "issue-scan stage started"
}
return ts.transitionIssueScanStageTo(source, ref.TaskID, StatusRunning, reason, nil, causes, convID)
}
// BlockIssueScanStage records a typed blocker and parks the task in blocked or
// policy_blocked. Repeating the same blocker while already parked is a no-op.
func (ts *TaskStore) BlockIssueScanStage(
source types.ActorID,
ref IssueScanStageRef,
blocker IssueScanBlocker,
causes []types.EventID,
convID types.ConversationID,
) (IssueScanStageBlockResult, error) {
if err := ts.validateIssueScanStageRef(ref); err != nil {
return IssueScanStageBlockResult{}, err
}
if err := validateIssueScanBlocker(blocker); err != nil {
return IssueScanStageBlockResult{}, err
}
targetStatus := blocker.Reason.taskStatus()
current, err := ts.GetStatus(ref.TaskID)
if err != nil {
return IssueScanStageBlockResult{}, err
}
if latest, ok, err := ts.latestIssueScanBlocker(ref.TaskID); err != nil {
return IssueScanStageBlockResult{}, err
} else if ok && current == targetStatus && latest.same(blocker) {
return IssueScanStageBlockResult{Created: false, Status: current}, nil
}
if current != targetStatus && !canReachIssueScanStatus(current, targetStatus) {
return IssueScanStageBlockResult{}, fmt.Errorf("%w: cannot park issue-scan stage %s -> %s", ErrInvalidLifecycleTransition, current, targetStatus)
}
if current != targetStatus && !canReachIssueScanStatusThroughTaskLifecycle(current, targetStatus) {
return IssueScanStageBlockResult{}, fmt.Errorf("%w: issue-scan stage transition is not valid in task lifecycle %s -> %s", ErrInvalidLifecycleTransition, current, targetStatus)
}
status := current
if current != targetStatus {
var err error
status, err = ts.transitionIssueScanStageTo(source, ref.TaskID, targetStatus, "issue-scan blocked: "+string(blocker.Reason), blocker.EvidenceRefs, causes, convID)
if err != nil {
return IssueScanStageBlockResult{}, err
}
}
content := IssueScanStageBlockedContent{
TaskID: ref.TaskID,
RunID: strings.TrimSpace(ref.RunID),
TargetRepo: strings.TrimSpace(ref.Target.Repository),
TargetIssueNumber: ref.Target.IssueNumber,
StageID: ref.Stage,
BlockerReason: blocker.Reason,
Detail: strings.TrimSpace(blocker.Detail),
EvidenceRefs: cloneStrings(blocker.EvidenceRefs),
BlockedBy: source,
}
ev, err := ts.factory.Create(EventTypeIssueScanStageBlocked, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return IssueScanStageBlockResult{}, fmt.Errorf("create issue-scan blocker event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return IssueScanStageBlockResult{}, fmt.Errorf("append issue-scan blocker event: %w", err)
}
return IssueScanStageBlockResult{Created: true, Status: status}, nil
}
// SatisfyIssueScanStageGate records a typed gate completion and certifies the
// issue-scan stage. Repeating the same gate after certification is a no-op.
func (ts *TaskStore) SatisfyIssueScanStageGate(
source types.ActorID,
ref IssueScanStageRef,
gate string,
evidenceRefs []string,
causes []types.EventID,
convID types.ConversationID,
) (IssueScanStageGateResult, error) {
if err := ts.validateIssueScanStageRef(ref); err != nil {
return IssueScanStageGateResult{}, err
}
gate = strings.TrimSpace(gate)
if gate == "" {
return IssueScanStageGateResult{}, fmt.Errorf("issue-scan gate is required")
}
if len(cloneStrings(evidenceRefs)) == 0 {
return IssueScanStageGateResult{}, fmt.Errorf("at least one issue-scan gate evidence reference is required")
}
def, ok := issueScanStageDefinitions[ref.Stage]
if !ok {
return IssueScanStageGateResult{}, fmt.Errorf("unknown issue-scan stage %q", ref.Stage)
}
if gate != def.Gate {
return IssueScanStageGateResult{}, fmt.Errorf("%w: issue-scan gate %q does not match stage %s gate %q", ErrInvalidLifecycleTransition, gate, ref.Stage, def.Gate)
}
current, err := ts.GetStatus(ref.TaskID)
if err != nil {
return IssueScanStageGateResult{}, err
}
if latest, ok, err := ts.latestIssueScanGate(ref.TaskID); err != nil {
return IssueScanStageGateResult{}, err
} else if ok && current == StatusCertified && latest.Gate == gate {
return IssueScanStageGateResult{Created: false, Status: current}, nil
}
status := current
switch current {
case StatusRunning, StatusVerified:
if !canReachIssueScanStatusThroughTaskLifecycle(current, StatusCertified) {
return IssueScanStageGateResult{}, fmt.Errorf("%w: issue-scan gate transition is not valid in task lifecycle %s -> %s", ErrInvalidLifecycleTransition, current, StatusCertified)
}
status, err = ts.transitionIssueScanStageTo(source, ref.TaskID, StatusCertified, "issue-scan gate satisfied: "+gate, evidenceRefs, causes, convID)
if err != nil {
return IssueScanStageGateResult{}, err
}
case StatusCertified:
default:
return IssueScanStageGateResult{}, fmt.Errorf("%w: issue-scan gate can only be satisfied from running or verified, got %s", ErrInvalidLifecycleTransition, current)
}
content := IssueScanStageGateSatisfiedContent{
TaskID: ref.TaskID,
RunID: strings.TrimSpace(ref.RunID),
TargetRepo: strings.TrimSpace(ref.Target.Repository),
TargetIssueNumber: ref.Target.IssueNumber,
StageID: ref.Stage,
Gate: gate,
EvidenceRefs: cloneStrings(evidenceRefs),
SatisfiedBy: source,
}
ev, err := ts.factory.Create(EventTypeIssueScanStageGateSatisfied, source, content, causes, convID, ts.store, ts.signer)
if err != nil {
return IssueScanStageGateResult{}, fmt.Errorf("create issue-scan gate event: %w", err)
}
if _, err := ts.store.Append(ev); err != nil {
return IssueScanStageGateResult{}, fmt.Errorf("append issue-scan gate event: %w", err)
}
return IssueScanStageGateResult{Created: true, Status: status}, nil
}
func normalizeIssueScanStageOptions(opts IssueScanStageOptions) (IssueScanStageOptions, issueScanStageDefinition, error) {
opts.RunID = strings.TrimSpace(opts.RunID)
if opts.RunID == "" {
return opts, issueScanStageDefinition{}, fmt.Errorf("issue-scan run_id is required")
}
opts.Target.Repository = strings.TrimSpace(opts.Target.Repository)
if opts.Target.Repository == "" {
return opts, issueScanStageDefinition{}, fmt.Errorf("issue-scan target repository is required")
}
if opts.Target.IssueNumber <= 0 {
return opts, issueScanStageDefinition{}, fmt.Errorf("issue-scan target issue number must be positive")
}
def, ok := issueScanStageDefinitions[opts.Stage]
if !ok {
return opts, issueScanStageDefinition{}, fmt.Errorf("unknown issue-scan stage %q", opts.Stage)
}
base := issueScanBaseID(opts.RunID, opts.Target, opts.Stage)
if opts.CanonicalTaskID == "" {
opts.CanonicalTaskID = "tsk_" + base
}
if opts.FactoryOrderID == "" {
opts.FactoryOrderID = "fo_issue_scan_" + issueScanIDPart(opts.RunID)
}
if len(opts.RequirementIDs) == 0 {
opts.RequirementIDs = []string{"req_" + base}
}
if len(opts.AcceptanceCriterionIDs) == 0 {
opts.AcceptanceCriterionIDs = []string{"ac_" + base}
}
if strings.TrimSpace(opts.Workspace) == "" {
opts.Workspace = IssueScanWorkspace
}
if opts.Priority == "" {
opts.Priority = PriorityHigh
}
if strings.TrimSpace(opts.Cell) == "" {
opts.Cell = defaultIssueScanCell
}
if strings.TrimSpace(opts.RiskClass) == "" {
opts.RiskClass = defaultIssueScanRiskClass
}
if len(opts.ExpectedOutputs) == 0 {
opts.ExpectedOutputs = cloneStrings(def.ExpectedOutputs)
}
if strings.TrimSpace(opts.Title) == "" {
opts.Title = fmt.Sprintf("Issue-scan stage %d: %s (%s)", def.Number, def.Title, opts.Target.Ref())
}
if strings.TrimSpace(opts.Description) == "" {
opts.Description = fmt.Sprintf("Issue-scan run: %s\nTarget: %s\nStage %d: %s\nGate: %s", opts.RunID, opts.Target.Ref(), def.Number, def.Title, def.Gate)
}
return opts, def, nil
}
func issueScanStageRecord(task Task, opts IssueScanStageOptions, def issueScanStageDefinition, created bool, duplicateOf types.EventID) IssueScanStageRecord {
return IssueScanStageRecord{
IssueScanStageRef: IssueScanStageRef{
TaskID: task.ID,
RunID: opts.RunID,
Target: opts.Target,
Stage: opts.Stage,
},
Task: task,
StageNumber: def.Number,
Gate: def.Gate,
Created: created,
DuplicateOf: duplicateOf,
CanonicalTaskID: opts.CanonicalTaskID,
FactoryOrderID: opts.FactoryOrderID,
}
}
func issueScanBaseID(runID string, target IssueScanTarget, stage IssueScanStageID) string {
raw := strings.TrimSpace(runID) + "\x00" + strings.TrimSpace(target.Repository) + "\x00" + strconv.Itoa(target.IssueNumber) + "\x00" + string(stage)
sum := sha256.Sum256([]byte(raw))
digest := fmt.Sprintf("%x", sum[:6])
return "issue_scan_" + issueScanIDPart(runID) + "_" + issueScanIDPart(target.Repository) + "_" + strconv.Itoa(target.IssueNumber) + "_" + issueScanIDPart(string(stage)) + "_" + digest
}
func issueScanIDPart(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
var b strings.Builder
lastUnderscore := true
for _, r := range value {
switch {
case unicode.IsLetter(r) || unicode.IsDigit(r):
b.WriteRune(r)
lastUnderscore = false
case !lastUnderscore:
b.WriteByte('_')
lastUnderscore = true
}
}
out := strings.Trim(b.String(), "_")
if out == "" {
return "unknown"
}
return out
}
func taskFromCreatedContent(id types.EventID, c TaskCreatedContent) Task {
p := c.Priority
if p == "" {
p = DefaultPriority
}
return Task{
ID: 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),
}
}
func validateIssueScanStageRefShape(ref IssueScanStageRef) error {
if ref.TaskID.IsZero() {
return fmt.Errorf("issue-scan task_id is required")
}
if strings.TrimSpace(ref.RunID) == "" {
return fmt.Errorf("issue-scan run_id is required")
}
if strings.TrimSpace(ref.Target.Repository) == "" {
return fmt.Errorf("issue-scan target repository is required")
}
if ref.Target.IssueNumber <= 0 {
return fmt.Errorf("issue-scan target issue number must be positive")
}
if _, ok := issueScanStageDefinitions[ref.Stage]; !ok {
return fmt.Errorf("unknown issue-scan stage %q", ref.Stage)
}
return nil
}
func (ts *TaskStore) validateIssueScanStageRef(ref IssueScanStageRef) error {
if err := validateIssueScanStageRefShape(ref); err != nil {
return err
}
ev, err := ts.store.Get(ref.TaskID)
if err != nil {
return fmt.Errorf("get issue-scan stage task: %w", err)
}
c, ok := ev.Content().(TaskCreatedContent)
if !ok || !isIssueScanTaskContent(c) {
return fmt.Errorf("%w: task %s is not an issue-scan stage task", ErrInvalidLifecycleTransition, ref.TaskID.Value())
}
expectedCanonicalTaskID := "tsk_" + issueScanBaseID(ref.RunID, ref.Target, ref.Stage)
if strings.TrimSpace(c.CanonicalTaskID) != expectedCanonicalTaskID {
return fmt.Errorf("%w: issue-scan stage ref does not match task %s", ErrInvalidLifecycleTransition, ref.TaskID.Value())
}
return nil
}
func isIssueScanTaskContent(c TaskCreatedContent) bool {
return strings.HasPrefix(strings.TrimSpace(c.CanonicalTaskID), "tsk_issue_scan_") &&
strings.HasPrefix(strings.TrimSpace(c.FactoryOrderID), "fo_issue_scan_")
}
func sourceIssueRefs(records []FactoryOrderSourceIssueRecord) []string {
out := make([]string, 0, len(records))
seen := make(map[string]bool)
for _, record := range records {
hadExplicitRef := false
for _, ref := range record.SourceRefs {
ref = strings.TrimSpace(ref)
if ref == "" {
continue
}
hadExplicitRef = true
if seen[ref] {
continue
}
seen[ref] = true
out = append(out, ref)
}
if !hadExplicitRef {
ref := issueSourceRef(record)
if ref != "" && !seen[ref] {
seen[ref] = true
out = append(out, ref)
}
}
}
return out
}
func issueScanMarkerAuthorityExclusions() []string {
return []string{
"github_issue_markers_are_projection_only",
"github_comments_are_not_work_lifecycle_truth",
"github_labels_are_not_work_lifecycle_truth",
"no_live_github_mutation_authority",
"no_eventgraph_production_write",
"no_hive_write_action_or_authority_api",
"no_deployment",
"no_test_001_green",
"no_merge_authority",
"no_issue_closure",
"no_autonomy_increase",
"no_value_allocation",
}
}
func validateIssueScanBlocker(blocker IssueScanBlocker) error {
if !blocker.Reason.known() {
return fmt.Errorf("unknown issue-scan blocker reason %q", blocker.Reason)
}
if strings.TrimSpace(blocker.Detail) == "" {
return fmt.Errorf("issue-scan blocker detail is required")
}
return nil
}
func (r IssueScanBlockerReason) known() bool {
switch r {
case IssueScanBlockerNeedsHumanScope, IssueScanBlockerProtectedAction, IssueScanBlockerStaleTarget,
IssueScanBlockerDuplicateChain, IssueScanBlockerMissingGateEvidence:
return true
default:
return false
}
}
func (r IssueScanBlockerReason) taskStatus() TaskStatus {
switch r {
case IssueScanBlockerNeedsHumanScope, IssueScanBlockerProtectedAction:
return StatusPolicyBlocked
default:
return StatusBlocked
}
}
func (b IssueScanStageBlockedContent) same(blocker IssueScanBlocker) bool {
return b.BlockerReason == blocker.Reason &&
strings.TrimSpace(b.Detail) == strings.TrimSpace(blocker.Detail) &&
strings.Join(cloneStrings(b.EvidenceRefs), "\x00") == strings.Join(cloneStrings(blocker.EvidenceRefs), "\x00")
}
func (ts *TaskStore) latestIssueScanBlocker(taskID types.EventID) (IssueScanStageBlockedContent, bool, error) {
after := types.None[types.Cursor]()
for {
page, err := ts.store.ByType(EventTypeIssueScanStageBlocked, 1000, after)
if err != nil {
return IssueScanStageBlockedContent{}, false, fmt.Errorf("fetch issue-scan blocker events: %w", err)
}
for _, ev := range page.Items() {
c, ok := ev.Content().(IssueScanStageBlockedContent)
if ok && c.TaskID == taskID {
return c, true, nil
}
}
if !page.HasMore() {
return IssueScanStageBlockedContent{}, false, nil
}
after = page.Cursor()
}
}
func (ts *TaskStore) latestIssueScanGate(taskID types.EventID) (IssueScanStageGateSatisfiedContent, bool, error) {
after := types.None[types.Cursor]()
for {
page, err := ts.store.ByType(EventTypeIssueScanStageGateSatisfied, 1000, after)
if err != nil {
return IssueScanStageGateSatisfiedContent{}, false, fmt.Errorf("fetch issue-scan gate events: %w", err)
}
for _, ev := range page.Items() {
c, ok := ev.Content().(IssueScanStageGateSatisfiedContent)
if ok && c.TaskID == taskID {
return c, true, nil
}
}
if !page.HasMore() {
return IssueScanStageGateSatisfiedContent{}, false, nil
}
after = page.Cursor()
}
}
func (ts *TaskStore) transitionIssueScanStageTo(
source types.ActorID,
taskID types.EventID,
target TaskStatus,
reason string,
evidenceRefs []string,
causes []types.EventID,
convID types.ConversationID,
) (TaskStatus, error) {
current, err := ts.GetStatus(taskID)
if err != nil {
return "", err
}
for current != target {
next, ok := nextIssueScanTransition(current, target)
if !ok {