diff --git a/.claude/skills/add-service/SKILL.md b/.claude/skills/add-service/SKILL.md index b1b5dd1..1535cce 100644 --- a/.claude/skills/add-service/SKILL.md +++ b/.claude/skills/add-service/SKILL.md @@ -15,10 +15,14 @@ A service is data. **No Swift changes** unless it needs a case ENGINE_DESIGN doe 1. Cloudflare's pricing and limits pages for the product: each counted thing, its Free and Paid allowance, its overage price, when it resets. -2. The GraphQL dataset and fields: introspect the schema with a read-only token - (`__type(name: "AccountTypes")`), then run one query over a day and compare with the - dashboard. Note the time filter (`date` or `datetime`) and the focus dimension. -3. Record what you found, with the date, in ENGINE §6 and `docs/services//design.md`. +2. The GraphQL dataset and fields: `scripts/introspect-datasets.sh ''` lists the + matching datasets with their `sum` / `max` / `dimensions` fields, using the token in the + Keychain and printing names only. Then run one query over a day and compare with the + dashboard. Note the time filter (`date` or `datetime`), the focus dimension, and any + `where` the limit needs (ENGINE §2). **A dataset name nobody verified never ships**: one + wrong name fails the whole refresh query for everyone watching that service. +3. Record what you found, with the date and how (docs, introspection, a live read), in + ENGINE §6. ## 2. Check the cases @@ -33,10 +37,12 @@ propose the new case in ENGINE_DESIGN and ask the user to confirm before code. 2. `Modules/Services/Resources/Services/.json`. 3. Its allowances (and prices) in **every** plan file under `Modules/Plans/Resources/Plans/`. A plan without an allowance for a limit doesn't show that limit. -4. A recorded GraphQL answer (account ID replaced) and an `AnswerReader` test that reads it. +4. A `ReadPlanTests` test on the query it writes, and on a recorded answer (account ID replaced). ## 4. Ship -- `docs/services//README.md`: what it watches, which token permission it needs. -- One README table row, one CHANGELOG line under `Added`. +- `watchedByDefault: false` in its file: a new service arrives off (model law 21). +- A row in `docs/features/service-tabs/README.md` for its tab, and its switch in + `docs/features/settings/README.md`. +- One README table row, one CHANGELOG line under `Added`, the slice in `docs/status.md`. - A mockup in `design-concept/` if the service gets a tab with a new kind of breakdown. diff --git a/.claude/skills/fix-bug/SKILL.md b/.claude/skills/fix-bug/SKILL.md index 34861f8..c1bda39 100644 --- a/.claude/skills/fix-bug/SKILL.md +++ b/.claude/skills/fix-bug/SKILL.md @@ -35,6 +35,16 @@ that the code breaks. Find the law and its **one owner**, and fix it there, not site. If the right fix changes a law or moves it, that is a design change: update the doc and ask the user to confirm first. If no law covers it, propose the law first. +### Think the domain first + +A bug is often a shape that let it happen: a rule a view could work out for itself, one +value meaning two states (`nil` or `""` for both *not read yet* and *none*), a `String` +where a type would have refused the bad value, a Swift branch where a definition field +belonged. Ask the five questions of the types the bug touches → +[domain-shape.md](../implement-feature/references/domain-shape.md). Fix the shape when it +is the cause, in the same change, test first; a new node or a moved owner is a design +change, confirmed first. + ### Locate in the modules The map is [implement-feature → Architecture](../implement-feature/SKILL.md#architecture). @@ -76,6 +86,7 @@ Then run the full suite: ## Checklist - [ ] Bug reproduced; the law it breaks and its owner found +- [ ] Domain thought through: is the bug a shape the [five questions](../implement-feature/references/domain-shape.md) would have refused? Fixed there if so - [ ] Failing test written, FAILS before the fix - [ ] Minimal fix at the owner; test PASSES - [ ] All tests pass diff --git a/.claude/skills/implement-feature/SKILL.md b/.claude/skills/implement-feature/SKILL.md index 71efa07..75a86a4 100644 --- a/.claude/skills/implement-feature/SKILL.md +++ b/.claude/skills/implement-feature/SKILL.md @@ -34,6 +34,16 @@ Read in order ([ARCHITECTURE.md](../../../docs/architecture/ARCHITECTURE.md) map | Is it a choice or a reading? | choices go to `settings.json`, readings stay in memory (CANONICAL §2) | | Is a law missing, or owned twice? | add it to CANONICAL §5 with **one** owner | +### Think the domain first + +Before components, ask how the domain should be: from the person's problem (the issue, +the journey) to the facts it must respect, to the concepts those force, then compare with +the code. Ask the five questions of every type the feature touches (would the person say +it, does the thing decide about itself, can you see every state, is it as small as it can +be, is what differs data) and draw now beside proposed → +[references/domain-shape.md](references/domain-shape.md). A new node, a moved law or a +changed owner goes into the docs change below. + Write the change into the docs first, then present it: an ASCII diagram in the module words ([references/architecture-diagrams.md](references/architecture-diagrams.md)) and a table (component · purpose · inputs · outputs · dependencies). Ask with AskUserQuestion, @@ -65,6 +75,10 @@ public struct Limit: Sendable, Equatable { Views read `Account` directly ([references/swift-observable.md](references/swift-observable.md)). +The patterns, on Overmind's own types (a type answers the person's questions, tell don't ask, +a case per state, values over classes, what differs is data) → +[references/domain-models.md](references/domain-models.md). + ### Ports are `@Mockable`, at the module's root; implementations are `internal` ```swift @@ -117,6 +131,7 @@ xcodebuild test -workspace Overmind.xcworkspace -scheme Overmind-Workspace \ ## Checklist - [ ] Read the five design docs; placed it: owner, law, module +- [ ] Thought the domain first: the five questions asked of touched types, now/proposed drawn ([domain-shape.md](references/domain-shape.md)) - [ ] Design change written into the docs; **user approval** before code - [ ] Failing test first, asserting STATE; minimal code; refactor - [ ] No Swift names a Cloudflare product, dataset or price diff --git a/.claude/skills/implement-feature/references/domain-models.md b/.claude/skills/implement-feature/references/domain-models.md new file mode 100644 index 0000000..00a3449 --- /dev/null +++ b/.claude/skills/implement-feature/references/domain-models.md @@ -0,0 +1,116 @@ +# Rich domain model patterns + +The basic patterns, shown on Overmind's own types. Before any change, think how the domain should be: [domain-shape.md](domain-shape.md) (five questions for a domain easy to understand). + +The aim of every pattern here is **less to hold in your head**. Someone reading `Limit` should be able to say what it is, what it answers and what it can be told, in the person's words, without opening another file. + +## A type answers the person's questions + +Each public member is a question the person asks, named the way they'd ask it, with time passed in: + +```swift +/// One thing counted against the plan: a card in *Every limit today*. +public struct Limit: Sendable, Equatable, Identifiable { + public let definition: LimitDefinition + public let allowance: Allowance + public private(set) var usage: Usage? + + // "How much have I used?" nil with no reading for this period + public func percent(at now: Date) -> Percent? { … } + // "Should I worry?" OK · WATCH · ACT NOW (law 2, law 3) + public func level(at now: Date) -> Level? { … } + // "Where will I end up?" nil in the period's first hour (law 6) + public func pace(at now: Date) -> Pace? { … } +} +``` + +- **The doc comment says what the screen prints**, in italics: `/// *OK · WATCH · ACT NOW*`. Reading the type is reading the screen. +- **Name the law it keeps** (`(law 7)`), so the owner is findable from CANONICAL §5 and back. +- **`at now: Date`, never `Date()`** inside a domain type. It keeps the type pure and the test one line. + +## Tell, don't ask + +The caller hands over a fact; the type decides what it means. No caller reads the state and decides for it: + +```swift +// The refresh tells it what Cloudflare said; it keeps the reading only if it is newer +// and not from an earlier period (law 7). +public mutating func record(_ reading: Usage) { + guard usage.map({ $0.isSuperseded(by: reading) }) ?? true else { return } + usage = reading +} + +// NOT at the caller: +// if reading.readAt > limit.usage?.readAt ?? .distantPast { limit.usage = reading } +``` + +A rule that needs data from several nodes lives on the node that holds them all: `Account.closest(at:)` compares limits, so neither the menu bar nor Today ever compares percents. + +## Enums for states, each state a case + +A finite set of states the person can meet is an enum, and the rule that picks the case lives on it: + +```swift +/// *OK · WATCH · ACT NOW* (CANONICAL law 2). +public enum Level: Sendable, Equatable, Comparable { + case ok, watch, actNow + + public init(_ percent: Percent) { … } // the thresholds live here, and only here +} + +public enum Freshness { case live, stale, refused, never } // not a Date? each view reads +public enum Allowance { case perDay(Quantity), perMonth(Quantity), perInvocation(Quantity), total(Quantity) } +``` + +- **One value never means two things.** If `nil`, `""` or `0` could mean both *not read yet* and *nothing there*, it's two cases ([domain-shape §3](domain-shape.md#five-questions)). +- **`Comparable` when the person ranks them**: the worst level is `levels.max()`. +- **No colours, fonts or glyphs in the domain.** The view maps `Level` to coral or butter; the domain says *act now*. + +## Values for data, one class for what changes + +| Shape | When | Overmind | +|---|---|---| +| `struct` | data with rules, compared by value | `Limit`, `Usage`, `Pace`, `Focus`, `Percent`, `Money`, `Period` | +| `enum` | a closed set of states or kinds | `Level`, `Allowance`, `Price`, `Read`, `Freshness` | +| `@MainActor @Observable final class` | the one thing that changes over time and that views watch | `Account` | +| `protocol` (`@Mockable`) | the outside world only | `AnalyticsAPI`, `BillingAPI`, `Notifier`, `TokenVault`, `SettingsStore` | + +A new class or protocol inside the domain needs a reason the table doesn't already give. No managers, no services-of-services, no ViewModel. + +## What differs is data, not code + +A Cloudflare product or plan is a definition read from JSON. A difference between products is a field, or a generic case every definition gains, never a `switch` on an id: + +```swift +// A plan without an allowance for a limit doesn't show it: the plan answers nil. +guard let allowance = plan.allowance(for: definition.id) else { return nil } + +// A per-invocation allowance doesn't run out; the Allowance case says so, not "is this CPU?" +public var runsOut: Bool { + if case .perInvocation = allowance { return false } + return true +} +``` + +## Kernel values carry their unit + +`Quantity`, `Money`, `Percent` and `Period` come from `Measures`. A number that has a unit is never a `Double` or `Int`: `"5M rows"` parses into a `Quantity`, a reset is a `Period`, a price is `Money`. The compiler then refuses rows compared to milliseconds. + +## Factories, one per module + +Construction that reads a bundle or builds a port lives on the module's factory enum, so callers never see `Internal/`: + +```swift +let services = try ServiceCatalog.builtIns() // every Resources/Services/*.json +let day = Period.day(containing: now) // 00:00 UTC to 00:00 UTC +let month = Period.month(containing: now, renewsOn: renewal) +``` + +## Checklist for a type you add or touch + +- [ ] Its doc comment quotes what the screen prints +- [ ] Every public member answers a question the person asks, or is a command they'd give +- [ ] Each state is a case; no `nil` or `""` with two meanings +- [ ] Time comes in as `at:`; units are `Measures` values +- [ ] No product id, dataset or Cloudflare number in Swift +- [ ] No colour or wording choice that belongs to the view diff --git a/.claude/skills/implement-feature/references/domain-shape.md b/.claude/skills/implement-feature/references/domain-shape.md new file mode 100644 index 0000000..44969e8 --- /dev/null +++ b/.claude/skills/implement-feature/references/domain-shape.md @@ -0,0 +1,74 @@ +# Think the domain first + +Before any change, a fix too, ask how the domain should be, not only where the line fits. The aim is a domain that is **easy to understand**: someone new reads a type's public surface and can explain it in the person's words. We borrow from DDD only what serves that; no pattern is added for its own sake. + +Adapted from ClaudeBar's reference of the same name. The tree, the words and each law's owner are in [CANONICAL_MODEL](../../../../docs/architecture/CANONICAL_MODEL.md); the cases a definition can use in [ENGINE_DESIGN](../../../../docs/architecture/ENGINE_DESIGN.md). + +## Five questions + +**1. Would the person say it?** +Names come from the screen and the person ([USER_JOURNEYS §4](../../../../docs/architecture/USER_JOURNEYS.md#4--the-words-the-screens-print), [CANONICAL §0.1](../../../../docs/architecture/CANONICAL_MODEL.md)), never from the mechanism. Start from their problem: if the facts need a concept the code doesn't have, it is hiding somewhere as optionals, a flag or an empty string. *`Allowance`, not quota: Cloudflare's pages say "limits" and "included", and quota is ClaudeBar's word for something else.* + +**2. Does the thing decide about itself?** +A rule lives on the node that holds its data; callers tell it, they don't read its state and decide. *`Limit.record(_:)` decides whether a reading counts (law 7); `Account.closest(at:)` picks the headline, so the menu bar and the Today header never compare percents themselves.* + +**3. Can you see every state?** +Each state the person can meet is a case, carrying its data; one value never means two things. *`Freshness` is `never · live · stale · refused`, not a `Date?` each view interprets.* + +**4. Is it as small as it can be?** +A plain value when it is data with rules; a class only when it changes over time; a protocol only at the outside world (Cloudflare, the Keychain, settings, notifications), so tests can stub it. No type, layer or flag the change doesn't need. *`Focus` is a value (a dimension and a value, or `.everything`); no `FocusManager`.* + +**5. Is what differs between services and plans data?** +A field in the service or plan file, or a generic case every definition gains ([ENGINE_DESIGN](../../../../docs/architecture/ENGINE_DESIGN.md)); never a `switch` on a service id or a Swift line naming a product, dataset or number Cloudflare can change. *A plan without an allowance for a limit doesn't show that limit: `plan.allowance(for:)` returns `nil`, and no code asks "is this Free?".* + +## An example: the menu bar that can't say why it's blank + +An issue asks to hide *CPU time 10%* from the menu bar. A fix at the view (a toggle in `MenuBarLabel`) would work, but asking the five questions of `MenuBarState` first finds a shape that would make that toggle a guess. + +```swift +// NOW (Modules/Monitor/Sources/Account.swift) +/// *D1 18%* and its level; the account's name before the first read. +public func menuBar(at now: Date) -> MenuBarState { + guard let closest = closest(at: now), let percent = closest.percent(at: now) + else { return MenuBarState(text: "", level: .ok) } // "": not read yet, OR nothing on the plan runs out + … +} + +// the view (Sources/App/MenuBarLabel.swift) +case (.connected, _): Text(state.text.isEmpty ? "☁" : "☁ \(state.text)") // which empty? +``` + +| Question | What it finds | +|---|---| +| 1. Would the person say it? | Yes: *D1 18%* is what USER_JOURNEYS journey 4 prints. Keep the words | +| 2. Does the thing decide about itself? | Mostly: `Account` picks the limit. But the view decides what `""` means | +| 3. Can you see every state? | No: `""` covers *not read yet* and *nothing runs out*, and the doc comment promises a third (the account's name) that the code never returns | +| 4. Is it as small as it can be? | A small enum is enough; no new type for the label, no flag on the view | +| 5. Is what differs data? | Yes already: `short` comes from the limit's definition | + +```swift +// PROPOSED: the states the person meets, each one a case +public enum MenuBarState: Equatable { + case notReadYet + case nothingRunsOut + case closest(short: String, percent: Percent, level: Level) +} + +// the view draws each state; the person's choice of *icon only* becomes one more input, not a guess +``` + +Since it changes what the menu bar says, it went into USER_JOURNEYS and CANONICAL (law 22) first. Built 2026-10-11 as `notReadYet · iconOnly(Level) · closest(short:percent:level:)`: *nothing runs out* and *the person chose icon only* draw the same, so they are one case. + +## Keep it in scope + +- Fix what these questions find **in the types the change touches**, test first. Leave the rest for its own change. +- A new node, a moved law or a changed owner is a design change: the docs first, confirmed before code ([AGENTS.md](../../../../AGENTS.md#design-docs-are-the-source-of-truth)). +- A new Cloudflare product is question 5 by default: a JSON file, or a new ENGINE case proposed first ([add-service](../../add-service/SKILL.md)). +- When it isn't obvious, draw now beside proposed as a few lines of ASCII: + +``` + NOW PROPOSED + Account Account + └─ limits ← every service ├─ watching: [Service.ID] a choice, in settings.json + └─ limits ← watched services only +``` diff --git a/.claude/skills/improvement/SKILL.md b/.claude/skills/improvement/SKILL.md index 8d81d81..cb7b41c 100644 --- a/.claude/skills/improvement/SKILL.md +++ b/.claude/skills/improvement/SKILL.md @@ -31,6 +31,14 @@ that only makes the code match the docs needs no approval. One that changes a la a word the screen prints, or adds a piece is a design change: write it into the docs and ask the user to confirm before coding. +**Think the domain first.** Ask how the domain should be, from the person's problem rather +than the type at hand. Ask the five questions of the types the improvement touches (would +the person say it, does the thing decide about itself, can you see every state, is it as +small as it can be, is what differs data) and refine them in the same change → +[domain-shape.md](../implement-feature/references/domain-shape.md). An improvement is the +usual moment to fit a type to its shape; a new node or a moved owner is a design change, +confirmed first. + ## Kinds of improvement | Kind | Examples | Test approach | @@ -51,6 +59,7 @@ tests green: `tuist test `, then the full `xcodebuild test`. ## Checklist - [ ] Design checked; doc changed and confirmed if a law/word/piece changed +- [ ] Domain thought through: the touched types asked [the five questions](../implement-feature/references/domain-shape.md), refined in scope - [ ] Test for the improved behavior written and FAILS first - [ ] Improvement implemented; all tests pass - [ ] Docs and a CHANGELOG line for a change the person notices diff --git a/AGENTS.md b/AGENTS.md index 21ed162..8e928ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ One module per bounded context ([MODULAR_DESIGN.md](docs/architecture/MODULAR_DE The design leads; code follows it. Before any change, in this order: 1. **Read the design, in order** ([the map](docs/architecture/ARCHITECTURE.md)): [USER_JOURNEYS](docs/architecture/USER_JOURNEYS.md), [CANONICAL_MODEL](docs/architecture/CANONICAL_MODEL.md), [TARGET_ARCHITECTURE](docs/architecture/TARGET_ARCHITECTURE.md), [MODULAR_DESIGN](docs/architecture/MODULAR_DESIGN.md), [ENGINE_DESIGN](docs/architecture/ENGINE_DESIGN.md). -2. **Place the change in it.** Which node owns it? Which law (CANONICAL §5) does it keep? +2. **Place the change in it.** Which node owns it? Which law (CANONICAL §5) does it keep? Think how the domain should be, from the person's problem rather than the type you are editing, for every change, a fix too: names the person would say, each thing deciding about itself, every state visible, nothing bigger than it needs, what differs between services and plans as data → [domain-shape.md](.claude/skills/implement-feature/references/domain-shape.md). 3. **Write the design change first** when the docs don't say it or say otherwise. Code that disagrees with the docs is behind. 4. **Ask the person to confirm the design** before writing code. 5. **Implement to the doc.** SRP: a type changes for one reason. OCP: a new product, plan or case is data or a new case, never an edit to a neighbour. diff --git a/CHANGELOG.md b/CHANGELOG.md index 3049207..d88667d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,9 +4,19 @@ All notable changes to Overmind are recorded here, in the reader's order: Remove ## [Unreleased] +### Fixed + +- Before the first read the menu bar shows `☁` alone, never an empty number. + ### Added - Install with Homebrew: `brew install --cask tddworks/tap/overmind`. +- Choose what Overmind watches: *Settings → Watching* turns Worker or D1 off. A service you don't watch is never read: no tab, no card, no menu bar number, no warning, and the Bill says what its estimate covers (*est. · Worker only*). New Cloudflare products will arrive off. +- *Settings → General → Menu bar shows: Icon only* keeps the menu bar to `☁`, with `◐` or `⚠︎` when a limit needs watching. +- Workers AI, Vectorize and Durable Objects (requests, SQLite rows, storage), each off until watched. On Workers Paid, Workers AI is billed day by day past its 10k neurons. +- R2, on an account with R2: Class A, Class B and storage against R2's own free tier, priced in the Bill beside your Workers plan. +- Queues: operations against Free's 10k a day or Workers Paid's 1M a month, once watched. +- KV: turn it on in *Settings → Watching* to see reads, writes, deletes, lists and storage against your plan, with a KV tab, warnings and its lines in the Bill. --- diff --git a/Modules/Analytics/Sources/GraphQL.swift b/Modules/Analytics/Sources/GraphQL.swift index 506b7e3..bd1350a 100644 --- a/Modules/Analytics/Sources/GraphQL.swift +++ b/Modules/Analytics/Sources/GraphQL.swift @@ -9,6 +9,11 @@ enum GraphQL { return "\"\(escaped)\"" } + /// The groups a limit counts: `actionType_in: ["write"]` (ENGINE §2). + static func filter(_ only: Read.Where) -> String { + "\(only.dimension)_in: [\(only.in.map(string).joined(separator: ", "))]" + } + /// `sum.rowsRead` → `sum { rowsRead }`; `count` → `count`. static func selection(_ path: String) -> String { let parts = path.split(separator: ".").map(String.init) diff --git a/Modules/Analytics/Sources/ReadPlan.swift b/Modules/Analytics/Sources/ReadPlan.swift index 1179f75..9fedd25 100644 --- a/Modules/Analytics/Sources/ReadPlan.swift +++ b/Modules/Analytics/Sources/ReadPlan.swift @@ -30,7 +30,8 @@ public struct ReadPlan: Sendable { for (index, read) in reads.enumerated() { let source = read.definition.read.source let period = read.period ?? .day(containing: now) - let range = GraphQL.range(source.time, from: period.start, to: min(now, period.end.addingTimeInterval(-1))) + var range = GraphQL.range(source.time, from: period.start, to: min(now, period.end.addingTimeInterval(-1))) + if let only = source.where { range += ", " + GraphQL.filter(only) } // What is kept is kept per database (or Worker): the largest size of each, added up. var selection = GraphQL.selection(source.field) if case .max = read.definition.read, let focus = source.focus { selection = "dimensions { \(focus) } \(selection)" } @@ -48,7 +49,8 @@ public struct ReadPlan: Sendable { public func daily(_ limits: [LimitDefinition], over period: Period, at now: Date) -> PlannedDaily { let fields = limits.enumerated().map { index, limit in let source = limit.read.source - let range = GraphQL.range(source.time, from: period.start, to: min(now, period.end.addingTimeInterval(-1))) + var range = GraphQL.range(source.time, from: period.start, to: min(now, period.end.addingTimeInterval(-1))) + if let only = source.where { range += ", " + GraphQL.filter(only) } return "d\(index): \(source.dataset)(limit: \(Self.groups), filter: { \(range) }) { dimensions { date } \(GraphQL.selection(source.field)) }" } return PlannedDaily(query: query(fields), limits: limits) @@ -64,6 +66,7 @@ public struct ReadPlan: Sendable { let source = limit.read.source let (dimension, filter, from) = Self.window(step, last: last, at: now) var filters = [GraphQL.range(filter, from: from, to: now)] + if let only = source.where { filters.append(GraphQL.filter(only)) } if let narrowed = focus.filter(for: source.focus) { filters.append(narrowed) } fields.append("\(alias): \(source.dataset)(limit: \(Self.groups), filter: { \(filters.joined(separator: ", ")) }, orderBy: [\(dimension)_ASC]) { dimensions { \(dimension) } \(GraphQL.selection(source.field)) }") case .top(let source, let dimension, let count): diff --git a/Modules/Analytics/Tests/ReadPlanTests.swift b/Modules/Analytics/Tests/ReadPlanTests.swift index cbbfe12..d68267e 100644 --- a/Modules/Analytics/Tests/ReadPlanTests.swift +++ b/Modules/Analytics/Tests/ReadPlanTests.swift @@ -40,6 +40,28 @@ struct ReadPlanTests { #expect(!query.contains("databaseId:")) } + @Test func `should count only KV's write operations for KV writes`() throws { + let writes = LimitRead(try Fixture.limit("kv", "kv.writes"), period: Fixture.today) + + let query = plan.limits([writes], at: Fixture.now).query.text + + #expect(query.contains(#"l0: kvOperationsAdaptiveGroups(limit: 10000, filter: { date_geq: "2026-10-09", date_leq: "2026-10-09", actionType_in: ["write"] })"#)) + } + + @Test func `should count only KV's write operations on each day of the month too`() throws { + let writes = try Fixture.limit("kv", "kv.writes") + + let query = plan.daily([writes], over: .month(containing: Fixture.now, renewsOn: nil), at: Fixture.now).query.text + + #expect(query.contains(#"actionType_in: ["write"]"#)) + } + + @Test func `should chart only KV's reads on the reads chart`() throws { + let query = plan.breakdowns(try ServiceCatalog.builtIn("kv"), focus: .everything, at: Fixture.now).query.text + + #expect(query.contains(#"actionType_in: ["read"]"#)) + } + @Test func `should read today's D1 rows read from Cloudflare's answer`() throws { let usages = try plan.limits(try reads(), at: Fixture.now).usages(from: AnalyticsAnswer(Fixture.limitsAnswer)) diff --git a/Modules/Billing/Sources/Bill.swift b/Modules/Billing/Sources/Bill.swift index 306189f..1ce9e9f 100644 --- a/Modules/Billing/Sources/Bill.swift +++ b/Modules/Billing/Sources/Bill.swift @@ -17,6 +17,8 @@ public struct Bill: Sendable, Equatable { let projected: [LimitID: Quantity] /// Each limit's use per UTC day of the month. let daily: [LimitID: [Date: Quantity]] + /// From the month so far to the whole month: a daily limit's overage is stretched by it (law 24). + let stretch: Double /// `monthToDate` is what was used up this billing month; `kept` is what is stored, which a /// pace doesn't stretch. @@ -28,20 +30,21 @@ public struct Bill: Sendable, Equatable { self.period = period let elapsed = max(period.elapsedFraction(at: now), 1.0 / 31) projected = monthToDate.mapValues { Quantity($0.value / elapsed, $0.unit) }.merging(kept) { $1 } - estimate = plan.cost(of: monthToDate.merging(kept) { $1 }) - forecast = plan.cost(of: projected) + stretch = 1 / elapsed + estimate = plan.cost(of: monthToDate.merging(kept) { $1 }, days: daily) + forecast = plan.cost(of: projected, days: daily, stretch: stretch) self.invoices = invoices.sorted { $0.at > $1.at } issued = invoices.first { period.contains($0.at) } } /// The same month's pace, priced by another plan: *On Workers Paid $5.00* (law 14). public func quote(on other: Plan) -> Money { - other.cost(of: projected) + other.cost(of: projected, days: daily, stretch: stretch) } /// Where a plan's price for this month's pace comes from, one line per limit (law 20). public func lines(on other: Plan) -> [CostLine] { - other.lines(of: projected) + other.lines(of: projected, days: daily, stretch: stretch) } /// For each limit `plan` allows per day: the allowance, the month's busiest day, and the days @@ -51,7 +54,7 @@ public struct Bill: Sendable, Equatable { for (limit, days) in daily { guard case .perDay(let allowance)? = plan.allowance(for: limit) else { continue } let busiest = days.max { $0.value.value < $1.value.value }.map { DayUse(day: $0.key, used: $0.value) } - let stopped = days.filter { $0.value.value >= allowance.value }.keys.sorted() + let stopped = plan.stops(at: limit) ? days.filter { $0.value.value >= allowance.value }.keys.sorted() : [] result[limit] = LimitDays(allowance: allowance, busiest: busiest, stopped: stopped) } return result diff --git a/Modules/Billing/Tests/BillTests.swift b/Modules/Billing/Tests/BillTests.swift index 0fcd1b0..20e7b36 100644 --- a/Modules/Billing/Tests/BillTests.swift +++ b/Modules/Billing/Tests/BillTests.swift @@ -39,6 +39,26 @@ struct BillTests { #expect(abs(NSDecimalNumber(decimal: bill.forecast.amount).doubleValue - 10) < 0.001) } + @Test func `should bill Workers AI day by day, and forecast by stretching the overage, not the total`() { + let days: [LimitID: [Date: Quantity]] = ["ai.neurons": [.utc("2026-10-01T00:00:00"): Quantity(25_000, .neurons), + .utc("2026-10-02T00:00:00"): Quantity(5_000, .neurons)]] + let bill = Bill(plan: paid, monthToDate: ["ai.neurons": Quantity(30_000, .neurons)], kept: [:], invoices: [], daily: days, at: now) + + #expect(bill.estimate == Money(Decimal(string: "5.165")!, "USD")) + // $0.165 so far, a third of the month gone: on pace for $0.495. + #expect(abs(NSDecimalNumber(decimal: bill.forecast.amount).doubleValue - 5.495) < 0.001) + } + + @Test func `should never say Workers Paid stopped Workers AI on a busy day, since it charges instead`() { + let days: [LimitID: [Date: Quantity]] = ["ai.neurons": [.utc("2026-10-01T00:00:00"): Quantity(25_000, .neurons)]] + + let onPaid = Bill(plan: paid, monthToDate: ["ai.neurons": Quantity(25_000, .neurons)], kept: [:], invoices: [], daily: days, at: now) + let onFree = Bill(plan: free, monthToDate: ["ai.neurons": Quantity(25_000, .neurons)], kept: [:], invoices: [], daily: days, at: now) + + #expect(onPaid.verdict == .enough) + #expect(onFree.verdict == .stopped(days: [.utc("2026-10-01T00:00:00")], limits: ["ai.neurons"])) + } + @Test func `should not stretch storage by the month's pace, since it is kept, not used up`() { let bill = Bill(plan: paid, monthToDate: [:], kept: ["d1.storage": Quantity(6e9, .bytes)], invoices: [], at: now) #expect(bill.forecast == Money(Decimal(string: "5.75")!, "USD")) diff --git a/Modules/Measures/Sources/Quantity.swift b/Modules/Measures/Sources/Quantity.swift index cf7aafd..e309fe3 100644 --- a/Modules/Measures/Sources/Quantity.swift +++ b/Modules/Measures/Sources/Quantity.swift @@ -4,11 +4,18 @@ import Foundation /// can't invent a unit nobody draws. public enum QuantityUnit: String, Sendable, Codable, CaseIterable { case rows, requests, milliseconds, bytes, count + /// Queues: 64 KB written, read or deleted. + case operations + /// Workers AI's unit of compute. + case neurons + /// Vectorize: one number of one vector. + case dimensions /// The word a definition file writes after the number, and how many base units it means: /// `GB` is a billion bytes, as Cloudflare prices storage. static let words: [String: (QuantityUnit, Double)] = [ - "rows": (.rows, 1), "requests": (.requests, 1), "count": (.count, 1), + "rows": (.rows, 1), "requests": (.requests, 1), "count": (.count, 1), "operations": (.operations, 1), + "neurons": (.neurons, 1), "dimensions": (.dimensions, 1), "ms": (.milliseconds, 1), "bytes": (.bytes, 1), "KB": (.bytes, 1e3), "MB": (.bytes, 1e6), "GB": (.bytes, 1e9), ] @@ -60,7 +67,7 @@ extension Quantity { return "\(Self.significant(value / size)) \(word)" } return "\(Int(value)) bytes" - case .rows, .requests, .count: + case .rows, .requests, .count, .operations, .neurons, .dimensions: for (size, word) in [(1e9, "B"), (1e6, "M"), (1e3, "k")] where value >= size { return "\(Self.significant(value / size))\(word)" } diff --git a/Modules/Measures/Tests/QuantityTests.swift b/Modules/Measures/Tests/QuantityTests.swift index d8866b6..0857d4c 100644 --- a/Modules/Measures/Tests/QuantityTests.swift +++ b/Modules/Measures/Tests/QuantityTests.swift @@ -12,6 +12,17 @@ struct QuantityTests { #expect(try Quantity(parsing: "100k requests") == Quantity(100_000, .requests)) } + @Test func `should read 10k operations as ten thousand Queues operations`() throws { + #expect(try Quantity(parsing: "10k operations") == Quantity(10_000, .operations)) + #expect(Quantity(1_250_000, .operations).short == "1.25M") + } + + @Test func `should read Workers AI's neurons and Vectorize's dimensions`() throws { + #expect(try Quantity(parsing: "10k neurons") == Quantity(10_000, .neurons)) + #expect(try Quantity(parsing: "30M dimensions") == Quantity(30_000_000, .dimensions)) + #expect(Quantity(12_500, .neurons).short == "12.5k") + } + @Test func `should read 25B rows as twenty-five billion rows`() throws { #expect(try Quantity(parsing: "25B rows") == Quantity(25_000_000_000, .rows)) } diff --git a/Modules/Monitor/Sources/Account.swift b/Modules/Monitor/Sources/Account.swift index 932cce6..5e551b3 100644 --- a/Modules/Monitor/Sources/Account.swift +++ b/Modules/Monitor/Sources/Account.swift @@ -70,6 +70,9 @@ public final class Account { } } + /// What the person chose in *Watching*, by service id; a service not here follows its file. + private var choices: [String: Bool] + let plans: [PlanDefinition] let analytics: any AnalyticsAPI let billing: any BillingAPI @@ -94,8 +97,10 @@ public final class Account { focus = saved.focus interval = TimeInterval((Self.intervals.contains(saved.interval) ? saved.interval : 5) * 60) alerts = Alerts(settings: saved.alerts, sent: saved.sent) + choices = saved.watch + menuBarShows = saved.menuBar plan = Plan(try PlanCatalog.plan(forRatePlans: [], among: plans), renewsOn: nil) - limits = Self.limits(services, on: plan, keeping: []) + limits = Self.limits(watching, on: plan, keeping: []) } // MARK: Connecting @@ -156,7 +161,7 @@ public final class Account { vault.delete() phase = .notConnected lastRead = nil - limits = Self.limits(services, on: plan, keeping: []) + limits = Self.limits(watching, on: plan, keeping: []) breakdowns = [:] bill = nil var saved = settings.load() @@ -177,13 +182,15 @@ public final class Account { planReadAt = now do { let subscriptions = try await billing.subscriptions(account: summary.id) - let definition = try PlanCatalog.plan(forRatePlans: subscriptions.map(\.ratePlan), among: plans) - let renewal = subscriptions.first { definition.matches.contains($0.ratePlan) }?.renewsOn - plan = Plan(definition, renewsOn: renewal) + let ratePlans = subscriptions.map(\.ratePlan) + let renewal = { (definition: PlanDefinition) in subscriptions.first { definition.matches.contains($0.ratePlan) }?.renewsOn } + let definition = try PlanCatalog.plan(forRatePlans: ratePlans, among: plans) + let addOns = PlanCatalog.addOns(forRatePlans: ratePlans, among: plans).map { Plan($0, renewsOn: renewal($0)) } + plan = Plan(definition, renewsOn: renewal(definition), addOns: addOns) } catch { missing.insert(.billing) } - limits = Self.limits(services, on: plan, keeping: limits) + limits = Self.limits(watching, on: plan, keeping: limits) } // MARK: Reading @@ -231,7 +238,7 @@ public final class Account { /// A service's tab (TARGET §3.3): its charts for the focus, and the focused Worker's /// deployments. Read again only when older than one refresh. public func open(_ serviceID: String, at now: Date) async { - guard case .connected(let summary) = phase, let service = services.first(where: { $0.id == serviceID }) else { return } + guard case .connected(let summary) = phase, let service = watching.first(where: { $0.id == serviceID }) else { return } if let readAt = breakdownsReadAt[serviceID], now.timeIntervalSince(readAt) < interval, breakdowns[serviceID] != nil { return } let planned = ReadPlan(account: summary.id).breakdowns(service, focus: focus, at: now) if let answer = try? await analytics.read(planned.query), let read = try? planned.breakdowns(from: answer) { @@ -250,7 +257,7 @@ public final class Account { // An upgrade made on Cloudflare shows here without a restart (law 18). await readPlan(summary, at: now) let month = Period.month(containing: now, renewsOn: plan.renewsOn) - let definitions = services.flatMap(\.limits).filter { definition in + let definitions = watching.flatMap(\.limits).filter { definition in plans.contains { $0.price(for: definition.id) != nil } } let reads = definitions.map { LimitRead($0, period: Self.isKept($0) ? nil : month) } @@ -265,7 +272,7 @@ public final class Account { missing.insert(.billing) } // Each day's use of every limit some plan allows per day: the days Free stops you (law 19). - let dailyLimits = services.flatMap(\.limits).filter { definition in + let dailyLimits = watching.flatMap(\.limits).filter { definition in plans.contains { if case .perDay = $0.allowance(for: definition.id) { true } else { false } } } var daily: [LimitID: [Date: Quantity]] = [:] @@ -275,8 +282,9 @@ public final class Account { } let bill = Bill(plan: plan, monthToDate: monthToDate, kept: kept, invoices: invoices, daily: daily, at: now) self.bill = bill - quotes = plans.filter { $0.id != plan.definition.id }.map { definition in - let other = Plan(definition, renewsOn: nil) + // Another Workers plan, with the same add-ons: R2 stays whatever Workers plan you pick (law 23). + quotes = plans.filter { !$0.addOn && $0.id != plan.definition.id }.map { definition in + let other = Plan(definition, renewsOn: nil, addOns: plan.addOns) return Quote(plan: definition, cost: bill.quote(on: other), lines: bill.lines(on: other), days: bill.days(on: other), upgradeURL: definition.upgradeURL(account: summary.id)) } @@ -303,6 +311,51 @@ public final class Account { save() } + // MARK: Watching + + /// *Worker ☑ · D1 ☑ · KV ☐*: the services Overmind reads, in catalog order. One the person + /// never chose for follows its file; never empty (law 21). + public var watching: [ServiceDefinition] { + let watched = services.filter { choices[$0.id] ?? $0.watchedByDefault } + return watched.isEmpty ? Array(services.prefix(1)) : watched + } + + public func isWatching(_ serviceID: String) -> Bool { watching.contains { $0.id == serviceID } } + + /// Whether the account's plans count any of this service: R2 needs R2 on the account + /// (*not on this account's plans*). + public func isCounted(_ serviceID: String) -> Bool { + services.first { $0.id == serviceID }?.limits.contains { plan.allowance(for: $0.id) != nil } ?? false + } + + /// Whether *Watching* lets this switch go off: never the last one (law 21). + public func canUnwatch(_ serviceID: String) -> Bool { isWatching(serviceID) && watching.count > 1 } + + /// Turns a service on, and reads it at once (law 21). + public func watch(_ serviceID: String, at now: Date) async { + guard services.contains(where: { $0.id == serviceID }), !isWatching(serviceID) else { return } + choices[serviceID] = true + limits = Self.limits(watching, on: plan, keeping: limits) + save() + await refresh(at: now) + } + + /// Turns a service off: its limits, tab and charts go; the sent-warnings log stays. The last + /// watched service stays on (law 21). + public func unwatch(_ serviceID: String) { + guard canUnwatch(serviceID) else { return } + choices[serviceID] = false + limits = Self.limits(watching, on: plan, keeping: limits) + breakdowns[serviceID] = nil + breakdownsReadAt[serviceID] = nil + save() + } + + /// What the Bill's estimate counts: *est.* or *est. · Worker only* (law 21). + public var estimateCovers: Coverage { + watching.count == services.count ? .everything : .only(watching.map(\.name)) + } + // MARK: Alerts public func setLevel(_ level: Int, on: Bool) { @@ -348,11 +401,22 @@ public final class Account { } } - /// *D1 18%* and its level; the account's name before the first read. + /// *Menu bar shows: Closest limit · Icon only* (law 22). + public private(set) var menuBarShows: MenuBarStyle + + public func setMenuBar(_ style: MenuBarStyle) { + menuBarShows = style + save() + } + + /// `☁` before the first read; *D1 18%* coloured by the worst level; or, on *icon only* or + /// when nothing on the plan runs out, the cloud and the worst level's mark (law 22). public func menuBar(at now: Date) -> MenuBarState { - guard let closest = closest(at: now), let percent = closest.percent(at: now) else { return MenuBarState(text: "", level: .ok) } - let worst = limits.compactMap { $0.level(at: now) }.max() ?? .ok - return MenuBarState(text: "\(closest.definition.short) \(percent.rounded)%", level: max(worst, closest.level(at: now) ?? .ok)) + guard let worst = limits.compactMap({ $0.level(at: now) }).max() else { return .notReadYet } + guard menuBarShows == .closestLimit, let closest = closest(at: now), let percent = closest.percent(at: now) else { + return .iconOnly(worst) + } + return .closest(short: closest.definition.short, percent: percent, level: worst) } /// *LIVE* · *STALE* (law 11). @@ -374,7 +438,7 @@ public final class Account { // MARK: Helpers - /// One limit per service limit the plan has an allowance for, keeping readings. + /// One limit per watched service's limit the plan has an allowance for, keeping readings. static func limits(_ services: [ServiceDefinition], on plan: Plan, keeping old: [Limit]) -> [Limit] { services.flatMap(\.limits).compactMap { definition in guard let allowance = plan.allowance(for: definition.id) else { return nil } @@ -386,19 +450,32 @@ public final class Account { private func save() { settings.save(Settings(account: summary ?? settings.load().account, focus: focus, interval: Int(interval / 60), - alerts: alerts.settings, sent: alerts.sent)) + alerts: alerts.settings, sent: alerts.sent, watch: choices, + menuBar: menuBarShows)) } } -/// What the menu bar shows: the closest limit, coloured by the worst level. -public struct MenuBarState: Sendable, Equatable { - public let text: String - public let level: Level +/// Which services the Bill's estimate counts (law 21). +public enum Coverage: Sendable, Equatable { + /// Every service: *est.* + case everything + /// Only these, by name: *est. · Worker only*. + case only([String]) +} + +/// What the menu bar shows, one state at a time (law 22). +public enum MenuBarState: Sendable, Equatable { + /// `☁`: nothing read yet. + case notReadYet + /// `☁`, `☁ ◐`, `☁ ⚠︎`: no limit named, by choice or because nothing on the plan runs out. + case iconOnly(Level) + /// `☁ D1 18%`, coloured by the worst level of any limit. + case closest(short: String, percent: Percent, level: Level) +} - public init(text: String, level: Level) { - self.text = text - self.level = level - } +/// *Menu bar shows: Closest limit · Icon only* — the person's choice (law 22). +public enum MenuBarStyle: String, Sendable, Equatable, Codable, CaseIterable { + case closestLimit, iconOnly } /// Another plan's price for this month's pace: *On Workers Paid $5.00*. diff --git a/Modules/Monitor/Sources/Ports.swift b/Modules/Monitor/Sources/Ports.swift index 2d40293..e493ab3 100644 --- a/Modules/Monitor/Sources/Ports.swift +++ b/Modules/Monitor/Sources/Ports.swift @@ -33,14 +33,21 @@ public struct Settings: Sendable, Equatable, Codable { public var interval: Int public var alerts: AlertSettings public var sent: Set + /// The services the person turned on or off, by id; one not here follows its file (law 21). + public var watch: [String: Bool] + /// *Closest limit* or *Icon only* (law 22). + public var menuBar: MenuBarStyle public init(account: AccountSummary? = nil, focus: Focus = .everything, interval: Int = 5, - alerts: AlertSettings = .standard, sent: Set = []) { + alerts: AlertSettings = .standard, sent: Set = [], watch: [String: Bool] = [:], + menuBar: MenuBarStyle = .closestLimit) { + self.menuBar = menuBar self.account = account self.focus = focus self.interval = interval self.alerts = alerts self.sent = sent + self.watch = watch } /// A file from an older version lacks the newer keys: each falls back to its default, and @@ -53,5 +60,7 @@ public struct Settings: Sendable, Equatable, Codable { interval = (try? container.decodeIfPresent(Int.self, forKey: .interval)) ?? defaults.interval alerts = (try? container.decodeIfPresent(AlertSettings.self, forKey: .alerts)) ?? defaults.alerts sent = (try? container.decodeIfPresent(Set.self, forKey: .sent)) ?? defaults.sent + watch = (try? container.decodeIfPresent([String: Bool].self, forKey: .watch)) ?? defaults.watch + menuBar = (try? container.decodeIfPresent(MenuBarStyle.self, forKey: .menuBar)) ?? defaults.menuBar } } diff --git a/Modules/Monitor/Tests/AccountTests.swift b/Modules/Monitor/Tests/AccountTests.swift index b8e380e..4f08843 100644 --- a/Modules/Monitor/Tests/AccountTests.swift +++ b/Modules/Monitor/Tests/AccountTests.swift @@ -4,6 +4,7 @@ import Measures import Limits import Analytics import Billing +import Services @testable import Monitor @MainActor @@ -127,7 +128,12 @@ struct RefreshTests { let account = try await connected(world) #expect(account.closest(at: .utc("2026-10-09T14:21:00"))?.id == "d1.rowsRead") - #expect(account.menuBar(at: .utc("2026-10-09T14:21:00")) == MenuBarState(text: "D1 18%", level: .ok)) + guard case .closest(let short, let percent, let level) = account.menuBar(at: .utc("2026-10-09T14:21:00")) else { + Issue.record("the menu bar names no limit"); return + } + #expect(short == "D1") + #expect(percent.rounded == 18) + #expect(level == .ok) } @Test func `should never call CPU the closest limit, however high its p99`() async throws { @@ -312,3 +318,186 @@ struct UpgradeTests { #expect(paid.upgradeURL?.absoluteString == "https://dash.cloudflare.com/acc1/workers/plans") } } + +/// Settings → Watching (law 21): only a watched service is read. +@MainActor +@Suite +struct WatchingTests { + /// A service that ships off, as each new one does. + static let later = try! ServiceDefinition(json: Data(""" + { "id": "later", "name": "Later", "order": 9, "look": { "glyph": "K", "color": "sky" }, + "limits": [ { "id": "later.calls", "name": "Later calls", "short": "Later", "unit": "count", + "read": { "sum": { "dataset": "laterGroups", "field": "sum.calls", "time": "date" } } } ], + "breakdowns": [] } + """.utf8)) + + @Test func `should watch Workers and D1 for someone who never chose, and say the bill counts only them`() throws { + let account = try World().account() + + #expect(account.watching.map(\.id) == ["workers", "d1"]) + #expect(account.estimateCovers == .only(["Worker", "D1"])) + } + + @Test func `should leave a new service off until the person turns it on`() throws { + let account = try World().account(adding: [Self.later]) + + #expect(account.watching.map(\.id) == ["workers", "d1"]) + #expect(account.isWatching("later") == false) + #expect(account.isWatching("kv") == false) + } + + @Test func `should never read D1, warn about it or count it as closest once the person stops watching it`() async throws { + let world = World() + world.cloudflare.numbers = ["rowsRead": 4_900_000, "requests": 9_814] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + + account.unwatch("d1") + await account.refresh(at: .utc("2026-10-09T14:30:00")) + + #expect(account.limit("d1.rowsRead") == nil) + #expect(world.cloudflare.queries.last?.contains("d1AnalyticsAdaptiveGroups") == false) + #expect(account.closest(at: .utc("2026-10-09T14:31:00"))?.id == "workers.requests") + #expect(account.estimateCovers == .only(["Worker"])) + } + + @Test func `should leave D1 out of the bill when D1 isn't watched`() async throws { + let world = World() + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + account.unwatch("d1") + let before = world.cloudflare.queries.count + + await account.openBill(at: .utc("2026-10-09T14:20:00")) + + #expect(world.cloudflare.queries.dropFirst(before).contains { $0.contains("d1AnalyticsAdaptiveGroups") || $0.contains("d1StorageAdaptiveGroups") } == false) + #expect(account.quotes.first?.lines.map(\.limit).contains("d1.rowsRead") == false) + } + + @Test func `should read a service at once when the person watches it again`() async throws { + let world = World() + world.cloudflare.numbers = ["rowsRead": 912_000] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + account.unwatch("d1") + + await account.watch("d1", at: .utc("2026-10-09T14:30:00")) + + #expect(account.limit("d1.rowsRead")?.percent(at: .utc("2026-10-09T14:31:00"))?.rounded == 18) + #expect(account.estimateCovers == .only(["Worker", "D1"])) + } + + @Test func `should keep watching the last service when the person tries to turn it off`() throws { + let account = try World().account() + + account.unwatch("d1") + account.unwatch("workers") + + #expect(account.watching.map(\.id) == ["workers"]) + #expect(account.canUnwatch("workers") == false) + } + + @Test func `should remember what the person watches after a relaunch`() throws { + let world = World() + try world.account(adding: [Self.later]).unwatch("d1") + let relaunched = try world.account(adding: [Self.later]) + + #expect(relaunched.watching.map(\.id) == ["workers"]) + } + + @Test func `should ignore a service the catalog doesn't have`() async throws { + let account = try World().account() + + await account.watch("nonesuch", at: .utc("2026-10-09T14:20:00")) + + #expect(account.watching.map(\.id) == ["workers", "d1"]) + } +} + +/// The menu bar's states and the *icon only* choice (law 22). +@MainActor +@Suite +struct MenuBarTests { + @Test func `should show only the cloud before the first read`() throws { + let account = try World().account() + #expect(account.menuBar(at: .utc("2026-10-09T14:21:00")) == .notReadYet) + } + + @Test func `should show only the cloud and the act-now mark when the person chooses icon only`() async throws { + let world = World() + world.cloudflare.numbers = ["rowsRead": 4_600_000] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + + account.setMenuBar(.iconOnly) + + #expect(account.menuBar(at: .utc("2026-10-09T14:21:00")) == .iconOnly(.actNow)) + } + + @Test func `should name the closest limit again when the person goes back to it`() async throws { + let world = World() + world.cloudflare.numbers = ["rowsRead": 912_000] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + account.setMenuBar(.iconOnly) + + account.setMenuBar(.closestLimit) + + guard case .closest(let short, _, _) = account.menuBar(at: .utc("2026-10-09T14:21:00")) else { + Issue.record("the menu bar names no limit"); return + } + #expect(short == "D1") + } + + @Test func `should remember icon only after a relaunch`() throws { + let world = World() + try world.account().setMenuBar(.iconOnly) + #expect(try world.account().menuBarShows == .iconOnly) + } +} + +/// R2: an add-on plan beside the Workers plan (law 23). +@MainActor +@Suite +struct AddOnTests { + @Test func `should count R2 against its own free tier once watched on an account with R2`() async throws { + let world = World() + world.cloudflare.ratePlans = ["r2_paid"] + world.cloudflare.numbers = ["requests": 250_000] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + + await account.watch("r2", at: .utc("2026-10-09T14:30:00")) + + #expect(account.plan.definition.id == "free") + #expect(account.limit("r2.classA")?.percent(at: .utc("2026-10-09T14:31:00"))?.rounded == 25) + #expect(account.isCounted("r2")) + } + + @Test func `should say R2 isn't on the account's plans when it has no R2`() async throws { + let world = World() + world.cloudflare.ratePlans = [] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + + await account.watch("r2", at: .utc("2026-10-09T14:30:00")) + + #expect(account.limit("r2.classA") == nil) + #expect(account.isCounted("r2") == false) + #expect(account.isCounted("d1")) + } + + @Test func `should never offer R2 as a plan to switch to, and quote Workers Paid with R2 kept`() async throws { + let world = World() + world.cloudflare.ratePlans = ["r2_paid"] + world.cloudflare.numbers = ["requests": 2_000_000] + let account = try world.account() + await account.connect(token: "tok", at: .utc("2026-10-09T14:20:00")) + await account.watch("r2", at: .utc("2026-10-09T14:20:00")) + + await account.openBill(at: .utc("2026-10-09T14:20:00")) + + #expect(account.quotes.map(\.plan.name) == ["Workers Paid"]) + #expect(account.quotes.first?.lines.map(\.limit).contains("r2.classA") == true) + } +} diff --git a/Modules/Monitor/Tests/Fakes.swift b/Modules/Monitor/Tests/Fakes.swift index 12ba314..632d229 100644 --- a/Modules/Monitor/Tests/Fakes.swift +++ b/Modules/Monitor/Tests/Fakes.swift @@ -3,6 +3,7 @@ import Measures import Analytics import Billing import Alerts +import Services @testable import Monitor extension Date { @@ -116,8 +117,8 @@ struct World { let settings = FakeSettings() let notifier = FakeNotifier() - func account() throws -> Account { - try Account(services: .builtIns(), plans: .builtIns(), analytics: cloudflare, billing: cloudflare, + func account(adding extra: [ServiceDefinition] = []) throws -> Account { + try Account(services: .builtIns() + extra, plans: .builtIns(), analytics: cloudflare, billing: cloudflare, vault: vault, settings: settings, notifier: notifier) } } diff --git a/Modules/Monitor/Tests/LiveAccountTests.swift b/Modules/Monitor/Tests/LiveAccountTests.swift index 967d3c5..0946025 100644 --- a/Modules/Monitor/Tests/LiveAccountTests.swift +++ b/Modules/Monitor/Tests/LiveAccountTests.swift @@ -24,7 +24,7 @@ struct LiveAccountTests { print("LIVE", limit.id, limit.current(at: now)?.used.short ?? "—", limit.percent(at: now).map { "\($0.rounded)%" } ?? "—", limit.level(at: now).map { "\($0)" } ?? "—") } - print("LIVE menu bar", account.menuBar(at: now).text, account.freshness(at: now)) + print("LIVE menu bar", account.menuBar(at: now), account.freshness(at: now)) if let worker = account.workers.first(where: { $0.contains("leaderboard") }) ?? account.workers.first { account.focus = Focus(dimension: "scriptName", value: worker) } diff --git a/Modules/Plans/Resources/Plans/free.json b/Modules/Plans/Resources/Plans/free.json index 99a307e..6419c81 100644 --- a/Modules/Plans/Resources/Plans/free.json +++ b/Modules/Plans/Resources/Plans/free.json @@ -8,6 +8,19 @@ "workers.cpu": { "perInvocation": "10 ms" }, "d1.rowsRead": { "perDay": "5M rows" }, "d1.rowsWritten": { "perDay": "100k rows" }, - "d1.storage": { "total": "5 GB" } + "d1.storage": { "total": "5 GB" }, + "kv.reads": { "perDay": "100k requests" }, + "kv.writes": { "perDay": "1k requests" }, + "kv.deletes": { "perDay": "1k requests" }, + "kv.lists": { "perDay": "1k requests" }, + "kv.storage": { "total": "1 GB" }, + "queues.operations": { "perDay": "10k operations" }, + "ai.neurons": { "perDay": "10k neurons" }, + "vectorize.queried": { "perMonth": "30M dimensions" }, + "vectorize.stored": { "total": "5M dimensions" }, + "durable-objects.requests": { "perDay": "100k requests" }, + "durable-objects.rowsRead": { "perDay": "5M rows" }, + "durable-objects.rowsWritten": { "perDay": "100k rows" }, + "durable-objects.storage": { "total": "5 GB" } } } diff --git a/Modules/Plans/Resources/Plans/r2-paid.json b/Modules/Plans/Resources/Plans/r2-paid.json new file mode 100644 index 0000000..14913fe --- /dev/null +++ b/Modules/Plans/Resources/Plans/r2-paid.json @@ -0,0 +1,18 @@ +{ + "id": "r2-paid", + "name": "R2", + "subscription": "0 USD", + "matches": ["r2_paid"], + "addOn": true, + "upgradeURL": "https://dash.cloudflare.com/{account}/r2/plans", + "allowances": { + "r2.classA": { "perMonth": "1M requests" }, + "r2.classB": { "perMonth": "10M requests" }, + "r2.storage": { "total": "10 GB" } + }, + "prices": { + "r2.classA": { "beyond": { "price": "4.50 USD", "per": "1M requests" } }, + "r2.classB": { "beyond": { "price": "0.36 USD", "per": "1M requests" } }, + "r2.storage": { "perMonthOver": { "price": "0.015 USD", "per": "1 GB" } } + } +} diff --git a/Modules/Plans/Resources/Plans/workers-paid.json b/Modules/Plans/Resources/Plans/workers-paid.json index a5ae0cf..775b6b9 100644 --- a/Modules/Plans/Resources/Plans/workers-paid.json +++ b/Modules/Plans/Resources/Plans/workers-paid.json @@ -9,13 +9,39 @@ "workers.cpuTime": { "perMonth": "30M ms" }, "d1.rowsRead": { "perMonth": "25B rows" }, "d1.rowsWritten": { "perMonth": "50M rows" }, - "d1.storage": { "total": "5 GB" } + "d1.storage": { "total": "5 GB" }, + "kv.reads": { "perMonth": "10M requests" }, + "kv.writes": { "perMonth": "1M requests" }, + "kv.deletes": { "perMonth": "1M requests" }, + "kv.lists": { "perMonth": "1M requests" }, + "kv.storage": { "total": "1 GB" }, + "queues.operations": { "perMonth": "1M operations" }, + "ai.neurons": { "perDay": "10k neurons" }, + "vectorize.queried": { "perMonth": "50M dimensions" }, + "vectorize.stored": { "total": "10M dimensions" }, + "durable-objects.requests": { "perMonth": "1M requests" }, + "durable-objects.rowsRead": { "perMonth": "25B rows" }, + "durable-objects.rowsWritten": { "perMonth": "50M rows" }, + "durable-objects.storage": { "total": "5 GB" } }, "prices": { "workers.requests": { "beyond": { "price": "0.30 USD", "per": "1M requests" } }, "workers.cpuTime": { "beyond": { "price": "0.02 USD", "per": "1M ms" } }, "d1.rowsRead": { "beyond": { "price": "0.001 USD", "per": "1M rows" } }, "d1.rowsWritten": { "beyond": { "price": "1.00 USD", "per": "1M rows" } }, - "d1.storage": { "perMonthOver": { "price": "0.75 USD", "per": "1 GB" } } + "d1.storage": { "perMonthOver": { "price": "0.75 USD", "per": "1 GB" } }, + "kv.reads": { "beyond": { "price": "0.50 USD", "per": "1M requests" } }, + "kv.writes": { "beyond": { "price": "5.00 USD", "per": "1M requests" } }, + "kv.deletes": { "beyond": { "price": "5.00 USD", "per": "1M requests" } }, + "kv.lists": { "beyond": { "price": "5.00 USD", "per": "1M requests" } }, + "kv.storage": { "perMonthOver": { "price": "0.50 USD", "per": "1 GB" } }, + "queues.operations": { "beyond": { "price": "0.40 USD", "per": "1M operations" } }, + "ai.neurons": { "beyond": { "price": "0.011 USD", "per": "1k neurons" } }, + "vectorize.queried": { "beyond": { "price": "0.01 USD", "per": "1M dimensions" } }, + "vectorize.stored": { "perMonthOver": { "price": "0.05 USD", "per": "100M dimensions" } }, + "durable-objects.requests": { "beyond": { "price": "0.15 USD", "per": "1M requests" } }, + "durable-objects.rowsRead": { "beyond": { "price": "0.001 USD", "per": "1M rows" } }, + "durable-objects.rowsWritten": { "beyond": { "price": "1.00 USD", "per": "1M rows" } }, + "durable-objects.storage": { "perMonthOver": { "price": "0.20 USD", "per": "1 GB" } } } } diff --git a/Modules/Plans/Sources/Plan.swift b/Modules/Plans/Sources/Plan.swift index 96cb09f..2b1dd61 100644 --- a/Modules/Plans/Sources/Plan.swift +++ b/Modules/Plans/Sources/Plan.swift @@ -1,43 +1,73 @@ import Foundation import Measures -/// The plan an account is on: a definition, and the day its billing month renews. +/// The plan an account is on: a definition, the day its billing month renews, and the add-ons +/// beside it (*R2*, CANONICAL law 23). public struct Plan: Sendable, Equatable { public let definition: PlanDefinition /// From the subscription's `current_period_end`; nil on Free. public let renewsOn: Date? + public let addOns: [Plan] - public init(_ definition: PlanDefinition, renewsOn: Date?) { + public init(_ definition: PlanDefinition, renewsOn: Date?, addOns: [Plan] = []) { self.definition = definition self.renewsOn = renewsOn + self.addOns = addOns } - public func allowance(for limit: LimitID) -> Allowance? { definition.allowance(for: limit) } + /// Whichever of this plan and its add-ons names the limit (law 23). + func owner(of limit: LimitID) -> Plan? { + definition.allowance(for: limit) != nil ? self : addOns.first { $0.definition.allowance(for: limit) != nil } + } + + public func allowance(for limit: LimitID) -> Allowance? { owner(of: limit)?.definition.allowance(for: limit) } + + func price(for limit: LimitID) -> Price? { owner(of: limit)?.definition.price(for: limit) } + + /// Whether use past the allowance fails instead of being charged: Free stops, Workers Paid + /// charges, even for a daily allowance like Workers AI's (laws 19, 24). + public func stops(at limit: LimitID) -> Bool { price(for: limit) == nil } - /// The period a limit's reading covers at `now` (CANONICAL law 5); nil for what never resets - /// and for a limit the plan doesn't count. + /// The period a limit's reading covers at `now` (CANONICAL law 5), on the renewal of the + /// subscription that names it; nil for what never resets and for a limit no plan counts. public func period(for limit: LimitID, at now: Date) -> Period? { - allowance(for: limit)?.period(at: now, renewsOn: renewsOn) + guard let owner = owner(of: limit) else { return nil } + return owner.definition.allowance(for: limit)?.period(at: now, renewsOn: owner.renewsOn) } /// One line per priced limit: its use, what the plan includes, and the price of the rest /// (law 20). The subscription is not a line; the lines and it add up to `cost(of:)`. - public func lines(of used: [LimitID: Quantity]) -> [CostLine] { + /// `days` is each daily limit's use per UTC day this month; `stretch` scales a daily limit's + /// overage to the month's end for a forecast or a quote (law 24). + public func lines(of used: [LimitID: Quantity], days: [LimitID: [Date: Quantity]] = [:], stretch: Double = 1) -> [CostLine] { used.compactMap { limit, quantity -> CostLine? in - guard let price = definition.price(for: limit), let allowance = allowance(for: limit) else { return nil } - return CostLine(limit: limit, used: quantity, included: allowance.amount, - cost: price.cost(of: quantity, allowance: allowance.amount)) + guard let cost = cost(of: limit, used: quantity, days: days[limit], stretch: stretch), + let allowance = allowance(for: limit) else { return nil } + return CostLine(limit: limit, used: quantity, included: allowance.amount, cost: cost) } .sorted { $0.limit.rawValue < $1.limit.rawValue } } - /// The subscription, plus for each limit the price of what went past its allowance - /// (CANONICAL laws 13–14). `used` is each limit's use over the billing month. - public func cost(of used: [LimitID: Quantity]) -> Money { - used.reduce(definition.subscription) { total, entry in - guard let price = definition.price(for: entry.key), let allowance = allowance(for: entry.key) else { return total } - return total + price.cost(of: entry.value, allowance: allowance.amount) + /// The subscriptions (this plan's and its add-ons'), plus for each limit the price of what + /// went past its allowance (CANONICAL laws 13–14, 23). `used` is each limit's use over the + /// billing month. + public func cost(of used: [LimitID: Quantity], days: [LimitID: [Date: Quantity]] = [:], stretch: Double = 1) -> Money { + let subscriptions = addOns.reduce(definition.subscription) { $0 + $1.definition.subscription } + return used.reduce(subscriptions) { total, entry in + guard let cost = cost(of: entry.key, used: entry.value, days: days[entry.key], stretch: stretch) else { return total } + return total + cost + } + } + + /// One limit's price past its allowance; nil when no plan prices it. A daily allowance with + /// a price is billed day by day: each UTC day's use past it, added up (law 24). + func cost(of limit: LimitID, used: Quantity, days: [Date: Quantity]?, stretch: Double) -> Money? { + guard let price = price(for: limit), let allowance = allowance(for: limit) else { return nil } + guard case .perDay(let daily) = allowance, let days, !days.isEmpty else { + return price.cost(of: used, allowance: allowance.amount) } + let over = days.values.reduce(0) { $0 + max($1.value - daily.value, 0) } * stretch + return price.cost(of: Quantity(over, daily.unit), allowance: Quantity(0, daily.unit)) } } diff --git a/Modules/Plans/Sources/PlanCatalog.swift b/Modules/Plans/Sources/PlanCatalog.swift index f086112..1f00e0a 100644 --- a/Modules/Plans/Sources/PlanCatalog.swift +++ b/Modules/Plans/Sources/PlanCatalog.swift @@ -17,17 +17,24 @@ public enum PlanCatalog { return plans.sorted { $0.id < $1.id } } - /// The plan an account is on, from the `rate_plan` ids of its subscriptions: the first - /// definition that matches one, else the one that matches nothing (Free). + /// The Workers plan an account is on, from the `rate_plan` ids of its subscriptions: the + /// first definition that matches one, else the one that matches nothing (Free). Add-ons + /// are never it. public static func plan(forRatePlans ratePlans: [String]) throws(PlanError) -> PlanDefinition { try plan(forRatePlans: ratePlans, among: builtIns()) } public static func plan(forRatePlans ratePlans: [String], among plans: [PlanDefinition]) throws(PlanError) -> PlanDefinition { - if let paid = plans.first(where: { !Set($0.matches).isDisjoint(with: ratePlans) }) { return paid } - guard let free = plans.first(where: \.matches.isEmpty) else { throw .notFound("a plan that matches nothing") } + let workers = plans.filter { !$0.addOn } + if let paid = workers.first(where: { !Set($0.matches).isDisjoint(with: ratePlans) }) { return paid } + guard let free = workers.first(where: \.matches.isEmpty) else { throw .notFound("a plan that matches nothing") } return free } + + /// The add-ons the account has beside its Workers plan: *R2* (law 23). + public static func addOns(forRatePlans ratePlans: [String], among plans: [PlanDefinition]) -> [PlanDefinition] { + plans.filter { $0.addOn && !Set($0.matches).isDisjoint(with: ratePlans) } + } } extension Array where Element == PlanDefinition { diff --git a/Modules/Plans/Sources/PlanDefinition.swift b/Modules/Plans/Sources/PlanDefinition.swift index d9044d1..d67f6f0 100644 --- a/Modules/Plans/Sources/PlanDefinition.swift +++ b/Modules/Plans/Sources/PlanDefinition.swift @@ -8,6 +8,8 @@ public struct PlanDefinition: Sendable, Equatable, Identifiable { public let subscription: Money /// The `rate_plan` ids in the account's subscriptions that mean this plan. public let matches: [String] + /// *R2*: a subscription beside the Workers plan, never instead of it (CANONICAL law 23). + public let addOn: Bool let allowances: [LimitID: Allowance] let prices: [LimitID: Price] /// Its page on Cloudflare's dashboard, `{account}` for the account ID. Overmind only @@ -21,6 +23,7 @@ public struct PlanDefinition: Sendable, Equatable, Identifiable { name = file.name subscription = try Money(parsing: file.subscription) matches = file.matches + addOn = file.addOn ?? false allowances = Dictionary(uniqueKeysWithValues: file.allowances.map { (LimitID($0.key), $0.value) }) prices = Dictionary(uniqueKeysWithValues: (file.prices ?? [:]).map { (LimitID($0.key), $0.value) }) upgradeTemplate = file.upgradeURL @@ -50,6 +53,7 @@ public struct PlanDefinition: Sendable, Equatable, Identifiable { private struct File: Decodable { let id, name, subscription: String let matches: [String] + let addOn: Bool? let allowances: [String: Allowance] let prices: [String: Price]? let upgradeURL: String? diff --git a/Modules/Plans/Tests/PlanTests.swift b/Modules/Plans/Tests/PlanTests.swift index e2a8a77..16b3673 100644 --- a/Modules/Plans/Tests/PlanTests.swift +++ b/Modules/Plans/Tests/PlanTests.swift @@ -101,6 +101,88 @@ struct BuiltInPlansTests { #expect(paid.cost(of: ["d1.rowsRead": Quantity(26_000_000_000, .rows)]) == Money(6, "USD")) } + @Test func `should know Free allows 100k KV reads and 1k KV writes a day, and 1 GB stored`() throws { + let free = try PlanCatalog.builtIn("free") + #expect(free.allowance(for: "kv.reads") == .perDay(Quantity(100_000, .requests))) + #expect(free.allowance(for: "kv.writes") == .perDay(Quantity(1_000, .requests))) + #expect(free.allowance(for: "kv.storage") == .total(Quantity(1_000_000_000, .bytes))) + } + + @Test func `should price 2M KV writes on Workers Paid at the subscription plus five dollars`() throws { + let paid = Plan(try PlanCatalog.builtIn("workers-paid"), renewsOn: nil) + #expect(paid.allowance(for: "kv.writes") == .perMonth(Quantity(1_000_000, .requests))) + #expect(paid.cost(of: ["kv.writes": Quantity(2_000_000, .requests)]) == Money(10, "USD")) + } + + @Test func `should know Free allows 10k Queues operations a day, and Workers Paid 1M a month`() throws { + #expect(try PlanCatalog.builtIn("free").allowance(for: "queues.operations") == .perDay(Quantity(10_000, .operations))) + #expect(try PlanCatalog.builtIn("workers-paid").allowance(for: "queues.operations") == .perMonth(Quantity(1_000_000, .operations))) + } + + @Test func `should price 3M Queues operations on Workers Paid at the subscription plus 80 cents`() throws { + let paid = Plan(try PlanCatalog.builtIn("workers-paid"), renewsOn: nil) + #expect(paid.cost(of: ["queues.operations": Quantity(3_000_000, .operations)]) == Money(Decimal(string: "5.80")!, "USD")) + } + + @Test func `should allow 10k Workers AI neurons a day on both plans, and charge past it only on Workers Paid`() throws { + #expect(try PlanCatalog.builtIn("free").allowance(for: "ai.neurons") == .perDay(Quantity(10_000, .neurons))) + #expect(try PlanCatalog.builtIn("free").price(for: "ai.neurons") == nil) + #expect(try PlanCatalog.builtIn("workers-paid").allowance(for: "ai.neurons") == .perDay(Quantity(10_000, .neurons))) + } + + @Test func `should charge Workers AI day by day: only each day's neurons past 10k`() throws { + let paid = Plan(try PlanCatalog.builtIn("workers-paid"), renewsOn: nil) + let days: [LimitID: [Date: Quantity]] = ["ai.neurons": [.utc("2026-10-01T00:00:00"): Quantity(25_000, .neurons), + .utc("2026-10-02T00:00:00"): Quantity(5_000, .neurons)]] + let used: [LimitID: Quantity] = ["ai.neurons": Quantity(30_000, .neurons)] + + // 15k past the allowance on the 1st, none on the 2nd: 15 × $0.011. + #expect(paid.cost(of: used, days: days) == Money(Decimal(string: "5.165")!, "USD")) + #expect(paid.lines(of: used, days: days).first?.cost == Money(Decimal(string: "0.165")!, "USD")) + } + + @Test func `should know Vectorize's allowances on each plan`() throws { + #expect(try PlanCatalog.builtIn("free").allowance(for: "vectorize.queried") == .perMonth(Quantity(30_000_000, .dimensions))) + #expect(try PlanCatalog.builtIn("free").allowance(for: "vectorize.stored") == .total(Quantity(5_000_000, .dimensions))) + #expect(try PlanCatalog.builtIn("workers-paid").allowance(for: "vectorize.queried") == .perMonth(Quantity(50_000_000, .dimensions))) + } + + @Test func `should know Durable Objects' allowances on each plan`() throws { + #expect(try PlanCatalog.builtIn("free").allowance(for: "durable-objects.requests") == .perDay(Quantity(100_000, .requests))) + #expect(try PlanCatalog.builtIn("workers-paid").allowance(for: "durable-objects.rowsRead") == .perMonth(Quantity(25_000_000_000, .rows))) + let paid = Plan(try PlanCatalog.builtIn("workers-paid"), renewsOn: nil) + #expect(paid.cost(of: ["durable-objects.requests": Quantity(3_000_000, .requests)]) == Money(Decimal(string: "5.30")!, "USD")) + } + + @Test func `should take R2 as an add-on beside the Workers plan when the account has R2`() throws { + #expect(try PlanCatalog.addOns(forRatePlans: ["r2_paid"], among: .builtIns()).map(\.id) == ["r2-paid"]) + #expect(try PlanCatalog.addOns(forRatePlans: ["workers_paid"], among: .builtIns()).isEmpty) + } + + @Test func `should count R2 Class A against R2's 1M a month beside the Free plan`() throws { + let free = Plan(try PlanCatalog.builtIn("free"), renewsOn: nil, addOns: [Plan(try PlanCatalog.builtIn("r2-paid"), renewsOn: nil)]) + + #expect(free.allowance(for: "r2.classA") == .perMonth(Quantity(1_000_000, .requests))) + #expect(free.allowance(for: "d1.rowsRead") == .perDay(Quantity(5_000_000, .rows))) + #expect(Plan(try PlanCatalog.builtIn("free"), renewsOn: nil).allowance(for: "r2.classA") == nil) + } + + @Test func `should charge R2's Class A past its free million on Free, with its own line`() throws { + let free = Plan(try PlanCatalog.builtIn("free"), renewsOn: nil, addOns: [Plan(try PlanCatalog.builtIn("r2-paid"), renewsOn: nil)]) + let used: [LimitID: Quantity] = ["r2.classA": Quantity(2_000_000, .requests), "d1.rowsRead": Quantity(1_000, .rows)] + + #expect(free.cost(of: used) == Money(Decimal(string: "4.50")!, "USD")) + #expect(free.lines(of: used).map(\.limit) == ["r2.classA"]) + } + + @Test func `should reset R2's month on R2's own renewal day`() throws { + let renewal = Date(timeIntervalSince1970: 1_792_022_400) // 2026-10-15 00:00 UTC + let paid = Plan(try PlanCatalog.builtIn("workers-paid"), renewsOn: nil, + addOns: [Plan(try PlanCatalog.builtIn("r2-paid"), renewsOn: renewal)]) + + #expect(paid.period(for: "r2.classA", at: Date(timeIntervalSince1970: 1_791_763_200))?.end == renewal) // 2026-10-12 + } + @Test func `should take an account with only R2 Paid to be on the Free Workers plan`() throws { #expect(try PlanCatalog.plan(forRatePlans: ["r2_paid"]).id == "free") } diff --git a/Modules/Services/Resources/Services/ai.json b/Modules/Services/Resources/Services/ai.json new file mode 100644 index 0000000..001f407 --- /dev/null +++ b/Modules/Services/Resources/Services/ai.json @@ -0,0 +1,17 @@ +{ + "id": "ai", + "name": "Workers AI", + "order": 6, + "watchedByDefault": false, + "look": { "glyph": "✦", "color": "pink" }, + "limits": [ + { "id": "ai.neurons", "name": "Workers AI neurons", "short": "AI", "unit": "neurons", + "read": { "sum": { "dataset": "aiInferenceAdaptiveGroups", "field": "sum.totalNeurons", "time": "datetime" } } } + ], + "breakdowns": [ + { "title": "Neurons · per hour today", "series": { "limit": "ai.neurons", "by": "hour", "last": 24 } }, + { "title": "Top models by neurons", + "top": { "dataset": "aiInferenceAdaptiveGroups", "dimension": "modelId", "measure": "sum.totalNeurons", + "count": 5, "time": "datetime" } } + ] +} diff --git a/Modules/Services/Resources/Services/d1.json b/Modules/Services/Resources/Services/d1.json index ab90d48..199c434 100644 --- a/Modules/Services/Resources/Services/d1.json +++ b/Modules/Services/Resources/Services/d1.json @@ -2,6 +2,7 @@ "id": "d1", "name": "D1", "order": 2, + "watchedByDefault": true, "look": { "glyph": "⛁", "color": "butter" }, "limits": [ { "id": "d1.rowsRead", "name": "D1 rows read", "short": "D1", "unit": "rows", diff --git a/Modules/Services/Resources/Services/durable-objects.json b/Modules/Services/Resources/Services/durable-objects.json new file mode 100644 index 0000000..621d77c --- /dev/null +++ b/Modules/Services/Resources/Services/durable-objects.json @@ -0,0 +1,27 @@ +{ + "id": "durable-objects", + "name": "Durable Objects", + "order": 8, + "watchedByDefault": false, + "look": { "glyph": "◈", "color": "sky" }, + "limits": [ + { "id": "durable-objects.requests", "name": "Durable Objects requests", "short": "DO", "unit": "requests", + "read": { "sum": { "dataset": "durableObjectsInvocationsAdaptiveGroups", "field": "sum.requests", + "time": "datetime", "focus": "scriptName" } } }, + { "id": "durable-objects.rowsRead", "name": "Durable Objects rows read", "short": "DO reads", "unit": "rows", + "read": { "sum": { "dataset": "durableObjectsPeriodicGroups", "field": "sum.rowsRead", + "time": "datetime", "focus": "namespaceId" } } }, + { "id": "durable-objects.rowsWritten", "name": "Durable Objects rows written", "short": "DO writes", "unit": "rows", + "read": { "sum": { "dataset": "durableObjectsPeriodicGroups", "field": "sum.rowsWritten", + "time": "datetime", "focus": "namespaceId" } } }, + { "id": "durable-objects.storage", "name": "Durable Objects storage", "short": "DO storage", "unit": "bytes", + "read": { "max": { "dataset": "durableObjectsSqlStorageGroups", "field": "max.storedBytes", + "time": "datetime", "focus": "namespaceId" } } } + ], + "breakdowns": [ + { "title": "Requests · per hour today", "series": { "limit": "durable-objects.requests", "by": "hour", "last": 24 } }, + { "title": "Requests by outcome", + "split": { "dataset": "durableObjectsInvocationsAdaptiveGroups", "dimension": "status", "measure": "sum.requests", + "time": "datetime", "focus": "scriptName" } } + ] +} diff --git a/Modules/Services/Resources/Services/kv.json b/Modules/Services/Resources/Services/kv.json new file mode 100644 index 0000000..2351164 --- /dev/null +++ b/Modules/Services/Resources/Services/kv.json @@ -0,0 +1,29 @@ +{ + "id": "kv", + "name": "KV", + "order": 3, + "watchedByDefault": false, + "look": { "glyph": "⚿", "color": "pink" }, + "limits": [ + { "id": "kv.reads", "name": "KV reads", "short": "KV", "unit": "requests", + "read": { "sum": { "dataset": "kvOperationsAdaptiveGroups", "field": "sum.requests", "time": "date", + "where": { "dimension": "actionType", "in": ["read"] } } } }, + { "id": "kv.writes", "name": "KV writes", "short": "KV writes", "unit": "requests", + "read": { "sum": { "dataset": "kvOperationsAdaptiveGroups", "field": "sum.requests", "time": "date", + "where": { "dimension": "actionType", "in": ["write"] } } } }, + { "id": "kv.deletes", "name": "KV deletes", "short": "KV deletes", "unit": "requests", + "read": { "sum": { "dataset": "kvOperationsAdaptiveGroups", "field": "sum.requests", "time": "date", + "where": { "dimension": "actionType", "in": ["delete"] } } } }, + { "id": "kv.lists", "name": "KV lists", "short": "KV lists", "unit": "requests", + "read": { "sum": { "dataset": "kvOperationsAdaptiveGroups", "field": "sum.requests", "time": "date", + "where": { "dimension": "actionType", "in": ["list"] } } } }, + { "id": "kv.storage", "name": "KV storage", "short": "KV storage", "unit": "bytes", + "read": { "max": { "dataset": "kvStorageAdaptiveGroups", "field": "max.byteCount", "time": "date", "focus": "namespaceId" } } } + ], + "breakdowns": [ + { "title": "Reads · last 7 days", "series": { "limit": "kv.reads", "by": "day", "last": 7 } }, + { "title": "Operations by type", + "split": { "dataset": "kvOperationsAdaptiveGroups", "dimension": "actionType", "measure": "sum.requests", + "time": "date" } } + ] +} diff --git a/Modules/Services/Resources/Services/queues.json b/Modules/Services/Resources/Services/queues.json new file mode 100644 index 0000000..ad3fb93 --- /dev/null +++ b/Modules/Services/Resources/Services/queues.json @@ -0,0 +1,18 @@ +{ + "id": "queues", + "name": "Queues", + "order": 4, + "watchedByDefault": false, + "look": { "glyph": "⇶", "color": "sky" }, + "limits": [ + { "id": "queues.operations", "name": "Queues operations", "short": "Queues", "unit": "operations", + "read": { "sum": { "dataset": "queueMessageOperationsAdaptiveGroups", "field": "sum.billableOperations", + "time": "datetime", "focus": "queueId" } } } + ], + "breakdowns": [ + { "title": "Operations · per hour today", "series": { "limit": "queues.operations", "by": "hour", "last": 24 } }, + { "title": "Operations by type", + "split": { "dataset": "queueMessageOperationsAdaptiveGroups", "dimension": "actionType", + "measure": "sum.billableOperations", "time": "datetime", "focus": "queueId" } } + ] +} diff --git a/Modules/Services/Resources/Services/r2.json b/Modules/Services/Resources/Services/r2.json new file mode 100644 index 0000000..340fd68 --- /dev/null +++ b/Modules/Services/Resources/Services/r2.json @@ -0,0 +1,30 @@ +{ + "id": "r2", + "name": "R2", + "order": 5, + "watchedByDefault": false, + "look": { "glyph": "◫", "color": "butter" }, + "limits": [ + { "id": "r2.classA", "name": "R2 Class A", "short": "R2 A", "unit": "requests", + "read": { "sum": { "dataset": "r2OperationsAdaptiveGroups", "field": "sum.requests", "time": "datetime", "focus": "bucketName", + "where": { "dimension": "actionType", + "in": ["ListBuckets", "PutBucket", "ListObjects", "PutObject", "CopyObject", + "CreateMultipartUpload", "UploadPart", "UploadPartCopy", "CompleteMultipartUpload", + "ListMultipartUploads", "ListParts", "LifecycleStorageTierTransition", + "PutBucketEncryption", "PutBucketCors", "PutBucketLifecycleConfiguration"] } } } }, + { "id": "r2.classB", "name": "R2 Class B", "short": "R2 B", "unit": "requests", + "read": { "sum": { "dataset": "r2OperationsAdaptiveGroups", "field": "sum.requests", "time": "datetime", "focus": "bucketName", + "where": { "dimension": "actionType", + "in": ["HeadBucket", "HeadObject", "GetObject", "UsageSummary", "GetBucketEncryption", + "GetBucketLocation", "GetBucketCors", "GetBucketLifecycleConfiguration"] } } } }, + { "id": "r2.storage", "name": "R2 storage", "short": "R2 storage", "unit": "bytes", + "read": { "max": { "dataset": "r2StorageAdaptiveGroups", "field": "max.payloadSize", "time": "datetime", "focus": "bucketName" } } } + ], + "breakdowns": [ + { "title": "Class A · per hour today", "series": { "limit": "r2.classA", "by": "hour", "last": 24 } }, + { "title": "Class B · per hour today", "series": { "limit": "r2.classB", "by": "hour", "last": 24 } }, + { "title": "Operations by type", + "split": { "dataset": "r2OperationsAdaptiveGroups", "dimension": "actionType", "measure": "sum.requests", + "time": "datetime", "focus": "bucketName" } } + ] +} diff --git a/Modules/Services/Resources/Services/vectorize.json b/Modules/Services/Resources/Services/vectorize.json new file mode 100644 index 0000000..0eb4ce8 --- /dev/null +++ b/Modules/Services/Resources/Services/vectorize.json @@ -0,0 +1,21 @@ +{ + "id": "vectorize", + "name": "Vectorize", + "order": 7, + "watchedByDefault": false, + "look": { "glyph": "⋰", "color": "mint" }, + "limits": [ + { "id": "vectorize.queried", "name": "Vectorize queried dimensions", "short": "Vectorize", "unit": "dimensions", + "read": { "sum": { "dataset": "vectorizeV2QueriesAdaptiveGroups", "field": "sum.queriedVectorDimensions", + "time": "datetime", "focus": "indexName" } } }, + { "id": "vectorize.stored", "name": "Vectorize stored dimensions", "short": "Vectorize stored", "unit": "dimensions", + "read": { "max": { "dataset": "vectorizeV2StorageAdaptiveGroups", "field": "max.storedVectorDimensions", + "time": "datetime", "focus": "indexName" } } } + ], + "breakdowns": [ + { "title": "Queried dimensions · last 7 days", "series": { "limit": "vectorize.queried", "by": "day", "last": 7 } }, + { "title": "Top indexes by queried dimensions", + "top": { "dataset": "vectorizeV2QueriesAdaptiveGroups", "dimension": "indexName", "measure": "sum.queriedVectorDimensions", + "count": 5, "time": "datetime" } } + ] +} diff --git a/Modules/Services/Resources/Services/workers.json b/Modules/Services/Resources/Services/workers.json index b8b6aab..5165add 100644 --- a/Modules/Services/Resources/Services/workers.json +++ b/Modules/Services/Resources/Services/workers.json @@ -2,6 +2,7 @@ "id": "workers", "name": "Worker", "order": 1, + "watchedByDefault": true, "look": { "glyph": "ƒ", "color": "sky" }, "limits": [ { "id": "workers.requests", "name": "Requests", "short": "Requests", "unit": "requests", diff --git a/Modules/Services/Sources/Read.swift b/Modules/Services/Sources/Read.swift index c01a248..61ff457 100644 --- a/Modules/Services/Sources/Read.swift +++ b/Modules/Services/Sources/Read.swift @@ -25,9 +25,13 @@ public enum Read: Sendable, Equatable { public let scale: Double? /// For a percentile: the invocations that went past the allowance. public let failures: Failures? + /// Only these groups count: KV writes are `actionType` `write`. Part of what the limit + /// is, so it always applies, unlike `focus` (ENGINE §2). + public let `where`: Where? public init(dataset: String, field: String, time: TimeFilter, focus: String? = nil, - scale: Double? = nil, failures: Failures? = nil) { + scale: Double? = nil, failures: Failures? = nil, where: Where? = nil) { + self.where = `where` self.dataset = dataset self.field = field self.time = time @@ -52,6 +56,19 @@ public enum Read: Sendable, Equatable { } } +extension Read { + /// The groups a limit counts: those whose `dimension` is one of `in`. + public struct Where: Sendable, Equatable, Codable { + public let dimension: String + public let `in`: [String] + + public init(dimension: String, in values: [String]) { + self.dimension = dimension + self.in = values + } + } +} + /// The filter a dataset takes for time: D1 filters by `date`, Workers by `datetime`, D1's /// query insights by `datetimeHour`. public enum TimeFilter: String, Sendable, Codable { diff --git a/Modules/Services/Sources/ServiceDefinition.swift b/Modules/Services/Sources/ServiceDefinition.swift index 45bbf28..d7e76b6 100644 --- a/Modules/Services/Sources/ServiceDefinition.swift +++ b/Modules/Services/Sources/ServiceDefinition.swift @@ -10,6 +10,22 @@ public struct ServiceDefinition: Sendable, Equatable, Decodable, Identifiable { public let look: Look public let limits: [LimitDefinition] public let breakdowns: [BreakdownDefinition] + /// Whether someone who never chose for it watches it: Workers and D1 yes, each later + /// service no, so it arrives off (CANONICAL law 21). + public let watchedByDefault: Bool + + enum CodingKeys: String, CodingKey { case id, name, order, look, limits, breakdowns, watchedByDefault } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + name = try container.decode(String.self, forKey: .name) + order = try container.decode(Int.self, forKey: .order) + look = try container.decode(Look.self, forKey: .look) + limits = try container.decode([LimitDefinition].self, forKey: .limits) + breakdowns = try container.decode([BreakdownDefinition].self, forKey: .breakdowns) + watchedByDefault = try container.decodeIfPresent(Bool.self, forKey: .watchedByDefault) ?? false + } public struct Look: Sendable, Equatable, Codable { public let glyph: String diff --git a/Modules/Services/Tests/BuiltInServicesTests.swift b/Modules/Services/Tests/BuiltInServicesTests.swift index b223880..0ba3798 100644 --- a/Modules/Services/Tests/BuiltInServicesTests.swift +++ b/Modules/Services/Tests/BuiltInServicesTests.swift @@ -5,8 +5,77 @@ import Measures /// The built-in service files, read through the real JSON. @Suite struct BuiltInServicesTests { - @Test func `should show Workers before D1`() throws { - #expect(try ServiceCatalog.builtIns().map(\.id) == ["workers", "d1"]) + @Test func `should show Workers, then D1, KV, Queues, R2, Workers AI, Vectorize and Durable Objects`() throws { + #expect(try ServiceCatalog.builtIns().map(\.id) == ["workers", "d1", "kv", "queues", "r2", "ai", "vectorize", "durable-objects"]) + } + + @Test func `should leave every service but Workers and D1 off until the person watches it`() throws { + #expect(try ServiceCatalog.builtIns().filter { !$0.watchedByDefault }.map(\.id) + == ["kv", "queues", "r2", "ai", "vectorize", "durable-objects"]) + } + + @Test func `should know Workers AI counts neurons across every model`() throws { + let neurons = try #require(try ServiceCatalog.builtIn("ai").limits.first) + #expect(neurons.id == "ai.neurons") + #expect(neurons.unit == .neurons) + #expect(neurons.read == .sum(Read.Source(dataset: "aiInferenceAdaptiveGroups", field: "sum.totalNeurons", time: .datetime))) + } + + @Test func `should know Vectorize counts queried dimensions, and stored dimensions across every index`() throws { + let vectorize = try ServiceCatalog.builtIn("vectorize") + #expect(vectorize.limits.map(\.id) == ["vectorize.queried", "vectorize.stored"]) + #expect(vectorize.limits[1].read == .max(Read.Source(dataset: "vectorizeV2StorageAdaptiveGroups", field: "max.storedVectorDimensions", + time: .datetime, focus: "indexName"))) + } + + @Test func `should know Durable Objects counts requests, SQLite rows and storage`() throws { + let objects = try ServiceCatalog.builtIn("durable-objects") + #expect(objects.limits.map(\.id) == ["durable-objects.requests", "durable-objects.rowsRead", + "durable-objects.rowsWritten", "durable-objects.storage"]) + #expect(objects.limits[1].read == .sum(Read.Source(dataset: "durableObjectsPeriodicGroups", field: "sum.rowsRead", + time: .datetime, focus: "namespaceId"))) + } + + @Test func `should know R2's Class B is reads like GetObject and HeadObject, and leave R2 off until watched`() throws { + let r2 = try ServiceCatalog.builtIn("r2") + + let classB = try #require(r2.limits.first { $0.id == "r2.classB" }) + #expect(classB.read.source.dataset == "r2OperationsAdaptiveGroups") + #expect(classB.read.source.where?.dimension == "actionType") + #expect(classB.read.source.where?.in.contains("GetObject") == true) + #expect(classB.read.source.where?.in.contains("PutObject") == false) + #expect(r2.watchedByDefault == false) + } + + @Test func `should know Queues counts billable operations across every queue, and leave Queues off until watched`() throws { + let queues = try ServiceCatalog.builtIn("queues") + + let operations = try #require(queues.limits.first) + #expect(operations.id == "queues.operations") + #expect(operations.unit == .operations) + #expect(operations.read == .sum(Read.Source(dataset: "queueMessageOperationsAdaptiveGroups", field: "sum.billableOperations", + time: .datetime, focus: "queueId"))) + #expect(queues.watchedByDefault == false) + } + + @Test func `should know KV writes are KV's write operations`() throws { + let kv = try ServiceCatalog.builtIn("kv") + + let writes = try #require(kv.limits.first { $0.id == "kv.writes" }) + #expect(writes.read == .sum(Read.Source(dataset: "kvOperationsAdaptiveGroups", field: "sum.requests", time: .date, + where: Read.Where(dimension: "actionType", in: ["write"])))) + #expect(kv.limits.map(\.id) == ["kv.reads", "kv.writes", "kv.deletes", "kv.lists", "kv.storage"]) + #expect(kv.watchedByDefault == false) + } + + @Test func `should add up every KV namespace's size for storage, since the 1 GB covers them all`() throws { + let storage = try #require(try ServiceCatalog.builtIn("kv").limits.first { $0.id == "kv.storage" }) + #expect(storage.read == .max(Read.Source(dataset: "kvStorageAdaptiveGroups", field: "max.byteCount", + time: .date, focus: "namespaceId"))) + } + + @Test func `should watch Workers and D1 for someone who never chose`() throws { + #expect(try ServiceCatalog.builtIns().filter(\.watchedByDefault).map(\.id) == ["workers", "d1"]) } @Test func `should know D1 counts rows read from D1's analytics, narrowed to a database only on its tab`() throws { diff --git a/Modules/Services/Tests/ServiceDefinitionTests.swift b/Modules/Services/Tests/ServiceDefinitionTests.swift index a652466..61592d2 100644 --- a/Modules/Services/Tests/ServiceDefinitionTests.swift +++ b/Modules/Services/Tests/ServiceDefinitionTests.swift @@ -47,6 +47,20 @@ struct ServiceDefinitionTests { #expect(acme.breakdowns[0].kind == .series(limit: "acme.widgets", by: .day, last: 7)) } + @Test func `should know a limit counts only the operations its file names`() throws { + let only = Self.acme.replacingOccurrences(of: #""focus": "factoryId" } }"#, + with: #""focus": "factoryId", "where": { "dimension": "actionType", "in": ["write"] } } }"#) + let acme = try ServiceDefinition(json: Data(only.utf8)) + + #expect(acme.limits[0].read.source.where == Read.Where(dimension: "actionType", in: ["write"])) + #expect(try ServiceDefinition(json: Data(Self.acme.utf8)).limits[0].read.source.where == nil) + } + + @Test func `should leave a service unwatched until the person turns it on when its file doesn't say otherwise`() throws { + let acme = try ServiceDefinition(json: Data(Self.acme.utf8)) + #expect(acme.watchedByDefault == false) + } + @Test func `should refuse a limit that is read in a way Overmind doesn't know`() { let odd = Self.acme.replacingOccurrences(of: "\"sum\": { \"dataset\"", with: "\"median\": { \"dataset\"") #expect(throws: DefinitionError.self) { try ServiceDefinition(json: Data(odd.utf8)) } diff --git a/Modules/Storage/Tests/SettingsFileTests.swift b/Modules/Storage/Tests/SettingsFileTests.swift index 1f6678d..7e9cbd6 100644 --- a/Modules/Storage/Tests/SettingsFileTests.swift +++ b/Modules/Storage/Tests/SettingsFileTests.swift @@ -10,11 +10,12 @@ import Monitor struct SettingsFileTests { let folder = FileManager.default.temporaryDirectory.appendingPathComponent("overmind-\(UUID().uuidString)") - @Test func `should remember the account, the focus and the warnings already sent across a relaunch`() { + @Test func `should remember the account, the focus, the services watched and the warnings already sent across a relaunch`() { let saved = Settings(account: AccountSummary(id: "acc1", name: "Acme"), focus: Focus(dimension: "scriptName", value: "leaderboard"), alerts: AlertSettings(levels: [90], pace: false, isOn: true), - sent: [Warning.Key(limit: "d1.rowsRead", mark: .level(75), period: Date(timeIntervalSince1970: 0))]) + sent: [Warning.Key(limit: "d1.rowsRead", mark: .level(75), period: Date(timeIntervalSince1970: 0))], + watch: ["d1": false]) Storage.makeSettings(folder: folder).save(saved) #expect(Storage.makeSettings(folder: folder).load() == saved) diff --git a/README.md b/README.md index 7525fef..29e442a 100644 --- a/README.md +++ b/README.md @@ -47,8 +47,14 @@ Try it without an account: `OVERMIND_DEMO=1 .build/dd/Build/Products/Debug/Overm |---|---|---| | Workers | requests, CPU per invocation (Free) or CPU time (Paid) | requests per hour, invocations by outcome, cron runs, deployments | | D1 | rows read, rows written, storage | rows read per day and hour, top queries | - -Plans: Free and Workers Paid; the Bill tab prices this month on both. Other Cloudflare products +| KV (off until you turn it on in *Settings → Watching*) | reads, writes, deletes, lists, storage | reads per day, operations by type | +| Queues (off until watched) | operations | operations per hour, operations by type | +| R2 (off until watched; needs R2 on the account) | Class A, Class B, storage, against R2's own free tier | Class A and B per hour, operations by type | +| Workers AI (off until watched) | neurons against 10k a day; on Workers Paid each day's overage is priced | neurons per hour, top models | +| Vectorize (off until watched) | queried and stored vector dimensions | queried dimensions per day, top indexes | +| Durable Objects (off until watched) | requests, SQLite rows read and written, storage | requests per hour, requests by outcome | + +Plans: Free and Workers Paid, with R2 as an add-on beside either; the Bill tab prices this month on both. Other Cloudflare products are one JSON file each → [ENGINE_DESIGN](docs/architecture/ENGINE_DESIGN.md). Overmind only reads: no call it makes can change your account. diff --git a/Sources/App/BillView.swift b/Sources/App/BillView.swift index 4f77870..22c55c6 100644 --- a/Sources/App/BillView.swift +++ b/Sources/App/BillView.swift @@ -188,7 +188,7 @@ struct MonthCard: View { VStack(alignment: .leading, spacing: 6) { HStack(alignment: .bottom) { VStack(alignment: .leading, spacing: 2) { - Text(bill.issued == nil ? "THIS MONTH · EST." : "THIS MONTH · INVOICED").font(Pop.label(10)).tracking(0.6) + Text(bill.issued == nil ? "THIS MONTH · EST.\(covers)" : "THIS MONTH · INVOICED").font(Pop.label(10)).tracking(0.6) Text(Say.money(bill.issued?.amount ?? bill.estimate)).font(Pop.display(30)) } Spacer() @@ -209,6 +209,12 @@ struct MonthCard: View { .popCard(Pop.butter) } + /// *· WORKER ONLY* when a service isn't watched (law 21). + private var covers: String { + guard case .only(let names) = account.estimateCovers else { return "" } + return " · " + names.joined(separator: ", ").uppercased() + (names.count == 1 ? " ONLY" : "") + } + private var note: String { let days = Int((bill.elapsed(at: now) * bill.period.length / 86_400).rounded(.up)) let total = Int((bill.period.length / 86_400).rounded()) diff --git a/Sources/App/MenuBarLabel.swift b/Sources/App/MenuBarLabel.swift index f2cd18a..8f2c801 100644 --- a/Sources/App/MenuBarLabel.swift +++ b/Sources/App/MenuBarLabel.swift @@ -8,13 +8,24 @@ struct MenuBarLabel: View { let account: Account var body: some View { - let state = account.menuBar(at: Demo.now ?? account.lastRead ?? .now) - switch (account.phase, state.level) { - case (.refused, _): Text("☁ ⚠︎") // any refusal - case (.connected, .actNow): Text("☁ ⚠︎ \(state.text)") - case (.connected, .watch): Text("☁ ◐ \(state.text)") - case (.connected, _): Text(state.text.isEmpty ? "☁" : "☁ \(state.text)") + switch account.phase { + case .refused: Text("☁ ⚠︎") // any refusal, whatever the choice (law 22) + case .connected: + switch account.menuBar(at: Demo.now ?? account.lastRead ?? .now) { + case .notReadYet: Text("☁") + case .iconOnly(let level): Text("☁" + Self.mark(level)) + case .closest(let short, let percent, let level): Text("☁\(Self.mark(level)) \(short) \(percent.rounded)%") + } default: Text("☁") } } + + /// ` ◐` at *WATCH*, ` ⚠︎` at *ACT NOW*. + static func mark(_ level: Level) -> String { + switch level { + case .ok: "" + case .watch: " ◐" + case .actNow: " ⚠︎" + } + } } diff --git a/Sources/App/OvermindApp.swift b/Sources/App/OvermindApp.swift index 315b530..25f302c 100644 --- a/Sources/App/OvermindApp.swift +++ b/Sources/App/OvermindApp.swift @@ -59,7 +59,7 @@ enum Snapshots { Task { @MainActor in try? await Task.sleep(for: .seconds(4)) await account.openBill(at: Demo.now ?? .now) - let tabs = ["today"] + account.services.map(\.id) + ["bill"] + let tabs = ["today"] + account.watching.map(\.id) + ["bill"] for tab in tabs { if tab != "today" && tab != "bill" { await account.open(tab, at: Demo.now ?? .now) } write(PopoverView(account: account, tab: tab, scrolls: false), to: folder, name: tab) diff --git a/Sources/App/PopoverView.swift b/Sources/App/PopoverView.swift index f1217fa..7a8ce14 100644 --- a/Sources/App/PopoverView.swift +++ b/Sources/App/PopoverView.swift @@ -49,7 +49,10 @@ struct PopoverView: View { switch tab { case "today": TodayView(account: account, now: now) case "bill": BillView(account: account, now: now, chosen: billChoice) - default: ServiceView(account: account, serviceID: tab, now: now) + default: + // A tab whose service was just turned off in Settings falls back to Today. + if account.isWatching(tab) { ServiceView(account: account, serviceID: tab, now: now) } + else { TodayView(account: account, now: now) } } } .task(id: tab) { await open(tab, now: now) } @@ -90,7 +93,7 @@ struct PopoverView: View { private var tabs: some View { HStack(spacing: 7) { TabPill(icon: "◔", title: "Today", tint: Pop.edgeSoft, isOn: tab == "today") { tab = "today" } - ForEach(account.services) { service in + ForEach(account.watching) { service in TabPill(icon: service.look.glyph, title: service.name, tint: Pop.named(service.look.color), isOn: tab == service.id) { tab = service.id } diff --git a/Sources/App/SettingsView.swift b/Sources/App/SettingsView.swift index ed35fb1..b3b2aa7 100644 --- a/Sources/App/SettingsView.swift +++ b/Sources/App/SettingsView.swift @@ -14,6 +14,7 @@ struct SettingsView: View { ScrollView { VStack(alignment: .leading, spacing: 12) { accountSection + watchingSection readingSection warningsSection generalSection @@ -52,26 +53,34 @@ struct SettingsView: View { } } + /// *Worker ☑ · D1 ☑ · KV ☐* (law 21): the last switch on is dimmed and stays on. + private var watchingSection: some View { + SettingsSection(title: "Watching") { + ForEach(account.services) { service in + let on = account.isWatching(service.id) + let locked = on && !account.canUnwatch(service.id) + SettingsRow(title: "\(service.look.glyph) \(service.name)", + note: locked ? "Overmind watches at least one service" + : account.summary != nil && !account.isCounted(service.id) ? "not on this account's plans" + : service.limits.map(\.name).joined(separator: " · ")) { + PopSwitch(isOn: on) { + if on { account.unwatch(service.id) } else { Task { await account.watch(service.id, at: Demo.now ?? .now) } } + } + .opacity(locked ? 0.45 : 1) + .disabled(locked) + } + .opacity(on ? 1 : 0.6) + } + Text("A service you don't watch is never read: no tab, no card, no warning, no line in the Bill.") + .font(Pop.body(10.5)).foregroundStyle(Pop.muted).padding(.top, 6) + } + } + private var readingSection: some View { SettingsSection(title: "Reading") { SettingsRow(title: "Read every", note: "STALE after two missed reads") { - HStack(spacing: 0) { - ForEach(Array(Account.intervals.enumerated()), id: \.offset) { index, minutes in - let on = Int(account.interval / 60) == minutes - Button { account.setInterval(minutes: minutes) } label: { - Text(index == 0 ? "\(minutes) min" : "\(minutes)").font(Pop.label(11)) - .foregroundStyle(on ? .white : Pop.ink) - .padding(.horizontal, 10).padding(.vertical, 3) - .background(on ? Pop.grape : Pop.paper) - .overlay(alignment: .leading) { - if index > 0 { Rectangle().fill(Pop.ink).frame(width: 2) } - } - } - .buttonStyle(.plain) - } - } - .clipShape(Capsule()) - .overlay(Capsule().stroke(Pop.ink, lineWidth: 2)) + Segments(options: Account.intervals.enumerated().map { index, minutes in (index == 0 ? "\(minutes) min" : "\(minutes)", minutes) }, + chosen: Int(account.interval / 60)) { account.setInterval(minutes: $0) } } } } @@ -103,6 +112,11 @@ struct SettingsView: View { private var generalSection: some View { SettingsSection(title: "General") { + SettingsRow(title: "Menu bar shows", + note: account.menuBarShows == .iconOnly ? "☁ alone; ☁ ◐ at WATCH, ☁ ⚠︎ at ACT NOW" : "☁ D1 18% — the limit closest to running out") { + Segments(options: [("Closest limit", MenuBarStyle.closestLimit), ("Icon only", .iconOnly)], + chosen: account.menuBarShows) { account.setMenuBar($0) } + } SettingsRow(title: "Start at login", note: loginItem.problem) { PopSwitch(isOn: loginItem.isOn) { loginItem.set(!loginItem.isOn) } } @@ -156,6 +170,33 @@ struct SettingsRow: View { } } +/// A row of choices, one on: *Closest limit · Icon only*. +struct Segments: View { + let options: [(String, Value)] + let chosen: Value + let tell: (Value) -> Void + + var body: some View { + HStack(spacing: 0) { + ForEach(Array(options.enumerated()), id: \.offset) { index, option in + let on = option.1 == chosen + Button { tell(option.1) } label: { + Text(option.0).font(Pop.label(11)) + .foregroundStyle(on ? .white : Pop.ink) + .padding(.horizontal, 10).padding(.vertical, 3) + .background(on ? Pop.grape : Pop.paper) + .overlay(alignment: .leading) { + if index > 0 { Rectangle().fill(Pop.ink).frame(width: 2) } + } + } + .buttonStyle(.plain) + } + } + .clipShape(Capsule()) + .overlay(Capsule().stroke(Pop.ink, lineWidth: 2)) + } +} + struct SmallButton: View { let title: String let tell: () -> Void diff --git a/design-concept/overmind-pop.html b/design-concept/overmind-pop.html index dcc92e4..7aa15ad 100644 --- a/design-concept/overmind-pop.html +++ b/design-concept/overmind-pop.html @@ -252,6 +252,10 @@ .seg span{padding:3px 10px;font-size:11px;font-weight:800;border-left:2px solid var(--ink);cursor:pointer} .seg span:first-child{border-left:none} .seg span.on{background:var(--purple);color:#fff} +.svc-i{width:24px;height:24px;border:2px solid var(--ink);border-radius:8px;display:grid;place-items:center;font-size:12px;flex:none} +.set-row.unwatched > div:first-of-type{opacity:.5} +.toggle.last{opacity:.45;cursor:not-allowed} +.set-note{font-size:10.5px;color:var(--muted);font-weight:600;padding-top:6px} .btn-s{border:2px solid var(--ink);border-radius:10px;padding:4px 10px;font-weight:800;font-size:11px;background:var(--paper);box-shadow:2px 2px 0 var(--ink)} @media (max-width:760px){ @@ -521,7 +525,7 @@
Design

