| 1 | package session |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | |
| 9 | "reasonix/internal/agent" |
| 10 | ) |
| 11 | |
| 12 | // ExistingCanonicalForLegacy uses a header lookup for a completed cutover. |
| 13 | // Older paired stores require a read-only prefix proof before choosing either |
| 14 | // source, since either transcript may contain work absent from the other. |
| 15 | // Missing candidates are not created, imported, repaired, or resumed here. |
| 16 | func (s *Service) ExistingCanonicalForLegacy(path string, legacy *agent.Session) (SessionRef, bool, error) { |
| 17 | filesystem, ok := s.persistence.(*FilesystemPersistence) |
| 18 | if !ok { |
| 19 | return SessionRef{}, false, nil |
| 20 | } |
| 21 | id := agent.BranchID(path) |
| 22 | dir, err := filesystem.sessionDir(id, true) |
| 23 | if errors.Is(err, ErrSessionNotFound) || os.IsNotExist(err) { |
| 24 | return SessionRef{}, false, nil |
| 25 | } |
| 26 | if err != nil { |
| 27 | return SessionRef{}, false, err |
| 28 | } |
| 29 | manifest, err := readStoredManifest(filepath.Join(dir, "manifest.json")) |
| 30 | if err != nil { |
| 31 | return SessionRef{}, false, err |
| 32 | } |
| 33 | if manifest.SessionID != id { |
| 34 | return SessionRef{}, false, ErrDamagedStore |
| 35 | } |
| 36 | if head, dag := legacy.Head(); dag { |
| 37 | // A path-derived store is not proof of ownership of every DAG head. |
| 38 | // Explicit source mappings are resolved by the host before this probe. |
| 39 | if manifest.Source != nil && manifest.Source.LegacyHeadID != "" { |
| 40 | if manifest.Source.LegacyHeadID != head.HeadID { |
| 41 | return SessionRef{}, false, nil |
| 42 | } |
| 43 | } else if head.HeadID != agent.SessionMainHead { |
| 44 | return SessionRef{}, false, nil |
| 45 | } |
| 46 | } |
| 47 | if manifest.Codec != Codec { |
| 48 | ref := SessionRef{HostID: s.HostID(), SessionID: id} |
| 49 | history, err := s.Query().History(context.Background(), ref) |
| 50 | if err != nil { |
| 51 | return SessionRef{}, false, err |
| 52 | } |
| 53 | if len(comparableImportMessages(history)) == 0 { |
| 54 | return SessionRef{}, false, nil |
| 55 | } |
| 56 | if MigrationHistoryContains(history, legacy.Snapshot()) { |
| 57 | return ref, true, nil |
| 58 | } |
| 59 | if MigrationHistoryContains(legacy.Snapshot(), history) { |
| 60 | return SessionRef{}, false, nil |
| 61 | } |
| 62 | return SessionRef{}, false, ErrImportConflict |
| 63 | } |
| 64 | return SessionRef{HostID: s.HostID(), SessionID: id}, true, nil |
| 65 | } |
| 66 |