From 3da269c3b7006bcd32187b6131c7078b6808c48e Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:35:04 -0400 Subject: [PATCH 01/11] Set up Go module and move Rust to legacy Co-Authored-By: Claude Opus 4.8 --- .gitignore | 4 ++++ cmd/antidriftd/main.go | 7 +++++++ go.mod | 3 +++ Cargo.lock => legacy/Cargo.lock | 0 Cargo.toml => legacy/Cargo.toml | 0 antidrift.desktop => legacy/antidrift.desktop | 0 {src => legacy/src}/constants.rs | 0 {src => legacy/src}/context.rs | 0 {src => legacy/src}/domain.rs | 0 {src => legacy/src}/event_log.rs | 0 {src => legacy/src}/lib.rs | 0 {src => legacy/src}/main.rs | 0 {src => legacy/src}/session.rs | 0 {src => legacy/src}/state_machine.rs | 0 {src => legacy/src}/window/linux.rs | 0 {src => legacy/src}/window/mod.rs | 0 {src => legacy/src}/window/windows.rs | 0 17 files changed, 14 insertions(+) create mode 100644 cmd/antidriftd/main.go create mode 100644 go.mod rename Cargo.lock => legacy/Cargo.lock (100%) rename Cargo.toml => legacy/Cargo.toml (100%) rename antidrift.desktop => legacy/antidrift.desktop (100%) rename {src => legacy/src}/constants.rs (100%) rename {src => legacy/src}/context.rs (100%) rename {src => legacy/src}/domain.rs (100%) rename {src => legacy/src}/event_log.rs (100%) rename {src => legacy/src}/lib.rs (100%) rename {src => legacy/src}/main.rs (100%) rename {src => legacy/src}/session.rs (100%) rename {src => legacy/src}/state_machine.rs (100%) rename {src => legacy/src}/window/linux.rs (100%) rename {src => legacy/src}/window/mod.rs (100%) rename {src => legacy/src}/window/windows.rs (100%) diff --git a/.gitignore b/.gitignore index 5a1161b..1afac72 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,7 @@ target/ # Local brainstorming companion artifacts .superpowers/ + +# Go +/antidriftd +*.test diff --git a/cmd/antidriftd/main.go b/cmd/antidriftd/main.go new file mode 100644 index 0000000..e567bbf --- /dev/null +++ b/cmd/antidriftd/main.go @@ -0,0 +1,7 @@ +package main + +import "fmt" + +func main() { + fmt.Println("antidriftd") +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b3e063b --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module antidrift + +go 1.26.3 diff --git a/Cargo.lock b/legacy/Cargo.lock similarity index 100% rename from Cargo.lock rename to legacy/Cargo.lock diff --git a/Cargo.toml b/legacy/Cargo.toml similarity index 100% rename from Cargo.toml rename to legacy/Cargo.toml diff --git a/antidrift.desktop b/legacy/antidrift.desktop similarity index 100% rename from antidrift.desktop rename to legacy/antidrift.desktop diff --git a/src/constants.rs b/legacy/src/constants.rs similarity index 100% rename from src/constants.rs rename to legacy/src/constants.rs diff --git a/src/context.rs b/legacy/src/context.rs similarity index 100% rename from src/context.rs rename to legacy/src/context.rs diff --git a/src/domain.rs b/legacy/src/domain.rs similarity index 100% rename from src/domain.rs rename to legacy/src/domain.rs diff --git a/src/event_log.rs b/legacy/src/event_log.rs similarity index 100% rename from src/event_log.rs rename to legacy/src/event_log.rs diff --git a/src/lib.rs b/legacy/src/lib.rs similarity index 100% rename from src/lib.rs rename to legacy/src/lib.rs diff --git a/src/main.rs b/legacy/src/main.rs similarity index 100% rename from src/main.rs rename to legacy/src/main.rs diff --git a/src/session.rs b/legacy/src/session.rs similarity index 100% rename from src/session.rs rename to legacy/src/session.rs diff --git a/src/state_machine.rs b/legacy/src/state_machine.rs similarity index 100% rename from src/state_machine.rs rename to legacy/src/state_machine.rs diff --git a/src/window/linux.rs b/legacy/src/window/linux.rs similarity index 100% rename from src/window/linux.rs rename to legacy/src/window/linux.rs diff --git a/src/window/mod.rs b/legacy/src/window/mod.rs similarity index 100% rename from src/window/mod.rs rename to legacy/src/window/mod.rs diff --git a/src/window/windows.rs b/legacy/src/window/windows.rs similarity index 100% rename from src/window/windows.rs rename to legacy/src/window/windows.rs From e66fddd29f4247912004f708eca537a8c4e4b908 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:36:51 -0400 Subject: [PATCH 02/11] Add domain types and validation Co-Authored-By: Claude Opus 4.8 --- go.mod | 2 + go.sum | 2 + internal/domain/domain.go | 127 +++++++++++++++++++++++++++++++++ internal/domain/domain_test.go | 69 ++++++++++++++++++ 4 files changed, 200 insertions(+) create mode 100644 go.sum create mode 100644 internal/domain/domain.go create mode 100644 internal/domain/domain_test.go diff --git a/go.mod b/go.mod index b3e063b..1afbe7e 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module antidrift go 1.26.3 + +require github.com/google/uuid v1.6.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..7790d7c --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= diff --git a/internal/domain/domain.go b/internal/domain/domain.go new file mode 100644 index 0000000..92779da --- /dev/null +++ b/internal/domain/domain.go @@ -0,0 +1,127 @@ +// Package domain holds the core commitment types and validation, ported from +// the original Rust implementation. These are pure data types with no I/O. +package domain + +import ( + "errors" + "strings" + "time" + + "github.com/google/uuid" +) + +const PolicySchemaVersion = 1 + +type CommitmentSource string + +const ( + SourceManual CommitmentSource = "manual" + SourcePlanner CommitmentSource = "planner" + SourceRecurring CommitmentSource = "recurring" + SourceRecovery CommitmentSource = "recovery" + SourceTemplate CommitmentSource = "template" +) + +type CommitmentState string + +const ( + CommitmentDraft CommitmentState = "draft" + CommitmentActive CommitmentState = "active" + CommitmentPaused CommitmentState = "paused" + CommitmentCompleted CommitmentState = "completed" + CommitmentAbandoned CommitmentState = "abandoned" + CommitmentViolated CommitmentState = "violated" +) + +type RuntimeState string + +const ( + RuntimeLocked RuntimeState = "locked" + RuntimePlanning RuntimeState = "planning" + RuntimeActive RuntimeState = "active" + RuntimeTransition RuntimeState = "transition" + RuntimeReview RuntimeState = "review" + RuntimeAdminOverride RuntimeState = "admin_override" +) + +type EnforcementLevel string + +const ( + EnforcementObserve EnforcementLevel = "observe" + EnforcementWarn EnforcementLevel = "warn" + EnforcementBlock EnforcementLevel = "block" + EnforcementLocked EnforcementLevel = "locked" +) + +// AllowedContext is carried by PolicySnapshot. Matching logic arrives in a +// later milestone; M0 only stores it. +type AllowedContext struct { + WindowClasses []string `json:"window_classes"` + WindowTitleSubstrings []string `json:"window_title_substrings"` + Domains []string `json:"domains"` + Repos []string `json:"repos"` + Commands []string `json:"commands"` +} + +type Commitment struct { + ID string `json:"id"` + CreatedAtUnixSecs int64 `json:"created_at_unix_secs"` + Source CommitmentSource `json:"source"` + NextAction string `json:"next_action"` + SuccessCondition string `json:"success_condition"` + TimeboxSecs int64 `json:"timebox_secs"` + State CommitmentState `json:"state"` +} + +type PolicySnapshot struct { + ID string `json:"id"` + CommitmentID string `json:"commitment_id"` + SchemaVersion int `json:"schema_version"` + CreatedAtUnixSecs int64 `json:"created_at_unix_secs"` + RuntimeState RuntimeState `json:"runtime_state"` + EnforcementLevel EnforcementLevel `json:"enforcement_level"` + AllowedContext AllowedContext `json:"allowed_context"` +} + +var ( + ErrMissingNextAction = errors.New("next action is required") + ErrMissingSuccessCondition = errors.New("success condition is required") + ErrMissingTimebox = errors.New("timebox must be nonzero") +) + +// NewManual builds a validated draft commitment from user input. +func NewManual(nextAction, successCondition string, timebox time.Duration) (Commitment, error) { + nextAction = strings.TrimSpace(nextAction) + successCondition = strings.TrimSpace(successCondition) + if nextAction == "" { + return Commitment{}, ErrMissingNextAction + } + if successCondition == "" { + return Commitment{}, ErrMissingSuccessCondition + } + if timebox <= 0 { + return Commitment{}, ErrMissingTimebox + } + return Commitment{ + ID: "commitment-" + uuid.Must(uuid.NewV7()).String(), + CreatedAtUnixSecs: time.Now().Unix(), + Source: SourceManual, + NextAction: nextAction, + SuccessCondition: successCondition, + TimeboxSecs: int64(timebox.Seconds()), + State: CommitmentDraft, + }, nil +} + +// ForRuntime builds a minimal accepted policy snapshot for a commitment. +func ForRuntime(commitmentID string, runtime RuntimeState, level EnforcementLevel) PolicySnapshot { + return PolicySnapshot{ + ID: "policy-" + uuid.Must(uuid.NewV7()).String(), + CommitmentID: commitmentID, + SchemaVersion: PolicySchemaVersion, + CreatedAtUnixSecs: time.Now().Unix(), + RuntimeState: runtime, + EnforcementLevel: level, + AllowedContext: AllowedContext{}, + } +} diff --git a/internal/domain/domain_test.go b/internal/domain/domain_test.go new file mode 100644 index 0000000..e016fd0 --- /dev/null +++ b/internal/domain/domain_test.go @@ -0,0 +1,69 @@ +package domain + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestNewManualRejectsEmptyNextAction(t *testing.T) { + _, err := NewManual("", "tests pass", 25*time.Minute) + if err != ErrMissingNextAction { + t.Fatalf("want ErrMissingNextAction, got %v", err) + } +} + +func TestNewManualRejectsEmptySuccessCondition(t *testing.T) { + _, err := NewManual("Refactor state", " ", 25*time.Minute) + if err != ErrMissingSuccessCondition { + t.Fatalf("want ErrMissingSuccessCondition, got %v", err) + } +} + +func TestNewManualRejectsZeroTimebox(t *testing.T) { + _, err := NewManual("Refactor state", "tests pass", 0) + if err != ErrMissingTimebox { + t.Fatalf("want ErrMissingTimebox, got %v", err) + } +} + +func TestNewManualPopulatesDraftCommitment(t *testing.T) { + c, err := NewManual(" Port domain ", "domain tests pass", 25*time.Minute) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if c.NextAction != "Port domain" { + t.Errorf("next action not trimmed: %q", c.NextAction) + } + if c.SuccessCondition != "domain tests pass" { + t.Errorf("success condition wrong: %q", c.SuccessCondition) + } + if c.TimeboxSecs != 1500 { + t.Errorf("timebox secs wrong: %d", c.TimeboxSecs) + } + if c.State != CommitmentDraft { + t.Errorf("state should be draft, got %s", c.State) + } + if c.Source != SourceManual { + t.Errorf("source should be manual, got %s", c.Source) + } + if !strings.HasPrefix(c.ID, "commitment-") { + t.Errorf("id should be prefixed, got %s", c.ID) + } +} + +func TestCommitmentSerializesSnakeCaseEnums(t *testing.T) { + c, _ := NewManual("Port domain", "domain tests pass", 25*time.Minute) + data, err := json.Marshal(c) + if err != nil { + t.Fatalf("marshal failed: %v", err) + } + s := string(data) + if !strings.Contains(s, `"source":"manual"`) { + t.Errorf("missing snake_case source in %s", s) + } + if !strings.Contains(s, `"state":"draft"`) { + t.Errorf("missing snake_case state in %s", s) + } +} From 0a934bf061047911f9d3501addce2575a387c10a Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:39:38 -0400 Subject: [PATCH 03/11] Harden timebox validation and test ForRuntime Co-Authored-By: Claude Opus 4.8 --- internal/domain/domain.go | 2 +- internal/domain/domain_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/internal/domain/domain.go b/internal/domain/domain.go index 92779da..48f3b1d 100644 --- a/internal/domain/domain.go +++ b/internal/domain/domain.go @@ -99,7 +99,7 @@ func NewManual(nextAction, successCondition string, timebox time.Duration) (Comm if successCondition == "" { return Commitment{}, ErrMissingSuccessCondition } - if timebox <= 0 { + if timebox < time.Second { return Commitment{}, ErrMissingTimebox } return Commitment{ diff --git a/internal/domain/domain_test.go b/internal/domain/domain_test.go index e016fd0..77db2b4 100644 --- a/internal/domain/domain_test.go +++ b/internal/domain/domain_test.go @@ -53,6 +53,32 @@ func TestNewManualPopulatesDraftCommitment(t *testing.T) { } } +func TestNewManualRejectsSubSecondTimebox(t *testing.T) { + _, err := NewManual("Refactor state", "tests pass", 500*time.Millisecond) + if err != ErrMissingTimebox { + t.Fatalf("want ErrMissingTimebox, got %v", err) + } +} + +func TestForRuntimePopulatesPolicySnapshot(t *testing.T) { + p := ForRuntime("commitment-123", RuntimeActive, EnforcementObserve) + if !strings.HasPrefix(p.ID, "policy-") { + t.Errorf("id should be prefixed, got %s", p.ID) + } + if p.CommitmentID != "commitment-123" { + t.Errorf("commitment id wrong: %s", p.CommitmentID) + } + if p.SchemaVersion != PolicySchemaVersion { + t.Errorf("schema version wrong: %d", p.SchemaVersion) + } + if p.RuntimeState != RuntimeActive { + t.Errorf("runtime state wrong: %s", p.RuntimeState) + } + if p.EnforcementLevel != EnforcementObserve { + t.Errorf("enforcement level wrong: %s", p.EnforcementLevel) + } +} + func TestCommitmentSerializesSnakeCaseEnums(t *testing.T) { c, _ := NewManual("Port domain", "domain tests pass", 25*time.Minute) data, err := json.Marshal(c) From de40fe73c797d7a064a4b29c97f7e9a0babc1b86 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:41:40 -0400 Subject: [PATCH 04/11] Add runtime and commitment state machines Co-Authored-By: Claude Opus 4.8 --- internal/statemachine/statemachine.go | 115 +++++++++++++++++++++ internal/statemachine/statemachine_test.go | 54 ++++++++++ 2 files changed, 169 insertions(+) create mode 100644 internal/statemachine/statemachine.go create mode 100644 internal/statemachine/statemachine_test.go diff --git a/internal/statemachine/statemachine.go b/internal/statemachine/statemachine.go new file mode 100644 index 0000000..18f6e92 --- /dev/null +++ b/internal/statemachine/statemachine.go @@ -0,0 +1,115 @@ +// Package statemachine holds the pure runtime and commitment transition +// functions ported from the Rust implementation. No I/O, no shared state. +package statemachine + +import ( + "fmt" + + "antidrift/internal/domain" +) + +// RuntimeAction enumerates runtime transitions. Activate's policy acceptance +// and admin-override exit targets from the Rust enum are flattened into +// distinct actions so the action type stays a simple value. +type RuntimeAction string + +const ( + EnterPlanning RuntimeAction = "enter_planning" + CancelOrTimeout RuntimeAction = "cancel_or_timeout" + ActivateAccepted RuntimeAction = "activate_accepted" + ActivateRejected RuntimeAction = "activate_rejected" + StartTransition RuntimeAction = "start_transition" + CompleteForReview RuntimeAction = "complete_for_review" + SevereViolation RuntimeAction = "severe_violation" + ReturnToActive RuntimeAction = "return_to_active" + SwitchTask RuntimeAction = "switch_task" + EndTransitionForReview RuntimeAction = "end_transition_for_review" + ContinuePlanning RuntimeAction = "continue_planning" + EndWorkPeriod RuntimeAction = "end_work_period" + EnterAdminOverride RuntimeAction = "enter_admin_override" + ExitAdminOverrideToLocked RuntimeAction = "exit_admin_override_to_locked" + ExitAdminOverrideToPlanning RuntimeAction = "exit_admin_override_to_planning" +) + +type CommitmentAction string + +const ( + CommitmentActivate CommitmentAction = "activate" + PauseForTransition CommitmentAction = "pause_for_transition" + ReturnFromPause CommitmentAction = "return_from_pause" + Complete CommitmentAction = "complete" + Abandon CommitmentAction = "abandon" + Violate CommitmentAction = "violate" + RecoverExplicitly CommitmentAction = "recover_explicitly" +) + +// IllegalTransitionError reports a rejected transition. +type IllegalTransitionError struct { + From string + Action string +} + +func (e IllegalTransitionError) Error() string { + return fmt.Sprintf("illegal transition from %s via %s", e.From, e.Action) +} + +// PolicyRejectedError reports an activation attempted with an unaccepted policy. +type PolicyRejectedError struct{} + +func (PolicyRejectedError) Error() string { return "policy was rejected" } + +func TransitionRuntime(current domain.RuntimeState, action RuntimeAction) (domain.RuntimeState, error) { + type key struct { + s domain.RuntimeState + a RuntimeAction + } + table := map[key]domain.RuntimeState{ + {domain.RuntimeLocked, EnterPlanning}: domain.RuntimePlanning, + {domain.RuntimePlanning, ActivateAccepted}: domain.RuntimeActive, + {domain.RuntimePlanning, CancelOrTimeout}: domain.RuntimeLocked, + {domain.RuntimeActive, StartTransition}: domain.RuntimeTransition, + {domain.RuntimeActive, CompleteForReview}: domain.RuntimeReview, + {domain.RuntimeActive, SevereViolation}: domain.RuntimeLocked, + {domain.RuntimeTransition, ReturnToActive}: domain.RuntimeActive, + {domain.RuntimeTransition, SwitchTask}: domain.RuntimePlanning, + {domain.RuntimeTransition, EndTransitionForReview}: domain.RuntimeReview, + {domain.RuntimeTransition, CancelOrTimeout}: domain.RuntimeLocked, + {domain.RuntimeReview, ContinuePlanning}: domain.RuntimePlanning, + {domain.RuntimeReview, EndWorkPeriod}: domain.RuntimeLocked, + {domain.RuntimeAdminOverride, ExitAdminOverrideToLocked}: domain.RuntimeLocked, + {domain.RuntimeAdminOverride, ExitAdminOverrideToPlanning}: domain.RuntimePlanning, + } + + if action == ActivateRejected && current == domain.RuntimePlanning { + return current, PolicyRejectedError{} + } + if action == EnterAdminOverride { + return domain.RuntimeAdminOverride, nil + } + if next, ok := table[key{current, action}]; ok { + return next, nil + } + return current, IllegalTransitionError{From: string(current), Action: string(action)} +} + +func TransitionCommitment(current domain.CommitmentState, action CommitmentAction) (domain.CommitmentState, error) { + type key struct { + s domain.CommitmentState + a CommitmentAction + } + table := map[key]domain.CommitmentState{ + {domain.CommitmentDraft, CommitmentActivate}: domain.CommitmentActive, + {domain.CommitmentActive, PauseForTransition}: domain.CommitmentPaused, + {domain.CommitmentPaused, ReturnFromPause}: domain.CommitmentActive, + {domain.CommitmentActive, Complete}: domain.CommitmentCompleted, + {domain.CommitmentActive, Abandon}: domain.CommitmentAbandoned, + {domain.CommitmentActive, Violate}: domain.CommitmentViolated, + {domain.CommitmentPaused, Abandon}: domain.CommitmentAbandoned, + {domain.CommitmentViolated, RecoverExplicitly}: domain.CommitmentActive, + {domain.CommitmentViolated, Abandon}: domain.CommitmentAbandoned, + } + if next, ok := table[key{current, action}]; ok { + return next, nil + } + return current, IllegalTransitionError{From: string(current), Action: string(action)} +} diff --git a/internal/statemachine/statemachine_test.go b/internal/statemachine/statemachine_test.go new file mode 100644 index 0000000..813eb49 --- /dev/null +++ b/internal/statemachine/statemachine_test.go @@ -0,0 +1,54 @@ +package statemachine + +import ( + "testing" + + "antidrift/internal/domain" +) + +func TestPlanningActivatesOnlyWithAcceptedPolicy(t *testing.T) { + got, err := TransitionRuntime(domain.RuntimePlanning, ActivateAccepted) + if err != nil || got != domain.RuntimeActive { + t.Fatalf("accepted: got %s err %v", got, err) + } + _, err = TransitionRuntime(domain.RuntimePlanning, ActivateRejected) + if err == nil { + t.Fatalf("rejected policy should error") + } +} + +func TestActiveCanCompleteForReview(t *testing.T) { + got, err := TransitionRuntime(domain.RuntimeActive, CompleteForReview) + if err != nil || got != domain.RuntimeReview { + t.Fatalf("got %s err %v", got, err) + } +} + +func TestReviewEndsToLocked(t *testing.T) { + got, err := TransitionRuntime(domain.RuntimeReview, EndWorkPeriod) + if err != nil || got != domain.RuntimeLocked { + t.Fatalf("got %s err %v", got, err) + } +} + +func TestLockedCannotBecomeActiveDirectly(t *testing.T) { + _, err := TransitionRuntime(domain.RuntimeLocked, ActivateAccepted) + if err == nil { + t.Fatalf("locked->active must be illegal") + } +} + +func TestCommitmentDraftActivatesAndViolatedRecovers(t *testing.T) { + got, err := TransitionCommitment(domain.CommitmentDraft, CommitmentActivate) + if err != nil || got != domain.CommitmentActive { + t.Fatalf("draft->active: got %s err %v", got, err) + } + got, err = TransitionCommitment(domain.CommitmentViolated, RecoverExplicitly) + if err != nil || got != domain.CommitmentActive { + t.Fatalf("violated->active: got %s err %v", got, err) + } + _, err = TransitionCommitment(domain.CommitmentViolated, ReturnFromPause) + if err == nil { + t.Fatalf("violated->returnFromPause must be illegal") + } +} From 63247e402a5d64cdd6e14a75f5f24076cdc1f8b3 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:43:31 -0400 Subject: [PATCH 05/11] Add snapshot store Co-Authored-By: Claude Opus 4.8 --- internal/store/store.go | 62 ++++++++++++++++++++++++++++++++++++ internal/store/store_test.go | 50 +++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 internal/store/store.go create mode 100644 internal/store/store_test.go diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..d8f8d77 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,62 @@ +// 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) +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go new file mode 100644 index 0000000..53fe597 --- /dev/null +++ b/internal/store/store_test.go @@ -0,0 +1,50 @@ +package store + +import ( + "path/filepath" + "testing" + "time" + + "antidrift/internal/domain" +) + +func TestLoadMissingFileReturnsLocked(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + s, err := Load(path) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if s.RuntimeState != domain.RuntimeLocked { + t.Errorf("missing file should be Locked, got %s", s.RuntimeState) + } + if s.Commitment != nil { + t.Errorf("missing file should have nil commitment") + } +} + +func TestSaveThenLoadRoundTrips(t *testing.T) { + path := filepath.Join(t.TempDir(), "nested", "state.json") + c, _ := domain.NewManual("Port store", "store tests pass", 25*time.Minute) + c.State = domain.CommitmentActive + want := Snapshot{ + RuntimeState: domain.RuntimeActive, + Commitment: &c, + DeadlineUnixSecs: 1748725200, + } + if err := Save(path, want); err != nil { + t.Fatalf("save failed: %v", err) + } + got, err := Load(path) + if err != nil { + t.Fatalf("load failed: %v", err) + } + if got.RuntimeState != want.RuntimeState { + t.Errorf("runtime state: got %s want %s", got.RuntimeState, want.RuntimeState) + } + if got.Commitment == nil || got.Commitment.NextAction != "Port store" { + t.Errorf("commitment did not round-trip: %+v", got.Commitment) + } + if got.DeadlineUnixSecs != want.DeadlineUnixSecs { + t.Errorf("deadline: got %d want %d", got.DeadlineUnixSecs, want.DeadlineUnixSecs) + } +} From 18108c3da36127ed66e0de006ea0d8643bab6f6c Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:45:46 -0400 Subject: [PATCH 06/11] Add session controller with snapshot persistence Co-Authored-By: Claude Opus 4.8 --- internal/session/session.go | 156 +++++++++++++++++++++++++++++++ internal/session/session_test.go | 87 +++++++++++++++++ 2 files changed, 243 insertions(+) create mode 100644 internal/session/session.go create mode 100644 internal/session/session_test.go diff --git a/internal/session/session.go b/internal/session/session.go new file mode 100644 index 0000000..e9ecddc --- /dev/null +++ b/internal/session/session.go @@ -0,0 +1,156 @@ +// Package session owns the daemon's in-memory state of truth and persists a +// snapshot on every change. Transitions go through the pure statemachine. +package session + +import ( + "sync" + "time" + + "antidrift/internal/domain" + "antidrift/internal/statemachine" + "antidrift/internal/store" +) + +// Controller holds runtime state and the active commitment behind a mutex. +type Controller struct { + mu sync.Mutex + runtimeState domain.RuntimeState + commitment *domain.Commitment + deadline time.Time + snapshotPath string +} + +// CommitmentView is the UI projection of the active commitment. +type CommitmentView struct { + NextAction string `json:"next_action"` + SuccessCondition string `json:"success_condition"` + TimeboxSecs int64 `json:"timebox_secs"` + DeadlineUnixSecs int64 `json:"deadline_unix_secs"` +} + +// State is the broadcastable view of the controller. +type State struct { + RuntimeState domain.RuntimeState `json:"runtime_state"` + Commitment *CommitmentView `json:"commitment"` +} + +// New loads any persisted snapshot, or starts Locked. +func New(snapshotPath string) (*Controller, error) { + s, err := store.Load(snapshotPath) + if err != nil { + return nil, err + } + c := &Controller{ + runtimeState: s.RuntimeState, + commitment: s.Commitment, + snapshotPath: snapshotPath, + } + if s.DeadlineUnixSecs > 0 { + c.deadline = time.Unix(s.DeadlineUnixSecs, 0) + } + if c.runtimeState == "" { + c.runtimeState = domain.RuntimeLocked + } + return c, nil +} + +// State returns the current broadcastable state. Safe for concurrent use. +func (c *Controller) State() State { + c.mu.Lock() + defer c.mu.Unlock() + return c.stateLocked() +} + +// Deadline returns the active commitment deadline, or the zero time. +func (c *Controller) Deadline() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.deadline +} + +func (c *Controller) stateLocked() State { + st := State{RuntimeState: c.runtimeState} + if c.commitment != nil { + st.Commitment = &CommitmentView{ + NextAction: c.commitment.NextAction, + SuccessCondition: c.commitment.SuccessCondition, + TimeboxSecs: c.commitment.TimeboxSecs, + DeadlineUnixSecs: c.deadline.Unix(), + } + } + return st +} + +func (c *Controller) persistLocked() error { + snap := store.Snapshot{RuntimeState: c.runtimeState, Commitment: c.commitment} + if !c.deadline.IsZero() { + snap.DeadlineUnixSecs = c.deadline.Unix() + } + return store.Save(c.snapshotPath, snap) +} + +// EnterPlanning moves Locked -> Planning. +func (c *Controller) EnterPlanning() error { + c.mu.Lock() + defer c.mu.Unlock() + next, err := statemachine.TransitionRuntime(c.runtimeState, statemachine.EnterPlanning) + if err != nil { + return err + } + c.runtimeState = next + return c.persistLocked() +} + +// StartManualCommitment validates input, activates a new commitment, and moves +// Planning -> Active. +func (c *Controller) StartManualCommitment(nextAction, successCondition string, timebox time.Duration) error { + c.mu.Lock() + defer c.mu.Unlock() + commitment, err := domain.NewManual(nextAction, successCondition, timebox) + if err != nil { + return err + } + commitment.State, err = statemachine.TransitionCommitment(commitment.State, statemachine.CommitmentActivate) + if err != nil { + return err + } + next, err := statemachine.TransitionRuntime(c.runtimeState, statemachine.ActivateAccepted) + if err != nil { + return err + } + c.runtimeState = next + c.commitment = &commitment + c.deadline = time.Now().Add(timebox) + return c.persistLocked() +} + +// Complete moves Active -> Review and marks the commitment completed. +func (c *Controller) Complete() error { + c.mu.Lock() + defer c.mu.Unlock() + next, err := statemachine.TransitionRuntime(c.runtimeState, statemachine.CompleteForReview) + if err != nil { + return err + } + c.runtimeState = next + if c.commitment != nil { + if s, e := statemachine.TransitionCommitment(c.commitment.State, statemachine.Complete); e == nil { + c.commitment.State = s + } + } + return c.persistLocked() +} + +// End moves Review -> Locked and clears the commitment. +func (c *Controller) End() error { + c.mu.Lock() + defer c.mu.Unlock() + next, err := statemachine.TransitionRuntime(c.runtimeState, statemachine.EndWorkPeriod) + if err != nil { + return err + } + c.runtimeState = next + c.commitment = nil + c.deadline = time.Time{} + return c.persistLocked() +} diff --git a/internal/session/session_test.go b/internal/session/session_test.go new file mode 100644 index 0000000..fe09cc0 --- /dev/null +++ b/internal/session/session_test.go @@ -0,0 +1,87 @@ +package session + +import ( + "path/filepath" + "testing" + "time" + + "antidrift/internal/domain" +) + +func newTestController(t *testing.T) (*Controller, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "state.json") + c, err := New(path) + if err != nil { + t.Fatalf("new controller: %v", err) + } + return c, path +} + +func TestHappyPathDrivesStates(t *testing.T) { + c, _ := newTestController(t) + if c.State().RuntimeState != domain.RuntimeLocked { + t.Fatalf("should start Locked") + } + if err := c.EnterPlanning(); err != nil { + t.Fatalf("enter planning: %v", err) + } + if err := c.StartManualCommitment("Port session", "session tests pass", 25*time.Minute); err != nil { + t.Fatalf("start commitment: %v", err) + } + st := c.State() + if st.RuntimeState != domain.RuntimeActive { + t.Fatalf("should be Active, got %s", st.RuntimeState) + } + if st.Commitment == nil || st.Commitment.NextAction != "Port session" { + t.Fatalf("active commitment missing: %+v", st.Commitment) + } + if st.Commitment.DeadlineUnixSecs <= time.Now().Unix() { + t.Fatalf("deadline should be in the future") + } + if err := c.Complete(); err != nil { + t.Fatalf("complete: %v", err) + } + if c.State().RuntimeState != domain.RuntimeReview { + t.Fatalf("should be Review after complete") + } + if err := c.End(); err != nil { + t.Fatalf("end: %v", err) + } + if c.State().RuntimeState != domain.RuntimeLocked { + t.Fatalf("should be Locked after end") + } +} + +func TestStartCommitmentRejectsInvalidInput(t *testing.T) { + c, _ := newTestController(t) + _ = c.EnterPlanning() + if err := c.StartManualCommitment("", "x", 25*time.Minute); err == nil { + t.Fatalf("empty next action should error") + } + if c.State().RuntimeState != domain.RuntimePlanning { + t.Fatalf("failed start must not change state, got %s", c.State().RuntimeState) + } +} + +func TestStateRestoresFromSnapshot(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + first, err := New(path) + if err != nil { + t.Fatalf("new: %v", err) + } + _ = first.EnterPlanning() + _ = first.StartManualCommitment("Persisted action", "done", 25*time.Minute) + + second, err := New(path) + if err != nil { + t.Fatalf("reopen: %v", err) + } + st := second.State() + if st.RuntimeState != domain.RuntimeActive { + t.Fatalf("restored state should be Active, got %s", st.RuntimeState) + } + if st.Commitment == nil || st.Commitment.NextAction != "Persisted action" { + t.Fatalf("restored commitment missing: %+v", st.Commitment) + } +} From a8216095de98f5368e1dbd5c88c03c70c17da165 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:49:03 -0400 Subject: [PATCH 07/11] Make Complete atomic and guard zero deadline Co-Authored-By: Claude Opus 4.8 --- internal/session/session.go | 19 +++++++++++++------ internal/session/session_test.go | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/internal/session/session.go b/internal/session/session.go index e9ecddc..53207e7 100644 --- a/internal/session/session.go +++ b/internal/session/session.go @@ -71,12 +71,15 @@ func (c *Controller) Deadline() time.Time { func (c *Controller) stateLocked() State { st := State{RuntimeState: c.runtimeState} if c.commitment != nil { - st.Commitment = &CommitmentView{ + view := &CommitmentView{ NextAction: c.commitment.NextAction, SuccessCondition: c.commitment.SuccessCondition, TimeboxSecs: c.commitment.TimeboxSecs, - DeadlineUnixSecs: c.deadline.Unix(), } + if !c.deadline.IsZero() { + view.DeadlineUnixSecs = c.deadline.Unix() + } + st.Commitment = view } return st } @@ -124,7 +127,9 @@ func (c *Controller) StartManualCommitment(nextAction, successCondition string, return c.persistLocked() } -// Complete moves Active -> Review and marks the commitment completed. +// Complete moves Active -> Review and marks the commitment completed. Both +// transitions are computed before any field is mutated, so a failure leaves +// state unchanged. func (c *Controller) Complete() error { c.mu.Lock() defer c.mu.Unlock() @@ -132,12 +137,14 @@ func (c *Controller) Complete() error { if err != nil { return err } - c.runtimeState = next if c.commitment != nil { - if s, e := statemachine.TransitionCommitment(c.commitment.State, statemachine.Complete); e == nil { - c.commitment.State = s + completed, err := statemachine.TransitionCommitment(c.commitment.State, statemachine.Complete) + if err != nil { + return err } + c.commitment.State = completed } + c.runtimeState = next return c.persistLocked() } diff --git a/internal/session/session_test.go b/internal/session/session_test.go index fe09cc0..37b37a9 100644 --- a/internal/session/session_test.go +++ b/internal/session/session_test.go @@ -85,3 +85,23 @@ func TestStateRestoresFromSnapshot(t *testing.T) { t.Fatalf("restored commitment missing: %+v", st.Commitment) } } + +func TestRestoredCommitmentKeepsDeadline(t *testing.T) { + path := filepath.Join(t.TempDir(), "state.json") + first, err := New(path) + if err != nil { + t.Fatalf("new: %v", err) + } + _ = first.EnterPlanning() + _ = first.StartManualCommitment("Keep deadline", "done", 25*time.Minute) + want := first.State().Commitment.DeadlineUnixSecs + + second, err := New(path) + if err != nil { + t.Fatalf("reopen: %v", err) + } + got := second.State().Commitment + if got == nil || got.DeadlineUnixSecs != want { + t.Fatalf("restored deadline: got %+v want %d", got, want) + } +} From f243f3004ed69ad3f231491b2f9c7d5d38906200 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:49:57 -0400 Subject: [PATCH 08/11] Add SSE broadcaster Co-Authored-By: Claude Opus 4.8 --- internal/web/broadcaster.go | 42 ++++++++++++++++++++++++++++++++ internal/web/broadcaster_test.go | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 internal/web/broadcaster.go create mode 100644 internal/web/broadcaster_test.go diff --git a/internal/web/broadcaster.go b/internal/web/broadcaster.go new file mode 100644 index 0000000..4a61a7b --- /dev/null +++ b/internal/web/broadcaster.go @@ -0,0 +1,42 @@ +package web + +import "sync" + +// Broadcaster fans a string message out to all SSE subscribers. Slow +// subscribers drop messages rather than blocking publishers. +type Broadcaster struct { + mu sync.Mutex + subs map[chan string]struct{} +} + +func NewBroadcaster() *Broadcaster { + return &Broadcaster{subs: make(map[chan string]struct{})} +} + +func (b *Broadcaster) Subscribe() chan string { + ch := make(chan string, 8) + b.mu.Lock() + b.subs[ch] = struct{}{} + b.mu.Unlock() + return ch +} + +func (b *Broadcaster) Unsubscribe(ch chan string) { + b.mu.Lock() + if _, ok := b.subs[ch]; ok { + delete(b.subs, ch) + close(ch) + } + b.mu.Unlock() +} + +func (b *Broadcaster) Publish(msg string) { + b.mu.Lock() + defer b.mu.Unlock() + for ch := range b.subs { + select { + case ch <- msg: + default: // drop for slow subscriber + } + } +} diff --git a/internal/web/broadcaster_test.go b/internal/web/broadcaster_test.go new file mode 100644 index 0000000..f83227c --- /dev/null +++ b/internal/web/broadcaster_test.go @@ -0,0 +1,42 @@ +package web + +import ( + "testing" + "time" +) + +func TestBroadcasterDeliversToSubscribers(t *testing.T) { + b := NewBroadcaster() + ch := b.Subscribe() + defer b.Unsubscribe(ch) + + b.Publish("hello") + + select { + case msg := <-ch: + if msg != "hello" { + t.Fatalf("got %q want hello", msg) + } + case <-time.After(time.Second): + t.Fatal("subscriber did not receive message") + } +} + +func TestBroadcasterDropsWhenSubscriberFull(t *testing.T) { + b := NewBroadcaster() + ch := b.Subscribe() + defer b.Unsubscribe(ch) + // Publishing many messages without reading must not block (slow client). + done := make(chan struct{}) + go func() { + for i := 0; i < 100; i++ { + b.Publish("x") + } + close(done) + }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Publish blocked on a full subscriber") + } +} From 0318aeb08d9cfe740fb07fbf11f7b510bb1f96dd Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:53:21 -0400 Subject: [PATCH 09/11] Add web server, SSE handlers, and UI Co-Authored-By: Claude Opus 4.8 --- go.mod | 37 ++++++- go.sum | 89 ++++++++++++++++ internal/web/static/index.html | 102 ++++++++++++++++++ internal/web/web.go | 185 +++++++++++++++++++++++++++++++++ internal/web/web_test.go | 71 +++++++++++++ 5 files changed, 483 insertions(+), 1 deletion(-) create mode 100644 internal/web/static/index.html create mode 100644 internal/web/web.go create mode 100644 internal/web/web_test.go diff --git a/go.mod b/go.mod index 1afbe7e..a304213 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,39 @@ module antidrift go 1.26.3 -require github.com/google/uuid v1.6.0 // indirect +require ( + github.com/gin-gonic/gin v1.12.0 + github.com/google/uuid v1.6.0 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + golang.org/x/arch v0.22.0 // indirect + golang.org/x/crypto v0.48.0 // indirect + golang.org/x/net v0.51.0 // indirect + golang.org/x/sys v0.41.0 // indirect + golang.org/x/text v0.34.0 // indirect + google.golang.org/protobuf v1.36.10 // indirect +) diff --git a/go.sum b/go.sum index 7790d7c..0b62b83 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,91 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts= +golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos= +golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo= +golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k= +golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk= +golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA= +google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= +google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/web/static/index.html b/internal/web/static/index.html new file mode 100644 index 0000000..bd7d4f3 --- /dev/null +++ b/internal/web/static/index.html @@ -0,0 +1,102 @@ + + + + + +AntiDrift + + + +
+

