carlos / platform Public

Plan: bytes served per instance, a read-only usage route

Implementation plan for the instance usage design (spec revision 5,
discussion #1519), and the round 1 Astra review brief for it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 971f8bf03fcf73ab248fe5f901e3e776d46cec34 parent 9673143
2 files changed, +693 −0
  • docs/superpowers/plans/2026-11-29-instance-usage.md +613 −0
  • docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-usage-plan.md +80 −0

CI cancelled — superseded by a newer push — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-JuSfml
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
go: downloading github.com/aws/smithy-go v1.28.1
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading github.com/prometheus/client_golang v1.17.0
go: downloading golang.org/x/sync v0.24.0
go: downloading github.com/aws/aws-sdk-go-v2/config v1.32.6
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0
go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1
go: downloading golang.org/x/sys v0.49.0
go: downloading github.com/pion/logging v0.2.4
go: downloading github.com/pion/stun/v3 v3.1.5
go: downloading github.com/pion/turn/v4 v4.1.4
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/pion/randutil v0.1.0
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/prometheus/client_model v0.5.0
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0
go: downloading golang.org/x/text v0.43.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/google/uuid v1.6.0
go: downloading modernc.org/mathutil v1.7.1

amadan: job cancelled — a newer push superseded it
diff --git a/docs/superpowers/plans/2026-11-29-instance-usage.md b/docs/superpowers/plans/2026-11-29-instance-usage.md
new file mode 100644
index 000000000..a94e86785
--- /dev/null
+++ b/docs/superpowers/plans/2026-11-29-instance-usage.md
@@ -0,0 +1,613 @@
+# Bytes served per instance: implementation plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Count edge bytes and requests per instance, by the UTC hour each
+exchange completed, into a new per-box, per-date, per-app object family,
+and serve one app's whole UTC month (counted so far, a lower bound) through
+a read-only route, a new `usage` service role and `carlos usage`.
+
+**Architecture:** The edge meter gains a second map keyed by
+`{hour, account, app, instance}`; the agent's five-minute flush hands each
+drain to a queue that CAS-merges it, exactly once per batch and object, into
+`usage/instances/<box>/<date>/<account>/<app>.json`. The console persists
+the attribution start (`usage/instances/@from.json`) once the hostname
+history is verified active, and a switch-gated route sums one app's objects
+for a month. Nothing under `usage/edge/` changes.
+
+**Tech Stack:** Go; `release.Store` (S3 / `release.DirStore`); console
+`routeDecls`; `clireg`.
+
+**Spec:** `docs/superpowers/specs/2026-11-29-instance-usage-design.md`
+(revision 5, reviewed in Astra rounds 1-3). Section numbers (§N) below are
+the spec's. Discussion: carlos/platform #1519.
+
+## Global Constraints
+
+- Nothing under `usage/edge/` changes: same keys, same bytes, same dating
+ by flush, still skipping empty flushes (§6, T10).
+- The new family's keys: `usage/instances/@from.json` and
+ `usage/instances/<box>/<date>/<account>/<app>.json`. Body `"v": 1`; its
+ `box`, `date`, `account`, `app` must match the key or the object is
+ refused (§6).
+- Record stays one lock and two map updates, no I/O, no new per-request
+ allocation beyond map growth (§5).
+- Drop horizon: no write or retry is started for a bucket whose hour began
+ more than 24 hours before the tick (§5 item 4).
+- Every writer marker in `applied` is kept for the object's life (§5, R3-1).
+- Route: `GET /api/cli/apps/{account}/{app}/usage?month=YYYY-MM`; memo 60 s
+ keyed `(account sqid, app, month)`; at most 10,000 instances; gate and
+ history check before every memo hit (§8).
+- Role `usage`: outside Admin's union; the door is
+ `Exactly(Usage, Instance, Operate, Admin)`; mint needs an app and the
+ switch on (§9).
+- Switches: box `CARLOS_INSTANCE_USAGE=off` in `host.env` stops counting
+ and writing; console `CONSOLE_INSTANCE_USAGE=true` registers the route,
+ allows the mint and writes `@from` (§12).
+- Go rules (AGENTS.md "Writing Go here"): ctx passed on; CLI returns errors,
+ never `log.Fatal`; tests wait on a seam, never `time.Sleep`; `errors.Is`;
+ no function over 300 lines, no file over 3,000. Run `make code-health`
+ before pushing Go.
+- `internal/edge` tests that read the standard log use `captureLog`; the
+ meter is under `make race` (T13).
+- Copy (the CLI's words and the route's messages) is the Luna-approved text
+ from Task 0, pinned by `approved_usage_copy_test.go`. No em dashes.
+- Commit subjects under 80 characters, a body, trailer
+ `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`; stage by path.
+- Dev only. No production change.
+
+## Review Focus
+
+1. **A bucket's hour exactly at the drop horizon** (hour began exactly 24 h
+ before the tick): kept; one second older: dropped and counted. Test in
+ Task 3.
+2. **An account or app name that is not a safe key segment** (empty, `.`,
+ `..`, contains `/`): the box drops those buckets with a log line and
+ never writes a key outside the family; the queue does not wedge. Test in
+ Task 3.
+3. **A month at the boundary of `from`**: `month` equal to `from`'s month
+ answers; the month before is 409 naming `from`'s month; the current month
+ answers dates up to today only and reads no future date. Test in Task 6.
+4. **The console's own clock vs a box's late write**: an object for date D
+ written after D settled is read once the cache entry ages out, never
+ double-counted (spec R3-2). Test in Task 6 (cache entry, re-read after
+ `usageDayMaxAge`).
+5. **Two consoles racing to create `@from`**: create-only Put; the loser
+ re-reads and adopts the winner's body. Test in Task 6.
+
+---
+
+## File structure
+
+| File | Responsibility |
+|---|---|
+| `internal/usage/instances.go` (new) | Family types, keys, decode with key check, merge, `@from` shape |
+| `internal/usage/instances_test.go` (new) | Key, decode, merge, size fixture (T9) |
+| `internal/edge/usagemeter.go` | `Record` gains `instance`; clock; instance map; `Drain` returns it |
+| `internal/edge/edge.go`, `demo_traffic.go`, `assetcatch.go` | The three callers |
+| `internal/host/instance_usage.go` (new) | The batch queue, exactly-once writes, drop horizon |
+| `internal/host/instance_usage_test.go` (new) | T1-T6 at the flush, the randomized simulation |
+| `internal/host/usage_loop.go`, `agent.go` | Wire the queue; `CARLOS_INSTANCE_USAGE=off` |
+| `internal/status/snapshot.go` | `instance_usage_dropped_bytes` on the box status |
+| `internal/svcrole/svcrole.go` | `Usage` role |
+| `internal/console/usagefrom.go` (new) | `@from`: write, hold, move on a break |
+| `internal/console/apiusage.go` (new) | The route, its memo, its reads |
+| `internal/console/usagedays.go` | `usageDayDate` learns the new family |
+| `internal/console/routedecls.go`, `config.go`, `cmd/console/main.go` | Switch, gate, door |
+| `internal/console/svcprincipal.go`, `apiservices.go`, `svcpage.go` | Mint and resolve rules for `usage` |
+| `usage_cmd.go` (new), `commands.go` | `carlos usage` |
+| `parity/parity.tsv`, `parity/cli.tsv`, `docs/site/cli.md` | Parity row, CLI heading |
+
+---
+
+### Task 0: UX pass and copy review (controller, no subagent)
+
+The CLI's human output and the route's error sentences are user-facing
+(AGENTS.md "Every UI change gets a UX pass"; spec §10).
+
+- [ ] **Step 1: UX pass.** Mock the human output for: the current month with
+ rows; a past month; no traffic yet; before `from`; history not active;
+ check pending; over the cap. Lead with the state (the app, the month, the
+ total), then the table. Check it at 80 columns.
+- [ ] **Step 2: Luna copy review.** Send every string (CLI output, CLI usage
+ text, the route's 400/409/503 messages, the `docs/site/cli.md` section,
+ the mint refusals for `--role usage`) to Luna
+ (`codex exec -m gpt-6-luna ...`). Record the approved strings in
+ `docs/superpowers/notes/instance-usage-copy.md`; tasks 5, 6 and 7 use them
+ verbatim.
+- [ ] **Step 3: Commit** the copy note.
+
+### Task 1: The family in `internal/usage` (Sonnet)
+
+**Files:** Create `internal/usage/instances.go`, `internal/usage/instances_test.go`; modify `internal/usage/edge.go` (`EdgeFlush` field).
+
+**Interfaces — Produces:**
+
+```go
+const InstancesPrefix = "usage/instances/"
+const InstanceFromKey = "usage/instances/@from.json"
+
+// InstanceBucket is one meter key: the Unix hour (seconds/3600) the
+// exchange completed in, and the route row's owner and instance host.
+type InstanceBucket struct {
+ Hour int64
+ Account, App, Instance string
+}
+
+type InstanceCount struct {
+ Requests int64 `json:"requests"`
+ BytesOut int64 `json:"bytes_out"`
+ HopRequests int64 `json:"hop_requests,omitempty"`
+ HopBytesOut int64 `json:"hop_bytes_out,omitempty"`
+}
+func (c *InstanceCount) Add(o InstanceCount)
+
+type InstanceDay struct {
+ V int `json:"v"` // 1
+ Box string `json:"box"`
+ Date string `json:"date"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Applied map[string]string `json:"applied"` // writer id -> last batch id
+ Instances map[string]InstanceCount `json:"instances"` // host -> counts; "" = unattributable
+}
+
+var ErrInstanceKey = errors.New("usage: not a safe instance usage key")
+var ErrInstanceDayMismatch = errors.New("usage: instance day does not match its key")
+
+func InstanceDayKey(box, date, account, app string) (string, error) // ErrInstanceKey unless every segment is a plain key segment and date parses as 2006-01-02
+func ParseInstanceDayKey(key string) (box, date, account, app string, ok bool)
+func DecodeInstanceDay(key string, raw []byte) (InstanceDay, error) // v==1, fields == key's, else ErrInstanceDayMismatch (wrapped); JSON error wrapped
+func (d *InstanceDay) Merge(writer, batch string, counts map[string]InstanceCount) // sums counts, sets Applied[writer]=batch, never removes a marker
+func HourDate(hour int64) string // UTC date of the hour, "2006-01-02"
+
+type InstanceFrom struct {
+ From string `json:"from"` // first day of a UTC month, "2006-01-02"
+ Activation time.Time `json:"activation"` // HostsState.At when written
+}
+```
+
+`EdgeFlush` gains `Instances map[InstanceBucket]InstanceCount`; `UpsertEdgeDay`
+ignores it (its empty check stays on `Rows` and `Guard`).
+
+A plain key segment: not empty, not `.` or `..`, no `/` (the console's
+`keySegment`). `@` is allowed in no box label, so `@from.json` never
+collides with a box directory.
+
+- [ ] **Step 1: Failing tests** in `instances_test.go`:
+ `TestInstanceDayKeyRoundTrip` (key for `("box-1","2026-11-30","bab","patrix-sites")` is
+ `usage/instances/box-1/2026-11-30/bab/patrix-sites.json`, parses back);
+ `TestInstanceDayKeyRefusesUnsafe` (`""`, `"."`, `".."`, `"a/b"` in each
+ segment, and date `"2026-13-01"` give `ErrInstanceKey`);
+ `TestDecodeInstanceDayChecksKey` (each of v=2, box, date, account, app
+ mismatched gives `errors.Is(err, ErrInstanceDayMismatch)`);
+ `TestMergeKeepsEveryMarker` (merge writer A batch 1, writer B batch 1,
+ writer A batch 2: `Applied == {"A":"2","B":"1"}`, counts summed);
+ `TestUpsertEdgeDayIgnoresInstances` (a flush with only `Instances` writes
+ no `usage/edge/` object);
+ `TestHourDate` (hour of 2026-11-30T23:58:30Z is `2026-11-30`; of
+ 2026-12-01T00:03Z is `2026-12-01`).
+- [ ] **Step 2: Size fixture (T9)** `TestInstanceDaySizeTable`: serialise
+ compactly one row for each §6 fixture (25-char host with 10-digit
+ counters, 32/12, 144/19, 253/19; all four counters set), assert the
+ per-row bytes within ±3 of 128, 143, 283, 392 (update the table's
+ numbers to the measured values if they differ, and say so in the commit
+ body), and that 10,000 rows of 253-character hosts and 19-digit counters
+ marshal under 8 MiB.
+- [ ] **Step 3: Run** `go test ./internal/usage -run 'InstanceDay|Merge|HourDate|UpsertEdgeDayIgnores' -count=1`: FAIL.
+- [ ] **Step 4: Implement** the interfaces above.
+- [ ] **Step 5: Run** the same: PASS. `gofmt -l internal/usage` empty.
+- [ ] **Step 6: Commit** `usage: the per-instance day family and its keys`.
+
+### Task 2: The meter and its three callers (Opus; per-task Astra review: billing)
+
+**Files:** Modify `internal/edge/usagemeter.go`, `internal/edge/edge.go:2771`,
+`internal/edge/demo_traffic.go:217`, `internal/edge/assetcatch.go:1159-1177`;
+every test calling `Record` (grep `\.Record(` under `internal/edge`). Test:
+`internal/edge/usagemeter_instances_test.go` (new).
+
+**Interfaces — Consumes:** Task 1's `InstanceBucket`, `InstanceCount`,
+`EdgeFlush.Instances`. **Produces:**
+
+```go
+func (u *UsageMeter) Record(rt registry.Route, instance string, requests, bytes int64, hopped bool)
+func (u *UsageMeter) SetClock(now func() time.Time) // tests; default time.Now
+func (u *UsageMeter) DisableInstances() // CARLOS_INSTANCE_USAGE=off
+// Drain also returns f.Instances (nil when empty) and resets it.
+```
+
+Record: the old per-host row exactly as today (keyed `rt.Host`). Then, only
+when `rt.Kind == "instance"` and instances are enabled, add to
+`{Hour: now().Unix()/3600 (floor, UTC), Account: release.RouteAccount(rt), App: rt.App, Instance: instance}`;
+`hopped` also adds the hop subset. Under the same one lock.
+
+Callers: `ServeHTTP` (edge.go) and the demo path pass `rt.Host` / `up.route.Host`.
+The far asset catch passes `host` only when `a.Primary == host`, else `""`;
+decide it once beside the synthetic route (`assetcatch.go:1159`).
+
+- [ ] **Step 1: Failing tests** (`usagemeter_instances_test.go`, fake clock):
+ `TestRecordPlacesHourAtCompletion` (Record at 23:58:30Z and 00:00:10Z on
+ the next day give two buckets with hours 1h apart, the first
+ `HourDate`=`2026-11-30`); `TestRecordStaticNotInInstances` (Kind
+ `"static"` row: old row counted, `Instances` empty);
+ `TestRecordOwnerChangeKeepsTwoBuckets` (same host, account A then B, two
+ buckets); `TestRecordHopSubset` (hopped adds `HopRequests/HopBytesOut`
+ inside the totals); `TestDisableInstances` (no buckets, old rows intact);
+ `TestOldRowsUnchangedByInstanceArg` (for one script, `Drain().Rows` equal
+ with instance `""` and with `rt.Host`).
+- [ ] **Step 2: Far catch tests (T11)** in the existing far-asset test file
+ (`asset_far_test.go`): a far delivery of the primary host is bucketed
+ under that host; a far alias delivery (request host != `a.Primary`) is
+ under the request host in `Rows` and `""` in `Instances`; a block with
+ `Primary == ""` is `""`.
+- [ ] **Step 3: Race (T13)** `TestRecordConcurrentDrain`: 8 goroutines
+ Record while one drains in a loop; total requests across drains equals
+ the number recorded, for both maps. Started with `goTracked`-style
+ bookkeeping if the package requires it; ends before the test does.
+- [ ] **Step 4: Run** `go test ./internal/edge -run 'Record|FarAsset|AssetFar' -count=1`: FAIL (compile).
+- [ ] **Step 5: Implement** the meter and update all callers and test call
+ sites (tests that do not care pass `rt.Host`).
+- [ ] **Step 6: Run** the tests above, then `go test -race ./internal/edge -run 'Record' -count=1`, then `go vet ./internal/edge`: PASS.
+- [ ] **Step 7: Commit** `edge: count bytes per instance by the hour each exchange ends`.
+
+### Task 3: The flush queue, the box switch and the dropped count (Opus; per-task Astra review: billing, root binary)
+
+**Files:** Create `internal/host/instance_usage.go`,
+`internal/host/instance_usage_test.go`; modify `internal/host/usage_loop.go`,
+`internal/host/agent.go:1430-1446`, `internal/status/snapshot.go` (box
+status field and its builder parameter).
+
+**Interfaces — Consumes:** Task 1 (`InstanceDayKey`, `DecodeInstanceDay`,
+`Merge`, `HourDate`), Task 2 (`EdgeFlush.Instances`, `DisableInstances`).
+**Produces:**
+
+```go
+type instanceFlusher struct { /* writer id, queue, now, dropped */ }
+func newInstanceFlusher(box string, now func() time.Time, rnd io.Reader) *instanceFlusher // writer id: 16 hex chars from rnd
+func (f *instanceFlusher) Add(counts map[usage.InstanceBucket]usage.InstanceCount) // one new batch (id from rnd), grouped by object key; an unsafe key's buckets are dropped and logged
+func (f *instanceFlusher) Flush(ctx context.Context, s release.Store) // works the queue once
+func (f *instanceFlusher) DroppedBytes() int64 // cumulative since start, horizon drops and unsafe keys
+func (f *instanceFlusher) Pending() int // batches queued, for tests
+```
+
+`usageFlush` gains a `*instanceFlusher` parameter (nil = switched off): it
+calls `fl.Add(f.Instances)` then `fl.Flush(ctx, s)` on the same store `s`
+the edge day uses (so a fleet box writes under its prefix), after the edge
+day write, whatever that returned.
+
+Flush, per tick (spec §5):
+
+```
+blocked := {}
+for batch in queue, oldest first:
+ for key in sorted(batch.owes):
+ drop buckets whose hour start < now - 24h (log bytes; add to dropped)
+ if no buckets left: delete owes[key]; continue
+ if blocked[key]: continue
+ if err := writePart(key, batch.id, buckets); err != nil { blocked[key] = true; log; continue }
+ delete owes[key]
+drop batches that owe nothing
+```
+
+`writePart`: up to three attempts on `release.ErrCASConflict`: Get; absent
+is a new `InstanceDay` from the key with Put etag `""` (create-only);
+present is `DecodeInstanceDay` (an error leaves the part queued, logged);
+if `Applied[writer] == batch` return nil; else `Merge` and conditional Put
+on the etag read. Any other error is returned.
+
+Box switch: in `agent.go` where the meter is made, when
+`os.Getenv("CARLOS_INSTANCE_USAGE") == "off"`: `m.DisableInstances()`, pass
+a nil flusher, log `agent: instance usage off (CARLOS_INSTANCE_USAGE=off)`.
+
+Status: `status.Box` gains
+`InstanceUsageDroppedBytes int64 \`json:"instance_usage_dropped_bytes,omitempty"\``,
+filled from the flusher through the snapshot builder's parameters (a
+package-level `atomic.Int64` the flusher updates is acceptable; pick the
+pattern the builder already uses for agent-side counters).
+
+- [ ] **Step 1: Failing tests** (`release.DirStore` wrapped by a
+ fault-injecting store with hooks: fail Get/Put N times; apply a Put and
+ return an error; hold a Put and land it later), fake clock:
+ - `TestInstanceFlushNovemberInDecember` (T1): buckets at 23:58:30Z
+ 30 Nov, drained and flushed at 00:03Z 1 Dec, land in
+ `.../2026-11-30/...`; nothing under `2026-12-01`.
+ - `TestInstanceFlushLateRetry` (T2): Puts fail at 00:03 and 00:08; the
+ 00:13 tick writes; counted once, still 30 Nov.
+ - `TestInstanceFlushLostAnswer` (T3): Put applied, error returned; next
+ tick reads `applied[writer]==batch` and Puts nothing; totals once.
+ - `TestInstanceFlushDelayedRace` (T3): first Put held; retry merges and
+ lands; held Put released fails its ETag; totals once.
+ - `TestInstanceFlushTwoWriters` (T3): two flushers, one box, same object,
+ alternating batches; totals are the sum; neither skips its batch
+ because of the other's marker; both markers present.
+ - `TestInstanceFlushOrder` (T4): batch X fails for object O, batch Y owes
+ O: Y not written that tick; next tick X then Y; `applied[writer]==Y.id`.
+ - `TestInstanceFlushHorizon`: a bucket whose hour began exactly 24 h
+ before the tick is written; 24 h + 1 s is dropped, `DroppedBytes`
+ grows by its bytes, no Put is started for it.
+ - `TestInstanceFlushUnsafeKey`: account `"a/b"` buckets dropped and
+ counted, the batch's other objects written, queue empties.
+ - `TestInstanceFlushSpanningResponse` (T6): one exchange recorded at
+ 00:00:05Z (started before midnight) is wholly in the new day.
+ - `TestInstanceFlushOffSwitch`: `usageFlush` with a nil flusher writes no
+ `usage/instances/` key and the same `usage/edge/` bytes.
+- [ ] **Step 2: Randomized simulation (T5)** `TestInstanceFlushSimulation`:
+ seeded (seed logged; 200 runs of 300 steps under `-short`, 2,000 without),
+ steps drawn from {record buckets for random hours within 30 h, drain+add,
+ flush, fail next Get/Put, lose next answer, hold next Put, land a held
+ Put, restart a flusher (new writer, empty queue), advance clock 5 min}.
+ After every step, for every object: total ≤ sum of what its batches
+ counted; every marker ever written is still present; no Put was started
+ for a bucket past the horizon (hook records the bucket hours of each
+ attempted part). When nothing is queued, nothing dropped, nothing held
+ and no restart lost a queue: total == counted.
+- [ ] **Step 3: Run** `go test ./internal/host -run 'InstanceFlush' -count=1`: FAIL.
+- [ ] **Step 4: Implement** `instance_usage.go`, wire `usage_loop.go` and
+ `agent.go`, add the status field.
+- [ ] **Step 5: Run** `go test ./internal/host -run 'InstanceFlush|UsageFlush' -count=1`
+ and `go test ./internal/status -count=1`: PASS. Then
+ `GOOS=darwin go build . && GOOS=windows go build .`.
+- [ ] **Step 6: Commit** `host: flush instance counts once per batch into their date`.
+
+### Task 4: Compatibility pins (Sonnet)
+
+**Files:** Test `internal/host/usage_compat_test.go` (new),
+`internal/console/economics_instances_compat_test.go` (new).
+
+**Interfaces — Consumes:** Tasks 1-3.
+
+- [ ] **Step 1: T10, the box side** `TestEdgeDayBytesUnchangedByInstances`:
+ for a fixed traffic script recorded through a real `UsageMeter` and
+ `usageFlush`, the `usage/edge/<box>/days/<date>.json` bytes equal a
+ golden file (`testdata/usage-edge-golden.json`) captured from the same
+ script with the instance flusher nil; a box serving nothing writes no
+ `usage/edge/` key with the flusher on.
+- [ ] **Step 2: T10, the console side**
+ `TestEconomicsIgnoresInstanceFamily`: a store with `usage/edge/` days for
+ two boxes, plus `usage/instances/` objects for a third box label: the
+ economics sweep's discovered boxes and meters (`EgressMetered` included)
+ equal the run without the `usage/instances/` objects.
+- [ ] **Step 3: Run** both; PASS (they pin existing behaviour; if one
+ fails, the change broke compatibility: stop and report).
+- [ ] **Step 4: Commit** `usage: pin the edge family against the instance family`.
+
+### Task 5: The switch, the role and the door's registration (Opus; per-task Astra review: security gate)
+
+**Files:** Modify `internal/svcrole/svcrole.go` (+ tests),
+`internal/console/config.go` (Config field), `cmd/console/main.go`
+(env), `internal/console/routedecls.go` (gate + declaration),
+`internal/console/svcprincipal.go` (mint and resolve), `apiservices.go`,
+`svcpage.go`, `services.go` (`roleNames` reads `svcrole.All()` already),
+`internal/console/svcroutes_test.go`. Placeholder handler
+`handleAPIUsage` answering 501 until Task 6 (in `apiusage.go`).
+
+**Interfaces — Produces:**
+
+```go
+// svcrole
+Usage Role = "usage" // catalogue order: after Platform, before Admin
+// Allow panics on Usage, as on Run and Platform.
+
+// console
+Config.InstanceUsage bool // CONSOLE_INSTANCE_USAGE == "true"
+var gateInstanceUsage = &routeGate{"instance-usage", func(c Config) bool { return c.InstanceUsage }} // added to routeGates
+{Pattern: "GET /api/cli/apps/{account}/{app}/usage", Kind: kindCLI, Gate: gateInstanceUsage,
+ Allow: svcrole.Exactly(svcrole.Usage, svcrole.Instance, svcrole.Operate, svcrole.Admin),
+ Handler: (*Server).handleAPIUsage}
+var ErrAccountScopedUsage, ErrUsageOff error // mint refusals, Task 0 copy
+```
+
+Mint (the shared mint in `svcprincipal.go` ~455, so CLI and browser both
+get it): `Usage` with no app is `ErrAccountScopedUsage`; `Usage` with
+`!cfg.InstanceUsage` is `ErrUsageOff`. Resolve (~195): a `usage` row with
+no app fails closed (the Run rule's twin). `svcpage.go`: the role list
+skips `usage` while the switch is off; its refusal for a usage mint with
+no app uses the Task 0 sentence. `platform_credentials.go` must not mint
+it (check its allow-list; add a test if it is not already closed).
+
+- [ ] **Step 1: Failing tests:**
+ - svcrole: `TestAllowPanicsOnUsage`; `All()` includes `usage`;
+ `Exactly(Usage)` permits it; `Allow(Publish)` does not.
+ - `TestUsageDoorIsTheOnlyUsageDoor` (svcroutes_test.go): across every
+ registered declaration, the only one whose Set permits `Usage` is the
+ usage route, and no `Allow`-built Set carries it; the intent list
+ gives Usage exactly this door.
+ - `TestInstanceRoleMatchesTodaysAppTokenReach` gains the usage door for
+ Instance; `closedDoors` and `mintDoors` unchanged and refuse a usage
+ credential (extend the existing per-role loops to include `usage`).
+ - `TestUsageRouteGatedBySwitch`: switch off, the route 404s for a member;
+ on, it is registered.
+ - `TestMintUsage`: no app refused; switch off refused; on with an app
+ minted, and the credential reaches the usage door for its app only
+ (another app 404, byte-identical to an unknown app); its `doors` list
+ is exactly the usage door.
+ - `TestResolveUsageWithoutAppFailsClosed`.
+ - `cmd/console`: `CONSOLE_INSTANCE_USAGE=true` sets the field; anything
+ else leaves it false.
+- [ ] **Step 2: Run** `go test ./internal/svcrole ./internal/console ./cmd/console -run 'Usage|InstanceRole|Allow|Exactly|DoorIntent' -count=1`: FAIL.
+- [ ] **Step 3: Implement.**
+- [ ] **Step 4: Run** the same, then `go test ./internal/console -run 'Svc|Service|Door|Route|Parity' -count=1`: PASS.
+- [ ] **Step 5: Commit** `console: a usage role and its one switched door`.
+
+### Task 6: `@from` and the route (Opus; per-task Astra review: security gate, cache)
+
+**Files:** Create `internal/console/usagefrom.go`,
+`internal/console/usagefrom_test.go`, fill `internal/console/apiusage.go`,
+`internal/console/apiusage_test.go`; modify `internal/console/usagedays.go`
+(`usageDayDate`), the console start (where `LoadHostsMode` is called in
+`cmd/console/main.go`, to start `RunUsageFrom`).
+
+**Interfaces — Consumes:** Task 1 (`InstanceFrom`, `InstanceFromKey`,
+`InstancesPrefix`, `ParseInstanceDayKey`, `DecodeInstanceDay`), Task 5
+(door, `Config.InstanceUsage`), `s.hostsCached()`, `s.usageDayReader(now)`,
+`readConcurrently`, `instanceGate`. **Produces:**
+
+```go
+type usageFromVerdict struct {
+ From usage.InstanceFrom
+ Status int // 0 ok; 503 pending; 409 not active, or not started
+ Msg string // Task 0 copy
+}
+func (s *Server) usageFromCheck(ctx context.Context, now time.Time) (usageFromVerdict, error)
+func (s *Server) RunUsageFrom(ctx context.Context) // at start when InstanceUsage: usageFromCheck every minute until @from is held, then returns
+func firstOfNextMonth(now time.Time) string
+type usageResponse struct {
+ App string `json:"app"`
+ Month string `json:"month"`
+ From string `json:"from"` // month start, RFC 3339
+ To string `json:"to"` // next month start
+ Instances []usageInstance `json:"instances"`
+ Unattributed usageTotals `json:"unattributed"`
+ Total usageTotals `json:"total"`
+ ReadAt string `json:"read_at"`
+}
+type usageInstance struct { Host string `json:"host"`; BytesOut, Requests int64; HopBytesOut, HopRequests int64 `omitempty` } // json bytes_out, requests, hop_bytes_out, hop_requests
+type usageTotals struct { BytesOut int64 `json:"bytes_out"`; Requests int64 `json:"requests"` }
+const usageInstanceCap = 10000
+const usageMemoTTL = time.Minute
+```
+
+`usageFromCheck` (spec §4), from the held state, never re-reading the
+history:
+
+1. `st, verified := s.hostsCached()`. `s.cfg.HostClaim`, or `st.Mode` not
+ active (incomplete, invalidated, or unread `""` after a failed read) is
+ 409 "history not active". Active and `!verified` is 503 (pending), and
+ touches nothing.
+2. Active and verified: if the held `@from` has `Activation.Equal(st.At)`,
+ ok. Otherwise read `InstanceFromKey`. Absent: create-only Put
+ `{From: firstOfNextMonth(now), Activation: st.At}`; on CAS conflict
+ re-read and use what is there (then re-apply this rule). Present with
+ `Activation.Equal(st.At)`: hold it. Present with another activation (a
+ break): CAS Put `{From: max(old.From, firstOfNextMonth(now)), Activation: st.At}`
+ and hold it.
+3. A store error is returned (the route answers 503 with `Retry-After: 60`).
+
+`handleAPIUsage` order: `instanceGate`; `month` param (absent = current UTC
+month; not `YYYY-MM` or after the current month = 400); `usageFromCheck`
+(503 with `Retry-After: 60`, or 409); before `@from` exists is impossible
+past step 2, but a month whose start is before `From` is 409 with body
+`{"error": <copy>, "first_month": "<From's YYYY-MM>"}`; memo lookup by
+`acct.Sqid+"/"+app+"/"+month` (60 s); else read:
+
+- `ListDirs(usage.InstancesPrefix)` for the boxes (skip a name that is not
+ a plain key segment); for each box and each date from
+ `max(monthStart, From)` to `min(monthEnd - 1 day, today UTC)`, Get
+ `InstanceDayKey(box, date, acct.Sqid, app)` through
+ `s.usageDayReader(now)` inside `readConcurrently`.
+- Absent: nothing. Any other error, a decode or key failure, or over the
+ read cap: the whole answer is 503 with `Retry-After: 60`, logged.
+- Sum per host over boxes and dates; `""` is `unattributed`; `total` is
+ both; instances sorted by host; more than 10,000 hosts is 409 (Task 0
+ copy). `read_at` is `now` RFC 3339 UTC.
+
+`usageDayDate`: a key `ParseInstanceDayKey` accepts (and only the root
+family, not a fleet prefix) yields its date, so the settled-day cache keeps
+it as it keeps the others.
+
+- [ ] **Step 1: Failing tests (T7)** `usagefrom_test.go`, fake clock and
+ a hosts state set through the test seam the hostsused tests use:
+ written only when active, verified and switched on, as the next month's
+ first day; not written while pending (503) or not active (409);
+ a pending-then-verified check leaves an existing `@from` unchanged;
+ a held state with a new `At` moves `From` to the month after now, never
+ back (old From later than that stays); two servers racing the create:
+ one Put wins, both hold the same body (Review Focus 5).
+- [ ] **Step 2: Failing tests (T8)** `apiusage_test.go`:
+ `TestUsageMemoKeyedByAccount` (same app name in two accounts, two
+ answers); `TestUsagePendingAndBreakOnMemoHit` (after a 200, flip to
+ pending: 503; to invalidated: 409; no memo answer leaks);
+ `TestUsageReadFaults` (read error, bad JSON, key mismatch, body over
+ `usageDayReadCap`: each 503 with `Retry-After: 60`);
+ `TestUsageCap` (10,001 hosts: 409; 10,000: 200);
+ `TestUsageOtherAppCredential` (a usage credential for app A asking for
+ app B: 404); `TestUsageMonthBounds` (Review Focus 3: malformed and
+ future 400; before `From` 409 with `first_month`; `From`'s month 200;
+ current month reads no date after today: the store hook sees no such
+ key); `TestUsageSumsBoxesAndDates` (two boxes, three dates, a deleted
+ instance's host still listed, `""` in `unattributed`, `total` = both,
+ sorted); `TestUsagePreFromObjectsIgnored` (objects dated before `From`
+ on the same boxes never counted); `TestUsageLateWriteAfterSettle`
+ (Review Focus 4: a settled date read, then rewritten with more bytes;
+ same answer until the cache entry is `usageDayMaxAge` old, then the new
+ total, never the sum of both); `TestUsageDayDateKnowsInstances`.
+- [ ] **Step 3: Run** `go test ./internal/console -run 'UsageFrom|Usage' -count=1`: FAIL.
+- [ ] **Step 4: Implement.**
+- [ ] **Step 5: Run** the same, then `go test ./internal/console -run 'UsageDay|Economics|Analytics' -count=1`: PASS.
+- [ ] **Step 6: Commit** `console: the instance usage route and its start month`.
+
+### Task 7: `carlos usage` (Sonnet)
+
+**Files:** Create `usage_cmd.go`, `usage_cmd_test.go`,
+`approved_usage_copy_test.go`; modify `commands.go` (beside `analytics`),
+`parity/parity.tsv`, `parity/cli.tsv` (regenerated), `docs/site/cli.md`
+(a `### carlos usage` heading after `### carlos analytics`),
+`docs/parity.md` or whatever `make parity-doc` regenerates.
+
+**Interfaces — Consumes:** the route's `usageResponse` JSON (Task 6) and
+its 409 `first_month` body. **Produces:** `rawErr("usage", cust, runUsage)`;
+`func runUsage(args []string) error`.
+
+Flags: `--app`, `--month YYYY-MM`, `--account`, `--account-id`, `--console`,
+`--json` (the analytics command's helpers: `appFlag`, `consoleOption`,
+`requireAPISession`, `resolvedAccount`, `resolvedApp`; the session's GET
+helper). `--json` prints the route's body as received. Human output: the
+Task 0 approved layout, bytes through the root package's existing
+human-bytes formatter. A 409 with `first_month` prints the approved
+"counting starts" line and exits 0; other non-2xx return an error with the
+route's message.
+
+- [ ] **Step 1: Failing tests:** `TestUsageHumanOutput` (a fixture
+ response renders exactly the approved text, rows sorted as received,
+ totals line); `TestUsageJSONPassThrough`; `TestUsageBeforeStart` (409
+ with `first_month` = `2027-01` prints the approved line);
+ `TestUsageRefusesBadMonth` (`--month 2027-1` errors before any request);
+ `approved_usage_copy_test.go` pins every approved string.
+- [ ] **Step 2: Run** `go test . -run 'Usage|Parity|DocSite' -count=1`: FAIL.
+- [ ] **Step 3: Implement;** add the parity row
+ (`usage observe gap usage GET /api/cli/apps/{account}/{app}/usage` with
+ the note "A console view is later.", matching the table's columns);
+ `make parity-doc`; the cli.md section (approved copy).
+- [ ] **Step 4: Run** `go test . ./internal/docsite -run 'Usage|Parity|CLI|DocSite' -count=1`: PASS.
+- [ ] **Step 5: Commit** `cli: carlos usage, an app's bytes per instance this month`.
+
+### Task 8: End to end (Opus)
+
+**Files:** Create `instance_usage_e2e_test.go` (root package, the pattern
+of the existing `*_e2e_test.go` files that build an edge in-process) or, if
+the console cannot be built there, `internal/console/apiusage_e2e_test.go`
+with a real `edge.UsageMeter` and the host flush called through an
+exported test seam.
+
+- [ ] **Step 1: Test** `TestInstanceUsageEndToEnd`: one edge with a real
+ meter serving an instance and an alias of it (both counted under the
+ instance host); a fake clock crossing 23:58 to 00:03 UTC on the last day
+ of a month; the flush writes; a console with the switch on, the history
+ active and verified, `@from` the month before, answers the route: the
+ pre-midnight bytes are in the earlier month's answer and not the later
+ one's.
+- [ ] **Step 2: Run** it; PASS.
+- [ ] **Step 3: Commit** `usage: an end-to-end test across a month boundary`.
+
+### Task 9: Census, code health, the gate (controller)
+
+- [ ] **Step 1:** `make census-card`; write the CLAIMS file from spec §12
+ "Census" (the flush's read of its own objects: who writes them, what is
+ checked, what it decides) for every changed unit; `make census-propose
+ NAME=instance-usage CLAIMS=<file>`; commit the overlay, chain line and
+ card.
+- [ ] **Step 2:** Astra census review (brief from
+ `REVIEW-BRIEF-TEMPLATE.md`, the card and the branch diff); record the
+ verdict on #280 with the tip.
+- [ ] **Step 3:** `make code-health` (record lowered counts with
+ `make code-health-record` if any fell); `make staticcheck`; `gofmt -l .`.
+- [ ] **Step 4:** Full gate once: `go build ./... && go vet ./... && make test`,
+ `make race`, cross builds. Then push and read `amadan ci status`.
+
+### Task 10: Whole-branch review and hand-off (controller)
+
+- [ ] **Step 1:** Whole-branch Astra review (template brief; round history
+ carried; three rounds at most; stops at the first round with no P1).
+- [ ] **Step 2:** Apply P2s; P3s to a follow-up list on the branch.
+- [ ] **Step 3:** CI green on the tip; `amadan branch describe`; status on
+ #1519; report to the coordinator. No merge.
diff --git a/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-usage-plan.md b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-usage-plan.md
new file mode 100644
index 000000000..79e1fde9f
--- /dev/null
+++ b/docs/superpowers/plans/CODEX-REVIEW-BRIEF-instance-usage-plan.md
@@ -0,0 +1,80 @@
+# Review brief: instance usage implementation plan, round 1 of 3
+
+Repo carlos/platform, branch `instance-usage`, commit <see the prompt>.
+Under review: `docs/superpowers/plans/2026-11-29-instance-usage.md`.
+Authorities: `docs/superpowers/specs/2026-11-29-instance-usage-design.md`
+(revision 5, merged on main as 96731431a; reviewed in three Astra rounds,
+review closed) and AGENTS.md. Do not review against unmerged branches; if
+this work needs one, say so as a P1 and stop.
+
+You are an independent reviewer. Read the plan, then the spec and the code
+it names, and check every claim against that code.
+
+## Fixed: do not re-argue
+
+- Paul's ruling (spec §2, posted on discussion #1519, 2026-11-29): cut
+ completeness. The route returns bytes counted so far as a lower bound,
+ no complete claim, no partial=1, counting valid from the first whole UTC
+ month after switch-on, one file per app. Report only mechanisms that fail
+ to honour it.
+- The spec's design (identity = instance hostname, the family's keys, the
+ role shape, the route's shape) is reviewed and closed. Review whether the
+ PLAN implements it faithfully and buildably, not the design itself.
+
+## What to check
+
+1. Spec coverage: every requirement R1-R7, decision D1-D8 and test T1-T13
+ has a task that implements and tests it.
+2. Exactly-once (spec §5): does Task 3's queue algorithm and `writePart`
+ guarantee at most once per batch and object, at least once while queued,
+ ordering per object, markers kept forever, and the drop horizon as a
+ limit on starting writes? Name any interleaving that double counts.
+3. `@from` (spec §4, Task 6): does `usageFromCheck` move `from` only on a
+ real break and only forward, leave it untouched on a pending or retried
+ start-up check, and read the console's hostname history correctly
+ (`internal/console/hostsused.go` `hostsCached`, `hostsActive`,
+ `invalidateHosts`, `provision.HostsState.At`)? Is `RunUsageFrom` enough
+ to write `@from` on switch-on day with no route call?
+4. Authority (Task 5): is the usage role truly confined to one door, and is
+ every mint path (CLI services door, browser services page, platform
+ credentials) covered? Check `internal/svcrole/svcrole.go`,
+ `internal/console/svcprincipal.go`, `apiservices.go`, `svcpage.go`,
+ `platform_credentials.go`, `svcroutes_test.go`.
+5. The meter (Task 2): the three callers (`internal/edge/edge.go` ~2771,
+ `demo_traffic.go` ~217, `assetcatch.go` ~1159-1177), the far catch's
+ primary rule, and that the old `usage/edge/` family is byte-identical.
+6. The cache (`internal/console/usagedays.go`): is the plan's change to
+ `usageDayDate` and the route's use of `usageDayReader` correct for keys
+ whose last segment is not a date?
+7. Buildability: names, signatures and file paths that do not exist or
+ conflict with the code; tests that cannot be written as described;
+ AGENTS.md rules (census, parity, docsite, code health, race, copy).
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). End with exactly one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.