| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "slices" |
| 7 | |
| 8 | "reasonix/internal/agent" |
| 9 | "reasonix/internal/store" |
| 10 | ) |
| 11 | |
| 12 | // recoveredLegacySiblings lists the other recovery snapshots of the lineage a |
| 13 | // recovered legacy source belongs to. Writers record either the shared root or |
| 14 | // the previous snapshot as ParentID, so the lineage is the set of recovered |
| 15 | // transcripts in the same directory whose ParentID chain ends at the same id. |
| 16 | func recoveredLegacySiblings(source historicalSource) ([]string, error) { |
| 17 | if source.format != "legacy" { |
| 18 | return nil, nil |
| 19 | } |
| 20 | dir := filepath.Dir(source.path) |
| 21 | entries, err := os.ReadDir(dir) |
| 22 | if err != nil { |
| 23 | return nil, err |
| 24 | } |
| 25 | parents := map[string]string{} |
| 26 | paths := map[string]string{} |
| 27 | for _, entry := range entries { |
| 28 | if entry.IsDir() || !store.IsSessionTranscriptName(entry.Name()) { |
| 29 | continue |
| 30 | } |
| 31 | path := filepath.Join(dir, entry.Name()) |
| 32 | meta, ok, err := agent.LoadBranchMeta(path) |
| 33 | if err != nil || !ok || !meta.Recovered { |
| 34 | continue |
| 35 | } |
| 36 | id := agent.BranchID(path) |
| 37 | parents[id] = meta.ParentID |
| 38 | paths[id] = path |
| 39 | } |
| 40 | self := agent.BranchID(source.path) |
| 41 | if _, recovered := parents[self]; !recovered { |
| 42 | return nil, nil |
| 43 | } |
| 44 | root := lineageRoot(self, parents) |
| 45 | var siblings []string |
| 46 | for id, path := range paths { |
| 47 | if id != self && lineageRoot(id, parents) == root { |
| 48 | siblings = append(siblings, path) |
| 49 | } |
| 50 | } |
| 51 | slices.Sort(siblings) |
| 52 | return siblings, nil |
| 53 | } |
| 54 | |
| 55 | func lineageRoot(id string, parents map[string]string) string { |
| 56 | for range len(parents) + 1 { |
| 57 | parent, ok := parents[id] |
| 58 | if !ok || parent == "" || parent == id { |
| 59 | return id |
| 60 | } |
| 61 | if _, recovered := parents[parent]; !recovered { |
| 62 | return parent |
| 63 | } |
| 64 | id = parent |
| 65 | } |
| 66 | return id |
| 67 | } |
| 68 |