Merge M0 walking skeleton: Go reimagining
Stand up the antidriftd daemon serving a local web UI that drives a manual commitment through Locked -> Planning -> Active -> Review -> Locked, with server-authoritative timebox expiry and snapshot persistence that survives restart. Rust moved to legacy/. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -10,3 +10,7 @@ target/
|
||||
|
||||
# Local brainstorming companion artifacts
|
||||
.superpowers/
|
||||
|
||||
# Go
|
||||
/antidriftd
|
||||
*.test
|
||||
|
||||
@@ -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`).
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Command antidriftd is the AntiDrift focus daemon: it serves a local web UI
|
||||
// and owns the commitment state machine.
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"antidrift/internal/session"
|
||||
"antidrift/internal/store"
|
||||
"antidrift/internal/web"
|
||||
)
|
||||
|
||||
const addr = "localhost:7777"
|
||||
|
||||
func main() {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
module antidrift
|
||||
|
||||
go 1.26.3
|
||||
|
||||
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
|
||||
)
|
||||
@@ -0,0 +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=
|
||||
@@ -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 < time.Second {
|
||||
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{},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
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 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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// 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 {
|
||||
view := &CommitmentView{
|
||||
NextAction: c.commitment.NextAction,
|
||||
SuccessCondition: c.commitment.SuccessCondition,
|
||||
TimeboxSecs: c.commitment.TimeboxSecs,
|
||||
}
|
||||
if !c.deadline.IsZero() {
|
||||
view.DeadlineUnixSecs = c.deadline.Unix()
|
||||
}
|
||||
st.Commitment = view
|
||||
}
|
||||
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. 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()
|
||||
next, err := statemachine.TransitionRuntime(c.runtimeState, statemachine.CompleteForReview)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.commitment != nil {
|
||||
completed, err := statemachine.TransitionCommitment(c.commitment.State, statemachine.Complete)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.commitment.State = completed
|
||||
}
|
||||
c.runtimeState = next
|
||||
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()
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -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)}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>AntiDrift</title>
|
||||
<style>
|
||||
:root { color-scheme: dark; }
|
||||
body { margin: 0; font: 16px/1.5 system-ui, sans-serif; background: #11131a; color: #e6e8ee; }
|
||||
main { max-width: 640px; margin: 8vh auto; padding: 0 24px; }
|
||||
h1 { font-size: 14px; letter-spacing: .2em; text-transform: uppercase; color: #7a8095; }
|
||||
.card { background: #1a1d27; border: 1px solid #272b38; border-radius: 14px; padding: 28px; }
|
||||
label { display: block; font-size: 13px; color: #9aa0b4; margin: 16px 0 6px; }
|
||||
input { width: 100%; box-sizing: border-box; padding: 10px 12px; background: #11131a;
|
||||
border: 1px solid #2d3242; border-radius: 8px; color: #e6e8ee; font: inherit; }
|
||||
button { margin-top: 22px; padding: 11px 18px; border: 0; border-radius: 8px;
|
||||
background: #4c6ef5; color: #fff; font: inherit; font-weight: 600; cursor: pointer; }
|
||||
button:disabled { background: #2d3242; color: #6a7186; cursor: not-allowed; }
|
||||
.timer { font-size: 56px; font-weight: 700; font-variant-numeric: tabular-nums; margin: 8px 0 4px; }
|
||||
.action { font-size: 22px; font-weight: 600; }
|
||||
.meta { color: #9aa0b4; }
|
||||
.pill { display: inline-block; font-size: 12px; letter-spacing: .15em; text-transform: uppercase;
|
||||
color: #7a8095; border: 1px solid #272b38; border-radius: 999px; padding: 3px 10px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>AntiDrift</h1>
|
||||
<div class="card" id="view">connecting…</div>
|
||||
</main>
|
||||
<script>
|
||||
const view = document.getElementById('view');
|
||||
let countdownTimer = null;
|
||||
|
||||
function post(path, body) {
|
||||
return fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
function fmt(secs) {
|
||||
secs = Math.max(0, Math.floor(secs));
|
||||
const m = String(Math.floor(secs / 60)).padStart(2, '0');
|
||||
const s = String(secs % 60).padStart(2, '0');
|
||||
return `${m}:${s}`;
|
||||
}
|
||||
|
||||
function render(state) {
|
||||
if (countdownTimer) { clearInterval(countdownTimer); countdownTimer = null; }
|
||||
const rs = state.runtime_state;
|
||||
if (rs === 'locked') {
|
||||
view.innerHTML = `<span class="pill">Locked</span>
|
||||
<p class="meta">No active commitment.</p>
|
||||
<button id="plan">Start planning</button>`;
|
||||
document.getElementById('plan').onclick = () => post('/planning');
|
||||
} else if (rs === 'planning') {
|
||||
view.innerHTML = `<span class="pill">Planning</span>
|
||||
<label>Next action</label><input id="na" placeholder="What exactly will you do?">
|
||||
<label>Success condition</label><input id="sc" placeholder="How do you know it's done?">
|
||||
<label>Minutes</label><input id="mins" type="number" min="1" value="25">
|
||||
<button id="start" disabled>Start commitment</button>`;
|
||||
const na = document.getElementById('na'), sc = document.getElementById('sc'),
|
||||
mins = document.getElementById('mins'), start = document.getElementById('start');
|
||||
const check = () => { start.disabled = !(na.value.trim() && sc.value.trim() && +mins.value > 0); };
|
||||
[na, sc, mins].forEach(el => el.oninput = check);
|
||||
start.onclick = () => post('/commitment', {
|
||||
next_action: na.value.trim(),
|
||||
success_condition: sc.value.trim(),
|
||||
timebox_secs: Math.round(+mins.value * 60),
|
||||
});
|
||||
} else if (rs === 'active') {
|
||||
const c = state.commitment || {};
|
||||
view.innerHTML = `<span class="pill">Active</span>
|
||||
<div class="timer" id="t">--:--</div>
|
||||
<div class="action">${c.next_action || ''}</div>
|
||||
<p class="meta">Done when: ${c.success_condition || ''}</p>
|
||||
<button id="done">Complete</button>`;
|
||||
document.getElementById('done').onclick = () => post('/complete');
|
||||
const t = document.getElementById('t');
|
||||
const tick = () => { t.textContent = fmt((c.deadline_unix_secs || 0) - Date.now() / 1000); };
|
||||
tick();
|
||||
countdownTimer = setInterval(tick, 250);
|
||||
} else if (rs === 'review') {
|
||||
const c = state.commitment || {};
|
||||
view.innerHTML = `<span class="pill">Review</span>
|
||||
<p class="action">Session ended</p>
|
||||
<p class="meta">${c.next_action || ''}</p>
|
||||
<button id="end">End</button>`;
|
||||
document.getElementById('end').onclick = () => post('/end');
|
||||
} else {
|
||||
view.textContent = rs;
|
||||
}
|
||||
}
|
||||
|
||||
const es = new EventSource('/events');
|
||||
es.onmessage = (e) => render(JSON.parse(e.data));
|
||||
es.onerror = () => { view.textContent = 'disconnected — is antidriftd running?'; };
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Generated
Reference in New Issue
Block a user