Settings

-

Opened from ⚙ → Settings… in the popover. Everything the popover offers, plus what only a window has room for: how often to read, starting at login, and updates. Changes save at once; there is no Save button.

+

Opened from ⚙ → Settings… in the popover. Everything the popover offers, plus what only a window has room for: which services to watch, how often to read, starting at login, and updates. Changes save at once; there is no Save button.

Overmind Settings
@@ -531,6 +535,18 @@

Account

acmeCloudflare account · token ••••7f3a in your Keychain
FREEDisconnect
Worker in focusthe D1 and Worker tabs; limits always count every Worker
leaderboard ▾
+
+

Watching

+
ƒ
WorkerRequests · CPU
+
⛁
D1rows read · rows written · storage
+
⚿
KVnew · reads · writes · deletes · lists · storage
+
⇶
Queuesnew · operations
+
◫
R2new · Class A · Class B · storage · not on this account's plans
+
✦
Workers AInew · neurons
+
⋰
Vectorizenew · queried dimensions · stored dimensions
+
◈
Durable Objectsnew · requests · rows read · rows written · storage
+
A service you don't watch is never read: no tab, no card, no warning, no line in the Bill.
+

Reading

Read everySTALE after two missed reads
5 min101530
@@ -543,6 +559,7 @@

Warnings