AntiDrift

+
connecting…
+
+ + + diff --git a/internal/web/web.go b/internal/web/web.go new file mode 100644 index 0000000..044f4d8 --- /dev/null +++ b/internal/web/web.go @@ -0,0 +1,185 @@ +// Package web serves the local UI and an SSE state stream, and owns the +// server-authoritative timebox expiry timer. +package web + +import ( + "embed" + "encoding/json" + "errors" + "fmt" + "io/fs" + "net/http" + "sync" + "time" + + "antidrift/internal/session" + "antidrift/internal/statemachine" + + "github.com/gin-gonic/gin" +) + +//go:embed static/* +var staticFS embed.FS + +// Server wires the session controller to HTTP and SSE. +type Server struct { + ctrl *session.Controller + bcast *Broadcaster + + mu sync.Mutex + timer *time.Timer +} + +func NewServer(ctrl *session.Controller) *Server { + return &Server{ctrl: ctrl, bcast: NewBroadcaster()} +} + +func (s *Server) Router() *gin.Engine { + r := gin.New() + r.Use(gin.Recovery()) + + sub, _ := fs.Sub(staticFS, "static") + r.GET("/", func(c *gin.Context) { + c.FileFromFS("/", http.FS(sub)) + }) + r.GET("/events", s.handleEvents) + r.POST("/planning", s.handlePlanning) + r.POST("/commitment", s.handleCommitment) + r.POST("/complete", s.handleComplete) + r.POST("/end", s.handleEnd) + return r +} + +func (s *Server) stateJSON() string { + data, _ := json.Marshal(s.ctrl.State()) + return string(data) +} + +func (s *Server) broadcast() { + s.bcast.Publish(s.stateJSON()) +} + +// respond maps a controller error to an HTTP status, otherwise broadcasts and +// returns the new state. +func (s *Server) respond(c *gin.Context, err error) { + if err != nil { + var illegal statemachine.IllegalTransitionError + if errors.As(err, &illegal) { + c.JSON(http.StatusConflict, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + s.broadcast() + c.Data(http.StatusOK, "application/json", []byte(s.stateJSON())) +} + +func (s *Server) handlePlanning(c *gin.Context) { + s.cancelExpiry() + s.respond(c, s.ctrl.EnterPlanning()) +} + +type commitmentRequest struct { + NextAction string `json:"next_action"` + SuccessCondition string `json:"success_condition"` + TimeboxSecs int64 `json:"timebox_secs"` +} + +func (s *Server) handleCommitment(c *gin.Context) { + var req commitmentRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid json"}) + return + } + err := s.ctrl.StartManualCommitment(req.NextAction, req.SuccessCondition, time.Duration(req.TimeboxSecs)*time.Second) + if err == nil { + s.armExpiry() + } + s.respond(c, err) +} + +func (s *Server) handleComplete(c *gin.Context) { + s.cancelExpiry() + s.respond(c, s.ctrl.Complete()) +} + +func (s *Server) handleEnd(c *gin.Context) { + s.respond(c, s.ctrl.End()) +} + +func (s *Server) handleEvents(c *gin.Context) { + c.Header("Content-Type", "text/event-stream") + c.Header("Cache-Control", "no-cache") + c.Header("Connection", "keep-alive") + + flusher, ok := c.Writer.(http.Flusher) + if !ok { + c.Status(http.StatusInternalServerError) + return + } + ch := s.bcast.Subscribe() + defer s.bcast.Unsubscribe(ch) + + fmt.Fprintf(c.Writer, "data: %s\n\n", s.stateJSON()) + flusher.Flush() + + for { + select { + case <-c.Request.Context().Done(): + return + case msg, open := <-ch: + if !open { + return + } + fmt.Fprintf(c.Writer, "data: %s\n\n", msg) + flusher.Flush() + } + } +} + +// armExpiry schedules an Active -> Review transition at the commitment deadline. +func (s *Server) armExpiry() { + deadline := s.ctrl.Deadline() + if deadline.IsZero() { + return + } + s.mu.Lock() + defer s.mu.Unlock() + if s.timer != nil { + s.timer.Stop() + } + d := time.Until(deadline) + if d < 0 { + d = 0 + } + s.timer = time.AfterFunc(d, func() { + if err := s.ctrl.Complete(); err == nil { + s.broadcast() + } + }) +} + +func (s *Server) cancelExpiry() { + s.mu.Lock() + defer s.mu.Unlock() + if s.timer != nil { + s.timer.Stop() + s.timer = nil + } +} + +// Init re-arms or expires a restored Active session at startup. +func (s *Server) Init() { + st := s.ctrl.State() + if st.RuntimeState != "active" { + return + } + if s.ctrl.Deadline().After(time.Now()) { + s.armExpiry() + return + } + if err := s.ctrl.Complete(); err == nil { + s.broadcast() + } +} diff --git a/internal/web/web_test.go b/internal/web/web_test.go new file mode 100644 index 0000000..34b1a05 --- /dev/null +++ b/internal/web/web_test.go @@ -0,0 +1,71 @@ +package web + +import ( + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + + "antidrift/internal/domain" + "antidrift/internal/session" + + "github.com/gin-gonic/gin" +) + +func newTestServer(t *testing.T) *Server { + t.Helper() + gin.SetMode(gin.TestMode) + path := filepath.Join(t.TempDir(), "state.json") + ctrl, err := session.New(path) + if err != nil { + t.Fatalf("controller: %v", err) + } + return NewServer(ctrl) +} + +func post(t *testing.T, r http.Handler, path, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w +} + +func TestPlanningThenCommitmentReachesActive(t *testing.T) { + s := newTestServer(t) + r := s.Router() + + if w := post(t, r, "/planning", ""); w.Code != http.StatusOK { + t.Fatalf("/planning code %d", w.Code) + } + body := `{"next_action":"Build web","success_condition":"web tests pass","timebox_secs":1500}` + if w := post(t, r, "/commitment", body); w.Code != http.StatusOK { + t.Fatalf("/commitment code %d body %s", w.Code, w.Body.String()) + } + if s.ctrl.State().RuntimeState != domain.RuntimeActive { + t.Fatalf("expected Active, got %s", s.ctrl.State().RuntimeState) + } +} + +func TestCommitmentRejectsInvalidInput(t *testing.T) { + s := newTestServer(t) + r := s.Router() + _ = post(t, r, "/planning", "") + body := `{"next_action":"","success_condition":"x","timebox_secs":1500}` + w := post(t, r, "/commitment", body) + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } +} + +func TestIllegalTransitionReturns409(t *testing.T) { + s := newTestServer(t) + r := s.Router() + // /complete from Locked is illegal. + w := post(t, r, "/complete", "") + if w.Code != http.StatusConflict { + t.Fatalf("expected 409, got %d", w.Code) + } +} From 937d714be2a473a8f1bd3f7835236fee30878ff0 Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 11:59:31 -0400 Subject: [PATCH 10/11] Wire antidriftd daemon entrypoint Co-Authored-By: Claude Opus 4.8 --- cmd/antidriftd/main.go | 56 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/cmd/antidriftd/main.go b/cmd/antidriftd/main.go index e567bbf..27e7d1c 100644 --- a/cmd/antidriftd/main.go +++ b/cmd/antidriftd/main.go @@ -1,7 +1,59 @@ +// Command antidriftd is the AntiDrift focus daemon: it serves a local web UI +// and owns the commitment state machine. package main -import "fmt" +import ( + "log" + "os/exec" + "runtime" + "time" + + "antidrift/internal/session" + "antidrift/internal/store" + "antidrift/internal/web" +) + +const addr = "localhost:7777" func main() { - fmt.Println("antidriftd") + path, err := store.DefaultPath() + if err != nil { + log.Fatalf("resolve snapshot path: %v", err) + } + ctrl, err := session.New(path) + if err != nil { + log.Fatalf("load session: %v", err) + } + + srv := web.NewServer(ctrl) + srv.Init() // re-arm or expire a restored Active session + + go openBrowser("http://" + addr) + + log.Printf("antidriftd listening on http://%s", addr) + if err := srv.Router().Run(addr); err != nil { + log.Fatalf("server: %v", err) + } +} + +// openBrowser best-effort launches the default browser after a short delay so +// the server is listening first. Failures are logged, not fatal. +func openBrowser(url string) { + time.Sleep(300 * time.Millisecond) + var cmd string + var args []string + switch runtime.GOOS { + case "linux": + cmd, args = "xdg-open", []string{url} + case "darwin": + cmd, args = "open", []string{url} + case "windows": + cmd, args = "rundll32", []string{"url.dll,FileProtocolHandler", url} + default: + log.Printf("open browser manually: %s", url) + return + } + if err := exec.Command(cmd, args...).Start(); err != nil { + log.Printf("could not open browser (%v); visit %s", err, url) + } } From d08cc9f8918fd9684ad498c5db1ce8da47b3103a Mon Sep 17 00:00:00 2001 From: Felix Martin Date: Sun, 31 May 2026 12:00:15 -0400 Subject: [PATCH 11/11] Document M0 walking skeleton Co-Authored-By: Claude Opus 4.8 --- README.md | 37 +++++++++++++++++++++---------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 1a6f0e6..86873e9 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,29 @@ # AntiDrift -Just my personal productivity tool. +A personal focus operating system: treat each work session as an explicit +commitment (next action, success condition, timebox), and make drift visible. -## Commitment OS Stage 1 +This is the Go reimagining. The original Rust implementation is preserved under +`legacy/` for reference. See `docs/superpowers/specs/` for the design. -AntiDrift treats a work session as a commitment: next action, success -condition, timebox, evidence, transition prompts, and review. Stage 1 is -user-space friction, not privileged enforcement. +## Run -The local event log is written to `~/.antidrift_events.jsonl`. It records -commitment creation, policy snapshots, runtime transitions, evidence health, -transition starts, and violation dismissals. The log is append-only and -hash-chained for tamper evidence, but it is not yet protected by a privileged -guardian. +```bash +go run ./cmd/antidriftd +``` -Linux active-window evidence depends on `xdotool` and is strongest on X11. -Wayland is degraded unless a compositor-specific adapter is added later. +The daemon serves a local web UI at http://localhost:7777 and opens your +browser. State is persisted to `~/.antidrift/state.json`. -To use AntiDrift, run `cargo run --release` directly, or `cargo build --release` -and copy the binary into your `PATH`. +## Test -Under Windows, AntiDrift uses the package `winapi` for window titles and window -minimization. +```bash +go test ./... +``` + +## Status + +M0 (walking skeleton): manual commitment lifecycle over a local web UI with +snapshot persistence. AI integration, active-window tracking, and the +tamper-evident audit log arrive in later milestones (see the roadmap in +`docs/superpowers/specs/2026-05-31-go-focus-os-design.md`).