feat: NellDB storage backend replacing SQLite (archie-core-abg.30)
Extracted store.TaskStore interface (20 methods) covering task lifecycle, queries, and observability. Separate WorkflowStore for the agent RPC proxy. New internal/nell/ package: - OpenStore(path, nodeID) — persistent logstore.LogStore backend - OpenMemory(nodeID) — in-memory store for tests - Full TaskStore implementation via sdk.DocDB with MVCC All consumers updated to interface: - daemon.Daemon.Store, webui.Server.Store, storerpc.Server.Store - workflow.TaskContext.Store (WorkflowStore) - cmd/archied uses nell.OpenStore(cfg.DBPath, cfg.BotUser) 7 integration tests. Build + 32 packages pass. Closes: archie-core-abg.30
This commit is contained in:
1 parent
54e21bfbde
commit
4c1cc151a5
10 files changed
+1282
-48
No files matched your search
+5
-4
@@ -18,15 +18,16 @@ import (
|
||||
|
||||
"github.com/moby/moby/client"
|
||||
"github.com/samcharles93/archie-core/internal/agentexec"
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/container"
|
||||
"github.com/samcharles93/archie-core/internal/channels/telegram"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/daemon"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/forge"
|
||||
"github.com/samcharles93/archie-core/internal/forgerpc"
|
||||
"github.com/samcharles93/archie-core/internal/gateway"
|
||||
"github.com/samcharles93/archie-core/internal/nats"
|
||||
"github.com/samcharles93/archie-core/internal/nell"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/plugin"
|
||||
"github.com/samcharles93/archie-core/internal/plugin/pluginextract"
|
||||
@@ -71,7 +72,7 @@ func run() int {
|
||||
return 1
|
||||
}
|
||||
|
||||
st, err := store.Open(cfg.DBPath)
|
||||
st, err := nell.OpenStore(cfg.DBPath, cfg.BotUser)
|
||||
if err != nil {
|
||||
log.Error("open store", "err", err)
|
||||
return 1
|
||||
@@ -314,7 +315,7 @@ func executionProviders(cfg config.Config) map[string]agentexec.Provider {
|
||||
// handlers on nc so an archie-agent container (which holds no DB
|
||||
// connection, forge token, or push credential) can proxy those operations
|
||||
// back to archied. The returned func unsubscribes all three.
|
||||
func registerTaskRPCServers(nc *natsio.Conn, st *store.Store, forgeClient forge.Forge, trees *worktree.Manager, log *slog.Logger) (unsubscribe func(), err error) {
|
||||
func registerTaskRPCServers(nc *natsio.Conn, st store.TaskStore, forgeClient forge.Forge, trees *worktree.Manager, log *slog.Logger) (unsubscribe func(), err error) {
|
||||
storeServer := &storerpc.Server{Store: st, Log: log}
|
||||
unsubStore, err := storeServer.Register(nc)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
module github.com/samcharles93/archie-core
|
||||
|
||||
go 1.26.2
|
||||
go 1.26.3
|
||||
|
||||
require (
|
||||
github.com/BurntSushi/toml v1.6.0
|
||||
@@ -12,6 +12,7 @@ require (
|
||||
github.com/42wim/httpsig v1.2.4 // indirect
|
||||
github.com/Microsoft/go-winio v0.6.2 // indirect
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/containerd/errdefs v1.0.0 // indirect
|
||||
github.com/containerd/errdefs/pkg v0.3.0 // indirect
|
||||
github.com/davidmz/go-pageant v1.0.2 // indirect
|
||||
@@ -21,11 +22,12 @@ require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/go-fed/httpsig v1.1.0 // indirect
|
||||
github.com/go-logr/logr v1.4.2 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/google/go-querystring v1.1.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/hashicorp/go-version v1.9.0 // indirect
|
||||
github.com/klauspost/compress v1.18.6 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
@@ -39,11 +41,11 @@ require (
|
||||
github.com/opencontainers/image-spec v1.1.1 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 // indirect
|
||||
go.opentelemetry.io/otel v1.35.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.35.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.35.0 // indirect
|
||||
go.opentelemetry.io/otel v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.44.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
golang.org/x/crypto v0.53.0 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
@@ -59,7 +61,10 @@ require (
|
||||
github.com/moby/moby/client v0.5.0
|
||||
github.com/nats-io/nats-server/v2 v2.14.3
|
||||
github.com/nats-io/nats.go v1.52.0
|
||||
github.com/samcharles93/NellDB v0.2.5
|
||||
github.com/samcharles93/ai-sdk v0.1.17
|
||||
github.com/traefik/yaegi v0.16.1
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
)
|
||||
|
||||
replace github.com/samcharles93/NellDB v0.2.5 => /work/apps/nell-engine
|
||||
@@ -8,6 +8,10 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op h1:Z/MZK75wC/NSrkgqeNIa7jexam9uWzhLmFTSCPI/kn0=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.0-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||
@@ -29,8 +33,8 @@ github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSw
|
||||
github.com/go-fed/httpsig v1.1.0 h1:9M+hb0jkEICD8/cAiNqEB66R87tTINszBRTjwjQzWcI=
|
||||
github.com/go-fed/httpsig v1.1.0/go.mod h1:RCMrTZvN1bJYtofsG4rd5NaO5obxQ5xBkdiS7xsT7bM=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/go-telegram/bot v1.18.0 h1:yQzv437DY42SYTPBY48RinAvwbmf1ox5QICskIYWCD8=
|
||||
@@ -48,10 +52,14 @@ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17k
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
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/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/go-version v1.9.0 h1:CeOIz6k+LoN3qX9Z0tyQrPtiB1DFYRPfCIBtaXPSCnA=
|
||||
github.com/hashicorp/go-version v1.9.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/hashicorp/mdns v1.0.7 h1:yWoQVMW5JOiDxQnIUcm3IDt0kCjf3TuXHDbdEKPsbAY=
|
||||
github.com/hashicorp/mdns v1.0.7/go.mod h1:yjuhYhZyPDqXXL48xC7cdpGwGUMwu7OViDmsuT5COvg=
|
||||
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
|
||||
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -60,6 +68,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
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/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
|
||||
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
@@ -68,6 +78,8 @@ github.com/moby/moby/api v1.55.0 h1:2/sexvQyqIWS8pRSCFddBfpW2qE7vR7FCL+vN8pxwMc=
|
||||
github.com/moby/moby/api v1.55.0/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||
github.com/moby/moby/client v0.5.0 h1:5XhyPk2fuOWf6RlSFa3MkIIgDZkF25xToXW8Q/BH7cc=
|
||||
github.com/moby/moby/client v0.5.0/go.mod h1:rcVpF8ncl9vo5gaIBdol6CnbEtSj1uxMvEV/UrykF/s=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.14.3 h1:+xjydPt7rkit67G+04TN0mcO2n+8nveZE7tK/PPV53A=
|
||||
@@ -88,30 +100,44 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
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/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=
|
||||
github.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=
|
||||
github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=
|
||||
github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=
|
||||
github.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=
|
||||
github.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/samcharles93/ai-sdk v0.1.17 h1:yH48jrYVyFv+VO1qYkbReVpVxP063XMs0T/Jb90bkEY=
|
||||
github.com/samcharles93/ai-sdk v0.1.17/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o=
|
||||
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/traefik/yaegi v0.16.1 h1:f1De3DVJqIDKmnasUF6MwmWv1dSEEat0wcpXhD2On3E=
|
||||
github.com/traefik/yaegi v0.16.1/go.mod h1:4eVhbPb3LnD2VigQjhYbEJ69vDRFdT2HQNrXx8eEwUY=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0 h1:sbiXRNDSWJOTobXh5HyQKjq6wUC5tNybqjIqDpAY4CU=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.60.0/go.mod h1:69uWxva0WgAA/4bu2Yy70SLDBwZXuQ6PbBpbsa5iZrQ=
|
||||
go.opentelemetry.io/otel v1.35.0 h1:xKWKPxrxB6OtMCbmMY021CqC45J+3Onta9MqjhnusiQ=
|
||||
go.opentelemetry.io/otel v1.35.0/go.mod h1:UEqy8Zp11hpkUrL73gSlELM0DupHoiq72dR+Zqel/+Y=
|
||||
go.opentelemetry.io/otel/metric v1.35.0 h1:0znxYu2SNyuMSQT4Y9WDWej0VpcsxkuklLa4/siN90M=
|
||||
go.opentelemetry.io/otel/metric v1.35.0/go.mod h1:nKVFgxBZ2fReX6IlyW28MgZojkoAkJGaE8CpgeAU3oE=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0 h1:iPctf8iprVySXSKJffSS79eOjl9pvxV9ZqOWT0QejKY=
|
||||
go.opentelemetry.io/otel/sdk v1.35.0/go.mod h1:+ga1bZliga3DxJ3CQGg3updiaAJoNECOgJREo9KHGQg=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0 h1:1RriWBmCKgkeHEhM7a2uMjMUfP7MsOF5JpUCaEqEI9o=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.35.0/go.mod h1:is6XYCUMpcKi+ZsOvfluY5YstFnhW0BidkR+gL+qN+w=
|
||||
go.opentelemetry.io/otel/trace v1.35.0 h1:dPpEfJu1sDIqruz7BHFG3c7528f6ddfSWfFDVt/xgMs=
|
||||
go.opentelemetry.io/otel/trace v1.35.0/go.mod h1:WUk7DtFp1Aw2MkvqGdwiXYDZZNvA/1J8o6xRXLrIkyc=
|
||||
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.66.0 h1:vkrK8PAznv2NKt2r+kdu252ccGzkEqLc2aSXbQIALYQ=
|
||||
go.opentelemetry.io/otel/exporters/prometheus v0.66.0/go.mod h1:V/UB6D3vMF/UBOL5igAsAYnk1nG/bzYYTzvsB16cy7o=
|
||||
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58=
|
||||
go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA=
|
||||
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
|
||||
@@ -121,6 +147,8 @@ golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||
golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
|
||||
golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
@@ -142,6 +170,8 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
@@ -36,7 +36,7 @@ import (
|
||||
|
||||
type Daemon struct {
|
||||
Cfg config.Config
|
||||
Store *store.Store
|
||||
Store store.TaskStore
|
||||
Forge forge.Forge
|
||||
Trees *worktree.Manager
|
||||
Runtime *runtime.Runtime
|
||||
|
||||
@@ -0,0 +1,921 @@
|
||||
// Package nell implements store.TaskStore on top of a NellDB log store.
|
||||
//
|
||||
// Tasks live in the "tasks" DocDB collection, keyed by
|
||||
// "<owner>:<repo>:<issue_number>". Events live in the "events" collection,
|
||||
// keyed by an auto-incrementing counter.
|
||||
//
|
||||
// Secondary indexes are not available — ClaimNext scans all tasks, and
|
||||
// lookups by task ID (Transition, Requeue, etc.) scan all tasks. This is
|
||||
// acceptable at the daemon's scale (tens to hundreds of tasks).
|
||||
package nell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/samcharles93/NellDB"
|
||||
"github.com/samcharles93/NellDB/logstore"
|
||||
"github.com/samcharles93/NellDB/sdk"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Adapter implements store.TaskStore backed by a NellDB store.
|
||||
type Adapter struct {
|
||||
store nell.Store // the underlying engine (LogStore or MemoryStore)
|
||||
tasks *sdk.DocDB // "tasks" collection
|
||||
events *sdk.DocDB // "events" collection
|
||||
nodeID string
|
||||
mu sync.Mutex // serialises ClaimNext, ClaimByIssue and atomic counter ops
|
||||
}
|
||||
|
||||
// ── Compile-time check ───────────────────────────────────────────────────────
|
||||
|
||||
var _ store.TaskStore = (*Adapter)(nil)
|
||||
|
||||
// ── Open / lifecycle ─────────────────────────────────────────────────────────
|
||||
|
||||
// OpenStore opens a persistent NellDB-backed TaskStore at the given file path.
|
||||
// Returns an error when path is empty.
|
||||
func OpenStore(path, nodeID string) (store.TaskStore, error) {
|
||||
if path == "" {
|
||||
return nil, errors.New("nell: path is required")
|
||||
}
|
||||
st, err := logstore.OpenLog(path, nodeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("nell: open log: %w", err)
|
||||
}
|
||||
return newAdapter(st, nodeID), nil
|
||||
}
|
||||
|
||||
// OpenMemory creates an in-memory TaskStore backed by nell.MemoryStore,
|
||||
// suitable for tests.
|
||||
func OpenMemory(nodeID string) store.TaskStore {
|
||||
return newAdapter(nell.NewMemoryStore(nodeID), nodeID)
|
||||
}
|
||||
|
||||
func newAdapter(st nell.Store, nodeID string) *Adapter {
|
||||
return &Adapter{
|
||||
store: st,
|
||||
tasks: sdk.New(st, nodeID, "tasks"),
|
||||
events: sdk.New(st, nodeID, "events"),
|
||||
nodeID: nodeID,
|
||||
}
|
||||
}
|
||||
|
||||
// Close shuts down the underlying store (flushes and closes the log file).
|
||||
func (a *Adapter) Close() error {
|
||||
return a.store.Close()
|
||||
}
|
||||
|
||||
// ── Task lifecycle ───────────────────────────────────────────────────────────
|
||||
|
||||
// EnqueueIssue inserts a new queued task; returns false if the issue is
|
||||
// already tracked (the idempotency key is owner/repo/number).
|
||||
func (a *Adapter) EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels string) (bool, error) {
|
||||
key := taskKey(owner, repo, number)
|
||||
|
||||
// Short-circuit if already tracked.
|
||||
existing, err := a.tasks.Get(ctx, key)
|
||||
if err != nil && !errors.Is(err, sdk.ErrNotFound) {
|
||||
return false, err
|
||||
}
|
||||
if err == nil {
|
||||
if status, _ := existing["status"].(string); status != "" {
|
||||
return false, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
a.mu.Lock()
|
||||
taskID, err := a.nextTaskID(ctx)
|
||||
a.mu.Unlock()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
doc := sdk.Doc{
|
||||
sdk.FieldID: key,
|
||||
"id": taskID,
|
||||
"owner": owner,
|
||||
"repo": repo,
|
||||
"issue_number": int64(number),
|
||||
"title": title,
|
||||
"body": body,
|
||||
"labels": labels,
|
||||
"status": store.StatusQueued,
|
||||
"workflow": "",
|
||||
"stage": "",
|
||||
"branch": "",
|
||||
"plan": "",
|
||||
"notes": "",
|
||||
"pr_number": int64(0),
|
||||
"tokens_used": int64(0),
|
||||
"iterations": int64(0),
|
||||
"attempt": int64(0),
|
||||
"park_reason": "",
|
||||
"retry_count": int64(0),
|
||||
"watch_comment_id": int64(0),
|
||||
"created_at": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
if _, err := a.tasks.Put(ctx, doc); err != nil {
|
||||
return false, fmt.Errorf("nell: enqueue: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// ClaimNext atomically moves the oldest queued task to running and returns
|
||||
// it; returns nil when the queue is empty.
|
||||
func (a *Adapter) ClaimNext(ctx context.Context) (*store.Task, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Scan for the oldest queued task (lowest task ID).
|
||||
var best *store.Task
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Status != store.StatusQueued {
|
||||
continue
|
||||
}
|
||||
if best == nil || t.ID < best.ID {
|
||||
best = t
|
||||
}
|
||||
}
|
||||
if best == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
best.Status = store.StatusRunning
|
||||
best.Attempt++
|
||||
if err := a.putTask(ctx, taskKey(best.Owner, best.Repo, best.IssueNumber), best); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return best, nil
|
||||
}
|
||||
|
||||
// ClaimByIssue atomically claims a queued task by owner/repo/issue_number.
|
||||
// Returns nil if the task is not in queued state.
|
||||
func (a *Adapter) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*store.Task, error) {
|
||||
key := taskKey(owner, repo, number)
|
||||
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
doc, err := a.tasks.Get(ctx, key)
|
||||
if err != nil {
|
||||
if errors.Is(err, sdk.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
t := docToTask(doc)
|
||||
if t.Status != store.StatusQueued {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
t.Status = store.StatusRunning
|
||||
t.Attempt++
|
||||
if err := a.putTask(ctx, key, t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// TaskByIssue returns the task tracking an issue, or nil.
|
||||
func (a *Adapter) TaskByIssue(ctx context.Context, owner, repo string, number int) (*store.Task, error) {
|
||||
doc, err := a.tasks.Get(ctx, taskKey(owner, repo, number))
|
||||
if err != nil {
|
||||
if errors.Is(err, sdk.ErrNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return docToTask(doc), nil
|
||||
}
|
||||
|
||||
// Transition moves a task to the given status.
|
||||
func (a *Adapter) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
|
||||
t, err := a.findTaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t == nil {
|
||||
return fmt.Errorf("nell: task %d not found", taskID)
|
||||
}
|
||||
t.Status = to
|
||||
return a.putTaskByID(ctx, t)
|
||||
}
|
||||
|
||||
// Update persists mutable task fields written by workflows.
|
||||
// Only writes the subset of fields that workflows are allowed to mutate:
|
||||
// workflow, stage, branch, plan, notes, pr_number, tokens_used,
|
||||
// iterations, park_reason, watch_comment_id. Status and identity fields
|
||||
// (owner, repo, issue_number, title, body, labels) are preserved.
|
||||
func (a *Adapter) Update(ctx context.Context, t *store.Task) error {
|
||||
key := taskKey(t.Owner, t.Repo, t.IssueNumber)
|
||||
doc, err := a.tasks.Get(ctx, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("nell: get task for update: %w", err)
|
||||
}
|
||||
// Copy only mutable fields — same set as the SQLite store's UPDATE.
|
||||
doc["workflow"] = t.Workflow
|
||||
doc["stage"] = t.Stage
|
||||
doc["branch"] = t.Branch
|
||||
doc["plan"] = t.Plan
|
||||
doc["notes"] = t.Notes
|
||||
doc["pr_number"] = int64(t.PRNumber)
|
||||
doc["tokens_used"] = int64(t.TokensUsed)
|
||||
doc["iterations"] = int64(t.Iterations)
|
||||
doc["park_reason"] = t.ParkReason
|
||||
doc["watch_comment_id"] = t.WatchCommentID
|
||||
if _, err := a.tasks.Put(ctx, doc); err != nil {
|
||||
return fmt.Errorf("nell: update task: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Requeue puts a task back on the queue with an optional workflow override.
|
||||
func (a *Adapter) Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error {
|
||||
t, err := a.findTaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t == nil {
|
||||
return fmt.Errorf("nell: task %d not found", taskID)
|
||||
}
|
||||
t.Status = store.StatusQueued
|
||||
if workflow != "" {
|
||||
t.Workflow = workflow
|
||||
}
|
||||
t.Stage = ""
|
||||
t.ParkReason = ""
|
||||
return a.putTaskByID(ctx, t)
|
||||
}
|
||||
|
||||
// RecoverStale re-queues all tasks left in "running" status. Returns the
|
||||
// number of tasks recovered.
|
||||
func (a *Adapter) RecoverStale(ctx context.Context) (int64, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
var count int64
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Status != store.StatusRunning {
|
||||
continue
|
||||
}
|
||||
t.Status = store.StatusQueued
|
||||
if err := a.putTask(ctx, row.ID, t); err != nil {
|
||||
return count, err
|
||||
}
|
||||
count++
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// IncrementRetryCount bumps the retry_count on a task.
|
||||
func (a *Adapter) IncrementRetryCount(ctx context.Context, taskID int64) error {
|
||||
t, err := a.findTaskByID(ctx, taskID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t == nil {
|
||||
return fmt.Errorf("nell: task %d not found", taskID)
|
||||
}
|
||||
t.RetryCount++
|
||||
return a.putTaskByID(ctx, t)
|
||||
}
|
||||
|
||||
// ── Queries ───────────────────────────────────────────────────────────────────
|
||||
|
||||
// WaitingTasks returns tasks in waiting_human state.
|
||||
func (a *Adapter) WaitingTasks(ctx context.Context) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []store.Task
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Status != store.StatusWaitingHuman {
|
||||
continue
|
||||
}
|
||||
out = append(out, *t)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// OpenPRs returns tasks in pr_open state.
|
||||
func (a *Adapter) OpenPRs(ctx context.Context) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []store.Task
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Status != store.StatusPROpen {
|
||||
continue
|
||||
}
|
||||
out = append(out, *t)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ClearTerminalTasks removes tasks in terminal status. Returns the count
|
||||
// of removed tasks.
|
||||
func (a *Adapter) ClearTerminalTasks(ctx context.Context) (int64, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var count int64
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
switch t.Status {
|
||||
case store.StatusMerged, store.StatusParked, store.StatusRejected, store.StatusClosedWontDo:
|
||||
if _, err := a.tasks.Remove(ctx, row.ID); err != nil {
|
||||
return count, err
|
||||
}
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count, nil
|
||||
}
|
||||
|
||||
// ── Observability ────────────────────────────────────────────────────────────
|
||||
|
||||
// InsertEvent appends an event to the events collection and returns its ID.
|
||||
func (a *Adapter) InsertEvent(ctx context.Context, e events.Event) (int64, error) {
|
||||
a.mu.Lock()
|
||||
defer a.mu.Unlock()
|
||||
|
||||
id, err := a.nextEventID(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
dataJSON := "{}"
|
||||
if len(e.Data) > 0 {
|
||||
b, mbErr := json.Marshal(e.Data)
|
||||
if mbErr != nil {
|
||||
dataJSON = fmt.Sprintf(`{"marshal_error":%q}`, mbErr.Error())
|
||||
} else {
|
||||
dataJSON = string(b)
|
||||
}
|
||||
}
|
||||
|
||||
doc := sdk.Doc{
|
||||
sdk.FieldID: fmt.Sprintf("event:%d", id),
|
||||
"id": id,
|
||||
"at": e.At.UTC().Format(time.RFC3339Nano),
|
||||
"kind": e.Kind,
|
||||
"task_id": e.TaskID,
|
||||
"repo": e.Repo,
|
||||
"issue": int64(e.Issue),
|
||||
"workflow": e.Workflow,
|
||||
"stage": e.Stage,
|
||||
"detail": clip(e.Detail, 4000),
|
||||
"data": dataJSON,
|
||||
}
|
||||
if _, err := a.events.Put(ctx, doc); err != nil {
|
||||
return 0, fmt.Errorf("nell: insert event: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
// EventsSince returns up to limit events with id > sinceID, oldest first.
|
||||
func (a *Adapter) EventsSince(ctx context.Context, sinceID int64, limit int) ([]events.Event, error) {
|
||||
all, err := a.events.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []events.Event
|
||||
for _, row := range all.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
e := docToEvent(row.Doc)
|
||||
if e.ID <= sinceID {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
if limit > 0 && len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RecentEvents returns the newest limit events, newest first.
|
||||
func (a *Adapter) RecentEvents(ctx context.Context, limit int) ([]events.Event, error) {
|
||||
all, err := a.events.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []events.Event
|
||||
for _, row := range all.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
e := docToEvent(row.Doc)
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
if limit > 0 && len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// TaskEvents returns a task's full event timeline, oldest first.
|
||||
func (a *Adapter) TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error) {
|
||||
all, err := a.events.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []events.Event
|
||||
for _, row := range all.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
e := docToEvent(row.Doc)
|
||||
if e.TaskID != taskID {
|
||||
continue
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID })
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Tasks returns all tasks, newest first (dashboard listing).
|
||||
func (a *Adapter) Tasks(ctx context.Context, limit int) ([]store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []store.Task
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
out = append(out, *t)
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool { return out[i].ID > out[j].ID })
|
||||
if limit > 0 && len(out) > limit {
|
||||
out = out[:limit]
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// StatusCounts returns task counts by status.
|
||||
func (a *Adapter) StatusCounts(ctx context.Context) (map[string]int, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
counts := map[string]int{}
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
counts[t.Status]++
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
// WorkflowStats aggregates outcomes and spend per workflow.
|
||||
func (a *Adapter) WorkflowStats(ctx context.Context) ([]store.WorkflowStat, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type acc struct {
|
||||
Runs int
|
||||
Merged int
|
||||
PROpen int
|
||||
Parked int
|
||||
SumTokens int
|
||||
SumSteps float64
|
||||
}
|
||||
agg := map[string]*acc{}
|
||||
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.Workflow == "" {
|
||||
continue
|
||||
}
|
||||
a, ok := agg[t.Workflow]
|
||||
if !ok {
|
||||
a = &acc{}
|
||||
agg[t.Workflow] = a
|
||||
}
|
||||
a.Runs++
|
||||
a.SumTokens += t.TokensUsed
|
||||
a.SumSteps += float64(t.Iterations)
|
||||
switch t.Status {
|
||||
case store.StatusMerged:
|
||||
a.Merged++
|
||||
case store.StatusPROpen:
|
||||
a.PROpen++
|
||||
case store.StatusParked:
|
||||
a.Parked++
|
||||
}
|
||||
}
|
||||
|
||||
// Deterministic ordering: most runs first, then by workflow name.
|
||||
keys := make([]string, 0, len(agg))
|
||||
for k := range agg {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if agg[keys[i]].Runs != agg[keys[j]].Runs {
|
||||
return agg[keys[i]].Runs > agg[keys[j]].Runs
|
||||
}
|
||||
return keys[i] < keys[j]
|
||||
})
|
||||
|
||||
stats := make([]store.WorkflowStat, 0, len(keys))
|
||||
for _, wf := range keys {
|
||||
a := agg[wf]
|
||||
avgTokens := 0
|
||||
avgSteps := 0.0
|
||||
if a.Runs > 0 {
|
||||
avgTokens = a.SumTokens / a.Runs
|
||||
avgSteps = a.SumSteps / float64(a.Runs)
|
||||
}
|
||||
stats = append(stats, store.WorkflowStat{
|
||||
Workflow: wf,
|
||||
Runs: a.Runs,
|
||||
Merged: a.Merged,
|
||||
PROpen: a.PROpen,
|
||||
Parked: a.Parked,
|
||||
AvgTokens: avgTokens,
|
||||
AvgSteps: avgSteps,
|
||||
TotalToken: a.SumTokens,
|
||||
})
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// StageStats aggregates stage_finish events — where time goes and which
|
||||
// stages fail.
|
||||
func (a *Adapter) StageStats(ctx context.Context) ([]store.StageStat, error) {
|
||||
all, err := a.events.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type stageKey struct {
|
||||
workflow, stage string
|
||||
}
|
||||
type acc struct {
|
||||
Runs int
|
||||
SumMs int
|
||||
Errors int
|
||||
}
|
||||
agg := map[stageKey]*acc{}
|
||||
|
||||
for _, row := range all.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
e := docToEvent(row.Doc)
|
||||
if e.Kind != events.KindStageFinish {
|
||||
continue
|
||||
}
|
||||
k := stageKey{workflow: e.Workflow, stage: e.Stage}
|
||||
a, ok := agg[k]
|
||||
if !ok {
|
||||
a = &acc{}
|
||||
agg[k] = a
|
||||
}
|
||||
a.Runs++
|
||||
if dur, _ := e.Data["duration_ms"].(float64); dur > 0 {
|
||||
a.SumMs += int(dur)
|
||||
}
|
||||
if errStr, _ := e.Data["error"].(string); errStr != "" {
|
||||
a.Errors++
|
||||
}
|
||||
}
|
||||
|
||||
keys := make([]stageKey, 0, len(agg))
|
||||
for k := range agg {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
if keys[i].workflow != keys[j].workflow {
|
||||
return keys[i].workflow < keys[j].workflow
|
||||
}
|
||||
return keys[i].stage < keys[j].stage
|
||||
})
|
||||
|
||||
stats := make([]store.StageStat, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
a := agg[k]
|
||||
avgMs := 0
|
||||
if a.Runs > 0 {
|
||||
avgMs = a.SumMs / a.Runs
|
||||
}
|
||||
stats = append(stats, store.StageStat{
|
||||
Workflow: k.workflow,
|
||||
Stage: k.stage,
|
||||
Runs: a.Runs,
|
||||
AvgMs: avgMs,
|
||||
Errors: a.Errors,
|
||||
})
|
||||
}
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// TokensByDay sums agent token spend per day from agent_finish events.
|
||||
func (a *Adapter) TokensByDay(ctx context.Context, days int) ([]store.DayTokens, error) {
|
||||
all, err := a.events.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
agg := map[string]int{}
|
||||
var dayKeys []string
|
||||
|
||||
for _, row := range all.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
e := docToEvent(row.Doc)
|
||||
if e.Kind != events.KindAgentFinish {
|
||||
continue
|
||||
}
|
||||
day := e.At.UTC().Format("2006-01-02")
|
||||
tokens := 0
|
||||
if t, ok := e.Data["tokens"].(float64); ok {
|
||||
tokens = int(t)
|
||||
}
|
||||
if _, seen := agg[day]; !seen {
|
||||
dayKeys = append(dayKeys, day)
|
||||
}
|
||||
agg[day] += tokens
|
||||
}
|
||||
|
||||
sort.Slice(dayKeys, func(i, j int) bool { return dayKeys[i] > dayKeys[j] }) // newest first
|
||||
if days > 0 && len(dayKeys) > days {
|
||||
dayKeys = dayKeys[:days]
|
||||
}
|
||||
|
||||
out := make([]store.DayTokens, len(dayKeys))
|
||||
for i, d := range dayKeys {
|
||||
out[i] = store.DayTokens{Day: d, Tokens: agg[d]}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// ── Internal helpers ─────────────────────────────────────────────────────────
|
||||
|
||||
// taskKey builds the composite Doc ID for a task.
|
||||
func taskKey(owner, repo string, number int) string {
|
||||
return fmt.Sprintf("%s:%s:%d", owner, repo, number)
|
||||
}
|
||||
|
||||
// isMetaKey returns true for internal meta documents (e.g. counters).
|
||||
func isMetaKey(key string) bool {
|
||||
return strings.HasPrefix(key, "meta:")
|
||||
}
|
||||
|
||||
// docToTask reconstructs a *store.Task from a Doc.
|
||||
func docToTask(doc sdk.Doc) *store.Task {
|
||||
return &store.Task{
|
||||
ID: intField(doc, "id"),
|
||||
Owner: strField(doc, "owner"),
|
||||
Repo: strField(doc, "repo"),
|
||||
IssueNumber: int(intField(doc, "issue_number")),
|
||||
Title: strField(doc, "title"),
|
||||
Body: strField(doc, "body"),
|
||||
Labels: strField(doc, "labels"),
|
||||
Status: strField(doc, "status"),
|
||||
Workflow: strField(doc, "workflow"),
|
||||
Stage: strField(doc, "stage"),
|
||||
Branch: strField(doc, "branch"),
|
||||
Plan: strField(doc, "plan"),
|
||||
Notes: strField(doc, "notes"),
|
||||
PRNumber: int(intField(doc, "pr_number")),
|
||||
TokensUsed: int(intField(doc, "tokens_used")),
|
||||
Iterations: int(intField(doc, "iterations")),
|
||||
Attempt: int(intField(doc, "attempt")),
|
||||
ParkReason: strField(doc, "park_reason"),
|
||||
RetryCount: int(intField(doc, "retry_count")),
|
||||
WatchCommentID: intField(doc, "watch_comment_id"),
|
||||
}
|
||||
}
|
||||
|
||||
// taskFields copies every mutable Task field into the Doc. It does not
|
||||
// touch _id or _rev so the caller can round-trip a live doc.
|
||||
func taskFields(t *store.Task, doc sdk.Doc) {
|
||||
doc["id"] = t.ID
|
||||
doc["owner"] = t.Owner
|
||||
doc["repo"] = t.Repo
|
||||
doc["issue_number"] = int64(t.IssueNumber)
|
||||
doc["title"] = t.Title
|
||||
doc["body"] = t.Body
|
||||
doc["labels"] = t.Labels
|
||||
doc["status"] = t.Status
|
||||
doc["workflow"] = t.Workflow
|
||||
doc["stage"] = t.Stage
|
||||
doc["branch"] = t.Branch
|
||||
doc["plan"] = t.Plan
|
||||
doc["notes"] = t.Notes
|
||||
doc["pr_number"] = int64(t.PRNumber)
|
||||
doc["tokens_used"] = int64(t.TokensUsed)
|
||||
doc["iterations"] = int64(t.Iterations)
|
||||
doc["attempt"] = int64(t.Attempt)
|
||||
doc["park_reason"] = t.ParkReason
|
||||
doc["retry_count"] = int64(t.RetryCount)
|
||||
doc["watch_comment_id"] = t.WatchCommentID
|
||||
}
|
||||
|
||||
// docToEvent reconstructs an events.Event from a Doc.
|
||||
func docToEvent(doc sdk.Doc) events.Event {
|
||||
e := events.Event{
|
||||
ID: intField(doc, "id"),
|
||||
Kind: strField(doc, "kind"),
|
||||
TaskID: intField(doc, "task_id"),
|
||||
Repo: strField(doc, "repo"),
|
||||
Issue: int(intField(doc, "issue")),
|
||||
Workflow: strField(doc, "workflow"),
|
||||
Stage: strField(doc, "stage"),
|
||||
Detail: strField(doc, "detail"),
|
||||
}
|
||||
if atStr := strField(doc, "at"); atStr != "" {
|
||||
e.At, _ = time.Parse(time.RFC3339Nano, atStr)
|
||||
}
|
||||
if dataStr := strField(doc, "data"); dataStr != "" {
|
||||
var data map[string]any
|
||||
if err := json.Unmarshal([]byte(dataStr), &data); err == nil {
|
||||
e.Data = data
|
||||
}
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// putTask performs a read-modify-write on a task document. It first reads
|
||||
// the current doc (to obtain the _rev for optimistic locking), stamps the
|
||||
// mutable fields from *store.Task, then writes it back.
|
||||
func (a *Adapter) putTask(ctx context.Context, key string, t *store.Task) error {
|
||||
doc, err := a.tasks.Get(ctx, key)
|
||||
if err != nil {
|
||||
if errors.Is(err, sdk.ErrNotFound) {
|
||||
doc = sdk.Doc{sdk.FieldID: key}
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
taskFields(t, doc)
|
||||
if _, err := a.tasks.Put(ctx, doc); err != nil {
|
||||
return fmt.Errorf("nell: put task: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// putTaskByID is a convenience wrapper that computes the key from the task.
|
||||
func (a *Adapter) putTaskByID(ctx context.Context, t *store.Task) error {
|
||||
return a.putTask(ctx, taskKey(t.Owner, t.Repo, t.IssueNumber), t)
|
||||
}
|
||||
|
||||
// findTaskByID scans all tasks and returns the one with the given internal
|
||||
// task ID. Returns nil without error when the ID is not found.
|
||||
func (a *Adapter) findTaskByID(ctx context.Context, taskID int64) (*store.Task, error) {
|
||||
result, err := a.tasks.AllDocs(ctx, sdk.DocRange{IncludeDocs: true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, row := range result.Rows {
|
||||
if row.Doc == nil || isMetaKey(row.ID) {
|
||||
continue
|
||||
}
|
||||
t := docToTask(row.Doc)
|
||||
if t.ID == taskID {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// ── Auto-increment counters ─────────────────────────────────────────────────
|
||||
|
||||
// nextTaskID atomically reads and increments the task ID counter.
|
||||
// Must be called under a.mu.
|
||||
func (a *Adapter) nextTaskID(ctx context.Context) (int64, error) {
|
||||
return a.nextCounter(ctx, a.tasks, "meta:task_id_counter")
|
||||
}
|
||||
|
||||
// nextEventID atomically reads and increments the event ID counter.
|
||||
// Must be called under a.mu.
|
||||
func (a *Adapter) nextEventID(ctx context.Context) (int64, error) {
|
||||
return a.nextCounter(ctx, a.events, "meta:event_id_counter")
|
||||
}
|
||||
|
||||
// nextCounter implements the read-modify-write for a counter doc.
|
||||
// Must be called under a.mu so that no two callers race on the _rev.
|
||||
func (a *Adapter) nextCounter(ctx context.Context, db *sdk.DocDB, metaKey string) (int64, error) {
|
||||
doc, err := db.Get(ctx, metaKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, sdk.ErrNotFound) {
|
||||
// First use: initialise to 2 (next call returns 1).
|
||||
doc = sdk.Doc{sdk.FieldID: metaKey, "next_id": int64(2)}
|
||||
if _, err := db.Put(ctx, doc); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return 1, nil
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
next := intField(doc, "next_id")
|
||||
doc["next_id"] = next + 1
|
||||
if _, err := db.Put(ctx, doc); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
|
||||
// ── Type-safe doc accessors ──────────────────────────────────────────────────
|
||||
|
||||
// strField extracts a string from a Doc by key. Returns "" when missing.
|
||||
func strField(doc sdk.Doc, key string) string {
|
||||
s, _ := doc[key].(string)
|
||||
return s
|
||||
}
|
||||
|
||||
// intField extracts an int64 from a Doc by key. JSON numbers round-trip as
|
||||
// float64 through the SDK's Doc map, so both float64 and int64 are handled.
|
||||
func intField(doc sdk.Doc, key string) int64 {
|
||||
switch v := doc[key].(type) {
|
||||
case float64:
|
||||
return int64(v)
|
||||
case int64:
|
||||
return v
|
||||
case int:
|
||||
return int64(v)
|
||||
case json.Number:
|
||||
n, _ := v.Int64()
|
||||
return n
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// clip truncates a string to at most n bytes, preserving full runes.
|
||||
func clip(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
pos := 0
|
||||
for pos < len(s) {
|
||||
_, size := utf8.DecodeRuneInString(s[pos:])
|
||||
if pos+size > n {
|
||||
break
|
||||
}
|
||||
pos += size
|
||||
}
|
||||
return s[:pos]
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
package nell
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
func openTest(t *testing.T) store.TaskStore {
|
||||
t.Helper()
|
||||
s, err := OpenStore(filepath.Join(t.TempDir(), "test.db"), "test-node")
|
||||
if err != nil {
|
||||
t.Fatalf("OpenStore: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := s.Close(); err != nil {
|
||||
t.Errorf("close: %v", err)
|
||||
}
|
||||
})
|
||||
return s
|
||||
}
|
||||
|
||||
func TestEnqueueIdempotent(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
ins, err := s.EnqueueIssue(ctx, "acme", "todo", 1, "add tests", "body", "widget")
|
||||
if err != nil || !ins {
|
||||
t.Fatalf("first enqueue = (%v, %v)", ins, err)
|
||||
}
|
||||
ins, err = s.EnqueueIssue(ctx, "acme", "todo", 1, "add tests", "body", "widget")
|
||||
if err != nil || ins {
|
||||
t.Fatalf("duplicate enqueue must be no-op, got (%v, %v)", ins, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClaimNextAndRecovery(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "todo", 7, "t", "", "archie,bug"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%v, %v)", task, err)
|
||||
}
|
||||
if task.Status != store.StatusRunning || task.Attempt != 1 {
|
||||
t.Fatalf("claimed task = %+v", task)
|
||||
}
|
||||
|
||||
// Only one queued task, next claim should be nil.
|
||||
if next, _ := s.ClaimNext(ctx); next != nil {
|
||||
t.Fatal("second claim must return nil while task is running")
|
||||
}
|
||||
|
||||
// Recovery.
|
||||
if n, err := s.RecoverStale(ctx); err != nil || n != 1 {
|
||||
t.Fatalf("recover = (%d, %v)", n, err)
|
||||
}
|
||||
task, err = s.ClaimNext(ctx)
|
||||
if err != nil || task == nil || task.Attempt != 2 {
|
||||
t.Fatalf("re-claim after recovery = (%+v, %v)", task, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransitionAndUpdate(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", 1, "t", "b", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.ClaimNext(ctx)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("claim = (%v, %v)", task, err)
|
||||
}
|
||||
|
||||
if err := s.Transition(ctx, task.ID, store.StatusRunning, store.StatusPROpen, "PR #3"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task.PRNumber = 3
|
||||
if err := s.Update(ctx, task); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
open, err := s.OpenPRs(ctx)
|
||||
if err != nil || len(open) != 1 || open[0].PRNumber != 3 {
|
||||
t.Fatalf("open PRs = (%+v, %v)", open, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEventRoundTrip(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
id1, err := s.InsertEvent(ctx, events.Event{Kind: "stage_start", TaskID: 1, Stage: "plan"})
|
||||
if err != nil || id1 == 0 {
|
||||
t.Fatalf("insert 1 = (%d, %v)", id1, err)
|
||||
}
|
||||
id2, err := s.InsertEvent(ctx, events.Event{
|
||||
Kind: "stage_finish", TaskID: 1, Workflow: "implement", Stage: "plan",
|
||||
Data: map[string]any{"duration_ms": float64(1200)},
|
||||
})
|
||||
if err != nil || id2 <= id1 {
|
||||
t.Fatalf("insert 2 = (%d, %v)", id2, err)
|
||||
}
|
||||
|
||||
evs, err := s.EventsSince(ctx, id1, 10)
|
||||
if err != nil || len(evs) != 1 || evs[0].Kind != "stage_finish" {
|
||||
t.Fatalf("EventsSince = (%+v, %v)", evs, err)
|
||||
}
|
||||
|
||||
timeline, err := s.TaskEvents(ctx, 1)
|
||||
if err != nil || len(timeline) != 2 {
|
||||
t.Fatalf("TaskEvents = (%d, %v)", len(timeline), err)
|
||||
}
|
||||
|
||||
stats, err := s.StageStats(ctx)
|
||||
if err != nil || len(stats) != 1 || stats[0].Stage != "plan" {
|
||||
t.Fatalf("StageStats = (%+v, %v)", stats, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatusCounts(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
for i := range 5 {
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "todo", i+1, "t", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
counts, err := s.StatusCounts(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts[store.StatusQueued] != 5 {
|
||||
t.Fatalf("expected 5 queued, got %d", counts[store.StatusQueued])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClearTerminalTasks(t *testing.T) {
|
||||
s := openTest(t)
|
||||
ctx := context.Background()
|
||||
|
||||
statuses := []string{store.StatusMerged, store.StatusParked, store.StatusRejected, store.StatusClosedWontDo, store.StatusQueued}
|
||||
for i, status := range statuses {
|
||||
if _, err := s.EnqueueIssue(ctx, "acme", "widget", i+1, "t", "b", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
task, err := s.TaskByIssue(ctx, "acme", "widget", i+1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("TaskByIssue(%d) = (%+v, %v)", i+1, task, err)
|
||||
}
|
||||
if status != store.StatusQueued {
|
||||
if err := s.Transition(ctx, task.ID, store.StatusQueued, status, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
n, err := s.ClearTerminalTasks(ctx)
|
||||
if err != nil || n != 4 {
|
||||
t.Fatalf("ClearTerminalTasks = (%d, %v), want (4, nil)", n, err)
|
||||
}
|
||||
|
||||
counts, err := s.StatusCounts(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counts[store.StatusQueued] != 1 {
|
||||
t.Fatalf("expected 1 queued, got %d", counts[store.StatusQueued])
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistenceAcrossRestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "test.db")
|
||||
ctx := context.Background()
|
||||
|
||||
// Write.
|
||||
s1, err := OpenStore(path, "node-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s1.EnqueueIssue(ctx, "acme", "todo", 1, "survive restart", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s1.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Reopen and verify.
|
||||
s2, err := OpenStore(path, "node-a")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s2.Close()
|
||||
|
||||
task, err := s2.TaskByIssue(ctx, "acme", "todo", 1)
|
||||
if err != nil || task == nil {
|
||||
t.Fatalf("data did not survive restart: (%+v, %v)", task, err)
|
||||
}
|
||||
if task.Title != "survive restart" {
|
||||
t.Fatalf("wrong title: %q", task.Title)
|
||||
}
|
||||
counts, err := s2.StatusCounts(ctx)
|
||||
if err != nil || counts[store.StatusQueued] != 1 {
|
||||
t.Fatalf("counts after restart = (%v, %v)", counts, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Package store defines the storage abstractions for archied's task and
|
||||
// event data. TaskStore is the full surface the daemon needs; *Store (SQLite)
|
||||
// and the nell adapter both satisfy it. Consumers depend on the interface,
|
||||
// never on a concrete backend.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
)
|
||||
|
||||
// TaskStore is the full store surface the daemon needs.
|
||||
// Every storage backend — SQLite, NellDB, future additions — implements this
|
||||
// interface. Consumers depend on TaskStore, never on a concrete type.
|
||||
type TaskStore interface {
|
||||
// ── Task lifecycle ──────────────────────────────────────────────
|
||||
|
||||
EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels string) (bool, error)
|
||||
ClaimNext(ctx context.Context) (*Task, error)
|
||||
ClaimByIssue(ctx context.Context, owner, repo string, number int) (*Task, error)
|
||||
TaskByIssue(ctx context.Context, owner, repo string, number int) (*Task, error)
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
Update(ctx context.Context, t *Task) error
|
||||
Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error
|
||||
RecoverStale(ctx context.Context) (int64, error)
|
||||
IncrementRetryCount(ctx context.Context, taskID int64) error
|
||||
|
||||
// ── Queries ─────────────────────────────────────────────────────
|
||||
|
||||
WaitingTasks(ctx context.Context) ([]Task, error)
|
||||
OpenPRs(ctx context.Context) ([]Task, error)
|
||||
ClearTerminalTasks(ctx context.Context) (int64, error)
|
||||
|
||||
// ── Observability ───────────────────────────────────────────────
|
||||
|
||||
InsertEvent(ctx context.Context, e events.Event) (int64, error)
|
||||
EventsSince(ctx context.Context, sinceID int64, limit int) ([]events.Event, error)
|
||||
RecentEvents(ctx context.Context, limit int) ([]events.Event, error)
|
||||
TaskEvents(ctx context.Context, taskID int64) ([]events.Event, error)
|
||||
Tasks(ctx context.Context, limit int) ([]Task, error)
|
||||
StatusCounts(ctx context.Context) (map[string]int, error)
|
||||
WorkflowStats(ctx context.Context) ([]WorkflowStat, error)
|
||||
StageStats(ctx context.Context) ([]StageStat, error)
|
||||
TokensByDay(ctx context.Context, days int) ([]DayTokens, error)
|
||||
|
||||
// ── Lifecycle ───────────────────────────────────────────────────
|
||||
|
||||
Close() error
|
||||
}
|
||||
|
||||
// WorkflowStore is the narrow subset of TaskStore that workflow stages call
|
||||
// mid-run. *Store, storerpc.Client, and the nell adapter all satisfy it.
|
||||
// This is the interface archie-agent uses via storerpc NATS proxy.
|
||||
type WorkflowStore interface {
|
||||
Update(ctx context.Context, t *Task) error
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
}
|
||||
|
||||
// Compile-time check: *Store satisfies TaskStore.
|
||||
var _ TaskStore = (*Store)(nil)
|
||||
|
||||
// Compile-time check: *Store satisfies WorkflowStore.
|
||||
var _ WorkflowStore = (*Store)(nil)
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package storerpc lets archie-agent (which does not hold a database
|
||||
// connection) mutate task state by calling back to archied over core NATS
|
||||
// request/reply, instead of the agent process needing direct SQLite access.
|
||||
// archied remains the sole owner of the store.Store.
|
||||
// archied remains the sole owner of the store.TaskStore.
|
||||
package storerpc
|
||||
|
||||
import (
|
||||
@@ -16,18 +16,18 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
// Subjects for the two store.Store methods workflow stages call mid-run.
|
||||
// Subjects for the two store.TaskStore methods workflow stages call mid-run.
|
||||
const (
|
||||
SubjectUpdate = "archie.store.update"
|
||||
SubjectTransition = "archie.store.transition"
|
||||
)
|
||||
|
||||
// UpdateRequest mirrors store.Store.Update's argument.
|
||||
// UpdateRequest mirrors store.TaskStore.Update's argument.
|
||||
type UpdateRequest struct {
|
||||
Task *store.Task `json:"task"`
|
||||
}
|
||||
|
||||
// TransitionRequest mirrors store.Store.Transition's arguments.
|
||||
// TransitionRequest mirrors store.TaskStore.Transition's arguments.
|
||||
type TransitionRequest struct {
|
||||
TaskID int64 `json:"task_id"`
|
||||
From string `json:"from"`
|
||||
@@ -40,9 +40,9 @@ type Response struct {
|
||||
natsrpc.Envelope
|
||||
}
|
||||
|
||||
// Server handles storerpc requests against the daemon's Store.
|
||||
// Server handles storerpc requests against the daemon's TaskStore.
|
||||
type Server struct {
|
||||
Store *store.Store
|
||||
Store store.TaskStore
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
@@ -78,15 +78,16 @@ func (s *Server) reply(msg *nats.Msg, err error) {
|
||||
}
|
||||
|
||||
// Client calls the storerpc Server from archie-agent's process.
|
||||
// It implements store.WorkflowStore (the narrow interface workflow stages
|
||||
// need — just Update + Transition), not the full store.TaskStore.
|
||||
type Client struct {
|
||||
Conn *nats.Conn
|
||||
// Timeout bounds each call when ctx has no deadline of its own.
|
||||
Timeout time.Duration
|
||||
Conn *nats.Conn
|
||||
Timeout time.Duration // bounds each call when ctx has no deadline
|
||||
}
|
||||
|
||||
func (c *Client) rpc() *natsrpc.Client { return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout} }
|
||||
|
||||
// Update calls store.Store.Update on the daemon over NATS request/reply.
|
||||
// Update calls store.TaskStore.Update on the daemon over NATS request/reply.
|
||||
func (c *Client) Update(ctx context.Context, task *store.Task) error {
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectUpdate, UpdateRequest{Task: task})
|
||||
if err != nil {
|
||||
@@ -95,7 +96,7 @@ func (c *Client) Update(ctx context.Context, task *store.Task) error {
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// Transition calls store.Store.Transition on the daemon over NATS request/reply.
|
||||
// Transition calls store.TaskStore.Transition on the daemon over NATS request/reply.
|
||||
func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
|
||||
req := TransitionRequest{TaskID: taskID, From: from, To: to, Detail: detail}
|
||||
resp, err := natsrpc.Call[Response](ctx, c.rpc(), SubjectTransition, req)
|
||||
@@ -104,3 +105,6 @@ func (c *Client) Transition(ctx context.Context, taskID int64, from, to, detail
|
||||
}
|
||||
return resp.Err()
|
||||
}
|
||||
|
||||
// Compile-time check: Client satisfies WorkflowStore.
|
||||
var _ store.WorkflowStore = (*Client)(nil)
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
var indexHTML []byte
|
||||
|
||||
type Server struct {
|
||||
Store *store.Store
|
||||
Store store.TaskStore
|
||||
Log *slog.Logger
|
||||
|
||||
mu sync.Mutex
|
||||
|
||||
@@ -29,14 +29,6 @@ type Forger interface {
|
||||
SetStateLabel(ctx context.Context, owner, repo string, number int, label string, knownLabels []string)
|
||||
}
|
||||
|
||||
// TaskStore is the subset of *store.Store that workflow stages call
|
||||
// mid-run. *store.Store (the daemon's real store) and storerpc.Client
|
||||
// (archie-agent's NATS-backed proxy) both satisfy it.
|
||||
type TaskStore interface {
|
||||
Update(ctx context.Context, t *store.Task) error
|
||||
Transition(ctx context.Context, taskID int64, from, to, detail string) error
|
||||
}
|
||||
|
||||
// Trees is the subset of *worktree.Manager that workflow stages call
|
||||
// mid-run. *worktree.Manager (the daemon's real manager, holding the push
|
||||
// token) and a hybrid RPC-backed implementation (archie-agent proxies
|
||||
@@ -58,7 +50,7 @@ type TaskContext struct {
|
||||
Repo config.Repo
|
||||
Cfg config.Config
|
||||
Forge Forger
|
||||
Store TaskStore
|
||||
Store store.WorkflowStore
|
||||
Trees Trees
|
||||
Agent agentexec.Runner
|
||||
Bus *events.Bus // nil-safe via Emit
|
||||
|
||||
Reference in new issue
Block a user