General

+
Menu bar shows☁ D1 18% — the limit closest to running out
Closest limitIcon only
Start at login
Check for updates automaticallyOvermind 0.1.0 · last checked today
Check now
@@ -560,6 +577,34 @@

General

+// Settings → Watching: law 21, at least one service stays watched +(function(){ + const box=document.getElementById('watching'); + const toggles=[...box.querySelectorAll('.toggle')]; + function render(){ + const on=toggles.filter(t=>!t.classList.contains('off')); + toggles.forEach(t=>{ + t.closest('.set-row').classList.toggle('unwatched',t.classList.contains('off')); + t.classList.toggle('last',on.length===1&&on[0]===t); + t.title=(on.length===1&&on[0]===t)?'Overmind watches at least one service':''; + }); + const names=on.map(t=>t.dataset.svc); + document.getElementById('watch-note').textContent=on.length===toggles.length + ? 'Every service is read; the Bill reads "This month · est."' + : 'A service you don\'t watch is never read: no tab, no card, no warning, no line in the Bill. Bill: "This month · est. · '+names.join(', ')+(names.length===1?' only':'')+'"'; + } + toggles.forEach(t=>t.onclick=()=>{ if(t.classList.contains('last')) return; t.classList.toggle('off'); render(); }); + render(); +})(); + +// Settings → Menu bar shows (law 22) +document.querySelectorAll('#mb-seg span').forEach(x=>x.onclick=()=>{ + document.querySelectorAll('#mb-seg span').forEach(y=>y.classList.toggle('on',y===x)); + document.getElementById('mb-note').textContent = x.textContent==='Icon only' + ? '☁ alone; ☁ ◐ at WATCH, ☁ ⚠︎ at ACT NOW' + : '☁ D1 18% — the limit closest to running out'; +}); + // Bill: the chosen plan card picks the detail list below it function pickPlan(which){ ['free','paid'].forEach(k=>{ diff --git a/design-concept/screenshots/popover-bill-paid.png b/design-concept/screenshots/popover-bill-paid.png index 23f1c36..88ffc39 100644 Binary files a/design-concept/screenshots/popover-bill-paid.png and b/design-concept/screenshots/popover-bill-paid.png differ diff --git a/design-concept/screenshots/popover-bill.png b/design-concept/screenshots/popover-bill.png index 934ea6e..fb869e5 100644 Binary files a/design-concept/screenshots/popover-bill.png and b/design-concept/screenshots/popover-bill.png differ diff --git a/design-concept/screenshots/popover-today.png b/design-concept/screenshots/popover-today.png index d58f622..0be9b95 100644 Binary files a/design-concept/screenshots/popover-today.png and b/design-concept/screenshots/popover-today.png differ diff --git a/design-concept/screenshots/settings.png b/design-concept/screenshots/settings.png index 8085c81..2129d59 100644 Binary files a/design-concept/screenshots/settings.png and b/design-concept/screenshots/settings.png differ diff --git a/docs/architecture/CANONICAL_MODEL.md b/docs/architecture/CANONICAL_MODEL.md index bd99399..af8b681 100644 --- a/docs/architecture/CANONICAL_MODEL.md +++ b/docs/architecture/CANONICAL_MODEL.md @@ -66,6 +66,7 @@ Account ◆ THE ROOT — one per app (v1) ├── plan: Plan ◇ "FREE" — a PlanDefinition, picked by the account's subscriptions │ ├── allowance(for: Limit.ID) 5M per day · 10 ms per invocation · 5 GB total │ ├── price(for: Limit.ID) beyond the allowance; nil on Free (it stops instead) +│ ├── addOns: [Plan] "R2" — plans matched by their own subscription, beside this one (law 23) │ ├── subscription: Money $0 · $5 a month │ └── period(for:at:) → Period Free: the UTC day · Paid: the billing month │ @@ -80,12 +81,19 @@ Account ◆ THE ROOT — one per app (v1) │ │ └── pace: Pace? DERIVED — nil in a period's first hour │ └── breakdowns: [Breakdown] ◇ read when the tab opens, for the focus │ +├── watching: [ServiceDefinition] "Worker ☑ · D1 ☑ · KV ☐" — DERIVED from the person's choices and +│ each file's watchedByDefault; never empty (law 21) +├── isCounted(service) DERIVED — false when no plan or add-on counts it: "not on this account's plans" +├── canUnwatch(service) DERIVED — false for the last one watched: its switch is dimmed +├── estimateCovers: Coverage DERIVED — everything · only(["Worker"]): "est. · Worker only" ├── focus: Focus ◇ .worker(name) · .allWorkers — breakdowns only ├── interval "Read every 5 min" — 5 · 10 · 15 · 30 minutes ├── deployments: [Deployment] ◇ id · when — pins on the charts -├── limits DERIVED — every service's limits, in catalog order +├── limits DERIVED — every watched service's limits, in catalog order ├── closest: Limit? DERIVED — the headline and the menu bar -├── menuBar: MenuBarState DERIVED — "D1 18%" and its level +├── menuBarShows: MenuBarStyle closestLimit · iconOnly — a choice (law 22) +├── menuBar: MenuBarState DERIVED — notReadYet · iconOnly(level) · closest(short, percent, level): +│ "☁", "☁ ◐", "☁ D1 18%". Nothing that runs out → iconOnly │ ├── bill: Bill ◇ "This month · est." — estimate · forecast · invoices │ ├── stopped: [LimitID: [Date]] "Free stopped you on 2 days" — days a daily allowance ran out @@ -104,7 +112,7 @@ Three kinds of fact, three homes. Mixing them is the usual bug. | Kind | Examples | Home | Changes when | |---|---|---|---| | **Definitions** (data) | D1 counts *rows read* from `d1AnalyticsAdaptiveGroups`; Free allows 5M per day | `Resources/Services/*.json` · `Resources/Plans/*.json` | Cloudflare changes a product or a price | -| **Choices** (settings) | the account, the focus, the read interval, the alert levels | `~/.overmind/settings.json`; the token in the Keychain | the person changes them | +| **Choices** (settings) | the account, the focus, the services watched, what the menu bar shows, the read interval, the alert levels | `~/.overmind/settings.json`; the token in the Keychain | the person changes them | | **Readings** (state) | 912k read at 14:20; the warnings already sent | memory; the sent-warnings log in settings | every refresh | **No Swift names a Cloudflare product or a number Cloudflare can change.** @@ -115,7 +123,7 @@ Three kinds of fact, three homes. Mixing them is the usual bug. | Context | Holds | Speaks to the outside through | |---|---|---| | **Measures** — the kernel | `Quantity` · `Unit` · `Money` · `Period` · `Percent` | nothing | -| **Services** | `ServiceDefinition` · `LimitDefinition` · `BreakdownDefinition` · the catalog | its bundle | +| **Services** | `ServiceDefinition` (with `watchedByDefault`) · `LimitDefinition` · `BreakdownDefinition` · the catalog | its bundle | | **Plans** | `PlanDefinition` · `Allowance` · `Price` · the catalog | its bundle | | **Limits** | `Limit` · `Usage` · `Pace` · `Level` | — (pure) | | **Analytics** | turning definitions into one GraphQL read, and the answer into `Usage` and `Breakdown` | `AnalyticsAPI` port | @@ -134,6 +142,8 @@ Three kinds of fact, three homes. Mixing them is the usual bug. | `open(service)` | `Account` | — (reads its breakdowns if older than one refresh) | | `toggle(level)` · `isOn` · `paceIsOn` | `Alerts` | — | | `setInterval(minutes:)` | `Account` | a choice other than 5, 10, 15 or 30 minutes | +| `setMenuBar(_ style)` | `Account` | — | +| `watch(serviceID)` · `unwatch(serviceID)` | `Account` | the service isn't in the catalog; `unwatch` of the last watched service | | `disconnect()` | `Account` | — (removes the token from the Keychain) | ## 5 · The laws, on the node that owns them @@ -160,5 +170,9 @@ Three kinds of fact, three homes. Mixing them is the usual bug. | 18 | **The plan is re-read** when the Bill tab opens and once a day, so an upgrade made on Cloudflare shows without a restart; the limits follow the new plan's allowances. | `Account` | | 19 | **A day Free stopped you** is a UTC day in the billing month when a *daily* allowance's use reached it. The verdict is *enough* when there is none, *stopped* otherwise. Each daily limit also answers its **busiest day** of the month. | `Bill` | | 20 | **A quote line** is one limit: its month's use, what the plan includes, and the price of the rest; the subscription is its own line and the lines add up to the quote. | `Plan` (`lines(of:)`) | +| 22 | **The menu bar says one state at a time**: `☁` before the first read and when nothing on the plan runs out; the closest limit (*D1 18%*) otherwise. On *icon only* it never names a limit, but still shows the worst level's mark (`◐` *WATCH*, `⚠︎` *ACT NOW*). A refused token is `☁ ⚠︎` whatever the choice. | `Account` (`menuBar`) | +| 23 | **An add-on plan** (*R2*) is a plan file matched by its own `rate_plan`; it adds its allowances and prices beside the Workers plan, never instead of it. A limit's allowance and price come from whichever of the two names it; its period uses that subscription's renewal. The estimate adds the add-on's subscription and lines; a quote prices another Workers plan **with the same add-ons**. The header and the plan cards name the Workers plan only. | `Plan` | +| 24 | **A daily allowance with a price is billed day by day**: each UTC day's use past the allowance, added up over the billing month. The forecast and a quote scale that overage by the share of the month gone, like every other limit's. | `Plan` (`cost(of:days:)`) | +| 21 | **Only a watched service is read.** One the person isn't watching has no limits, no tab, no query, no warning and no line in the Bill, which then names what its estimate covers (*est. · Worker only*). A service the person has never chosen for is watched if its file says `watchedByDefault`; at least one service is always watched. Watching again reads it at once; unwatching drops its readings but never clears the sent-warnings log (law 9). Law 1 holds within what is watched. | `Account` | *Start at login* and *updates* are the system's and Sparkle's, not the account's: the App holds them (`LoginItem`, `Updater`) and no law of the tree depends on them. diff --git a/docs/architecture/ENGINE_DESIGN.md b/docs/architecture/ENGINE_DESIGN.md index a10b2fd..b25b6c8 100644 --- a/docs/architecture/ENGINE_DESIGN.md +++ b/docs/architecture/ENGINE_DESIGN.md @@ -38,7 +38,19 @@ Every `Read` names: - `scale`, when the answer's unit isn't the limit's: CPU comes in microseconds, so `0.001` turns it into milliseconds; - `failures`, for a `quantile`: the dimension value that marks an invocation - that went past the allowance (`status = exceededResources`). + that went past the allowance (`status = exceededResources`); +- `where`, for any case: only the groups whose `dimension` is one of `in`. One + dataset can then hold several limits: KV's reads and writes are both + `kvOperationsAdaptiveGroups`, told apart by `actionType`; R2's Class A is a + set of action types. `ReadPlan` adds it as `_in: [...]` to the + limit's read, its daily read (law 19) and its `series` charts. It is part of + what the limit **is**, so unlike `focus` it always applies (law 1 holds). + +```jsonc +{ "id": "kv.writes", "name": "KV writes", "short": "KV writes", "unit": "requests", + "read": { "sum": { "dataset": "kvOperationsAdaptiveGroups", "field": "sum.requests", "time": "date", + "where": { "dimension": "actionType", "in": ["write"] } } } } +``` `ReadPlan` writes each limit as an aliased field of one `viewer.accounts` query filtered by `accountTag`, so a refresh is one request whatever the @@ -59,11 +71,21 @@ number of limits. | `beyond(Money, per: Quantity)` | each unit past the allowance costs this (*$0.001 per 1M rows*) | | `perMonthOver(Money, per: Quantity)` | storage: billed on the month's average past the allowance (*$0.75 per GB-month*) | +**Add-on plans** (`"addOn": true`, model law 23): *R2* is billed apart from Workers, so its +allowances and prices live in `r2-paid.json`, matched by `r2_paid`. `PlanCatalog` picks the +Workers plan among the files without `addOn`, then every add-on whose `matches` the account has. +An add-on is never a plan card and never quoted alone. + A plan also carries `subscription` (`$5` a month), `upgradeURL` (its page on Cloudflare's dashboard, with `{account}` for the account ID; Overmind only links to it) and `matches`: the `rate_plan` ids from `/accounts/{id}/subscriptions` that mean this plan. No match means Free. +**A daily allowance with a price** (Workers AI on Workers Paid: 10k neurons a day, then +$0.011 per 1k) is billed **day by day**: each UTC day's use past the allowance, added up over the +billing month (model law 24). `Bill` already reads every daily limit per day (law 19) and hands +those days to `Plan`. On Free the same allowance has no price, so it stops instead. + **A plan without an allowance for a limit doesn't show that limit.** Free caps CPU per invocation (`workers.cpu`); Workers Paid bills CPU time by the month (`workers.cpuTime`, `sum.cpuTimeUs`). Each plan file names only its own. @@ -88,6 +110,7 @@ by `date`, in one query; `Bill` counts the days whose use reached the allowance // Services/Resources/Services/d1.json { "id": "d1", "name": "D1", "look": { "glyph": "⛁", "color": "butter" }, + "watchedByDefault": true, // Worker and D1: true; each later service: false (model law 21) "limits": [ { "id": "d1.rowsRead", "name": "D1 rows read", "short": "D1", "unit": "rows", "read": { "sum": { "dataset": "d1AnalyticsAdaptiveGroups", "field": "sum.rowsRead", @@ -128,6 +151,20 @@ by `date`, in one query; `Bill` counts the days whose use reached the allowance | Workers by hour | `datetimeHour` (also `datetimeFifteenMinutes`, `datetimeSixHours`) | verified by introspection | | CPU time unit | `cpuTimeP50` · `cpuTimeP99` are **microseconds** | verified by a read | | Cron runs | GraphQL `workersInvocationsScheduled`: `cron` · `status` · `cpuTimeUs` · `scheduledDatetime` | verified by introspection | +| KV operations | GraphQL `kvOperationsAdaptiveGroups` · `sum.requests` by `actionType`, filtered by `date` | dataset, `actionType`, `namespaceId` and `date`/`datetime` verified by introspection 2026-10-11; `actionType: "read"` is documented, **`write` · `delete` · `list` are unverified**: the account read had no KV traffic | +| KV storage | GraphQL `kvStorageAdaptiveGroups` · `max.byteCount` per `namespaceId` (also `max.keyCount`), filtered by `date` | verified by introspection 2026-10-11 | +| KV limits | Free per day: 100k reads, 1k writes, 1k deletes, 1k lists, 1 GB. Paid per month: 10M reads, 1M each of writes, deletes and lists, 1 GB; overage $0.50/M reads, $5.00/M writes, deletes and lists, $0.50/GB-month. Free resets at 00:00 UTC and fails the operation past it | verified on [KV pricing](https://developers.cloudflare.com/kv/platform/pricing/), 2026-10-11 | +| Queues operations | GraphQL `queueMessageOperationsAdaptiveGroups` · `sum.billableOperations`, `datetime`, focus `queueId` (the docs' `queueID` is wrong), by `actionType` (`WriteMessage` · `ReadMessage` · `DeleteMessage`) | verified by introspection 2026-10-11 | +| Queues limits | Free 10k operations a day; Paid 1M a month, then $0.40/M; an operation is 64 KB written, read or deleted | verified on [Queues pricing](https://developers.cloudflare.com/queues/platform/pricing/), 2026-10-11 | +| R2 operations | GraphQL `r2OperationsAdaptiveGroups` · `sum.requests` by `actionType`, `datetime`, focus `bucketName`. Class A: `ListBuckets` `PutBucket` `ListObjects` `PutObject` `CopyObject` `CreateMultipartUpload` `UploadPart` `UploadPartCopy` `CompleteMultipartUpload` `ListMultipartUploads` `ListParts` `LifecycleStorageTierTransition` `PutBucketEncryption` `PutBucketCors` `PutBucketLifecycleConfiguration`. Class B: `HeadBucket` `HeadObject` `GetObject` `UsageSummary` `GetBucketEncryption` `GetBucketLocation` `GetBucketCors` `GetBucketLifecycleConfiguration`. Deletes and aborts are free | verified by introspection and a live read (`GetObject` · `HeadObject` · `ListBuckets` seen), 2026-10-11 | +| R2 storage | GraphQL `r2StorageAdaptiveGroups` · `max.payloadSize` per `bucketName`, `datetime`; also a `storageClass` dimension (only Standard is free) | verified by introspection 2026-10-11 | +| R2 limits (Standard) | per month: 10 GB-month, 1M Class A, 10M Class B; then $0.015/GB-month, $4.50/M Class A, $0.36/M Class B. A separate subscription (`r2_paid`, verified on a real account) | verified on R2 pricing, 2026-10-11 | +| Workers AI | GraphQL `aiInferenceAdaptiveGroups` · `sum.totalNeurons`, `datetime`; dimensions `modelId`, `errorCode` | verified by introspection 2026-10-11 | +| Workers AI limits | 10k neurons a day on both plans, reset 00:00 UTC; Paid $0.011 per 1k beyond, day by day (law 24); Free stops | verified on [Workers AI pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/), 2026-10-11 | +| Vectorize | GraphQL `vectorizeV2QueriesAdaptiveGroups` · `sum.queriedVectorDimensions`; `vectorizeV2StorageAdaptiveGroups` · `max.storedVectorDimensions` per `indexName`; `datetime` (the v1 datasets `vectorizeQueries…` · `vectorizeStorage…` also exist, by `vectorizeIndexId`) | verified by introspection 2026-10-11 | +| Vectorize limits | Free: 30M queried dimensions a month, 5M stored; Paid: 50M queried a month then $0.01/M, 10M stored then $0.05 per 100M a month | verified on [Vectorize pricing](https://developers.cloudflare.com/vectorize/platform/pricing/), 2026-10-11 | +| Durable Objects | GraphQL `durableObjectsInvocationsAdaptiveGroups` · `sum.requests`; `durableObjectsPeriodicGroups` · `sum.rowsRead` · `sum.rowsWritten` (also `sum.duration`, `sum.activeTime`); `durableObjectsSqlStorageGroups` · `max.storedBytes` per `namespaceId`; all by `datetime` | verified by introspection 2026-10-11; **the unit of `sum.duration` is not**, so GB-s duration waits for a live read on an account using Durable Objects | +| Durable Objects limits | Free per day: 100k requests, SQLite 5M rows read, 100k written, 5 GB stored; Paid per month: 1M requests then $0.15/M, 25B rows read then $0.001/M, 50M written then $1.00/M, 5 GB then $0.20/GB-month | verified on [Durable Objects pricing](https://developers.cloudflare.com/durable-objects/platform/pricing/), 2026-10-11 | | Rate Limiting bindings | none exists | out of scope ([journeys §5](USER_JOURNEYS.md#5--out-of-scope-for-now)) | | GraphQL budget | 300 queries / 5 min / user; 31 days retention on adaptive datasets | verified | | Plan | `GET /accounts/{id}/subscriptions`: one entry per rate plan (an account can have *R2 Paid* without *Workers Paid*) | verified | diff --git a/docs/architecture/TARGET_ARCHITECTURE.md b/docs/architecture/TARGET_ARCHITECTURE.md index 205c2f9..41db164 100644 --- a/docs/architecture/TARGET_ARCHITECTURE.md +++ b/docs/architecture/TARGET_ARCHITECTURE.md @@ -37,7 +37,7 @@ description: How Overmind runs. It covers the pieces, each with one job, and the | Piece | Job | Context | Inputs → outputs | |---|---|---|---| | `ServiceCatalog` | load the built-in service files | Services | bundle → `[ServiceDefinition]` | -| `PlanCatalog` | load the plan files; pick the account's plan from its subscriptions | Plans | bundle, `[Subscription]` → `PlanDefinition` | +| `PlanCatalog` | load the plan files; pick the account's Workers plan and its add-ons from its subscriptions | Plans | bundle, `[Subscription]` → `Plan` (with `addOns`) | | `Limit` | turn usage and an allowance into percent, level and pace | Limits | `Usage`, `Allowance`, now → derived values | | `ReadPlan` | every limit's read for one period, as **one** query | Analytics | `[LimitDefinition]`, `Period`s, accountID → `AnalyticsQuery` | | `AnalyticsAPI` (port) | send a query, return the rows | Analytics | `AnalyticsQuery` → `AnalyticsAnswer` | @@ -50,7 +50,7 @@ description: How Overmind runs. It covers the pieces, each with one job, and the | `Account` | the root; owns the refresh and every law that spans services | Monitor | all of the above | | `Refresher` | tell `Account.refresh` every 5 minutes, on wake and on *Refresh* | Monitor | a clock → commands | | `TokenVault` (port) | keep the token | Monitor | Keychain | -| `SettingsStore` (port) | keep the choices and the sent-warnings log | Monitor | `~/.overmind/settings.json` | +| `SettingsStore` (port) | keep the choices (with `watch: [ServiceID: Bool]`, only the services the person chose for) and the sent-warnings log | Monitor | `~/.overmind/settings.json` | | `SettingsView` | the Settings window: renders `Account` and tells it, like the popover | App | — | | `LoginItem` | *Start at login*, over `SMAppService.mainApp` | App | the system's login items | | `Updater` | Sparkle: checks the appcast, installs signed updates | App | `https://tddworks.github.io/Overmind/appcast.xml` | @@ -73,6 +73,7 @@ ConnectSheet ─ account.connect(token) ```text Refresher ─ account.refresh(at: now) + limits of the watched services only law 21 plan.period(for: each limit, at: now) law 5 ReadPlan(limits, periods) → one AnalyticsQuery one POST per refresh: the GraphQL API allows 300 per 5 min AnalyticsAPI.read(query) → answer @@ -86,6 +87,19 @@ Refresher ─ account.refresh(at: now) A failed read changes `freshness` and nothing else: the last good usage stays on screen with *STALE*, never zeros. +### 3.2a · Watching a service (journey 21) + +```text +SettingsView ─ account.watch(id) / unwatch(id) + unknown id, or the last watched one → no (law 21) + settings.watch[id] = true / false · SettingsStore.save + limits = Account.limits(watched services, on: plan, keeping: limits) + watch → refresh(at: now) its numbers appear at once +``` + +A choice for a service the files no longer have is ignored; a service the +choices don't name takes its file's `watchedByDefault`. + ### 3.3 · Opening a service tab (journeys 12–14) ```text @@ -101,6 +115,7 @@ parameter, so law 1 can't be broken by a caller. ```text account.bill + only the watched services' limits; the estimate names them when one isn't watched (law 21) invoice for this period? → shown as is (law 13) else plan.cost(of: limits' month-to-date) — Paid only; Free is $0 and can't overspend forecast = plan.cost(of: limits' month pace) diff --git a/docs/architecture/USER_JOURNEYS.md b/docs/architecture/USER_JOURNEYS.md index 43a78d3..8693ad5 100644 --- a/docs/architecture/USER_JOURNEYS.md +++ b/docs/architecture/USER_JOURNEYS.md @@ -25,6 +25,7 @@ description: Who uses Overmind and what they ask. It covers the people and the m | **Kai**, after the warning | which query or route spent it, and whether yesterday's deploy fixed it | *Find the cause* | | **Lee** — a contributor deciding whether to pay | what this month costs, and what Workers Paid would cost at today's pace | *Read the bill* | | **Lee**, first run | to connect an account without giving the app any power to change it | *Connect* | +| **Kai**, who only cares about the Worker | the products they use, and nothing about the ones they don't | *Choose what to watch* | Each journey is a promise. A screen that serves none of them is a screen to question, and a person here that no screen serves is a gap. @@ -40,6 +41,8 @@ do, the command that lands on the domain, and the node that answers. | 2 | The token answers for two accounts | *Account ▾ tddworks · personal* | picks *tddworks* | `account.choose(accountID)` | `Connection` | | 3 | The token can't read billing | *Connected · Bill needs Billing Read* | carries on | — | `Connection.missing` — a reading the token can't do is a reason on that tab, never a failed connect | | 4 | Kai glances at the menu bar | *D1 18%* | nothing | `account.menuBar` | the closest `Limit` | +| 4a | Kai wants a quiet menu bar | *Settings → General → Menu bar shows: Closest limit · Icon only*; on *Icon only* the bar shows `☁`, with `◐` or `⚠︎` beside it while a limit is at *WATCH* or *ACT NOW* | picks *Icon only* | `account.setMenuBar(.iconOnly)` | `MenuBarState` (law 22) | +| 4b | Before the first read, or when nothing on the plan runs out | `☁` alone, never an empty or stale number | nothing | `account.menuBar` | `MenuBarState.notReadYet` · `.iconOnly` | | 5 | Kai opens the popover | *FREE · resets in 9h 40m* · *claudebar-leaderboard · LIVE · read 1 min ago* · *CLOSEST TO THE LIMIT · D1 rows read · 18% of 5M · on pace for 31% by midnight* | reads | `account.closest` · `limit.pace` | `Limit` · `Pace` · `Plan` | | 6 | Kai reads *Every limit today* | one card per limit: *D1 reads 912k 18% · OK*, *CPU 7.8 ms 78% · WATCH* … *resets 00:00 UTC* · *82% left* | taps a card | `account.limits` | `Limit` · `Level` | | 7 | It's 00:20 UTC | the headline reads *too early to tell* instead of a pace | nothing | `limit.pace` | `Pace` is nil in a period's first hour | @@ -57,9 +60,15 @@ do, the command that lands on the domain, and the node that answers. | 16 | The Mac slept for a night | the strip reads *STALE · read 9h ago* until the next read lands | nothing | `account.refresh()` | `Connection.freshness` | | 17 | The token is revoked | *Cloudflare refused the token* · *Connect again* | pastes a new one | `account.connect(token)` | `Connection` | | 17 | Kai clicks *Dashboard ↗* | the Cloudflare dashboard opens on that account | — | — | `Account.dashboardURL` | -| 18 | Kai opens *⚙ → Settings…* | the Settings window: *Account* · *Reading* · *Warnings* · *General* | — | — | the same `Account` the popover reads | +| 18 | Kai opens *⚙ → Settings…* | the Settings window: *Account* · *Watching* · *Reading* · *Warnings* · *General* | — | — | the same `Account` the popover reads | | 19 | Kai wants fewer reads | *Read every 5 min · 10 · 15 · 30*; *STALE* waits for two missed reads | picks *15* | `account.setInterval(minutes:)` | `Account.interval` (law 17) | | 20 | Lee wants it there after a restart | *Start at login* | turns it on | — | the system's login items (`LoginItem`, App) | +| 21 | Kai opens *Settings → Watching* | one row per service: *ƒ Worker · Requests · CPU time* ☑ · *⛁ D1 · rows read · rows written · storage* ☑ · *KV* ☐ (once KV ships) | turns *D1* off | `account.unwatch("d1")` | `Account.watching` (law 21) | +| 21a | After turning *D1* off | no *D1* tab; no D1 card in *Every limit today*; the menu bar picks among the Worker's limits; no D1 warning; the Bill reads *This month · est. · Worker only* | nothing | — | `Account.limits` · `Bill` follow `watching` | +| 21b | Kai tries to turn the last service off | the last switch is dimmed: *Overmind watches at least one service* | — | `account.unwatch(…)` says no | `Account` (law 21) | +| 21d | Lee watches *R2* on an account with an R2 subscription | R2 cards (*Class A*, *Class B*, *R2 storage*) against R2's own free tier; the Bill adds R2's lines to the Workers plan's; the header still reads *FREE* or *WORKERS PAID* | — | `account.watch("r2")` | `Plan.addOns` (law 23) | +| 21e | Lee watches *R2* without an R2 subscription | the *R2* row reads *not on this account's plans*; no R2 cards | — | — | `account.isCounted("r2")`: no allowance, so no limit (ENGINE §3) | +| 21c | A new version ships KV | *KV* appears in *Watching*, off; Worker and D1 keep Kai's choices | turns it on if they use KV | `account.watch("kv")` | the service file's `watchedByDefault` | | 22 | A new version is out | Sparkle's *A new version of Overmind is available* · *Check now* in Settings | installs | — | `Updater` (App, Sparkle) | ## 3 · What the person never has to know @@ -82,18 +91,21 @@ do, the command that lands on the domain, and the node that answers. | **Level** — *OK · WATCH · ACT NOW* | under 50% · 50 to 90% · 90% and over | | | **Warning** | a notification Overmind sent | alert (the setting is *Warn me at*) | | **Service** — *D1*, *Worker* | a Cloudflare product with its own tab | product | +| **Watching** — *Worker ☑ · D1 ☑ · KV ☐* | the services Overmind reads; one it isn't watching is never read | enabled, tracked | | **Breakdown** | a chart or list that says where a limit's use came from | report | | **Deployment** — *d605dc93* | a Worker version going live, pinned on charts | release | | **Focus** — *leaderboard · All workers* | which Worker the breakdowns describe | scope, filter | | **Bill** · **Forecast** · **Invoice** | money: this month's, its projection, past months | | | **Stale** | the last read is older than two refreshes | offline | -| **Settings** | the window for the choices: account, reading, warnings, general | preferences | +| **Add-on** — *R2* | a Cloudflare subscription beside the Workers plan, with its own allowances and prices | plan (the plan is *Free* or *Workers Paid*) | +| **Icon only** | the menu bar without a number: `☁`, and a mark at *WATCH* or *ACT NOW* | compact, minimal | +| **Settings** | the window for the choices: account, watching, reading, warnings, general | preferences | ## 5 · Out of scope, for now - **Changing anything on Cloudflare.** The token is read-only, and no port has a write call. - **Several accounts at once.** One connected account; switching is *Connect again*. -- **Services other than Workers and D1.** KV, R2, Queues and Durable Objects are one JSON file each once someone needs them ([ENGINE_DESIGN](ENGINE_DESIGN.md)); none ships in v1. +- **Services other than Workers and D1, all at once.** They ship one at a time, each off until the person watches it (moment 21c): KV, then Queues and R2 (an add-on plan, law 23), then Workers AI (billed day by day, law 24), Vectorize and Durable Objects, each once its datasets were confirmed by introspection (ENGINE §6): a wrong dataset name would fail the whole refresh. Durable Objects' GB-s duration waits for a live read. Decided 2026-10-11. - **The `cf` CLI's login.** v1 connects with an API token. `Analytics` and `BillingAPI` are ports, so a `cf`-backed credential or adapter can come later without touching the domain. - **Changing the plan from Overmind.** Cloudflare's API can (`POST`/`PUT`/`DELETE /accounts/{id}/subscriptions`), but it needs *Billing: Edit*, which can cancel any subscription, and the payment belongs in Cloudflare's own flow. Decided 2026-10-09: a link to Cloudflare's plans page instead; revisit as an opt-in capability once a Paid account can verify it. - **Rate limits.** Cloudflare keeps no analytics for Rate Limiting bindings, and a request the Worker answers with 429 is a *success* to Workers analytics. Once a Worker writes an Analytics Engine data point per block, a *Blocked by rate limit* breakdown is one entry in `worker.json`. Decided 2026-10-09: not in v1. diff --git a/docs/features/bill/README.md b/docs/features/bill/README.md index 658dc23..3f11d7a 100644 --- a/docs/features/bill/README.md +++ b/docs/features/bill/README.md @@ -4,7 +4,7 @@ description: What the Bill tab says — this month's estimate, the forecast, the # Bill -- **This month · est.** — what the month has cost so far by the plan's prices. On Free it is always $0: Free stops at its limits instead of charging. +- **This month · est.** — what the month has cost so far by the plan's prices. On Free it is always $0: Free stops at its limits instead of charging. When a service isn't watched (*Settings → Watching*), the estimate leaves it out and says so: *est. · Worker only*. R2 is an add-on: its lines join the Workers plan's, and a quote for the other Workers plan keeps R2. Workers AI's 10k neurons are a day's allowance even on Workers Paid, so its line charges each day's neurons past 10k, never the month's total. - **Forecast** — the month at its pace. - **If you upgraded** — first a verdict: *Free is enough*, or *Free stopped you on N days* (days a daily limit ran out). Then both plans for this month, and *This month on Workers Paid*: the subscription and one line per limit, so you see where each dollar would come from. - **Upgrade on Cloudflare ↗** — opens Cloudflare's Workers plans page; Cloudflare takes the payment. Overmind never changes your plan; after you upgrade, the next look at the Bill tab shows Workers Paid. diff --git a/docs/features/menu-bar/README.md b/docs/features/menu-bar/README.md index b83bb76..53e59e9 100644 --- a/docs/features/menu-bar/README.md +++ b/docs/features/menu-bar/README.md @@ -12,5 +12,8 @@ description: What the menu bar shows — the limit closest to running out, as " | `☁ ⚠︎ D1 91%` | something is at 90% or more, or Cloudflare stopped invocations | | `☁ ⚠︎` | Cloudflare refused the token: open the popover to connect again | +**Icon only** (*Settings → General → Menu bar shows*): the bar never names a limit. It shows `☁`, +`☁ ◐` while something is at *WATCH*, and `☁ ⚠︎` at *ACT NOW* or when the token is refused. + The percent is the closest limit's; the mark is the worst level of any limit. CPU per invocation never names the menu bar: it never runs out ([design](design.md)). diff --git a/docs/features/service-tabs/README.md b/docs/features/service-tabs/README.md index 5437154..1395759 100644 --- a/docs/features/service-tabs/README.md +++ b/docs/features/service-tabs/README.md @@ -1,5 +1,5 @@ --- -description: The Worker and D1 tabs — the charts and lists each shows, the Worker focus, and the deployment pins. Read when a chart looks empty or different from the dashboard. +description: The Worker, D1, KV, Queues, R2, Workers AI, Vectorize and Durable Objects tabs — the charts and lists each shows, the Worker focus, and the deployment pins. Read when a chart looks empty or different from the dashboard. --- # Service tabs @@ -8,6 +8,12 @@ description: The Worker and D1 tabs — the charts and lists each shows, the Wor |---|---| | **Worker** | requests per hour today · invocations by outcome · cron runs · the Worker limits | | **D1** | rows read per day (7 days) and per hour · top queries by rows read · the D1 limits | +| **KV** | reads per day (7 days) · operations by type · the KV limits. Only when KV is watched (*Settings → Watching*); Cloudflare keeps KV's analytics by day, so there is no per-hour chart | +| **Queues** | operations per hour today · operations by type (write, read, delete) · the Queues limit. Only when watched; the focus doesn't narrow it | +| **R2** | Class A and Class B per hour today · operations by type · the R2 limits, against R2's own free tier. Only when watched, and only on an account with an R2 subscription | +| **Workers AI** | neurons per hour today · top models by neurons · the neurons limit (10k a day on both plans) | +| **Vectorize** | queried dimensions per day (7 days) · top indexes · queried and stored dimensions | +| **Durable Objects** | requests per hour today · requests by outcome · requests, SQLite rows read and written, storage. The Worker focus narrows the request charts. GB-s duration isn't counted yet | - **The focus** (*leaderboard ▾ · All Workers*) narrows the charts to one Worker. The limits never change: Cloudflare counts them across the account. - **Pins** (*d605dc93*) mark when a version of the focused Worker went live. diff --git a/docs/features/settings/README.md b/docs/features/settings/README.md index 373697d..6fbc1ce 100644 --- a/docs/features/settings/README.md +++ b/docs/features/settings/README.md @@ -1,5 +1,5 @@ --- -description: The Settings window — account, Worker focus, how often to read, warnings, start at login and updates. Read to change how Overmind behaves. +description: The Settings window — account, Worker focus, which services to watch, how often to read, warnings, start at login and updates. Read to change how Overmind behaves. --- # Settings @@ -9,6 +9,7 @@ Open it from the popover: **⚙ → Settings…**. Changes save at once. | Section | Holds | |---|---| | **Account** | the connected account and its plan · *Disconnect* · the Worker in focus | +| **Watching** | one switch per service: *Worker* · *D1* · *KV* · *Queues* · *R2* · *Workers AI* · *Vectorize* · *Durable Objects*. A service the account's plans don't count reads *not on this account's plans*. A service you don't watch is never read: no tab, no card, no menu bar number, no warning, no line in the Bill. The last one stays on. New services arrive off | | **Reading** | *Read every 5 · 10 · 15 · 30 minutes*. *STALE* shows after two missed reads | | **Warnings** | *Warn me at 50% 75% 90%* · *Warn on pace* · *Notifications* | | **General** | *Start at login* · *Check for updates automatically* · *Check now* | diff --git a/docs/status.md b/docs/status.md index 3afae47..72a4302 100644 --- a/docs/status.md +++ b/docs/status.md @@ -4,7 +4,7 @@ description: Where Overmind stands — what is built per module with test counts # Status -> As of **2026-10-09** · **137 tests** (and 4 live checks), all passing. Every slice is built; the app +> As of **2026-10-11** · **182 tests** (and 4 live checks), all passing. Every slice is built; the app > runs on a real account and on demo data. This file is the one home for > "what's built and what's next". Update it when a slice lands. @@ -15,14 +15,14 @@ description: Where Overmind stands — what is built per module with test counts | Design: the five docs, the mockup | approved | — | | `Overmind` app | the menu bar, Today, the Workers and D1 tabs, Bill, Connect, the Settings window, `LoginItem`, `Updater` (Sparkle), the icon; demo mode and screenshots | — | | Release | `tests.yml`, `release.yml` (sign, notarize, DMG, appcast), ClaudeBar's scripts; a universal Release archive built and Developer-ID-signed locally | — | -| `Measures` | `Quantity` (reads *5M rows*, prints *3.75M*, *75.7k ms*), `Money` (Decimal), `Period` (UTC day, billing month), `Percent`, `LimitID` | 18 | -| `Services` | `ServiceDefinition`, `LimitDefinition`, `Read`, `BreakdownDefinition`, `ServiceCatalog`; `workers.json`, `d1.json` | 10 | -| `Plans` | `PlanDefinition` (upgrade link), `Plan`, `Allowance`, `Price`, `cost(of:)`, `lines(of:)`, `PlanCatalog`; `free.json`, `workers-paid.json` | 20 | +| `Measures` | `Quantity` (reads *5M rows*, prints *3.75M*, *75.7k ms*), `Money` (Decimal), `Period` (UTC day, billing month), `Percent`, `LimitID`; units rows, requests, ms, bytes, count, operations, neurons, dimensions | 20 | +| `Services` | `ServiceDefinition` (`watchedByDefault`), `LimitDefinition`, `Read` (`where`), `BreakdownDefinition`, `ServiceCatalog`; `workers.json`, `d1.json`, `kv.json`, `queues.json`, `r2.json`, `ai.json`, `vectorize.json`, `durable-objects.json` | 20 | +| `Plans` | `PlanDefinition` (upgrade link, `addOn`), `Plan` (`addOns`), `Allowance`, `Price`, `cost(of:)`, `lines(of:)`, `PlanCatalog`; `free.json`, `workers-paid.json` (every service but R2), `r2-paid.json`; law 24 (a priced daily allowance billed by the day) | 32 | | `Limits` | `Limit` (laws 2–8), `Usage`, `Level`, `Pace` | 16 | -| `Analytics` | `ReadPlan` (one query; storage summed per database; per-day use), answers, breakdowns, `Focus`; `GraphQLAnalytics` | 15 + 2 live | -| `Billing` | `Bill` (estimate, forecast, quote, lines, days stopped, verdict), `BillingAPI`; `CloudflareREST` | 16 + 1 live | +| `Analytics` | `ReadPlan` (one query; storage summed per database; per-day use; `where` filters), answers, breakdowns, `Focus`; `GraphQLAnalytics` | 18 + 2 live | +| `Billing` | `Bill` (estimate, forecast, quote, lines, days stopped, verdict, day-by-day overage), `BillingAPI`; `CloudflareREST` | 18 + 1 live | | `Alerts` | laws 9–10, CPU stopped invocations; `UserNotifier` | 11 | -| `Monitor` | `Account` (connect, choose, refresh, freshness, tabs, bill, alerts, read interval, plan re-read), `Refresher` | 27 + 1 live | +| `Monitor` | `Account` (connect, choose, refresh, freshness, tabs, bill, alerts, read interval, plan re-read, watching, menu bar, add-ons), `Refresher` | 42 + 1 live | | `Storage` | `KeychainTokenVault`, `JSONSettingsFile` (older files still read) | 4 | | `Diagnostics` | `AppLog` | — | @@ -37,6 +37,14 @@ description: Where Overmind stands — what is built per module with test counts | 5 ✅ | Warnings | `Alerts` | laws 9–10, with the sent log kept across relaunches | | 6 ✅ | Service tabs | `Analytics` breakdowns, `Billing` deployments | D1 and Worker tabs, with deployment pins and the focus picker | | 7 ✅ | The bill | `Billing` | estimate, forecast, quote, invoices | +| 8 ✅ | Watching | `Services` (`watchedByDefault`), `Monitor` (`watching`, `watch`, `unwatch`, law 21), App (Settings → *Watching*, Bill caption) | an unwatched service has no tab, card, query, warning or bill line; the choice survives a relaunch; the last one can't be turned off | +| 9 ✅ | KV | `Services` (`where` on a read, ENGINE §2), `Analytics` (`ReadPlan` writes it), `kv.json` (`watchedByDefault: false`), both plan files | KV reads, writes, deletes, lists and storage on Today, a KV tab, warnings and Bill lines once watched; the unverified `actionType` values in ENGINE §6 checked by a live read | +| 10 ✅ | The quiet menu bar | `Monitor` (`MenuBarState` as cases, `menuBarShows`, law 22), App (Settings row, label) | *Icon only* shows `☁` and the worst mark; before the first read the bar is `☁`, never an empty number. The GitHub issue's ask | +| 11 ✅ | Queues | `queues.json`, both plan files, the `operations` unit | Queues operations against Free's 10k a day and Paid's 1M a month, off until watched | +| 12 ✅ | R2, an add-on plan | `Plans` (`addOn`, `Plan.addOns`, law 23), `r2-paid.json`, `r2.json` | Class A, Class B and storage against R2's own free tier, on either Workers plan, priced in the Bill; off until watched | +| 13 ✅ | Workers AI | `Plans` (law 24: a priced daily allowance billed day by day), `Billing`, `ai.json`, both plan files, the `neurons` unit | neurons against 10k a day; on Paid the Bill charges each day's overage | +| 14 ✅ | Vectorize | `vectorize.json`, both plan files, the `dimensions` unit | queried and stored vector dimensions against each plan, off until watched | +| 15 ✅ | Durable Objects | `durable-objects.json`, both plan files | requests, SQLite rows read and written, and storage; GB-s duration after a live read | ## Decisions @@ -48,12 +56,16 @@ description: Where Overmind stands — what is built per module with test counts | 2026-10-09 | The API implementation only: an API token, HTTP behind the `Analytics` and `BillingAPI` ports. The `cf` CLI can't serve every read (ENGINE §6) | | 2026-10-09 | Design approved; slices 1–7 built the same day | | 2026-10-09 | A per-invocation limit acts only when Cloudflare stopped invocations, and is never the closest: a real account ran p99 17 ms past Free's 10 ms with none stopped | +| 2026-10-11 | R2 is an add-on plan beside the Workers plan, not a third plan (law 23) | +| 2026-10-11 | A dataset nobody verified never ships. Introspection (`scripts/introspect-datasets.sh`) confirmed Workers AI, Vectorize and Durable Objects, and found Queues' `queueId` and KV storage's `namespaceId` | +| 2026-10-11 | New services ship one at a time, each off until the person watches it; an unwatched service is not read at all, and the Bill says what its estimate covers (law 21) | ## Open questions - The first release needs the GitHub repo, its secrets and Pages turned on ([release setup](release/RELEASE_SETUP.md)); notarization has not run yet. - The name *Overmind* is a working name. +- KV's `actionType` values `write`, `delete`, `list` and a per-namespace storage dimension are unverified until a live read (ENGINE §6); `read` is documented. - Workers Paid's `rate_plan` id (`workers_paid`) is unverified: no Paid account has been read. - Invoices have only been read as *forbidden* (the `cf` login has no billing scope); a token with Billing Read will show them. - Checked end to end on a real Free account on 2026-10-09: plan, 5 limits, both tabs with 10 deployment pins, and the Workers Paid quote ($5). diff --git a/scripts/introspect-datasets.sh b/scripts/introspect-datasets.sh new file mode 100755 index 0000000..47ebfbd --- /dev/null +++ b/scripts/introspect-datasets.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Lists Cloudflare GraphQL account datasets whose name matches a pattern, with the fields of +# their sum / max / quantiles / dimensions — names only, never a token, an id or a number. +# The token comes from the Keychain item the app keeps (CANONICAL law 15). +# +# scripts/introspect-datasets.sh 'ai|vectorize|durableObjects' +set -euo pipefail +pattern="${1:?usage: introspect-datasets.sh }" +token="$(security find-generic-password -s com.tddworks.overmind -a cloudflare-api-token -w)" + +ask() { + curl -sS https://api.cloudflare.com/client/v4/graphql \ + -H "Authorization: Bearer ${token}" -H 'Content-Type: application/json' \ + --data "$(python3 -c 'import json,sys; print(json.dumps({"query": sys.argv[1]}))' "$1")" +} + +type_of='fields { name type { name kind ofType { name kind ofType { name ofType { name } } } } }' +account="$(ask "{ __type(name: \"account\") { ${type_of} } }")" + +python3 -I - "$pattern" "$account" <<'EOF' > /tmp/overmind-datasets.$$ +import json, re, sys +pattern, answer = sys.argv[1], json.loads(sys.argv[2]) +if not answer.get("data") or not answer["data"].get("__type"): + sys.exit("Cloudflare said: " + "; ".join(e.get("message", "?") for e in answer.get("errors") or []) or "no schema") +def name(t): + while t and not t.get("name"): t = t.get("ofType") + return t and t["name"] +for f in answer["data"]["__type"]["fields"]: + if re.search(pattern, f["name"], re.I): + print(f["name"], name(f["type"])) +EOF + +while read -r dataset group; do + echo "== ${dataset}" + fields="$(ask "{ __type(name: \"${group}\") { ${type_of} } }")" + python3 -I - "$fields" <<'EOF' | while read -r part sub; do +import json, sys +def name(t): + while t and not t.get("name"): t = t.get("ofType") + return t and t["name"] +for f in json.loads(sys.argv[1])["data"]["__type"]["fields"]: + print(f["name"], name(f["type"]) or "-") +EOF + case "$part" in + sum|max|avg|quantiles|dimensions|count) + inner="$(ask "{ __type(name: \"${sub}\") { fields { name } } }")" + echo " ${part}: $(python3 -I -c 'import json,sys; print(" ".join(f["name"] for f in json.loads(sys.argv[1])["data"]["__type"]["fields"] or []))' "$inner")" ;; + esac + done +done < /tmp/overmind-datasets.$$ +rm -f /tmp/overmind-datasets.$$