From 01acb97f96da4cc96881029bc03ded99e260d05f Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 17 Oct 2026 10:14:26 +1100 Subject: [PATCH] chore: delete code no binary or test reaches --- internal/app/controlplane/client.go | 5 - internal/config/config.go | 5 - internal/domain/drain/drain.go | 13 - internal/domain/image/contract.go | 145 ---------- internal/domain/image/registry.go | 76 ----- internal/domain/messaging/message.go | 5 - internal/domain/sampling/all.go | 19 -- internal/domain/sampling/contract.go | 47 ---- internal/domain/sampling/random.go | 32 --- internal/domain/sampling/recency.go | 32 --- internal/domain/sampling/staleness.go | 16 -- internal/domain/workflow/prreview/diff.go | 18 -- internal/domain/workflow/steps.go | 40 --- internal/domain/workflow/vocabulary.go | 14 - internal/domain/workintake/review_resolver.go | 22 -- internal/forgerpc/forgerpc.go | 8 - internal/infrastructure/access/live.go | 9 - .../infrastructure/embedding/embedding.go | 137 --------- internal/infrastructure/gatewayrpc/client.go | 3 +- .../infrastructure/gatewayrpc/store_client.go | 105 ------- internal/infrastructure/kit/kit.go | 18 -- internal/infrastructure/readiness/probes.go | 58 ---- internal/logging/reader.go | 64 ----- internal/pairing/atomic.go | 37 --- internal/pairing/code.go | 34 --- internal/pairing/hash.go | 49 ---- internal/pairing/store.go | 261 ------------------ internal/plugin/host.go | 13 - internal/taskstate/taskstate.go | 19 -- internal/tools/availability.go | 105 ------- internal/tools/disclosure.go | 35 --- internal/webui/api_chat.go | 4 - internal/webui/auth.go | 30 -- internal/worktreerpc/worktreerpc.go | 6 - 34 files changed, 1 insertion(+), 1483 deletions(-) delete mode 100644 internal/domain/image/contract.go delete mode 100644 internal/domain/image/registry.go delete mode 100644 internal/domain/sampling/all.go delete mode 100644 internal/domain/sampling/contract.go delete mode 100644 internal/domain/sampling/random.go delete mode 100644 internal/domain/sampling/recency.go delete mode 100644 internal/domain/sampling/staleness.go delete mode 100644 internal/infrastructure/embedding/embedding.go delete mode 100644 internal/pairing/atomic.go delete mode 100644 internal/pairing/code.go delete mode 100644 internal/pairing/hash.go delete mode 100644 internal/pairing/store.go delete mode 100644 internal/tools/availability.go diff --git a/internal/app/controlplane/client.go b/internal/app/controlplane/client.go index c1f417caa..2c6d5258a 100644 --- a/internal/app/controlplane/client.go +++ b/internal/app/controlplane/client.go @@ -26,11 +26,6 @@ type Client struct { ApplyStatus *applystatus.Reporter } -// NewClient dials the control plane over an existing connection. -func NewClient(conn grpc.ClientConnInterface) *Client { - return &Client{rpc: pb.NewControlPlaneServiceClient(conn)} -} - // NewRPCClient wraps an already-constructed generated client. func NewRPCClient(client pb.ControlPlaneServiceClient) *Client { return &Client{Client: controlplanerpc.NewRPCClient(client), rpc: client} diff --git a/internal/config/config.go b/internal/config/config.go index 65802ca64..bdd153b3e 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -493,11 +493,6 @@ type TaskConfig struct { Review Review `json:"review"` } -// DiffCapOf returns a DiffCapLines value for n. -// -//go:fix inline -func DiffCapOf(n int) *int { return new(n) } - // DiffCap returns the changed-line cap; 0 means no cap. func (c Config) DiffCap() int { if c.DiffCapLines == nil { diff --git a/internal/domain/drain/drain.go b/internal/domain/drain/drain.go index 56fac1a20..17e88fdd4 100644 --- a/internal/domain/drain/drain.go +++ b/internal/domain/drain/drain.go @@ -55,19 +55,6 @@ const ( DecisionValid ) -func (d Decision) String() string { - switch d { - case DecisionNone: - return "none" - case DecisionStale: - return "stale" - case DecisionValid: - return "valid" - default: - return "unknown" - } -} - // Decide returns the decision for marker. Nil means none; an empty current // epoch or a mismatched marker is stale. func Decide(current Epoch, marker *Marker) Decision { diff --git a/internal/domain/image/contract.go b/internal/domain/image/contract.go deleted file mode 100644 index 6525f7b51..000000000 --- a/internal/domain/image/contract.go +++ /dev/null @@ -1,145 +0,0 @@ -// Package image defines the image generation provider contract. -package image - -import ( - "context" - "errors" - "time" -) - -// Sentinel errors every provider wraps with fmt.Errorf("%w: %s", ...) so -// callers can errors.Is regardless of backend. -var ( - // ErrUnavailable means the provider cannot serve right now (missing - // credential, backend down). Per the epic: this must degrade the - // capability to a reported error, never prevent Archie from starting - // or break text chat. - ErrUnavailable = errors.New("image provider unavailable") - // ErrUnsupported means the request needs a capability (e.g. Edit, or - // Mask) the provider does not declare. - ErrUnsupported = errors.New("image capability unsupported by provider") - // ErrInputTooLarge means an input image exceeded a limit the provider - // itself enforces. Caller-side limits are the routing layer's concern, - // not this contract's — see the design doc. - ErrInputTooLarge = errors.New("image input exceeds configured limit") - // ErrTimeout means the provider's own deadline elapsed, distinct from - // the caller's ctx being canceled. - ErrTimeout = errors.New("image request timed out") - // ErrCanceled means the caller's ctx was canceled. - ErrCanceled = errors.New("image request canceled") -) - -// ProviderClass distinguishes hosted (spends money/quota per call) from -// local (spends host GPU/time). Selection and config validation key off -// this, never off Name, so a new provider cannot silently slip through the -// hosted-cost gate under an unrecognized name. -type ProviderClass string - -const ( - ClassHosted ProviderClass = "hosted" - ClassLocal ProviderClass = "local" -) - -// Capability declares what one provider supports, discoverable before a -// request is built so a caller can reject an unsupported combination (e.g. -// edit-with-mask on a generate-only provider) instead of sending it and -// parsing a provider-specific error back out. -type Capability struct { - Generate bool - // Edit requires at least one input image. MaxInputs bounds how many. - Edit bool - MaxInputs int - // Mask reports whether Edit supports restricting the edited region to - // a mask image. - Mask bool - // Sizes lists provider-declared output sizes (e.g. "1024x1024"). Empty - // means the provider does not constrain size. - Sizes []string -} - -// Validate checks that a declared Capability is internally consistent: -// Edit implies at least one allowed input, and Mask cannot be declared -// without Edit. -func (c Capability) Validate() error { - if c.Edit && c.MaxInputs < 1 { - return errors.New("image capability: edit requires MaxInputs >= 1") - } - if c.Mask && !c.Edit { - return errors.New("image capability: mask requires edit") - } - return nil -} - -// ImageData carries image bytes in-process, never a path or URL: the -// domain layer must not assume a filesystem or a fetchable location. -type ImageData struct { - Bytes []byte - MIMEType string -} - -// GenerateRequest asks a provider to create images from a prompt alone. -type GenerateRequest struct { - Prompt string - // Size is a provider-declared value from Capability.Sizes, or "" for - // the provider's default. - Size string - // N is the number of images requested. Zero means 1. - N int - // Options carries provider-specific overflow (e.g. "quality"), - // deliberately untyped so the contract does not grow a field per - // provider. - Options map[string]string -} - -// Validate checks the fields every provider needs regardless of backend. -func (r GenerateRequest) Validate() error { - if r.Prompt == "" { - return errors.New("image generate request: prompt must not be empty") - } - return nil -} - -// EditRequest asks a provider to edit one or more input images per a -// prompt, optionally restricted to a masked region. -type EditRequest struct { - Prompt string - Inputs []ImageData - // Mask restricts the edited region. Only valid when the provider's - // Capability.Mask is true. - Mask *ImageData - Size string - N int - - Options map[string]string -} - -// Validate checks the fields every provider needs regardless of backend. -// Capability-specific bounds (MaxInputs, Mask support) are the provider's -// own responsibility to enforce against its declared Capability. -func (r EditRequest) Validate() error { - if r.Prompt == "" { - return errors.New("image edit request: prompt must not be empty") - } - if len(r.Inputs) == 0 { - return errors.New("image edit request: at least one input image is required") - } - return nil -} - -// Result is what a provider returns from Generate or Edit. -type Result struct { - Images []ImageData - Provider string - Model string - CreatedAt time.Time -} - -// Provider is the typed contract every image backend implements — hosted -// (gpt-image-2-class) or local (GPU recipe). -type Provider interface { - Name() string - Class() ProviderClass - Capability() Capability - Generate(ctx context.Context, req GenerateRequest) (Result, error) - Edit(ctx context.Context, req EditRequest) (Result, error) -} diff --git a/internal/domain/image/registry.go b/internal/domain/image/registry.go deleted file mode 100644 index 77faa35ca..000000000 --- a/internal/domain/image/registry.go +++ /dev/null @@ -1,76 +0,0 @@ -package image - -import ( - "errors" - "fmt" - "maps" - "slices" - "sync" - - "github.com/samcharles93/archie-core/internal/domain/lifecycle" -) - -// ErrDuplicate is returned when a provider name is already registered. -var ErrDuplicate = errors.New("duplicate image provider") - -// Registry is the image family owner: registration and discovery only. A -// Provider is call-scoped (see package doc), so unlike curator's and -// memory's registries there is no Start/Health/Stop to orchestrate here. -type Registry struct { - mu sync.RWMutex - providers map[string]Provider -} - -// NewRegistry builds an empty provider registry. -func NewRegistry() *Registry { - return &Registry{providers: make(map[string]Provider)} -} - -// Register validates the provider's declared capability and adds it. -// Registration fails on a nil provider, an invalid Capability, or a -// duplicate name. -func (r *Registry) Register(p Provider) error { - if lifecycle.IsNil(p) { - return errors.New("image: nil provider") - } - if err := p.Capability().Validate(); err != nil { - return err - } - - r.mu.Lock() - defer r.mu.Unlock() - if _, dup := r.providers[p.Name()]; dup { - return fmt.Errorf("%w: %s", ErrDuplicate, p.Name()) - } - r.providers[p.Name()] = p - return nil -} - -// Get returns the registered provider by name. -func (r *Registry) Get(name string) (Provider, bool) { - r.mu.RLock() - defer r.mu.RUnlock() - p, ok := r.providers[name] - return p, ok -} - -// Names returns every registered provider name, sorted. -func (r *Registry) Names() []string { - r.mu.RLock() - defer r.mu.RUnlock() - return slices.Sorted(maps.Keys(r.providers)) -} - -// ByClass returns the sorted names of registered providers matching class. -func (r *Registry) ByClass(class ProviderClass) []string { - r.mu.RLock() - defer r.mu.RUnlock() - var names []string - for name, p := range r.providers { - if p.Class() == class { - names = append(names, name) - } - } - slices.Sort(names) - return names -} diff --git a/internal/domain/messaging/message.go b/internal/domain/messaging/message.go index a2d657518..f8a895dfd 100644 --- a/internal/domain/messaging/message.go +++ b/internal/domain/messaging/message.go @@ -56,11 +56,6 @@ type Conversation struct { CreatedAt time.Time } -// IsBranch reports whether this Conversation was forked from another. -func (c Conversation) IsBranch() bool { - return c.ParentConversationID != ConversationID{} -} - // Message is one immutable, persisted turn in a Conversation. type Message struct { ID MessageID diff --git a/internal/domain/sampling/all.go b/internal/domain/sampling/all.go deleted file mode 100644 index be23f7f41..000000000 --- a/internal/domain/sampling/all.go +++ /dev/null @@ -1,19 +0,0 @@ -package sampling - -import "context" - -// allSampler is the "all" strategy: no filtering, returns every candidate -// in input order, truncated to Request.Cap. -type allSampler struct{} - -// NewAll builds the "all" strategy. -func NewAll() Sampler { return allSampler{} } - -func (allSampler) Name() string { return "all" } - -func (allSampler) Sample(_ context.Context, candidates []Candidate, req Request) ([]Candidate, error) { - n := effectiveCap(req.Cap, len(candidates)) - out := make([]Candidate, n) - copy(out, candidates[:n]) - return out, nil -} diff --git a/internal/domain/sampling/contract.go b/internal/domain/sampling/contract.go deleted file mode 100644 index f249cb0a4..000000000 --- a/internal/domain/sampling/contract.go +++ /dev/null @@ -1,47 +0,0 @@ -// Package sampling is the curator sampler family: given a bounded set of -// candidates, pick a subset to spend a curator pass's agentic budget on. The -// embedding-backed surprisal strategy is a separate, deferred consumer of this -// same interface -- it does not live here. -package sampling - -import ( - "context" - "time" -) - -// Candidate is an item eligible for sampling. -type Candidate struct { - ID string - At time.Time - Metadata map[string]any -} - -// Request carries the knobs every strategy shares: a selection cap and a -// deterministic seed. Both are optional -- Cap 0 (or negative) means -// unlimited (the "all" strategy relies on this), Seed 0 is a valid seed, -// not "unset". -type Request struct { - Cap int - Seed int64 -} - -// Sampler selects candidates for a curator pass. Implementations must be -// deterministic. -type Sampler interface { - // Name identifies the strategy for logging/attribution (e.g. - // "recency", "random", "all", "staleness", later "surprisal"). - Name() string - // Sample selects from candidates per req. Implementations must not - // mutate candidates or rely on anything but candidates and req -- - // determinism depends on that. - Sample(ctx context.Context, candidates []Candidate, req Request) ([]Candidate, error) -} - -// effectiveCap resolves req.Cap against n candidates: zero, negative, or -// larger than n means unlimited (every candidate); otherwise req.Cap. -func effectiveCap(reqCap, n int) int { - if reqCap <= 0 || reqCap > n { - return n - } - return reqCap -} diff --git a/internal/domain/sampling/random.go b/internal/domain/sampling/random.go deleted file mode 100644 index eda838db9..000000000 --- a/internal/domain/sampling/random.go +++ /dev/null @@ -1,32 +0,0 @@ -package sampling - -import ( - "context" - "math/rand/v2" -) - -// randomSampler is the "random" strategy: a uniform random subset, seeded -// per call from Request.Seed so the same (candidates, req) pair always -// produces the same selection -- a package-level or struct-level generator -// would not give that guarantee under concurrent or repeated calls. -type randomSampler struct{} - -// NewRandom builds the "random" strategy. -func NewRandom() Sampler { return randomSampler{} } - -func (randomSampler) Name() string { return "random" } - -func (randomSampler) Sample(_ context.Context, candidates []Candidate, req Request) ([]Candidate, error) { - if len(candidates) == 0 { - return nil, nil - } - n := effectiveCap(req.Cap, len(candidates)) - seed := uint64(req.Seed) // deterministic seeding, not a security boundary - rng := rand.New(rand.NewPCG(seed, seed)) - order := rng.Perm(len(candidates)) - out := make([]Candidate, n) - for i := range n { - out[i] = candidates[order[i]] - } - return out, nil -} diff --git a/internal/domain/sampling/recency.go b/internal/domain/sampling/recency.go deleted file mode 100644 index 6ddcee088..000000000 --- a/internal/domain/sampling/recency.go +++ /dev/null @@ -1,32 +0,0 @@ -package sampling - -import ( - "context" - "slices" -) - -// recencySampler is the "recency" strategy: prefers more recently -// created/updated content, i.e. the largest Candidate.At first. -type recencySampler struct{} - -// NewRecency builds the "recency" strategy. -func NewRecency() Sampler { return recencySampler{} } - -func (recencySampler) Name() string { return "recency" } - -func (recencySampler) Sample(_ context.Context, candidates []Candidate, req Request) ([]Candidate, error) { - sorted := sortByTime(candidates, true) - return sorted[:effectiveCap(req.Cap, len(sorted))], nil -} - -// sortByTime returns a stably sorted copy of candidates by At. -func sortByTime(candidates []Candidate, newestFirst bool) []Candidate { - sorted := append([]Candidate(nil), candidates...) - slices.SortStableFunc(sorted, func(a, b Candidate) int { - if newestFirst { - return b.At.Compare(a.At) - } - return a.At.Compare(b.At) - }) - return sorted -} diff --git a/internal/domain/sampling/staleness.go b/internal/domain/sampling/staleness.go deleted file mode 100644 index f96733906..000000000 --- a/internal/domain/sampling/staleness.go +++ /dev/null @@ -1,16 +0,0 @@ -package sampling - -import "context" - -// stalenessSampler prefers the oldest Candidate.At. -type stalenessSampler struct{} - -// NewStaleness builds the "staleness" strategy. -func NewStaleness() Sampler { return stalenessSampler{} } - -func (stalenessSampler) Name() string { return "staleness" } - -func (stalenessSampler) Sample(_ context.Context, candidates []Candidate, req Request) ([]Candidate, error) { - sorted := sortByTime(candidates, false) - return sorted[:effectiveCap(req.Cap, len(sorted))], nil -} diff --git a/internal/domain/workflow/prreview/diff.go b/internal/domain/workflow/prreview/diff.go index 6bdf06af7..34f251c43 100644 --- a/internal/domain/workflow/prreview/diff.go +++ b/internal/domain/workflow/prreview/diff.go @@ -548,24 +548,6 @@ func AddedLines(files []FileChange) []AddedLine { return added } -// MapLine maps a line of the file a change produces onto the diff: a line the -// change added, a line a hunk quotes as context, or a line no hunk contains. -func MapLine(files []FileChange, path string, line int) LineKind { - for _, file := range files { - if file.Path != path { - continue - } - for _, hunk := range file.Hunks { - for _, placed := range hunk.positions() { - if placed.Line == line { - return placed.Kind - } - } - } - } - return LineOutside -} - // SummarizeFiles computes the aggregate statistics of a parsed change. func SummarizeFiles(files []FileChange) DiffStats { stats := DiffStats{TotalFiles: len(files)} diff --git a/internal/domain/workflow/steps.go b/internal/domain/workflow/steps.go index 4d98d410d..482ced8f2 100644 --- a/internal/domain/workflow/steps.go +++ b/internal/domain/workflow/steps.go @@ -125,46 +125,6 @@ func prepareWorktreeStage(name string, target func(*TaskContext) (PrepareTarget, }} } -// StageCommit commits everything in the worktree without pushing -- -// used mid-workflow so a PR tells its story in multiple commits (TDD: -// failing tests first, fix second). An empty tree parks. -func StageCommit(name string, message func(*TaskContext) string) Stage { - return Stage{Name: name, Run: func(ctx context.Context, tc *TaskContext) error { - changed, err := tc.Trees.CommitAll(ctx, tc.Dir, message(tc)) - if err != nil { - return err - } - if !changed { - return fmt.Errorf("worktree has no changes to commit") - } - tc.captureChanges(ctx, capturedAfterCommit) - return nil - }} -} - -// StageCommitPush commits the worktree and pushes the branch. With no changes -// it closes the issue with a comment, unless a baseline fix was committed, in -// which case it still pushes. -func StageCommitPush(message func(*TaskContext) string) Stage { - return Stage{Name: "commit-push", Run: func(ctx context.Context, tc *TaskContext) error { - if tc.BuildNoChanges { - return closeNoChangesIssue(ctx, tc) - } - changed, err := tc.Trees.CommitAll(ctx, tc.Dir, message(tc)) - if err != nil { - return err - } - if !changed && !tc.BaselineFixed { - return fmt.Errorf("worktree has no changes to commit") - } - if err := tc.Trees.Push(ctx, tc.Dir, tc.Branch); err != nil { - return err - } - tc.captureChanges(ctx, capturedAfterCommitPush) - return nil - }} -} - func closeNoChangesIssue(ctx context.Context, tc *TaskContext) error { if !tc.Task.IsForgeBacked() { tc.Outcome = Outcome{Status: StatusCompleted, Detail: "completed -- no changes required"} diff --git a/internal/domain/workflow/vocabulary.go b/internal/domain/workflow/vocabulary.go index 894db4d05..87a3020f7 100644 --- a/internal/domain/workflow/vocabulary.go +++ b/internal/domain/workflow/vocabulary.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "maps" - "slices" "sync" "github.com/samcharles93/archie-core/internal/domain/lifecycle" @@ -119,16 +118,3 @@ func (m *Manager) Settings() map[string]any { defer m.mu.Unlock() return maps.Clone(m.settings) } - -// StepTypes returns every registered step type name, sorted. -func (m *Manager) StepTypes() []string { - registry := m.Registry() - return slices.Sorted(maps.Keys(registry)) -} - -// Providers returns the registered provider names, sorted. -func (m *Manager) Providers() []string { - m.mu.Lock() - defer m.mu.Unlock() - return slices.Sorted(slices.Values(m.providers)) -} diff --git a/internal/domain/workintake/review_resolver.go b/internal/domain/workintake/review_resolver.go index 60439ed97..a3c4fa264 100644 --- a/internal/domain/workintake/review_resolver.go +++ b/internal/domain/workintake/review_resolver.go @@ -2,7 +2,6 @@ package workintake import ( "context" - "sync/atomic" workflowtask "github.com/samcharles93/archie-core/internal/domain/workflow/task" ) @@ -11,24 +10,3 @@ import ( type ReviewTaskLookup interface { OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflowtask.Task, error) } - -// ReviewTaskResolver admits only reactions for live Archie-owned pull requests. -type ReviewTaskResolver struct { - Tasks ReviewTaskLookup - dropped atomic.Int64 -} - -// Resolve returns the live task that owns reaction's pull request. -func (r *ReviewTaskResolver) Resolve(ctx context.Context, reaction ReviewCommentEnvelope) (*workflowtask.Task, error) { - task, err := r.Tasks.OpenTaskByPR(ctx, reaction.Owner, reaction.Repo, reaction.PRNumber) - if err != nil { - return nil, err - } - if task == nil { - r.dropped.Add(1) - } - return task, nil -} - -// Dropped reports how many reactions did not resolve to a live owned task. -func (r *ReviewTaskResolver) Dropped() int64 { return r.dropped.Load() } diff --git a/internal/forgerpc/forgerpc.go b/internal/forgerpc/forgerpc.go index ad0042ccf..28a9ddefc 100644 --- a/internal/forgerpc/forgerpc.go +++ b/internal/forgerpc/forgerpc.go @@ -152,14 +152,6 @@ type Server struct { Log *slog.Logger } -// Register subscribes all handlers on nc under the root (identity-less) -// subjects. RegisterFor(nc, identity) registers the same handlers under -// that identity's scoped subjects; the daemon calls it once per identity -// so container-mode tasks route to their own forge client. -func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) { - return s.RegisterFor(nc, "") -} - // RegisterFor registers all handlers under the subjects scoped to identity. func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) { as := func(h func(string, *nats.Msg)) nats.MsgHandler { diff --git a/internal/infrastructure/access/live.go b/internal/infrastructure/access/live.go index 6cb912568..1aaab53bc 100644 --- a/internal/infrastructure/access/live.go +++ b/internal/infrastructure/access/live.go @@ -19,15 +19,6 @@ type Live struct { engine atomic.Pointer[Engine] } -// NewLive builds the first engine from load. -func NewLive(ctx context.Context, load func(context.Context) ([]access.Policy, error), log *slog.Logger) (*Live, error) { - l := NewPending(load, log) - if err := l.Reload(ctx); err != nil { - return nil, err - } - return l, nil -} - // NewPending returns a chain whose engine refuses every request until Run or // Reload loads the stored policies, so a process that starts before its State // Store is closed rather than opened. diff --git a/internal/infrastructure/embedding/embedding.go b/internal/infrastructure/embedding/embedding.go deleted file mode 100644 index 3e093b87f..000000000 --- a/internal/infrastructure/embedding/embedding.go +++ /dev/null @@ -1,137 +0,0 @@ -// Package embedding implements the internal/domain/embedding.Client -// contract over the ai-sdk provider SDKs already vendored for chat, so -// this capability is config-driven the same way chat model roles already -// are (a providers table + a role in [models]). -package embedding - -import ( - "context" - "fmt" - "net/http" - "os" - "strings" - "time" - - sdkembed "github.com/samcharles93/ai-sdk/embed" - "github.com/samcharles93/ai-sdk/provider/cohere" - "github.com/samcharles93/ai-sdk/provider/gemini" - "github.com/samcharles93/ai-sdk/provider/mistral" - "github.com/samcharles93/ai-sdk/provider/ollama" - "github.com/samcharles93/ai-sdk/provider/openai" - - "github.com/samcharles93/archie-core/internal/config" - domainembedding "github.com/samcharles93/archie-core/internal/domain/embedding" -) - -// DefaultTimeout bounds one embedding request when Options.Timeout is -// unset. -const DefaultTimeout = 30 * time.Second - -// Options configures New. -type Options struct { - // Getenv resolves a provider's APIKeyEnv to its credential. Defaults to - // os.Getenv; overridable for tests. - Getenv func(string) string - // Timeout bounds one embedding request. Defaults to DefaultTimeout. - Timeout time.Duration -} - -// New builds an embedding client from the embedding model alias and its provider. It -// returns (nil, false) when unavailable. Provider secrets must already be -// resolved. -func New(cfg config.Config, opts Options) (domainembedding.Client, bool) { - getenv := opts.Getenv - if getenv == nil { - getenv = os.Getenv - } - timeout := opts.Timeout - if timeout <= 0 { - timeout = DefaultTimeout - } - - ref, err := config.ResolveModel(cfg.Models, "", config.PurposeEmbedding) - if err != nil { - return nil, false - } - providerID, modelID, ok := parseModelRef(ref) - if !ok { - return nil, false - } - provider, ok := cfg.Providers[providerID] - if !ok { - return nil, false - } - - apiKey := "" - if provider.APIKeyEnv != "" { - apiKey = strings.TrimSpace(getenv(provider.APIKeyEnv)) - if apiKey == "" { - return nil, false - } - } - - sdkProvider, err := newSDKProvider(provider.Class, apiKey, provider.BaseURL, &http.Client{Timeout: timeout}) - if err != nil { - return nil, false - } - return &client{provider: sdkembed.NewClient(sdkProvider), model: modelID}, true -} - -// parseModelRef splits a "provider/model" role value the same way -// ai-sdk/runtime.Runtime.ParseModelRef does, without depending on a -// Runtime instance. -func parseModelRef(ref string) (providerID, modelID string, ok bool) { - ref = strings.TrimSpace(ref) - if ref == "" { - return "", "", false - } - providerID, modelID, hasSlash := strings.Cut(ref, "/") - providerID, modelID = strings.TrimSpace(providerID), strings.TrimSpace(modelID) - if !hasSlash || providerID == "" || modelID == "" { - return "", "", false - } - return providerID, modelID, true -} - -// newSDKProvider builds the ai-sdk embed provider for class. Unsupported -// classes, including azure, return an error. -func newSDKProvider(class, apiKey, baseURL string, httpClient *http.Client) (sdkembed.Provider, error) { - switch class { - case "openai", "openai-compatible": - return openai.New(openai.Config{APIKey: apiKey, BaseURL: baseURL, HTTPClient: httpClient}) - case "gemini": - return gemini.New(gemini.Config{APIKey: apiKey, BaseURL: baseURL, HTTPClient: httpClient}) - case "ollama": - return ollama.New(ollama.Config{BaseURL: baseURL, HTTPClient: httpClient}), nil - case "cohere": - return cohere.New(cohere.Config{APIKey: apiKey, BaseURL: baseURL, HTTPClient: httpClient}) - case "mistral": - return mistral.New(mistral.Config{APIKey: apiKey, BaseURL: baseURL, HTTPClient: httpClient}) - default: - return nil, fmt.Errorf("embedding: provider class %q does not support embeddings", class) - } -} - -// client adapts an ai-sdk embed.Client to domainembedding.Client. -type client struct { - provider *sdkembed.Client - model string -} - -func (c *client) Embed(ctx context.Context, texts []string) ([]domainembedding.Vector, error) { - if len(texts) == 0 { - return nil, domainembedding.ErrEmptyInput - } - resp, err := c.provider.Embed(ctx, sdkembed.Request{Model: c.model, Inputs: texts}) - if err != nil { - return nil, fmt.Errorf("embedding: %w", err) - } - vectors := make([]domainembedding.Vector, len(texts)) - for _, e := range resp.Embeddings { - if e.Index < 0 || e.Index >= len(vectors) { - continue - } - vectors[e.Index] = domainembedding.Vector(e.Vector) - } - return vectors, nil -} diff --git a/internal/infrastructure/gatewayrpc/client.go b/internal/infrastructure/gatewayrpc/client.go index d3b60d89e..6f1b0088f 100644 --- a/internal/infrastructure/gatewayrpc/client.go +++ b/internal/infrastructure/gatewayrpc/client.go @@ -18,8 +18,7 @@ var _ messaging.ChatContract = (*Client)(nil) // Client implements messaging.ChatContract over the chat service. The proto // is unchanged by the messaging migration, so history crosses without its -// role and is re-addressed from the owning session on arrival; StoreClient -// serves the SessionStore view over the same RPCs. +// role and is re-addressed from the owning session on arrival. type Client struct{ client pb.ChatServiceClient } func NewClient(conn grpc.ClientConnInterface) *Client { diff --git a/internal/infrastructure/gatewayrpc/store_client.go b/internal/infrastructure/gatewayrpc/store_client.go index cd4923405..8fb843b1a 100644 --- a/internal/infrastructure/gatewayrpc/store_client.go +++ b/internal/infrastructure/gatewayrpc/store_client.go @@ -3,115 +3,10 @@ package gatewayrpc import ( "context" - "google.golang.org/grpc" - pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1" "github.com/samcharles93/archie-core/internal/domain/messaging" ) -var _ messaging.SessionStore = (*StoreClient)(nil) - -// StoreClient implements messaging.SessionStore over the Gateway's session -// RPCs. Role is derived from the session. -type StoreClient struct{ client pb.ChatServiceClient } - -func NewStoreClient(conn grpc.ClientConnInterface) *StoreClient { - return &StoreClient{client: pb.NewChatServiceClient(conn)} -} - -func (c *StoreClient) Get(ctx context.Context, id string) (*messaging.SessionContext, error) { - v, err := c.client.GetSession(ctx, &pb.GetSessionRequest{SessionId: id}) - if err != nil { - return nil, err - } - if !v.Found { - return nil, nil - } - s := sessionValue(v.Session) - return &s, nil -} - -func (c *StoreClient) Save(ctx context.Context, s messaging.SessionContext) error { - _, e := c.client.SaveSession(ctx, &pb.SaveSessionRequest{Session: sessionProto(s)}) - return e -} - -func (c *StoreClient) GetByChannel(ctx context.Context, p, ch string) ([]messaging.SessionContext, error) { - v, e := c.client.GetSessionsByChannel(ctx, &pb.GetSessionsByChannelRequest{Platform: p, ChannelId: ch}) - if e != nil { - return nil, e - } - return mapValues(v.Sessions, sessionValue), nil -} - -func (c *StoreClient) Delete(ctx context.Context, id string) error { - _, e := c.client.DeleteSession(ctx, &pb.DeleteSessionRequest{SessionId: id}) - return e -} - -func (c *StoreClient) Touch(ctx context.Context, id string) error { - _, e := c.client.TouchSession(ctx, &pb.TouchSessionRequest{SessionId: id}) - return e -} - -func (c *StoreClient) List(ctx context.Context) ([]messaging.SessionContext, error) { - v, e := c.client.ListSessions(ctx, &pb.ListSessionsRequest{}) - if e != nil { - return nil, e - } - return mapValues(v.Sessions, sessionValue), nil -} - -func (c *StoreClient) SaveMessage(ctx context.Context, id string, m messaging.Message) error { - _, e := c.client.SaveMessage(ctx, &pb.SaveMessageRequest{SessionId: id, Message: storedProto(m)}) - return e -} - -func (c *StoreClient) DeleteRecentMessages(ctx context.Context, id string, n int) (int, error) { - v, e := c.client.DeleteRecentMessages(ctx, &pb.DeleteRecentMessagesRequest{SessionId: id, Limit: int64(n)}) - return int(v.Deleted), e -} - -func (c *StoreClient) MessageCount(ctx context.Context, id string) (int, error) { - v, e := c.client.MessageCount(ctx, &pb.MessageCountRequest{SessionId: id}) - return int(v.Count), e -} - -func (c *StoreClient) SaveMessages(ctx context.Context, id string, m []messaging.Message) error { - _, e := c.client.SaveMessages(ctx, &pb.SaveMessagesRequest{SessionId: id, Messages: mapValues(m, storedProto)}) - return e -} - -func (c *StoreClient) ReplaceMessages(ctx context.Context, id string, m []messaging.Message, s []string) error { - _, e := c.client.ReplaceMessages(ctx, &pb.ReplaceMessagesRequest{SessionId: id, Messages: mapValues(m, storedProto), Superseded: s}) - return e -} - -func (c *StoreClient) RecentMessages(ctx context.Context, id string, n int) ([]messaging.Message, error) { - // No store-RecentMessages RPC exists; the chat contract serves the same - // history in-process and over the wire. Re-address it (see - // addressRecords). - v, err := c.client.RecentMessages(ctx, &pb.RecentMessagesRequest{SessionId: id, Limit: int64(n)}) - if err != nil { - return nil, err - } - return addressRecords(ctx, c.client, id, v.Messages) -} - -func (c *StoreClient) SearchMessages(ctx context.Context, id string, q messaging.MessageQuery) (messaging.MessagePage, error) { - v, e := c.client.SearchMessages(ctx, &pb.SearchMessagesRequest{SessionId: id, Query: q.Query, Limit: int64(q.Limit), Offset: int64(q.Offset)}) - if e != nil { - return messaging.MessagePage{}, e - } - msgs, err := addressRecords(ctx, c.client, id, v.Messages) - if err != nil { - return messaging.MessagePage{}, err - } - return messaging.MessagePage{Messages: msgs, NextOffset: int(v.NextOffset), HasMore: v.HasMore, Truncated: v.Truncated}, nil -} - -func (c *StoreClient) Close() error { return nil } - // addressRecords restores the canonical fields the wire drops -- role and // conversation address -- from the owning session, which is where the // server derived them from on the way out. A missing session yields zero diff --git a/internal/infrastructure/kit/kit.go b/internal/infrastructure/kit/kit.go index 3d5e26d78..1e2f087db 100644 --- a/internal/infrastructure/kit/kit.go +++ b/internal/infrastructure/kit/kit.go @@ -51,24 +51,6 @@ type Plan struct { ContextSources []spec.ContextSource } -// DecodePublished reads the descriptor from an image's manifest annotations -// and holds it to the published form: strict decoding, full validation, and -// no unexpanded build-phase args. -func DecodePublished(annotations map[string]string) (*spec.Descriptor, error) { - raw, ok := annotations[spec.AnnotationDescriptor] - if !ok { - return nil, fmt.Errorf("image is not a kit: no %s annotation", spec.AnnotationDescriptor) - } - d, err := spec.Decode([]byte(raw)) - if err != nil { - return nil, err - } - if _, err := spec.ValidatePublished([]byte(raw), d); err != nil { - return nil, err - } - return d, nil -} - // SelectCapability applies Archie's runtime policy before composition. func SelectCapability(_ context.Context, _ spec.Descriptor, c spec.Capability) spec.CapabilityDecision { reason, err := refusalReason(c) diff --git a/internal/infrastructure/readiness/probes.go b/internal/infrastructure/readiness/probes.go index 9a09eed54..a8b8515ba 100644 --- a/internal/infrastructure/readiness/probes.go +++ b/internal/infrastructure/readiness/probes.go @@ -184,11 +184,6 @@ type DiskProbe struct { Statfs func(string, *syscall.Statfs_t) error } -// NewDiskProbe returns a single-path disk probe. -func NewDiskProbe(path string) *DiskProbe { - return NewDiskProbeTargets([]DiskTarget{{Name: "work", Path: path}}) -} - // NewDiskProbeTargets returns a disk probe for the supplied, stable-ordered targets. func NewDiskProbeTargets(targets []DiskTarget) *DiskProbe { return &DiskProbe{Targets: append([]DiskTarget(nil), targets...), Threshold: DefaultDiskThreshold, Statfs: syscall.Statfs} @@ -292,56 +287,3 @@ type GatewayProbe struct { Channels func() []ChannelState CountSessions sessionCounter } - -// NewGatewayProbe returns a gateway probe. Either function may be nil. -func NewGatewayProbe(channels func() []ChannelState, countSessions sessionCounter) *GatewayProbe { - return &GatewayProbe{Channels: channels, CountSessions: countSessions} -} - -func (p *GatewayProbe) Name() string { return "gateway" } - -func (p *GatewayProbe) Check(ctx context.Context) health.Result { - configChannels := 0 - runningChannels := 0 - failed := false - if p.Channels != nil { - for _, c := range p.Channels() { - if c.Configured { - configChannels++ - } - if c.Configured && c.State == "running" { - runningChannels++ - } - if c.Configured && c.State == "failed" { - failed = true - } - } - } - sessions := 0 - if p.CountSessions != nil { - sessions = p.CountSessions(ctx) - } - - switch { - case configChannels == 0: - return health.Result{ - Status: health.StatusDegraded, - Detail: "no gateway channels configured, " + fmt.Sprintf("%d sessions", sessions), - } - case failed: - return health.Result{ - Status: health.StatusDegraded, - Detail: fmt.Sprintf("channel failed, %d/%d running, %d sessions", runningChannels, configChannels, sessions), - } - case runningChannels == 0: - return health.Result{ - Status: health.StatusDegraded, - Detail: fmt.Sprintf("gateway not running, %d/%d channels up, %d sessions", runningChannels, configChannels, sessions), - } - default: - return health.Result{ - Status: health.StatusOK, - Detail: fmt.Sprintf("%d/%d channels running, %d sessions, not draining", runningChannels, configChannels, sessions), - } - } -} diff --git a/internal/logging/reader.go b/internal/logging/reader.go index 9bc4f8340..9162504c3 100644 --- a/internal/logging/reader.go +++ b/internal/logging/reader.go @@ -327,70 +327,6 @@ func Tail(path string, q Query) (Result, error) { return res, nil } -// Page returns up to Limit matching entries from cursor, and the cursor to -// resume at. Truncated means older entries were not examined. A cursor past -// the end returns an empty page. -func Page(path string, q Query, cursor int64) (PageResult, error) { - res := PageResult{Entries: []Entry{}, File: path} - limit := q.Limit - if limit <= 0 { - limit = DefaultTailLines - } - if limit > MaxTailLines { - limit = MaxTailLines - } - - // Stat for Found without reading the window twice. readLines cannot report - // the difference between a missing file and a cursor at EOF. - if strings.TrimSpace(path) != "" { - if _, err := os.Stat(path); err == nil { - res.Found = true - } else if !os.IsNotExist(err) { - return PageResult{}, fmt.Errorf("logging: stat %s: %w", path, err) - } - } - - type lineAt struct { - entry Entry - endOff int64 - } - matches := make([]lineAt, 0, limit) - truncated, endOff, ok, err := readLines(path, q, cursor, func(e Entry, _, end int64) bool { - if len(matches) < limit { - matches = append(matches, lineAt{entry: e, endOff: end}) - return true - } - // Once we have limit matches, any further match means more is - // available; we keep walking only to maintain endOff accuracy. - res.MoreAvailable = true - return true - }) - if err != nil { - return PageResult{}, err - } - if !ok { - // Preserved endOff carries the cursor the caller asked for - // (when ok=false because cursor > EOF, so the next call can - // detect overshoot). The scan-cap signal is also preserved. - res.Truncated = truncated - res.Cursor = endOff - return res, nil - } - res.Truncated = truncated - res.Entries = make([]Entry, len(matches)) - for i, m := range matches { - res.Entries[i] = m.entry - } - // Resume after the last returned entry when the page filled, else at the end - // of the walk. - if res.MoreAvailable { - res.Cursor = matches[len(matches)-1].endOff - } else { - res.Cursor = endOff - } - return res, nil -} - // PageBefore returns up to Limit matching entries whose end offset is at or // before before (the whole scan window when before is zero), oldest first. It // is the backward counterpart of Page: Cursor is the before value for the next diff --git a/internal/pairing/atomic.go b/internal/pairing/atomic.go deleted file mode 100644 index ba4853436..000000000 --- a/internal/pairing/atomic.go +++ /dev/null @@ -1,37 +0,0 @@ -package pairing - -import ( - "fmt" - "os" - "path/filepath" -) - -// writeFileAtomic writes data to path, mode 0600, through a temp file and -// rename. -func writeFileAtomic(path string, data []byte) error { - dir := filepath.Dir(path) - tmp, err := os.CreateTemp(dir, filepath.Base(path)+".tmp-*") - if err != nil { - return fmt.Errorf("pairing: create temp file: %w", err) - } - tmpPath := tmp.Name() - // Clean up the temp file on any failure path; a successful rename - // removes the source, so os.Remove no-ops (ENOENT, discarded) on the - // success path. - defer func() { _ = os.Remove(tmpPath) }() - - if _, err := tmp.Write(data); err != nil { - _ = tmp.Close() - return fmt.Errorf("pairing: write temp file: %w", err) - } - if err := tmp.Close(); err != nil { - return fmt.Errorf("pairing: close temp file: %w", err) - } - if err := os.Chmod(tmpPath, 0o600); err != nil { - return fmt.Errorf("pairing: chmod temp file: %w", err) - } - if err := os.Rename(tmpPath, path); err != nil { - return fmt.Errorf("pairing: rename into place: %w", err) - } - return nil -} diff --git a/internal/pairing/code.go b/internal/pairing/code.go deleted file mode 100644 index c8de82b91..000000000 --- a/internal/pairing/code.go +++ /dev/null @@ -1,34 +0,0 @@ -// Package pairing implements device-pairing codes for gateway -// authorization: a short, human-typeable code an operator hands to a -// new chat user, which the daemon verifies before granting access. -package pairing - -import ( - "crypto/rand" - "fmt" - "math/big" -) - -// Alphabet is the set of characters a pairing code is drawn from: digits -// 2-9 and uppercase A-Z excluding I and O. It deliberately excludes 0, -// O, 1, and I -- characters humans commonly misread or mistype when -// copying a code from a screen. -const Alphabet = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ" - -// CodeLength is the number of characters in a generated pairing code. -const CodeLength = 8 - -// GenerateCode returns a random CodeLength-character code drawn -// uniformly from Alphabet using crypto/rand. -func GenerateCode() (string, error) { - alphabetLen := big.NewInt(int64(len(Alphabet))) - code := make([]byte, CodeLength) - for i := range code { - n, err := rand.Int(rand.Reader, alphabetLen) - if err != nil { - return "", fmt.Errorf("pairing: generate code: %w", err) - } - code[i] = Alphabet[n.Int64()] - } - return string(code), nil -} diff --git a/internal/pairing/hash.go b/internal/pairing/hash.go deleted file mode 100644 index 49d00d4db..000000000 --- a/internal/pairing/hash.go +++ /dev/null @@ -1,49 +0,0 @@ -package pairing - -import ( - "crypto/rand" - "crypto/sha256" - "crypto/subtle" - "fmt" -) - -// saltLen is the size in bytes of a generated salt. 16 bytes (128 bits) -// is standard practice for a salt -- large enough that two salts -// colliding is negligible, without adding meaningful storage cost. -const saltLen = 16 - -// HashedCode is a salted SHA-256 digest of a pairing code, safe to store -// (the plaintext code itself never needs to be persisted after hashing). -type HashedCode struct { - Salt []byte - Hash []byte -} - -// HashCode generates a random salt and returns the salted SHA-256 digest -// of code. Each call produces a different salt (and therefore a -// different Hash) even for the same code. -func HashCode(code string) (HashedCode, error) { - salt := make([]byte, saltLen) - if _, err := rand.Read(salt); err != nil { - return HashedCode{}, fmt.Errorf("pairing: generate salt: %w", err) - } - return HashedCode{Salt: salt, Hash: digest(salt, code)}, nil -} - -// Verify reports whether code hashes to the same digest as h, using a -// constant-time comparison so the check doesn't leak timing information -// about how much of the digest matched. -func (h HashedCode) Verify(code string) bool { - if len(h.Salt) == 0 || len(h.Hash) == 0 { - return false - } - return subtle.ConstantTimeCompare(h.Hash, digest(h.Salt, code)) == 1 -} - -// digest computes SHA-256(salt || code). -func digest(salt []byte, code string) []byte { - sum := sha256.New() - sum.Write(salt) - sum.Write([]byte(code)) - return sum.Sum(nil) -} diff --git a/internal/pairing/store.go b/internal/pairing/store.go deleted file mode 100644 index 6b418d3df..000000000 --- a/internal/pairing/store.go +++ /dev/null @@ -1,261 +0,0 @@ -package pairing - -import ( - "encoding/json" - "errors" - "fmt" - "os" - "path/filepath" - "sync" - "time" -) - -// Tuning constants. -const ( - // CodeTTL is how long a requested pairing code remains valid. - CodeTTL = time.Hour - // MaxPendingPerPlatform caps how many unexpired pairing codes may be - // outstanding at once for a single Store (one Store per platform). - MaxPendingPerPlatform = 3 - // RateLimitWindow is the minimum time between two RequestCode calls - // from the same user. - RateLimitWindow = 10 * time.Minute - // MaxFailures is how many wrong-code VerifyCode attempts a user gets - // before being locked out. - MaxFailures = 5 - // LockoutDuration is the base lockout length after MaxFailures wrong - // attempts. Matches CodeTTL for consistency -- both bound the - // window an attacker has to brute-force or retry. - LockoutDuration = time.Hour - // MaxLockoutDuration caps the escalated lockout length for a user - // who keeps re-offending after each lockout expires, so escalation - // converges instead of growing without bound. - MaxLockoutDuration = 24 * time.Hour -) - -// Sentinel errors returned by Store methods. Callers should use -// errors.Is against these rather than matching error strings. -var ( - ErrRateLimited = errors.New("pairing: rate limited, try again later") - ErrQuotaExceeded = errors.New("pairing: too many pending codes for this platform") - ErrLockedOut = errors.New("pairing: locked out after too many failed attempts") - ErrNoPendingCode = errors.New("pairing: no valid pending code for this user") -) - -// pendingCode is the persisted state for one outstanding pairing code. -type pendingCode struct { - Hashed HashedCode `json:"hashed"` - CreatedAt time.Time `json:"created_at"` - ExpiresAt time.Time `json:"expires_at"` -} - -// userLimit is the persisted rate-limit/lockout state for one user. -type userLimit struct { - LastRequestAt time.Time `json:"last_request_at"` - Failures int `json:"failures"` - LockedUntil time.Time `json:"locked_until"` - // LockoutCount counts consecutive lockouts, escalating the lockout duration; - // reset on success. - LockoutCount int `json:"lockout_count"` -} - -// lockoutDuration returns the lockout length for a user who has been -// locked out lockoutCount times before (0 for a first offense), -// doubling each time and capped at MaxLockoutDuration. -func lockoutDuration(lockoutCount int) time.Duration { - d := LockoutDuration - for range lockoutCount { - if d >= MaxLockoutDuration { - return MaxLockoutDuration - } - d *= 2 - } - if d > MaxLockoutDuration { - return MaxLockoutDuration - } - return d -} - -// Store is a file-backed pairing store for one platform: pending codes, -// approved users and rate limits. -type Store struct { - dir string - now func() time.Time - - mu sync.Mutex - pending map[string]pendingCode - approved map[string]time.Time - limits map[string]userLimit -} - -// New opens (creating if necessary) a Store backed by dir, loading any -// existing pending.json/approved.json/rate_limits.json found there. -// Missing files are treated as empty state, not an error -- a fresh -// platform has no prior pairing history. -func New(dir string) (*Store, error) { - if err := os.MkdirAll(dir, 0o700); err != nil { - return nil, fmt.Errorf("pairing: create state dir: %w", err) - } - s := &Store{ - dir: dir, - now: time.Now, - pending: map[string]pendingCode{}, - approved: map[string]time.Time{}, - limits: map[string]userLimit{}, - } - if err := loadJSON(filepath.Join(dir, "pending.json"), &s.pending); err != nil { - return nil, err - } - if err := loadJSON(filepath.Join(dir, "approved.json"), &s.approved); err != nil { - return nil, err - } - if err := loadJSON(filepath.Join(dir, "rate_limits.json"), &s.limits); err != nil { - return nil, err - } - return s, nil -} - -// RequestCode creates and returns a pairing code for userID; only its hash -// is stored. -func (s *Store) RequestCode(userID string) (string, error) { - s.mu.Lock() - defer s.mu.Unlock() - - now := s.now() - s.purgeExpiredLocked(now) - - if limit, ok := s.limits[userID]; ok && now.Before(limit.LockedUntil) { - return "", ErrLockedOut - } - if limit, ok := s.limits[userID]; ok && now.Sub(limit.LastRequestAt) < RateLimitWindow { - return "", ErrRateLimited - } - - _, alreadyPending := s.pending[userID] - if !alreadyPending && len(s.pending) >= MaxPendingPerPlatform { - return "", ErrQuotaExceeded - } - - code, err := GenerateCode() - if err != nil { - return "", err - } - hashed, err := HashCode(code) - if err != nil { - return "", err - } - - s.pending[userID] = pendingCode{Hashed: hashed, CreatedAt: now, ExpiresAt: now.Add(CodeTTL)} - limit := s.limits[userID] - limit.LastRequestAt = now - s.limits[userID] = limit - - if err := s.persistLocked(); err != nil { - return "", err - } - return code, nil -} - -// VerifyCode checks code for userID. Success approves the user and consumes -// the code; a failure counts toward lockout. -func (s *Store) VerifyCode(userID, code string) (bool, error) { - s.mu.Lock() - defer s.mu.Unlock() - - now := s.now() - s.purgeExpiredLocked(now) - - if limit, ok := s.limits[userID]; ok && now.Before(limit.LockedUntil) { - return false, ErrLockedOut - } - - pending, ok := s.pending[userID] - if !ok { - return false, ErrNoPendingCode - } - - if !pending.Hashed.Verify(code) { - limit := s.limits[userID] - limit.Failures++ - if limit.Failures >= MaxFailures { - limit.LockedUntil = now.Add(lockoutDuration(limit.LockoutCount)) - limit.LockoutCount++ - } - s.limits[userID] = limit - if err := s.persistLocked(); err != nil { - return false, err - } - return false, nil - } - - delete(s.pending, userID) - s.approved[userID] = now - limit := s.limits[userID] - limit.Failures = 0 - limit.LockoutCount = 0 - s.limits[userID] = limit - - if err := s.persistLocked(); err != nil { - return false, err - } - return true, nil -} - -// IsApproved reports whether userID has successfully paired. -func (s *Store) IsApproved(userID string) bool { - s.mu.Lock() - defer s.mu.Unlock() - _, ok := s.approved[userID] - return ok -} - -// purgeExpiredLocked removes pending codes past their ExpiresAt. Must be -// called with s.mu held. Does not persist -- callers persist once after -// their own mutation, avoiding a redundant write on every call when -// nothing was actually expired. -func (s *Store) purgeExpiredLocked(now time.Time) { - for userID, p := range s.pending { - if !now.Before(p.ExpiresAt) { - delete(s.pending, userID) - } - } -} - -// persistLocked writes all three state files. Must be called with s.mu held. -func (s *Store) persistLocked() error { - if err := saveJSON(filepath.Join(s.dir, "pending.json"), s.pending); err != nil { - return err - } - if err := saveJSON(filepath.Join(s.dir, "approved.json"), s.approved); err != nil { - return err - } - if err := saveJSON(filepath.Join(s.dir, "rate_limits.json"), s.limits); err != nil { - return err - } - return nil -} - -// loadJSON decodes the JSON file at path into v. A missing file leaves v -// unchanged (its zero/initialized value from the caller). -func loadJSON(path string, v any) error { - data, err := os.ReadFile(path) - if err != nil { - if os.IsNotExist(err) { - return nil - } - return fmt.Errorf("pairing: read %s: %w", path, err) - } - if err := json.Unmarshal(data, v); err != nil { - return fmt.Errorf("pairing: parse %s: %w", path, err) - } - return nil -} - -// saveJSON encodes v as JSON and writes it atomically to path. -func saveJSON(path string, v any) error { - data, err := json.Marshal(v) - if err != nil { - return fmt.Errorf("pairing: encode %s: %w", path, err) - } - return writeFileAtomic(path, data) -} diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 6bc3c1803..7cce71cce 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -431,19 +431,6 @@ func reverseClone(values []string) []string { return out } -// Manifests returns the registered modules' manifests sorted by id. It is the -// read side of the running set: a live load reports what is loaded from here. -func (h *Host) Manifests() []Manifest { - h.mu.RLock() - defer h.mu.RUnlock() - out := make([]Manifest, 0, len(h.modules)) - for _, entry := range h.modules { - out = append(out, entry.manifest.clone()) - } - slices.SortFunc(out, func(a, b Manifest) int { return strings.Compare(a.ID, b.ID) }) - return out -} - // prepareModule validates a module and returns its cloned manifest, the // validation Register, Add and Replace all share. func prepareModule(module Module) (Manifest, error) { diff --git a/internal/taskstate/taskstate.go b/internal/taskstate/taskstate.go index a3d91cbfa..3c268a126 100644 --- a/internal/taskstate/taskstate.go +++ b/internal/taskstate/taskstate.go @@ -52,17 +52,6 @@ const ( Completed = "completed" ) -// Terminal reports whether a status is an end state, from which no further -// work happens without an operator asking for it. -func Terminal(status string) bool { - switch status { - case Merged, Rejected, Dead, Declined, Completed: - return true - default: - return false - } -} - // Actions returns the actions valid for status, as a new slice. Reject is // available in every non-terminal state; terminal states offer archive. func Actions(status string) []Action { @@ -117,14 +106,6 @@ func CheckApprove(status string) error { return nil } -// CheckRetry allows retry only from Parked. -func CheckRetry(status string) error { - if status != Parked { - return fmt.Errorf("task is %s, not parked", status) - } - return nil -} - // RetryMode is the worktree mode for a retried task's next dispatch. Stored // on the task row. type RetryMode string diff --git a/internal/tools/availability.go b/internal/tools/availability.go deleted file mode 100644 index d0b3c3e73..000000000 --- a/internal/tools/availability.go +++ /dev/null @@ -1,105 +0,0 @@ -package tools - -import ( - "sync" - "time" -) - -// AvailabilityCache wraps a [CheckFn] with TTL-based result caching. -// -// Positive results (tool is available) are cached for the TTL duration. -// Negative results (tool is unavailable) are cached for the failure -// grace period. A nil check function means "always available" -- Check -// returns true immediately with no caching overhead. -// -// All methods are safe for concurrent use. -type AvailabilityCache struct { - TTL time.Duration - FailureGracePeriod time.Duration - - check CheckFn - - mu sync.Mutex - lastResult bool - checkedAt time.Time -} - -// NewAvailabilityCache creates an [AvailabilityCache] wrapping the given -// check function. If check is nil, Check always returns true (the tool -// is permanently available and no caching is needed). -// -// Typical values: TTL=30s for positive results, FailureGracePeriod=60s -// for negative results (avoid churn when a dependency is temporarily down). -func NewAvailabilityCache(check CheckFn, ttl, failureGrace time.Duration) *AvailabilityCache { - return &AvailabilityCache{ - TTL: ttl, - FailureGracePeriod: failureGrace, - check: check, - } -} - -// Check reports whether the tool is available. It returns the cached -// result when the cache is still fresh; otherwise it re-evaluates the -// underlying check function. -// -// When the underlying check returns true (available), the result is -// cached for c.TTL. When it returns false (unavailable), the result is -// cached for c.FailureGracePeriod -- this prevents tight re-check loops -// while a dependency is temporarily down. -func (c *AvailabilityCache) Check() bool { - if c.check == nil { - return true - } - - c.mu.Lock() - defer c.mu.Unlock() - - now := time.Now() - cacheDuration := c.TTL - if !c.lastResult { - cacheDuration = c.FailureGracePeriod - } - - if c.checkedAt.IsZero() || now.Sub(c.checkedAt) >= cacheDuration { - c.lastResult = c.check() - c.checkedAt = now - } - - return c.lastResult -} - -// Invalidate forces the next call to Check to bypass the cache and -// re-evaluate the underlying check function. -func (c *AvailabilityCache) Invalidate() { - c.mu.Lock() - c.checkedAt = time.Time{} - c.mu.Unlock() -} - -// LastChecked reports when the cache was last refreshed. A zero time -// means the cache has never been evaluated. -func (c *AvailabilityCache) LastChecked() time.Time { - c.mu.Lock() - defer c.mu.Unlock() - return c.checkedAt -} - -// CachedAvailable returns the most recent cached result without -// re-evaluating the check function. For tools with a nil check, -// this always returns true. -func (c *AvailabilityCache) CachedAvailable() bool { - if c.check == nil { - return true - } - c.mu.Lock() - defer c.mu.Unlock() - return c.lastResult -} - -// NewAvailabilityCacheFromEntry is a convenience constructor that creates -// an [AvailabilityCache] from a [ToolEntry]'s CheckFn using the given TTL -// and failure grace period. When the entry has a nil CheckFn the returned -// cache reports always-available. -func NewAvailabilityCacheFromEntry(e ToolEntry, ttl, failureGrace time.Duration) *AvailabilityCache { - return NewAvailabilityCache(e.CheckFn, ttl, failureGrace) -} diff --git a/internal/tools/disclosure.go b/internal/tools/disclosure.go index c98676161..5ba3ed218 100644 --- a/internal/tools/disclosure.go +++ b/internal/tools/disclosure.go @@ -262,18 +262,6 @@ const ( DisclosureBridge ) -// String returns a human-readable representation of the mode. -func (m DisclosureMode) String() string { - switch m { - case DisclosureFull: - return "full" - case DisclosureBridge: - return "bridge" - default: - return "unknown" - } -} - // ContextPressureGate monitors the size of tool schemas relative to the // LLM context window and dynamically switches between full disclosure // and bridge-tool mode. @@ -331,13 +319,6 @@ func (g *ContextPressureGate) Evaluate(tools []ToolEntry) DisclosureMode { return g.currentMode } -// Mode returns the current disclosure mode. -func (g *ContextPressureGate) Mode() DisclosureMode { - g.mu.RLock() - defer g.mu.RUnlock() - return g.currentMode -} - // FilterTools returns the set of tools that should be disclosed given the // current mode. In full mode, all tools are returned. In bridge mode, only // bridge tools and always-visible tools are returned. @@ -373,22 +354,6 @@ func (g *ContextPressureGate) FilterTools(reg *Registry) []ToolEntry { return filtered } -// SetAlwaysVisible marks tools that are always visible regardless of mode. -func (g *ContextPressureGate) SetAlwaysVisible(names ...string) { - g.mu.Lock() - defer g.mu.Unlock() - for _, name := range names { - g.AlwaysVisible[name] = true - } -} - -// Reset returns the gate to full disclosure mode. -func (g *ContextPressureGate) Reset() { - g.mu.Lock() - defer g.mu.Unlock() - g.currentMode = DisclosureFull -} - // alwaysVisibleCopy returns a copy of the always-visible set. func (g *ContextPressureGate) alwaysVisibleCopy() map[string]bool { out := make(map[string]bool, len(g.AlwaysVisible)) diff --git a/internal/webui/api_chat.go b/internal/webui/api_chat.go index 2b635aa33..7a5cc6dd3 100644 --- a/internal/webui/api_chat.go +++ b/internal/webui/api_chat.go @@ -338,10 +338,6 @@ type chatStreamSink struct { owner string } -func (s chatStreamSink) Delta(text string) { - s.write(chatStreamEvent{Type: "delta", Text: text}) -} - func (s chatStreamSink) ToolCall(event messaging.ToolCallEvent) { // A dashboard_navigate call is an explicit point-the-operator-there // result, not tool narration, so it renders a clickable chip even when diff --git a/internal/webui/auth.go b/internal/webui/auth.go index 2c9b923f0..91ece0515 100644 --- a/internal/webui/auth.go +++ b/internal/webui/auth.go @@ -11,8 +11,6 @@ import ( "net" "net/http" "net/url" - "os" - "path/filepath" "strings" "github.com/samcharles93/archie-core/internal/domain/access" @@ -74,34 +72,6 @@ func DashboardURL(listen string) string { return "http://" + net.JoinHostPort(host, port) + "/" } -// LoadOrCreateToken returns the dashboard token, generating and persisting one -// on first use. The token is created rather than configured so a non-loopback -// bind cannot be brought up unprotected by omission: there is no setup step to -// forget. -func LoadOrCreateToken(path string) (string, error) { - if b, err := os.ReadFile(path); err == nil { - if tok := strings.TrimSpace(string(b)); tok != "" { - return tok, nil - } - } else if !os.IsNotExist(err) { - return "", fmt.Errorf("webui: read token: %w", err) - } - - raw := make([]byte, 32) - if _, err := rand.Read(raw); err != nil { - return "", fmt.Errorf("webui: generate token: %w", err) - } - tok := base64.RawURLEncoding.EncodeToString(raw) - - if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { - return "", fmt.Errorf("webui: token dir: %w", err) - } - if err := os.WriteFile(path, []byte(tok+"\n"), 0o600); err != nil { - return "", fmt.Errorf("webui: write token: %w", err) - } - return tok, nil -} - // requireToken checks the request's credential: a provider-issued bearer // token when an identity provider is configured, else the shared token. A // ?t= token is moved into a cookie and the request redirected. diff --git a/internal/worktreerpc/worktreerpc.go b/internal/worktreerpc/worktreerpc.go index c6bf7d2dc..442ef69be 100644 --- a/internal/worktreerpc/worktreerpc.go +++ b/internal/worktreerpc/worktreerpc.go @@ -91,12 +91,6 @@ func (s *Server) handlerContext() (context.Context, context.CancelFunc) { return context.WithTimeout(context.Background(), timeout) } -// Register subscribes the publication handler under the root identity. -// RegisterFor subscribes it under one identity-scoped subject. -func (s *Server) Register(nc *nats.Conn) (unsubscribe func(), err error) { - return s.RegisterFor(nc, "") -} - // RegisterFor registers publication under the subject scoped to identity. func (s *Server) RegisterFor(nc *nats.Conn, identity string) (unsubscribe func(), err error) { subject := SubjectFor(identity, SubjectPush)