63247e402a
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
// Package store persists and restores the daemon's current state as a single
|
|
// JSON snapshot. It is the M0 source of durability; the hash-chained audit log
|
|
// arrives in a later milestone.
|
|
package store
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"antidrift/internal/domain"
|
|
)
|
|
|
|
// Snapshot is the persisted current state of the daemon.
|
|
type Snapshot struct {
|
|
RuntimeState domain.RuntimeState `json:"runtime_state"`
|
|
Commitment *domain.Commitment `json:"commitment,omitempty"`
|
|
DeadlineUnixSecs int64 `json:"deadline_unix_secs,omitempty"`
|
|
}
|
|
|
|
// DefaultPath returns ~/.antidrift/state.json.
|
|
func DefaultPath() (string, error) {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return filepath.Join(home, ".antidrift", "state.json"), nil
|
|
}
|
|
|
|
// Load reads a snapshot. A missing file yields a default Locked snapshot.
|
|
func Load(path string) (Snapshot, error) {
|
|
data, err := os.ReadFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return Snapshot{RuntimeState: domain.RuntimeLocked}, nil
|
|
}
|
|
if err != nil {
|
|
return Snapshot{}, err
|
|
}
|
|
var s Snapshot
|
|
if err := json.Unmarshal(data, &s); err != nil {
|
|
return Snapshot{}, err
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
// Save writes a snapshot atomically (temp file + rename), creating the
|
|
// directory if needed.
|
|
func Save(path string, s Snapshot) error {
|
|
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
|
return err
|
|
}
|
|
data, err := json.MarshalIndent(s, "", " ")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
tmp := path + ".tmp"
|
|
if err := os.WriteFile(tmp, data, 0o644); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp, path)
|
|
}
|