An open-source, faster Devin alternative
TypeScript
remove dead code + references
Brian Reardon943a2ac03c74
diff --git a/internal/auth/jwt.go b/internal/auth/jwt.goindex 8e823a5c..944074fb 100644--- a/internal/auth/jwt.go+++ b/internal/auth/jwt.go@@ -145,9 +145,9 @@ type CapabilityClaims struct {// debits for a now-pro org.Plan string `json:"plan,omitempty"`// BillingProvider mirrors orgs.billing_provider ("legacy" | "autumn") from- // D1 → cell-PG via UpsertOrgFromCapToken, so the cell's AutumnReporter sees- // which orgs it owns without a separate sync. Empty on older tokens / paths- // that don't carry it — the cell then leaves the existing value untouched.+ // D1 → cell-PG via UpsertOrgFromCapToken, so the cell's size gates know which+ // orgs are autumn (metered, no free-tier ceiling) vs legacy, without a+ // separate sync. Empty on older tokens / paths — the cell leaves it untouched.BillingProvider string `json:"billing_provider,omitempty"`}diff --git a/internal/billing/autumn/autumn.go b/internal/billing/autumn/autumn.godeleted file mode 100644index 816c7a79..00000000--- a/internal/billing/autumn/autumn.go+++ /dev/null@@ -1,195 +0,0 @@-// Package autumn is a thin Go client for the Autumn billing API-// (useautumn.com). Autumn is the source of truth for credit balances and the-// customer's active plans; this package is how the cell creates customers,-// reports usage (track), reads balances/plans, and starts checkouts.-//-// The shapes here were validated against the live sandbox API:-//-// POST /v1/customers {id,name,email} -> Customer-// GET /v1/customers/{id} -> Customer-// POST /v1/track {customer_id,feature_id,value,idempotency_key} -> {balance}-// POST /v1/check {customer_id,feature_id} -> {allowed,balance}-// POST /v1/checkout {customer_id,product_id,options,success_url} -> {url,total}-//-// Auth: Authorization: Bearer am_sk_… JSON bodies are snake_case. Notably the-// idempotency field is `idempotency_key` (snake_case) — the camelCase form in-// Autumn's docs is silently ignored and will NOT dedupe.-package autumn--import (- "context"- "fmt"-)--// CreditsFeatureID is the monetary credit-balance feature.-const CreditsFeatureID = "credits"--// Client is the Autumn API surface the platform depends on. A fake-// implementation (see fake.go) backs tests and lets the rest of the billing-// system be built before pointing at the live API.-type Client interface {- // CreateCustomer registers an org as an Autumn customer. Autumn auto-attaches- // the default plan (base) and its one-time credit grant.- CreateCustomer(ctx context.Context, p CreateCustomerParams) (*Customer, error)- // GetCustomer returns the customer's active subscriptions + feature balances.- // This is the authoritative read used to sync the is_halted / max_concurrent- // projections and to re-check on resume.- GetCustomer(ctx context.Context, customerID string) (*Customer, error)- // Track reports usage of a feature, deducting from the credit balance. The- // returned balance is the post-deduction state, so callers can halt inline- // when Remaining <= 0. IdempotencyKey makes retries safe.- Track(ctx context.Context, p TrackParams) (*TrackResult, error)- // Check reports whether the customer has access/balance for a feature.- Check(ctx context.Context, p CheckParams) (*CheckResult, error)- // Checkout starts a Stripe checkout for a product — a one-off top-up or a- // recurring plan subscription — and returns the URL to redirect the user to.- Checkout(ctx context.Context, p CheckoutParams) (*CheckoutResult, error)- // SetCreditBalance overwrites the customer's `credits` balance to the given- // dollar amount. Used by the migration backfill to carry an org's legacy- // balance over to Autumn (Autumn floors at 0 when overage isn't allowed).- SetCreditBalance(ctx context.Context, customerID string, balance float64) error-}--// CreateCustomerParams identifies a new customer (we use the org UUID as the id).-type CreateCustomerParams struct {- ID string `json:"id"`- Name string `json:"name,omitempty"`- Email string `json:"email,omitempty"`- // StripeID links an existing Stripe customer (confirmed accepted live) so a- // migrated card-on-file org keeps its saved payment method — no re-entry.- StripeID string `json:"stripe_id,omitempty"`-}--// TrackParams reports `Value` units of `FeatureID` for a customer.-//-// IdempotencyKey is GLOBAL across all customers (Autumn dedupes on the bare key,-// not customer+key), so it must be globally unique — use e.g.-// "<org_id>:<bucket_start>:<feature_id>". A repeat returns 409, surfaced as-// TrackResult.Duplicate.-type TrackParams struct {- CustomerID string `json:"customer_id"`- FeatureID string `json:"feature_id"`- Value float64 `json:"value"`- IdempotencyKey string `json:"idempotency_key,omitempty"`-}--// TrackResult carries the post-deduction balance. Duplicate is true when the-// idempotency_key had already been seen (Autumn returns 409-// duplicate_idempotency_key) — the usage was applied by the earlier call, and-// Balance reflects the current re-fetched state so callers can still act on it.-type TrackResult struct {- Balance Balance- Duplicate bool-}--// CheckParams asks whether a customer can use a feature.-type CheckParams struct {- CustomerID string `json:"customer_id"`- FeatureID string `json:"feature_id"`-}--// CheckResult is the access decision + current balance.-type CheckResult struct {- Allowed bool- Balance Balance-}--// CheckoutParams starts a checkout for a product. Options sets per-feature-// quantities (e.g. credits=10 for a $10 top-up). SuccessURL is where Stripe-// redirects after payment — our handler re-checks the balance there to resume.-type CheckoutParams struct {- CustomerID string `json:"customer_id"`- ProductID string `json:"product_id"`- Options []CheckoutOption `json:"options,omitempty"`- SuccessURL string `json:"success_url,omitempty"`-}--// CheckoutOption sets a quantity for a priced feature in the product.-type CheckoutOption struct {- FeatureID string `json:"feature_id"`- Quantity int `json:"quantity"`-}--// CheckoutResult is the Stripe checkout to redirect the user to.-type CheckoutResult struct {- URL string `json:"url"`- Total float64 `json:"total"`- Currency string `json:"currency"`-}--// Customer is the Autumn customer record: who they are, their active plans, and-// their feature balances.-type Customer struct {- ID string `json:"id"`- Name string `json:"name"`- Email string `json:"email"`- Subscriptions []Subscription `json:"subscriptions"`- Balances map[string]Balance `json:"balances"`-}--// Subscription is one active plan the customer holds (base, a concurrency tier,-// etc.). AddOn distinguishes a stacking add-on (concurrency) from the default.-type Subscription struct {- PlanID string `json:"plan_id"`- AddOn bool `json:"add_on"`- Status string `json:"status"`-}--// Balance is a feature balance (for `credits`: the prepaid $ balance).-type Balance struct {- FeatureID string `json:"feature_id"`- Granted float64 `json:"granted"`- Remaining float64 `json:"remaining"`- Usage float64 `json:"usage"`- Unlimited bool `json:"unlimited"`-}--// CreditsRemaining returns the customer's prepaid credit balance ($). Drives the-// is_halted projection: <= 0 means halt.-func (c *Customer) CreditsRemaining() float64 {- return c.Balances[CreditsFeatureID].Remaining-}--// ConcurrencyByPlan maps a plan id to the concurrent-sandbox limit it grants.-// Concurrency is enforced from our DB; Autumn only tells us which plan the org-// is on. Keep in sync with the Autumn concurrency products.-var ConcurrencyByPlan = map[string]int{- "base": 5,- "concurrency_pro": 100,- "concurrency_pro_plus": 600,- "concurrency_pro_plus_plus": 1000,-}--// DefaultConcurrency applies when no known concurrency plan is active.-const DefaultConcurrency = 5--// MaxConcurrency resolves the customer's concurrency limit from their active-// plans — the highest limit among them (so an add-on tier wins over base).-func (c *Customer) MaxConcurrency() int {- limit := DefaultConcurrency- for _, s := range c.Subscriptions {- if s.Status != "" && s.Status != "active" {- continue- }- if v, ok := ConcurrencyByPlan[s.PlanID]; ok && v > limit {- limit = v- }- }- return limit-}--// APIError is a non-2xx response from Autumn.-type APIError struct {- StatusCode int- Body string-}--func (e *APIError) Error() string {- return fmt.Sprintf("autumn: http %d: %s", e.StatusCode, e.Body)-}--// IsNotFound reports whether err is a 404 from Autumn (e.g. unknown customer).-func IsNotFound(err error) bool {- var ae *APIError- return asAPIError(err, &ae) && ae.StatusCode == 404-}diff --git a/internal/billing/autumn/autumn_test.go b/internal/billing/autumn/autumn_test.godeleted file mode 100644index b28a6cee..00000000--- a/internal/billing/autumn/autumn_test.go+++ /dev/null@@ -1,134 +0,0 @@-package autumn--import (- "context"- "encoding/json"- "io"- "net/http"- "net/http/httptest"- "testing"-)--// The REST client must send the snake_case wire format we validated against the-// sandbox — especially idempotency_key (the camelCase form is silently ignored).-func TestRESTClient_Track_WireFormat(t *testing.T) {- var got map[string]any- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if r.URL.Path != "/track" || r.Method != http.MethodPost {- t.Errorf("unexpected %s %s", r.Method, r.URL.Path)- }- if r.Header.Get("Authorization") != "Bearer am_sk_test_x" {- t.Errorf("bad auth header: %q", r.Header.Get("Authorization"))- }- b, _ := io.ReadAll(r.Body)- _ = json.Unmarshal(b, &got)- _, _ = w.Write([]byte(`{"balance":{"feature_id":"credits","remaining":4.46,"usage":0.54,"granted":5}}`))- }))- defer srv.Close()-- c := New("am_sk_test_x", WithBaseURL(srv.URL))- res, err := c.Track(context.Background(), TrackParams{- CustomerID: "org-1", FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: "k1",- })- if err != nil {- t.Fatalf("track: %v", err)- }- if got["customer_id"] != "org-1" || got["feature_id"] != "compute_64gb" {- t.Fatalf("wrong body: %v", got)- }- if got["value"].(float64) != 1000 {- t.Fatalf("wrong value: %v", got["value"])- }- if got["idempotency_key"] != "k1" {- t.Fatalf("idempotency_key must be snake_case and present, got: %v", got["idempotency_key"])- }- if res.Balance.Remaining != 4.46 {- t.Fatalf("decoded remaining = %v, want 4.46", res.Balance.Remaining)- }-}--func TestRESTClient_GetCustomer_DecodesPlansAndBalance(t *testing.T) {- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- _, _ = w.Write([]byte(`{- "id":"org-1",- "subscriptions":[- {"plan_id":"base","add_on":false,"status":"active"},- {"plan_id":"concurrency_pro","add_on":true,"status":"active"}- ],- "balances":{"credits":{"feature_id":"credits","remaining":3.38,"granted":5,"usage":1.62}}- }`))- }))- defer srv.Close()-- c := New("am_sk_test_x", WithBaseURL(srv.URL))- cust, err := c.GetCustomer(context.Background(), "org-1")- if err != nil {- t.Fatalf("get: %v", err)- }- if cust.CreditsRemaining() != 3.38 {- t.Fatalf("credits = %v, want 3.38", cust.CreditsRemaining())- }- if cust.MaxConcurrency() != 100 {- t.Fatalf("concurrency = %d, want 100 (base+pro → max)", cust.MaxConcurrency())- }-}--func TestRESTClient_APIError(t *testing.T) {- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- w.WriteHeader(http.StatusNotFound)- _, _ = w.Write([]byte(`{"error":"not found"}`))- }))- defer srv.Close()- c := New("am_sk_test_x", WithBaseURL(srv.URL))- _, err := c.GetCustomer(context.Background(), "missing")- if !IsNotFound(err) {- t.Fatalf("expected IsNotFound, got %v", err)- }-}--func TestMaxConcurrency_Mapping(t *testing.T) {- cases := []struct {- plans []string- want int- }{- {[]string{"base"}, 5},- {[]string{"base", "concurrency_pro"}, 100},- {[]string{"base", "concurrency_pro_plus"}, 600},- {[]string{"base", "concurrency_pro_plus_plus"}, 1000},- {[]string{"base", "concurrency_pro", "concurrency_pro_plus_plus"}, 1000}, // max wins- {nil, 5}, // no plans → default- }- for _, tc := range cases {- c := &Customer{}- for _, p := range tc.plans {- c.Subscriptions = append(c.Subscriptions, Subscription{PlanID: p, Status: "active"})- }- if got := c.MaxConcurrency(); got != tc.want {- t.Errorf("plans %v → %d, want %d", tc.plans, got, tc.want)- }- }-}--func TestFake_TrackDeductsAndDedupes(t *testing.T) {- f := NewFake()- ctx := context.Background()- if _, err := f.CreateCustomer(ctx, CreateCustomerParams{ID: "org-1"}); err != nil {- t.Fatal(err)- }- // compute_64gb × 1000 = 0.54 credits.- r, _ := f.Track(ctx, TrackParams{CustomerID: "org-1", FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: "k1"})- if d := 5 - r.Balance.Remaining; d < 0.539 || d > 0.541 {- t.Fatalf("deducted %v, want ~0.54", d)- }- // same key again → no further deduction.- r2, _ := f.Track(ctx, TrackParams{CustomerID: "org-1", FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: "k1"})- if r2.Balance.Remaining != r.Balance.Remaining {- t.Fatalf("idempotency failed: %v → %v", r.Balance.Remaining, r2.Balance.Remaining)- }- // top-up restores balance.- f.SimulateTopUp("org-1", 10)- cust, _ := f.GetCustomer(ctx, "org-1")- if cust.CreditsRemaining() < 14 {- t.Fatalf("after top-up remaining = %v, want > 14", cust.CreditsRemaining())- }-}diff --git a/internal/billing/autumn/client.go b/internal/billing/autumn/client.godeleted file mode 100644index dea134fe..00000000--- a/internal/billing/autumn/client.go+++ /dev/null@@ -1,159 +0,0 @@-package autumn--import (- "bytes"- "context"- "encoding/json"- "errors"- "fmt"- "io"- "net/http"- "strings"- "time"-)--// DefaultBaseURL is the Autumn API root. The sandbox and live environments are-// selected by the API key (am_sk_test_… vs am_sk_…), not the URL.-const DefaultBaseURL = "https://api.useautumn.com/v1"--// RESTClient is the live Autumn API client.-type RESTClient struct {- baseURL string- apiKey string- http *http.Client-}--// Option configures a RESTClient.-type Option func(*RESTClient)--// WithBaseURL overrides the API root (tests point this at an httptest server).-func WithBaseURL(u string) Option { return func(c *RESTClient) { c.baseURL = u } }--// WithHTTPClient overrides the underlying HTTP client.-func WithHTTPClient(h *http.Client) Option { return func(c *RESTClient) { c.http = h } }--// New builds a live client. apiKey is the Autumn secret key (am_sk_…).-func New(apiKey string, opts ...Option) *RESTClient {- c := &RESTClient{- baseURL: DefaultBaseURL,- apiKey: apiKey,- http: &http.Client{Timeout: 15 * time.Second},- }- for _, o := range opts {- o(c)- }- return c-}--var _ Client = (*RESTClient)(nil)--// do executes a JSON request and decodes the response into out (if non-nil).-func (c *RESTClient) do(ctx context.Context, method, path string, body, out any) error {- var rdr io.Reader- if body != nil {- b, err := json.Marshal(body)- if err != nil {- return fmt.Errorf("autumn: marshal %s: %w", path, err)- }- rdr = bytes.NewReader(b)- }- req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, rdr)- if err != nil {- return fmt.Errorf("autumn: build request %s: %w", path, err)- }- req.Header.Set("Authorization", "Bearer "+c.apiKey)- req.Header.Set("Content-Type", "application/json")-- resp, err := c.http.Do(req)- if err != nil {- return fmt.Errorf("autumn: %s %s: %w", method, path, err)- }- defer resp.Body.Close()-- data, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))- if resp.StatusCode < 200 || resp.StatusCode >= 300 {- return &APIError{StatusCode: resp.StatusCode, Body: string(data)}- }- if out != nil {- if err := json.Unmarshal(data, out); err != nil {- return fmt.Errorf("autumn: decode %s: %w", path, err)- }- }- return nil-}--func (c *RESTClient) CreateCustomer(ctx context.Context, p CreateCustomerParams) (*Customer, error) {- var cust Customer- if err := c.do(ctx, http.MethodPost, "/customers", p, &cust); err != nil {- return nil, err- }- return &cust, nil-}--func (c *RESTClient) GetCustomer(ctx context.Context, customerID string) (*Customer, error) {- var cust Customer- if err := c.do(ctx, http.MethodGet, "/customers/"+customerID, nil, &cust); err != nil {- return nil, err- }- return &cust, nil-}--func (c *RESTClient) Track(ctx context.Context, p TrackParams) (*TrackResult, error) {- var resp struct {- Balance Balance `json:"balance"`- }- err := c.do(ctx, http.MethodPost, "/track", p, &resp)- if err == nil {- return &TrackResult{Balance: resp.Balance}, nil- }- // A duplicate idempotency_key means this usage was already applied (a retry- // after the first call succeeded server-side). Not an error — re-fetch the- // current balance so the caller can still act (e.g. halt on remaining <= 0).- if isDuplicateIdempotency(err) {- cust, gerr := c.GetCustomer(ctx, p.CustomerID)- if gerr != nil {- return &TrackResult{Duplicate: true}, nil- }- return &TrackResult{Balance: cust.Balances[CreditsFeatureID], Duplicate: true}, nil- }- return nil, err-}--// isDuplicateIdempotency reports whether err is Autumn's 409-// duplicate_idempotency_key response.-func isDuplicateIdempotency(err error) bool {- var ae *APIError- return errors.As(err, &ae) && ae.StatusCode == http.StatusConflict &&- strings.Contains(ae.Body, "duplicate_idempotency_key")-}--func (c *RESTClient) Check(ctx context.Context, p CheckParams) (*CheckResult, error) {- var resp struct {- Allowed bool `json:"allowed"`- Balance Balance `json:"balance"`- }- if err := c.do(ctx, http.MethodPost, "/check", p, &resp); err != nil {- return nil, err- }- return &CheckResult{Allowed: resp.Allowed, Balance: resp.Balance}, nil-}--func (c *RESTClient) Checkout(ctx context.Context, p CheckoutParams) (*CheckoutResult, error) {- var res CheckoutResult- if err := c.do(ctx, http.MethodPost, "/checkout", p, &res); err != nil {- return nil, err- }- return &res, nil-}--// SetCreditBalance overwrites the `credits` balance via POST /customers/{id}/balances.-func (c *RESTClient) SetCreditBalance(ctx context.Context, customerID string, balance float64) error {- body := map[string]any{- "balances": []map[string]any{{"feature_id": CreditsFeatureID, "balance": balance}},- }- return c.do(ctx, http.MethodPost, "/customers/"+customerID+"/balances", body, nil)-}--func asAPIError(err error, target **APIError) bool {- return errors.As(err, target)-}diff --git a/internal/billing/autumn/fake.go b/internal/billing/autumn/fake.godeleted file mode 100644index 4e1e3f62..00000000--- a/internal/billing/autumn/fake.go+++ /dev/null@@ -1,157 +0,0 @@-package autumn--import (- "context"- "sync"-)--// Fake is an in-memory Client for tests. It mirrors Autumn's behavior: customers-// get the base plan + a signup grant, track() deducts per the credit schema and-// dedupes on idempotency_key, and checkout() returns a stub URL (call-// SimulateTopUp/SimulatePlanChange to model payment completing).-type Fake struct {- mu sync.Mutex- customers map[string]*Customer- seenKeys map[string]bool-- // CreditCosts maps a metered feature to its per-unit credit cost (mirrors the- // Autumn credit schema). SignupGrant is the one-time base grant.- CreditCosts map[string]float64- SignupGrant float64-}--// NewFake builds a Fake seeded with the production credit schema + $5 grant.-func NewFake() *Fake {- return &Fake{- customers: map[string]*Customer{},- seenKeys: map[string]bool{},- CreditCosts: map[string]float64{- "compute_1gb": 0.00000108,- "compute_4gb": 0.00000579,- "compute_8gb": 0.0000135,- "compute_16gb": 0.0000270,- "compute_32gb": 0.000193,- "compute_64gb": 0.000540,- "disk_overage": 0.0000001,- },- SignupGrant: 5,- }-}--var _ Client = (*Fake)(nil)--func (f *Fake) CreateCustomer(_ context.Context, p CreateCustomerParams) (*Customer, error) {- f.mu.Lock()- defer f.mu.Unlock()- if c, ok := f.customers[p.ID]; ok {- return clone(c), nil- }- c := &Customer{- ID: p.ID,- Name: p.Name,- Email: p.Email,- Subscriptions: []Subscription{- {PlanID: "base", AddOn: false, Status: "active"},- },- Balances: map[string]Balance{- CreditsFeatureID: {FeatureID: CreditsFeatureID, Granted: f.SignupGrant, Remaining: f.SignupGrant},- },- }- f.customers[p.ID] = c- return clone(c), nil-}--func (f *Fake) GetCustomer(_ context.Context, customerID string) (*Customer, error) {- f.mu.Lock()- defer f.mu.Unlock()- c, ok := f.customers[customerID]- if !ok {- return nil, &APIError{StatusCode: 404, Body: "customer not found"}- }- return clone(c), nil-}--func (f *Fake) Track(_ context.Context, p TrackParams) (*TrackResult, error) {- f.mu.Lock()- defer f.mu.Unlock()- c, ok := f.customers[p.CustomerID]- if !ok {- return nil, &APIError{StatusCode: 404, Body: "customer not found"}- }- if p.IdempotencyKey != "" {- dk := p.IdempotencyKey // global dedupe, mirroring Autumn- if f.seenKeys[dk] {- return &TrackResult{Balance: c.Balances[CreditsFeatureID], Duplicate: true}, nil // deduped- }- f.seenKeys[dk] = true- }- cost := p.Value * f.CreditCosts[p.FeatureID]- b := c.Balances[CreditsFeatureID]- b.Remaining -= cost- b.Usage += cost- c.Balances[CreditsFeatureID] = b- return &TrackResult{Balance: b}, nil-}--func (f *Fake) Check(_ context.Context, p CheckParams) (*CheckResult, error) {- f.mu.Lock()- defer f.mu.Unlock()- c, ok := f.customers[p.CustomerID]- if !ok {- return nil, &APIError{StatusCode: 404, Body: "customer not found"}- }- b := c.Balances[p.FeatureID]- return &CheckResult{Allowed: b.Unlimited || b.Remaining > 0, Balance: b}, nil-}--func (f *Fake) Checkout(_ context.Context, p CheckoutParams) (*CheckoutResult, error) {- return &CheckoutResult{- URL: "https://checkout.stripe.test/" + p.ProductID,- Currency: "usd",- }, nil-}--// SetCreditBalance overwrites the credits balance (migration carry-over).-func (f *Fake) SetCreditBalance(_ context.Context, customerID string, balance float64) error {- f.mu.Lock()- defer f.mu.Unlock()- c, ok := f.customers[customerID]- if !ok {- return &APIError{StatusCode: 404, Body: "customer not found"}- }- b := c.Balances[CreditsFeatureID]- b.Remaining = balance- c.Balances[CreditsFeatureID] = b- return nil-}--// SimulateTopUp models a completed credit purchase (manual or auto-recharge).-func (f *Fake) SimulateTopUp(customerID string, credits float64) {- f.mu.Lock()- defer f.mu.Unlock()- if c, ok := f.customers[customerID]; ok {- b := c.Balances[CreditsFeatureID]- b.Remaining += credits- b.Granted += credits- c.Balances[CreditsFeatureID] = b- }-}--// SimulatePlanChange models subscribing to / changing a concurrency plan.-func (f *Fake) SimulatePlanChange(customerID, planID string) {- f.mu.Lock()- defer f.mu.Unlock()- if c, ok := f.customers[customerID]; ok {- c.Subscriptions = append(c.Subscriptions, Subscription{PlanID: planID, AddOn: true, Status: "active"})- }-}--func clone(c *Customer) *Customer {- cp := *c- cp.Subscriptions = append([]Subscription(nil), c.Subscriptions...)- cp.Balances = make(map[string]Balance, len(c.Balances))- for k, v := range c.Balances {- cp.Balances[k] = v- }- return &cp-}diff --git a/internal/billing/autumn/integration_test.go b/internal/billing/autumn/integration_test.godeleted file mode 100644index 6a699d72..00000000--- a/internal/billing/autumn/integration_test.go+++ /dev/null@@ -1,70 +0,0 @@-package autumn--import (- "context"- "os"- "testing"- "time"-)--// Live smoke test against the Autumn sandbox. Skipped unless AUTUMN_SANDBOX_KEY-// is set, so normal `go test` stays offline. Run with:-//-// AUTUMN_SANDBOX_KEY=am_sk_test_… go test ./internal/billing/autumn/ -run TestLive -v-func TestLive_CustomerTrackFlow(t *testing.T) {- key := os.Getenv("AUTUMN_SANDBOX_KEY")- if key == "" {- t.Skip("set AUTUMN_SANDBOX_KEY to run the live sandbox smoke test")- }- c := New(key)- ctx := context.Background()- id := "oc-itest-" + time.Now().Format("20060102150405")-- cust, err := c.CreateCustomer(ctx, CreateCustomerParams{ID: id, Name: "oc integration test"})- if err != nil {- t.Fatalf("create: %v", err)- }- if cust.CreditsRemaining() != 5 {- t.Fatalf("signup grant = %v, want 5", cust.CreditsRemaining())- }- if cust.MaxConcurrency() != 5 {- t.Fatalf("base concurrency = %d, want 5", cust.MaxConcurrency())- }-- // Track 1000s of compute_64gb (× 0.00054 = 0.54 credits). The idempotency key- // is GLOBAL, so make it unique per run.- idemKey := id + ":compute_64gb:1"- r, err := c.Track(ctx, TrackParams{CustomerID: id, FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: idemKey})- if err != nil {- t.Fatalf("track: %v", err)- }- if d := 5 - r.Balance.Remaining; d < 0.539 || d > 0.541 {- t.Fatalf("deducted %v, want ~0.54", d)- }-- // Same key → no further deduction (live idempotency).- r2, err := c.Track(ctx, TrackParams{CustomerID: id, FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: idemKey})- if err != nil {- t.Fatalf("track 2: %v", err)- }- if !r2.Duplicate {- t.Fatalf("expected Duplicate=true on repeated idempotency_key")- }- if r2.Balance.Remaining != r.Balance.Remaining {- t.Fatalf("live idempotency failed: %v → %v", r.Balance.Remaining, r2.Balance.Remaining)- }-- // Checkout a top-up → must return a Stripe URL.- co, err := c.Checkout(ctx, CheckoutParams{- CustomerID: id, ProductID: "top_up",- Options: []CheckoutOption{{FeatureID: "credits", Quantity: 10}},- SuccessURL: "https://app.opencomputer.dev/billing",- })- if err != nil {- t.Fatalf("checkout: %v", err)- }- if co.URL == "" {- t.Fatalf("checkout returned no url")- }- t.Logf("live OK: remaining=%.4f checkout=%s", r2.Balance.Remaining, co.URL[:40])-}diff --git a/internal/billing/autumn/usage.go b/internal/billing/autumn/usage.godeleted file mode 100644index 5072b292..00000000--- a/internal/billing/autumn/usage.go+++ /dev/null@@ -1,34 +0,0 @@-package autumn--import "fmt"--// DiskOverageFeatureID is the metered feature for disk used above the included-// allowance (value tracked in GB-seconds).-const DiskOverageFeatureID = "disk_overage"--// tierFeatureByMemoryMB maps a sandbox memory tier (MB) to its Autumn compute-// feature. Keep in sync with the per-tier rates in internal/billing/pricing.go-// and the credit schema configured in Autumn.-var tierFeatureByMemoryMB = map[int]string{- 1024: "compute_1gb",- 4096: "compute_4gb",- 8192: "compute_8gb",- 16384: "compute_16gb",- 32768: "compute_32gb",- 65536: "compute_64gb",-}--// FeatureForMemoryMB returns the Autumn compute feature id for a memory tier,-// or ("", false) if the tier is unknown (caller should skip + log).-func FeatureForMemoryMB(mb int) (string, bool) {- f, ok := tierFeatureByMemoryMB[mb]- return f, ok-}--// UsageIdempotencyKey builds a globally-unique, retry-stable idempotency key for-// a usage bucket. Autumn dedupes on the bare key across all customers, so it-// must include the org; it must also be stable across retries, so it's keyed on-// the bucket start (not wall-clock now).-func UsageIdempotencyKey(orgID string, bucketStartUnix int64, featureID string) string {- return fmt.Sprintf("usage:%s:%d:%s", orgID, bucketStartUnix, featureID)-}diff --git a/internal/billing/autumn/usage_test.go b/internal/billing/autumn/usage_test.godeleted file mode 100644index 6db6dd16..00000000--- a/internal/billing/autumn/usage_test.go+++ /dev/null@@ -1,44 +0,0 @@-package autumn--import "testing"--func TestFeatureForMemoryMB(t *testing.T) {- cases := map[int]string{- 1024: "compute_1gb",- 4096: "compute_4gb",- 8192: "compute_8gb",- 16384: "compute_16gb",- 32768: "compute_32gb",- 65536: "compute_64gb",- }- for mb, want := range cases {- if got, ok := FeatureForMemoryMB(mb); !ok || got != want {- t.Errorf("FeatureForMemoryMB(%d) = (%q,%v), want (%q,true)", mb, got, ok, want)- }- }- if got, ok := FeatureForMemoryMB(2048); ok {- t.Errorf("FeatureForMemoryMB(2048) = (%q,true), want unknown", got)- }-}--func TestUsageIdempotencyKey(t *testing.T) {- // Stable across calls (retry-safe) and namespaced by org+bucket+feature so- // it's globally unique under Autumn's bare-key dedupe.- a := UsageIdempotencyKey("org-1", 1000, "compute_8gb")- if a != "usage:org-1:1000:compute_8gb" {- t.Fatalf("unexpected key %q", a)- }- if UsageIdempotencyKey("org-1", 1000, "compute_8gb") != a {- t.Fatal("key not deterministic")- }- // Any axis change must produce a distinct key.- for _, other := range []string{- UsageIdempotencyKey("org-2", 1000, "compute_8gb"),- UsageIdempotencyKey("org-1", 1001, "compute_8gb"),- UsageIdempotencyKey("org-1", 1000, "compute_4gb"),- } {- if other == a {- t.Fatalf("key collision: %q", other)- }- }-}diff --git a/internal/config/config.go b/internal/config/config.goindex ac2fd696..81a9a86c 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -150,16 +150,8 @@ type Config struct {StripeSuccessURL stringStripeCancelURL string- // Autumn billing (useautumn.com) — the prepaid credit ledger + concurrency- // plans. AutumnSecretKey empty disables the Autumn path (orgs stay legacy).- // AutumnBaseURL is an optional override; empty uses autumn.DefaultBaseURL.- AutumnSecretKey string- AutumnWebhookSecret string- AutumnBaseURL string- // AutumnEnforce flips the Autumn usage reporter out of shadow: on balance- // exhaustion it hibernates the org locally and projects is_halted to the- // edge (D1). Default false — ship shadow first, then flip to go live.- AutumnEnforce bool+ // Autumn billing is edge-native (api-edge worker reads Autumn directly); the+ // cell holds no Autumn client or secrets. See cloudflare-workers/api-edge.// Per-agent paywalled-feature prices (set in Stripe dashboard, referenced// by ID here). Empty = feature ungated on this deployment (dev mode).@@ -380,10 +372,6 @@ func Load() (*Config, error) {StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),- AutumnSecretKey: os.Getenv("AUTUMN_SECRET_KEY"),- AutumnWebhookSecret: os.Getenv("AUTUMN_WEBHOOK_SECRET"),- AutumnBaseURL: os.Getenv("AUTUMN_BASE_URL"),- AutumnEnforce: os.Getenv("AUTUMN_ENFORCE") == "true",StripeTelegramAgentPriceID: os.Getenv("STRIPE_TELEGRAM_AGENT_PRICE_ID"),StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),diff --git a/internal/config/keyvault.go b/internal/config/keyvault.goindex 96af7997..2d4b7aab 100644--- a/internal/config/keyvault.go+++ b/internal/config/keyvault.go@@ -47,8 +47,6 @@ var kvMapping = map[string]string{"server-cf-zone-id": "OPENSANDBOX_CF_ZONE_ID","server-stripe-secret-key": "STRIPE_SECRET_KEY","server-stripe-webhook-secret": "STRIPE_WEBHOOK_SECRET",- "server-autumn-secret-key": "AUTUMN_SECRET_KEY",- "server-autumn-webhook-secret": "AUTUMN_WEBHOOK_SECRET","server-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",// Machine-size fallback lists (PR #209). Comma-separated ranked// instance types the autoscaler tries in order on quota / capacitydiff --git a/internal/db/usage.go b/internal/db/usage.goindex 064717ce..6ad49b33 100644--- a/internal/db/usage.go+++ b/internal/db/usage.go@@ -291,9 +291,9 @@ func (s *Store) UpdateLastUsageReportedAt(ctx context.Context, orgID uuid.UUID,}// SetBillingProvider flips an org's billing system selector in cell-PG. The-// migrate tool pairs this with edgeclient.SetAutumnProvider (D1) for an-// atomic-as-possible per-org cutover; ordering across the two stores is chosen-// so the legacy and Autumn chargers are never both live for the same org.+// per-org migration (a follow-up tool) pairs this with the D1 flip for an+// atomic-as-possible cutover; ordering across the two stores is chosen so the+// legacy and Autumn chargers are never both live for the same org.func (s *Store) SetBillingProvider(ctx context.Context, orgID uuid.UUID, provider string) error {_, err := s.pool.Exec(ctx,`UPDATE orgs SET billing_provider = $2, updated_at = NOW() WHERE id = $1`,diff --git a/internal/edgeclient/client.go b/internal/edgeclient/client.goindex 32062dc1..9f0abb96 100644--- a/internal/edgeclient/client.go+++ b/internal/edgeclient/client.go@@ -287,40 +287,6 @@ func (c *Client) UpdateTemplateStatus(ctx context.Context, id uuid.UUID, statusreturn nil}-// ── Autumn billing projection ──────────────────────────────────────────--// ProjectAutumnOrg triggers the edge to re-read the org's authoritative Autumn-// state and re-project it into D1 (is_halted / max_concurrent) + dispatch halt-// to cells. Used by the cell's inline halt (off track()) so the cell never owns-// Autumn reads or D1 writes — those stay at the edge, same as /webhooks/autumn.-func (c *Client) ProjectAutumnOrg(ctx context.Context, orgID uuid.UUID) error {- body, _ := json.Marshal(map[string]string{"org_id": orgID.String()})- respBody, status, err := c.do(ctx, "POST", "/internal/autumn-project", body)- if err != nil {- return err- }- if status != 200 {- return fmt.Errorf("edge status %d: %s", status, string(respBody))- }- return nil-}--// SetAutumnProvider flips D1 orgs.billing_provider for one org (the migrate-// tool's D1 half; the cell-PG half is a direct store write). On →autumn the-// edge also projects is_halted/max_concurrent so the edge gates are correct the-// instant the flag flips.-func (c *Client) SetAutumnProvider(ctx context.Context, orgID uuid.UUID, provider string) error {- body, _ := json.Marshal(map[string]string{"org_id": orgID.String(), "provider": provider})- respBody, status, err := c.do(ctx, "POST", "/internal/autumn-set-provider", body)- if err != nil {- return err- }- if status != 200 {- return fmt.Errorf("edge status %d: %s", status, string(respBody))- }- return nil-}-// ── Secret stores ──────────────────────────────────────────────────────// edgeStore intentionally omits createdAt / updatedAt. The edge worker