| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | |
| 9 | "reasonix/internal/fileutil" |
| 10 | "reasonix/internal/store" |
| 11 | ) |
| 12 | |
| 13 | func migratePinnedContextSidecar(oldPath, newPath, newID string) error { |
| 14 | source := store.SessionPinnedContext(oldPath) |
| 15 | // As with the other session sidecars, an overlong source component cannot |
| 16 | // exist. Avoid turning the recovery pass itself into ENAMETOOLONG. |
| 17 | if len(filepath.Base(source)) > nameMaxBytes { |
| 18 | return nil |
| 19 | } |
| 20 | raw, err := os.ReadFile(source) |
| 21 | if os.IsNotExist(err) { |
| 22 | return nil |
| 23 | } |
| 24 | if err != nil { |
| 25 | return err |
| 26 | } |
| 27 | var state map[string]json.RawMessage |
| 28 | if err := json.Unmarshal(raw, &state); err != nil { |
| 29 | return fmt.Errorf("decode pinned context sidecar: %w", err) |
| 30 | } |
| 31 | encodedID, err := json.Marshal(newID) |
| 32 | if err != nil { |
| 33 | return err |
| 34 | } |
| 35 | state["sessionId"] = encodedID |
| 36 | raw, err = json.Marshal(state) |
| 37 | if err != nil { |
| 38 | return err |
| 39 | } |
| 40 | if err := fileutil.AtomicWriteFileStrict(store.SessionPinnedContext(newPath), append(raw, '\n'), 0o600); err != nil { |
| 41 | return err |
| 42 | } |
| 43 | if err := os.Remove(source); err != nil && !os.IsNotExist(err) { |
| 44 | return err |
| 45 | } |
| 46 | return nil |
| 47 | } |
| 48 |