返回 DeepSeek-Reasonix
lineage.go
根目录 / internal / sessioncatalog / lineage.go
1 package sessioncatalog
2
3 import (
4 "path/filepath"
5 "sort"
6 "strings"
7
8 "reasonix/internal/agent"
9 )
10
11 // classifyRecoveryLineage assigns recovery_group_id, recovery_role, and
12 // recovery_canonical from real content ancestry. File names alone never decide
13 // ownership; covered copies are those whose messages are a prefix of a still-
14 // present parent/ancestor, adopted is a unique leaf covering the group, and
15 // diverged marks multiple non-covering leaves under one group.
16 func classifyRecoveryLineage(record SessionRecord) SessionRecord {
17 if !record.Recovered {
18 if record.RecoveryRole == "" {
19 record.RecoveryRole = RecoveryRoleNormal
20 }
21 return record
22 }
23 parentPath := recoveryParentPath(record)
24 groupID := firstNonEmpty(record.ParentID, agent.BranchID(record.Path))
25 record.RecoveryGroupID = groupID
26
27 if record.RecoveryCopy || (parentPath != "" && agent.RecoveryBranchCoveredByParent(record.Path, filepath.Dir(record.Path))) {
28 record.RecoveryCopy = true
29 record.RecoveryRole = RecoveryRoleCoveredCopy
30 record.RecoveryCanonical = false
31 return record
32 }
33 // Default for non-covered recovery leaves: diverged until a group pass
34 // promotes a unique covering leaf to adopted/canonical.
35 record.RecoveryRole = RecoveryRoleDiverged
36 record.RecoveryCanonical = false
37 return record
38 }
39
40 type recoveryContentResult struct {
41 snapshot agent.SessionContentSnapshot
42 ok bool
43 }
44
45 type recoveryContentCache struct {
46 entries map[string]recoveryContentResult
47 onLoad func(string)
48 strict bool
49 }
50
51 func newRecoveryContentCache(onLoad func(string)) *recoveryContentCache {
52 return &recoveryContentCache{entries: map[string]recoveryContentResult{}, onLoad: onLoad}
53 }
54
55 func newStrictRecoveryContentCache(onLoad func(string)) *recoveryContentCache {
56 return &recoveryContentCache{entries: map[string]recoveryContentResult{}, onLoad: onLoad, strict: true}
57 }
58
59 func listSessionOrderWithContent(dir string, content *recoveryContentCache) ([]agent.SessionOrderInfo, error) {
60 return agent.ListSessionOrderWithRecoveryPreferenceResolver(dir, func(path string, meta agent.BranchMeta) bool {
61 digest := strings.TrimSpace(meta.RecoveryPreferredDigest)
62 if !meta.RecoveryPreferred || digest == "" {
63 return false
64 }
65 _, ok := content.load(path, digest)
66 return ok
67 })
68 }
69
70 func (c *recoveryContentCache) load(path, digest string) (agent.SessionContentSnapshot, bool) {
71 key := PathIdentityKey(path)
72 result, loaded := c.entries[key]
73 if !loaded {
74 if c.onLoad != nil {
75 c.onLoad(path)
76 }
77 result.snapshot, result.ok = agent.LoadSessionContentSnapshot(path)
78 c.entries[key] = result
79 }
80 if !result.ok || strings.TrimSpace(digest) != "" && !result.snapshot.MatchesDigest(digest) {
81 return agent.SessionContentSnapshot{}, false
82 }
83 return result.snapshot, true
84 }
85
86 func (c *recoveryContentCache) loadRecord(record SessionRecord) (agent.SessionContentSnapshot, bool) {
87 if c.strict && record.Recovered && strings.TrimSpace(record.RecoveryDigest) == "" {
88 return agent.SessionContentSnapshot{}, false
89 }
90 return c.load(record.Path, record.RecoveryDigest)
91 }
92
93 func classifyRecoveryLineageWithContent(record SessionRecord, content *recoveryContentCache) SessionRecord {
94 if !record.Recovered {
95 if record.RecoveryRole == "" {
96 record.RecoveryRole = RecoveryRoleNormal
97 }
98 return record
99 }
100 record.RecoveryCopy = false
101 record.RecoveryGroupID = firstNonEmpty(record.ParentID, agent.BranchID(record.Path))
102 record.RecoveryRole = RecoveryRoleDiverged
103 record.RecoveryCanonical = false
104 parentPath := recoveryParentPath(record)
105 if parentPath == "" {
106 return record
107 }
108 branch, branchOK := content.loadRecord(record)
109 parent, parentOK := content.load(parentPath, "")
110 if branchOK && parentOK && parent.Covers(branch) {
111 record.RecoveryCopy = true
112 record.RecoveryRole = RecoveryRoleCoveredCopy
113 }
114 return record
115 }
116
117 // promoteCanonicalLeaves marks unique non-covered leaves that cover every
118 // ancestor in their group as adopted/canonical. Multiple non-covering leaves
119 // stay diverged. open/running/pinned/leased decisions are left to callers.
120 func promoteCanonicalLeaves(records []SessionRecord) []SessionRecord {
121 return promoteCanonicalLeavesWithContent(records, newRecoveryContentCache(nil))
122 }
123
124 func promoteCanonicalLeavesWithContent(records []SessionRecord, cache *recoveryContentCache) []SessionRecord {
125 byGroup, groupRoot := recoveryLineageGroups(records)
126 for groupID, idxs := range byGroup {
127 for _, i := range idxs {
128 records[i].RecoveryRole = RecoveryRoleDiverged
129 records[i].RecoveryCanonical = false
130 }
131 rootIndex, hasRoot := groupRoot[groupID]
132 preferred := -1
133 preferenceIndexes := append([]int{}, idxs...)
134 if hasRoot {
135 preferenceIndexes = append(preferenceIndexes, rootIndex)
136 }
137 for _, index := range preferenceIndexes {
138 if records[index].RecoveryPreferred {
139 if preferred >= 0 {
140 preferred = -2 // multiple stale preferences fail closed
141 break
142 }
143 preferred = index
144 }
145 }
146 if preferred >= 0 {
147 records[preferred].RecoveryRole = RecoveryRolePreferred
148 records[preferred].RecoveryCanonical = true
149 continue
150 }
151 contentIdxs := append([]int{}, idxs...)
152 if hasRoot {
153 contentIdxs = append(contentIdxs, rootIndex)
154 }
155 content := loadRecoveryGroupContent(records, contentIdxs, cache)
156 candidate, ok := uniqueLongestRecovery(records, idxs, content)
157 if !ok {
158 // No unique covering leaf: still pick one stable representative so
159 // ordinary visibility never expands into a wall of forks.
160 if len(idxs) > 0 {
161 stable := pickPreferredRecovery(indexesToRecords(records, idxs))
162 for _, i := range idxs {
163 if records[i].Path == stable.Path {
164 records[i].RecoveryCanonical = true
165 break
166 }
167 }
168 }
169 continue
170 }
171 if hasRoot && !recoveryCandidateCovers(candidate, rootIndex, idxs, content) {
172 records[candidate].RecoveryCanonical = true
173 continue
174 }
175 if !hasRoot {
176 // Root missing: the unique covering leaf is still the ordinary
177 // representative, but without a parent it cannot prove adoption.
178 records[candidate].RecoveryCanonical = true
179 for _, i := range idxs {
180 if i == candidate {
181 continue
182 }
183 if member, ok := content[i]; ok {
184 if candidateContent, ok := content[candidate]; ok && candidateContent.Covers(member) {
185 records[i].RecoveryCopy = true
186 records[i].RecoveryRole = RecoveryRoleCoveredCopy
187 }
188 }
189 }
190 continue
191 }
192 records[candidate].RecoveryRole = RecoveryRoleAdopted
193 records[candidate].RecoveryCanonical = true
194 // Once one leaf contains the entire group, every other recovery
195 // member is an ancestor/equivalent copy covered by that canonical.
196 // Marking them covered is what lets History and explicit cleanup
197 // converge an old chain instead of leaving hundreds of non-canonical
198 // "diverged" rows that preserve no unique content.
199 for _, i := range idxs {
200 if i == candidate {
201 continue
202 }
203 records[i].RecoveryCopy = true
204 records[i].RecoveryRole = RecoveryRoleCoveredCopy
205 }
206 }
207 return projectLogicalSessions(records)
208 }
209
210 func indexesToRecords(records []SessionRecord, idxs []int) []SessionRecord {
211 out := make([]SessionRecord, 0, len(idxs))
212 for _, i := range idxs {
213 out = append(out, records[i])
214 }
215 return out
216 }
217
218 // projectLogicalSessions re-anchors recovered physical files onto one logical
219 // topic and marks the single ordinary-list representative. Catalog projection
220 // only — authoritative JSONL/meta topic_id values are never rewritten.
221 func projectLogicalSessions(records []SessionRecord) []SessionRecord {
222 byID := make(map[string]int, len(records))
223 for i := range records {
224 byID[agent.BranchID(records[i].Path)] = i
225 if !records[i].Recovered {
226 if records[i].LogicalTopicID == "" {
227 records[i].LogicalTopicID = records[i].TopicID
228 }
229 continue
230 }
231 // Filename fallback when meta ParentID is empty.
232 if strings.TrimSpace(records[i].ParentID) == "" {
233 if parent, ok := agent.RecoveryFilenameParentID(records[i].Path); ok {
234 records[i].ParentID = parent
235 if records[i].RecoveryGroupID == "" {
236 records[i].RecoveryGroupID = parent
237 }
238 }
239 }
240 if records[i].RecoveryGroupID == "" {
241 records[i].RecoveryGroupID = firstNonEmpty(records[i].ParentID, agent.BranchID(records[i].Path))
242 }
243 }
244 // Walk parent chains so intermediate recovery files also share the root id.
245 for i := range records {
246 if !records[i].Recovered {
247 continue
248 }
249 groupID := strings.TrimSpace(records[i].RecoveryGroupID)
250 seen := map[string]struct{}{}
251 parentID := strings.TrimSpace(records[i].ParentID)
252 for parentID != "" {
253 if _, loop := seen[parentID]; loop {
254 break
255 }
256 seen[parentID] = struct{}{}
257 parentIndex, ok := byID[parentID]
258 if !ok {
259 groupID = firstNonEmpty(groupID, parentID)
260 break
261 }
262 parent := records[parentIndex]
263 if !parent.Recovered {
264 groupID = parentID
265 break
266 }
267 parentID = strings.TrimSpace(parent.ParentID)
268 if parent.RecoveryGroupID != "" {
269 groupID = parent.RecoveryGroupID
270 }
271 }
272 if groupID != "" {
273 records[i].RecoveryGroupID = groupID
274 }
275 }
276
277 anchors := logicalSessionAnchors(records)
278 for i := range records {
279 groupID := ""
280 if records[i].Recovered {
281 groupID = strings.TrimSpace(records[i].RecoveryGroupID)
282 } else {
283 groupID = agent.BranchID(records[i].Path)
284 }
285 anchor := anchors[groupID]
286 if anchor == nil {
287 records[i].LogicalTopicID = firstNonEmpty(records[i].TopicID, "recovery:"+agent.BranchID(records[i].Path))
288 continue
289 }
290 records[i].LogicalTopicID = anchor.topicID
291 // Catalog ListTopics keys off TopicID. Re-anchor recovered physical
292 // rows (and roots that only inherited a member topic) onto one logical
293 // topic so pagination never materializes recovery replica walls.
294 if anchor.topicID != "" && (records[i].Recovered || strings.TrimSpace(records[i].TopicID) == "") {
295 records[i].TopicID = anchor.topicID
296 }
297 if anchor.topicTitle != "" && (records[i].Recovered || strings.TrimSpace(records[i].TopicTitle) == "") {
298 records[i].TopicTitle = anchor.topicTitle
299 }
300 }
301
302 preferred := PreferredOrdinarySessionPaths(records)
303 for i := range records {
304 _, records[i].OrdinaryVisible = preferred[strings.TrimSpace(records[i].Path)]
305 // When a group has a normal root, the root is the ordinary row even if
306 // an adopted leaf is the open target (canonical path).
307 if !records[i].Recovered {
308 records[i].OrdinaryVisible = true
309 }
310 }
311 // Exactly one ordinary-visible recovered leaf when the root is missing.
312 byGroup := map[string][]int{}
313 rootPresent := map[string]bool{}
314 for i, rec := range records {
315 if !rec.Recovered {
316 rootPresent[agent.BranchID(rec.Path)] = true
317 continue
318 }
319 if rec.RecoveryCopy || rec.RecoveryRole == RecoveryRoleCoveredCopy {
320 records[i].OrdinaryVisible = false
321 continue
322 }
323 byGroup[rec.RecoveryGroupID] = append(byGroup[rec.RecoveryGroupID], i)
324 }
325 for groupID, idxs := range byGroup {
326 if rootPresent[groupID] {
327 for _, i := range idxs {
328 records[i].OrdinaryVisible = false
329 }
330 continue
331 }
332 best := -1
333 for _, i := range idxs {
334 if records[i].RecoveryCanonical {
335 best = i
336 break
337 }
338 }
339 if best < 0 {
340 bestIdx := pickPreferredRecovery(indexesToRecords(records, idxs))
341 for _, i := range idxs {
342 if records[i].Path == bestIdx.Path {
343 best = i
344 break
345 }
346 }
347 }
348 for _, i := range idxs {
349 records[i].OrdinaryVisible = i == best
350 }
351 }
352 return records
353 }
354
355 func recoveryLineageGroups(records []SessionRecord) (map[string][]int, map[string]int) {
356 byID := make(map[string]int, len(records))
357 for i := range records {
358 byID[agent.BranchID(records[i].Path)] = i
359 }
360 byGroup := map[string][]int{}
361 groupRoot := map[string]int{}
362 for i := range records {
363 rec := records[i]
364 if !rec.Recovered {
365 continue
366 }
367 parentID := strings.TrimSpace(rec.ParentID)
368 seen := map[string]struct{}{}
369 for parentID != "" {
370 if _, loop := seen[parentID]; loop {
371 parentID = ""
372 break
373 }
374 seen[parentID] = struct{}{}
375 parentIndex, ok := byID[parentID]
376 if !ok {
377 parentID = ""
378 break
379 }
380 parent := records[parentIndex]
381 if !parent.Recovered {
382 groupRoot[parentID] = parentIndex
383 break
384 }
385 parentID = strings.TrimSpace(parent.ParentID)
386 }
387 if parentID != "" {
388 records[i].RecoveryGroupID = parentID
389 }
390 }
391 for i, rec := range records {
392 if rec.RecoveryGroupID == "" || rec.RecoveryRole == RecoveryRoleCoveredCopy || rec.RecoveryRole == RecoveryRoleNormal {
393 continue
394 }
395 byGroup[rec.RecoveryGroupID] = append(byGroup[rec.RecoveryGroupID], i)
396 }
397 return byGroup, groupRoot
398 }
399
400 func loadRecoveryGroupContent(records []SessionRecord, idxs []int, cache *recoveryContentCache) map[int]agent.SessionContentSnapshot {
401 content := make(map[int]agent.SessionContentSnapshot, len(idxs))
402 for _, index := range idxs {
403 if _, loaded := content[index]; loaded {
404 continue
405 }
406 if snapshot, ok := cache.loadRecord(records[index]); ok {
407 content[index] = snapshot
408 }
409 }
410 return content
411 }
412
413 func uniqueLongestRecovery(records []SessionRecord, idxs []int, content map[int]agent.SessionContentSnapshot) (int, bool) {
414 if len(idxs) == 0 {
415 return 0, false
416 }
417 // Turns/preview metadata is repaired asynchronously and must not decide
418 // lineage. Doing so made the first scan permanently label every legacy fork
419 // diverged when its sidecar still had turns_state=unknown. Instead, find the
420 // leaves that actually cover every recovered member. Equivalent leaves are
421 // safe to collapse and use a deterministic activity/path tie-breaker.
422 maxLen := -1
423 for _, index := range idxs {
424 if snapshot, ok := content[index]; ok && snapshot.Len() > maxLen {
425 maxLen = snapshot.Len()
426 }
427 }
428 if maxLen < 0 {
429 return 0, false
430 }
431 candidates := make([]int, 0, 1)
432 for _, candidate := range idxs {
433 candidateContent, ok := content[candidate]
434 if !ok || candidateContent.Len() != maxLen {
435 continue
436 }
437 coversAll := true
438 for _, other := range idxs {
439 otherContent, ok := content[other]
440 if !ok || (candidate != other && !candidateContent.Covers(otherContent)) {
441 coversAll = false
442 break
443 }
444 }
445 if coversAll {
446 candidates = append(candidates, candidate)
447 }
448 }
449 if len(candidates) == 0 {
450 return 0, false
451 }
452 sort.SliceStable(candidates, func(i, j int) bool {
453 a, b := records[candidates[i]], records[candidates[j]]
454 if a.LastActivityAt != b.LastActivityAt {
455 return a.LastActivityAt > b.LastActivityAt
456 }
457 return a.Path < b.Path
458 })
459 return candidates[0], true
460 }
461
462 func recoveryCandidateCovers(candidate, root int, idxs []int, content map[int]agent.SessionContentSnapshot) bool {
463 candidateContent, ok := content[candidate]
464 if !ok {
465 return false
466 }
467 rootContent, ok := content[root]
468 if !ok || !candidateContent.Covers(rootContent) {
469 return false
470 }
471 for _, i := range idxs {
472 memberContent, ok := content[i]
473 if !ok || (i != candidate && !candidateContent.Covers(memberContent)) {
474 return false
475 }
476 }
477 return true
478 }
479
480 func recoveryParentPath(record SessionRecord) string {
481 parentID := strings.TrimSpace(record.ParentID)
482 if parentID == "" {
483 return ""
484 }
485 dir := filepath.Dir(record.Path)
486 if dir == "" || dir == "." {
487 return ""
488 }
489 candidate := filepath.Join(dir, parentID+".jsonl")
490 return candidate
491 }
492
493 func firstNonEmpty(values ...string) string {
494 for _, v := range values {
495 if strings.TrimSpace(v) != "" {
496 return strings.TrimSpace(v)
497 }
498 }
499 return ""
500 }
501
502 // CanonicalSessionPathForTopic returns the path that open/restore should bind
503 // when a unique adopted/canonical leaf exists for the topic's sessions.
504 // Empty means keep the caller's path.
505 func CanonicalSessionPathForTopic(sessions []SessionRecord, current string) string {
506 var canonical string
507 canonicalRole := ""
508 for _, s := range sessions {
509 if s.RecoveryCanonical && (s.RecoveryRole == RecoveryRoleAdopted || s.RecoveryRole == RecoveryRolePreferred) {
510 if canonical != "" && canonical != s.Path {
511 // Ambiguous: do not retarget.
512 return ""
513 }
514 canonical = s.Path
515 canonicalRole = s.RecoveryRole
516 }
517 }
518 if canonicalRole == RecoveryRolePreferred && current != "" {
519 for _, session := range sessions {
520 if session.Path == current && session.Recovered {
521 // An explicit click on another recovery leaf is inspection, not a
522 // request to follow the default choice.
523 return ""
524 }
525 }
526 }
527 if canonical == "" || canonical == current {
528 return ""
529 }
530 return canonical
531 }
532
533 // OrdinaryContinuePath returns a safe continuation when current is the ordinary
534 // parent. Explicit recovery paths stay put so History can inspect them.
535 func OrdinaryContinuePath(sessions []SessionRecord, current string) string {
536 canonical := CanonicalSessionPathForTopic(sessions, current)
537 if canonical == "" {
538 canonical = uniqueLinearRecoveryLeaf(sessions)
539 }
540 current = strings.TrimSpace(current)
541 if canonical == "" || current == canonical {
542 return ""
543 }
544 if current == "" {
545 return canonical
546 }
547 for _, session := range sessions {
548 if session.Path != current {
549 continue
550 }
551 if session.Recovered {
552 return ""
553 }
554 return canonical
555 }
556 return canonical
557 }
558
559 // uniqueLinearRecoveryLeaf selects the only monotonic descendant in a complete
560 // parent chain. It is an open target only; content coverage still exclusively
561 // controls adoption and cleanup.
562 func uniqueLinearRecoveryLeaf(sessions []SessionRecord) string {
563 if len(sessions) < 2 {
564 return ""
565 }
566 byID := make(map[string]int, len(sessions))
567 root := -1
568 recovered := 0
569 for i, session := range sessions {
570 id := agent.BranchID(session.Path)
571 if id == "" {
572 return ""
573 }
574 if _, duplicate := byID[id]; duplicate {
575 return ""
576 }
577 byID[id] = i
578 if session.Recovered {
579 recovered++
580 continue
581 }
582 if root >= 0 {
583 return ""
584 }
585 root = i
586 }
587 if root < 0 || recovered == 0 {
588 return ""
589 }
590 children := make(map[string]int, recovered)
591 for i, session := range sessions {
592 if !session.Recovered {
593 continue
594 }
595 parentID := strings.TrimSpace(session.ParentID)
596 parent, ok := byID[parentID]
597 if parentID == "" || !ok {
598 return ""
599 }
600 if _, forked := children[parentID]; forked {
601 return ""
602 }
603 if session.TurnsState == TurnsValid && sessions[parent].TurnsState == TurnsValid && session.Turns < sessions[parent].Turns {
604 return ""
605 }
606 if session.LastActivityAt > 0 && sessions[parent].LastActivityAt > 0 && session.LastActivityAt < sessions[parent].LastActivityAt {
607 return ""
608 }
609 children[parentID] = i
610 }
611 seen := make(map[int]struct{}, recovered+1)
612 leaf := root
613 for {
614 if _, duplicate := seen[leaf]; duplicate {
615 return ""
616 }
617 seen[leaf] = struct{}{}
618 next, ok := children[agent.BranchID(sessions[leaf].Path)]
619 if !ok {
620 break
621 }
622 leaf = next
623 }
624 if len(seen) != len(sessions) || !sessions[leaf].Recovered {
625 return ""
626 }
627 return strings.TrimSpace(sessions[leaf].Path)
628 }
629
629 lines GO