Skip to content

Codecaps Muse Code Plugin - #390

Closed
jaywedgeworth22 wants to merge 3 commits into
mainfrom
Muse-Assist/codecaps-muse-code-plugin
Closed

jaywedgeworth22 wants to merge 3 commits into
mainfrom
Muse-Assist/codecaps-muse-code-plugin

Conversation

@jaywedgeworth22

@jaywedgeworth22 jaywedgeworth22 commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Codecaps Muse Code Plugin

Adds a deterministic Muse monitor as a Console Plugins section with local burn and standard-model alerts plus an optional Usage Monitor bridge. It reads on-device Muse session stores alongside quota refreshes and surfaces totals, contributor share, and per-model split on a dedicated page.

What changed

  • Console gains plugin:muse-code navigation, a Plugins sidebar section with warning badge, and a Muse monitor page showing status, burn, contributor share, models, alerts, and bridge state. Totals are labeled as floors because session snapshots rotate.
  • MonitorModel polls the session store with quota reads, publishes report, issue, burn alert, standard-session event, and bridge status, and adds user defaults for burn threshold (default 4,000,000 tokens in 90 minutes), alert enablement (ships on), and bridge enablement (ships off).
  • QuotaCore adds a session-store reader scanning ~/.local/.../.msp-view-g6 HEAD and snapshots, deduping segments per session and aggregating 60- and 90-minute windows.
  • Burn rule fires only when trailing 90-minute burn strictly exceeds the threshold while at least one current session is on a standard model. Presence is used instead of token share.
  • Standard-session detector fires once when a session is first seen on a standard model or switches from contributor to standard, re-arms on return to contributor, persists across relaunches, and ignores model-less observations.
  • Alerting adds museCodeBurn and museCodeStandardSession kinds shipping enabled with popup opt-in for standard sessions, plus an app-level dispatcher with a local channel to allow future channels without monitor changes.
  • Bridge posts only positive per-session deltas to /api/ingest/usage under the muse-code producer contract in batches of 100, validates complete ingest acknowledgments, persists baselines only after acknowledgment, and uses a separate Keychain service for the scoped ingest token.

Tests added

Tests added, not reported as run in this change set: MuseCodePluginTests, MuseCodeBurnMonitorTests, MuseCodeSessionReaderTests, MuseCodeStandardSessionDetectorTests, and MuseCodeSessionIngestTests covering navigation persistence, both alert kinds with cooldown and re-arm behavior, detector persistence, aggregation and dedupe, contract shape, delta discipline, and acknowledgment validation. Runtime delivery, notification display, and live bridge posting remain unverified.

Unresolved risks from automated review

Review reported 8 findings (high: 2, medium: 6) and no resolutions are claimed here. High: ingest token is never saved, and missing source ranges collapse segment identities. Medium: overlapping bridge tasks can double-count tokens, growing snapshots double-counted as new burn, unchanged snapshots reparsed on every read, snapshot cap discards newest snapshots, standard-session alert hidden when burn alert exists, and detector state grows unbounded and is rewritten every evaluation.

Muse-Assist and others added 3 commits November 2, 2026 21:21
Reads the Muse session stores in QuotaCore (segment-summed burn,
contributor share, per-model split, latest per-session observations),
adds a Plugins section to the Console with the Muse monitor as its
first plugin, and evaluates two deterministic alert kinds in pure code:
museCodeBurn (trailing-90-minute burn over a configurable threshold,
default 4,000,000 tokens, with contributor share below 100%) and
museCodeContributorBelow100 (the contributor finding on its own,
edge-triggered, independent of the burn threshold).

Alerts emit as CodeCapsAlertEvents through an app-level dispatcher
(CodeCapsAlertDispatcher); the only registered channel today is the
local alert surface via ResetAlarmManager, and channels select on the
stable UsageAlertKind identifier, so a future app-level channel (the
planned per-kind SMS opt-in) registers once without producer changes.

The Usage Monitor bridge posts per-session token deltas under the
verified muse-code contract (Usage Monitor PR #1862): latest snapshot
totals are cumulative, so only positive deltas are posted, with stable
codecaps-muse-code:<session>:<snapshot>:<model> event ids and baselines
persisted only after complete acknowledgments.
The museCodeContributorBelow100 kind fired on the contributor token share of a trailing window.  That share is computed from rotating session snapshots, so it moves for reasons unrelated to the finding — stale sessions inside the window, token weight, last-segment attribution — and reads below 100% even when every live session is on a contributor model.  An alert that fires on that number is noise, and the owner rejected the design on those grounds.

The finding is now presence, not percentage.  A new MuseCodeStandardSessionDetector in QuotaCore tracks each muse-code session's current model across polls and fires a museCodeStandardSession event exactly when a session starts on a standard model or switches to one from a contributor model; returning to a contributor model re-arms the session, and re-polls of a session still on the same standard model do not refire.  Each event names the session id, the model id, and the time observed.  Sessions whose current segment carries no model id never fire and leave the tracked state untouched.

The museCodeBurn kind keeps its trailing-90-minute threshold (default 4,000,000 tokens) and its cooldown, but its second condition is now at least one standard-model session observed in the window, taken from the same detector's presence test over the reading's latest per-session observations instead of the share.

The detector's state is Codable and persists in UserDefaults with the same JSON pattern as the Usage Monitor bridge baselines, so a session already reported does not refire after a relaunch; on the first scan after install, sessions already present count as first-observed and fire if standard, by design.  The Usage Monitor bridge is unchanged.

Tests are written but unrun — there is no Swift toolchain on this machine, so repo CI is the first compile gate.  The detector tests cover first-observed firing, no refire on re-poll, contributor-to-standard switches, re-arming after recovery, contributor-only silence, null-model silence, per-session independence, and state surviving a Codable round trip; the monitor and plugin tests now assert the burn rule's presence condition and the per-session event behavior end to end.
The delivery path already knew how to pop a warning: ResetAlarmManager presents an NSAlert window for any alert kind whose per-kind popup option is on, and the Muse monitor already routes its standard-session events through that path.  What was missing was a switch beside the feature — the only Popup toggle lived on the generic Alerts & Alarms page.

The Muse plugin page now offers Popup Warning For Standard Sessions, bound to the same stored preference as the Alerts & Alarms toggle for the museCodeStandardSession kind, so the two surfaces can never disagree.  The option ships off; turning it on makes a standard-session alert also open a popup window naming the session and its model.

Tests cover the shipped-off default, persistence of the enabled choice across a manager reload, and delivery of a standard-session event carrying the popup option through the manager.  Tests are written but unrun — there is no Swift toolchain on this machine, so repo CI is the first compile gate.
@kody-ai

kody-ai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Code Review Completed! 🔥

The code review was successfully completed based on your current configurations.

Kody Guide: Usage and Configuration
Interacting with Kody
  • Request a Review: Ask Kody to review your PR manually by adding a comment with the @kody start-review command at the root of your PR.

  • Validate Business Logic: Ask Kody to validate your code against business rules by adding a comment with the @kody -v business-logic command.

  • Provide Feedback: Help Kody learn and improve by reacting to its comments with a 👍 for helpful suggestions or a 👎 if improvements are needed.

Current Kody Configuration
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ✅

Access your configuration settings here.

​

Comment on lines +3222 to +3223
let plan = MuseCodeDeltaPlanner.plan(observations: report.latestObservations,
previous: loadMuseCodeIngestState())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug medium

Overlapping bridge tasks can double-count Muse tokens

When refreshMuseCodePlugin clears museCodeRequest and applyMuseCodeResult starts another task before the prior save completes, both tasks can load the same loadMuseCodeIngestState baseline and publish overlapping deltas with distinct eventId values, double-counting tokens. Serialize the baseline load, delta plan, publish, and save as one cycle, or retain only a single in-flight bridge task, so each post uses the prior completed save.

Prompt for LLM
File Sources/CodeCaps/MonitorModel.swift, lines 3222-3223:

Overlapping bridge tasks can double-count Muse tokens

The bridge baseline is loaded, then the function awaits the token read and the network publish before saving it (line 3252), so two overlapping bridge tasks can both read the same baseline. `refreshMuseCodePlugin` clears `museCodeRequest` (line 3142) before `applyMuseCodeResult` spawns the bridge task, so the next reading's task can start while the previous one is still in flight; the second task then computes its delta against the pre-save baseline and posts the full cumulative total as a new delta with a different eventId, which the server cannot dedupe — the session's tokens are counted twice in Usage Monitor. Serialize the load/plan/publish/save cycle (for example with a dedicated actor or a single in-flight bridge task) so a post completes before the next baseline is read.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +113 to +117
if let alert = model.museCodeBurnAlert {
row("Burn Alert", alert.body)
} else if let alert = model.museCodeStandardSessionAlert {
row("Standard Session Alert", alert.body)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug medium

Standard-session alert is hidden when a burn alert exists

When museCodeBurnAlert and museCodeStandardSessionAlert are both present, the else if hides museCodeStandardSessionAlert even though the model contract requires both alerts to remain visible. Render each alert in an independent if let block so mixed burn and standard-session findings both reach the plugin page.

Prompt for LLM
File Sources/CodeCaps/MuseCodePluginView.swift, lines 113-117:

Standard-session alert is hidden when a burn alert exists

The `else if` makes the standard-session alert mutually exclusive with the burn alert, so the standard-session alert is never shown on the plugin page whenever a burn alert exists — precisely the mixed reading (burn over threshold plus a session on a standard model) where both kinds fire. This contradicts the model contract in MonitorModel.swift:363-365 ("Both stay visible on the plugin page"), and `museCodeStandardSessionAlert` is surfaced nowhere else in the UI (grep confirms the only read is this line), so the finding silently disappears from the screen while its notification still fires. Fix: render the two alerts as independent `if let` blocks rather than an if/else-if chain.

Suggested code:

if let alert = model.museCodeBurnAlert {
    row("Burn Alert", alert.body)
}
if let alert = model.museCodeStandardSessionAlert {
    row("Standard Session Alert", alert.body)
}

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +29 to +37
/// The Muse plugin's bridge token: a producer-scoped Usage Monitor
/// ingest token for `muse-code`, kept apart from this app's own Push
/// Token because a scoped token authorizes exactly one producer.
static let museCodeIngestService = serviceName(suffix: "muse-code-ingest-token")

/// The service names this build owns: its Read Token, its Push Token,
/// and the Muse bridge token. A `.dev` build's names differ from the
/// release app's, so neither can reach the other's items.
static var ownServices: Set<String> { [readService, syncService, museCodeIngestService] }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug high

Muse ingest token is never saved

The Usage Monitor bridge cannot post any event because its producer-scoped token is never persisted; TokenStore.save calls only write readService and syncService, leaving postMuseCodeBridge without a token. Add a scoped UI field and a save path that calls TokenStore.save with service: TokenStore.museCodeIngestService so the app can create the required Keychain item.

Prompt for LLM
File Sources/CodeCaps/TokenStore.swift, lines 29-37:

Muse ingest token is never saved

The new `museCodeIngestService` is only ever read, never written: grep for `museCodeIngestService` yields just this declaration and the read at MonitorModel.swift:3235, and every `TokenStore.save` call site (MonitorModel.swift:2042, :2109) uses `readService`/`syncService`. The Keychain item the bridge reads can therefore never be created by the app, so `postMuseCodeBridge` always takes the `guard let token, !token.isEmpty` branch and the Usage Monitor bridge never posts a single event in production — the plugin's "Bridge Status" row always shows the missing-token message. Add a save path (a UI field plus `TokenStore.save(..., service: TokenStore.museCodeIngestService)`) scoped to the muse ingest endpoint.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +236 to +244
if let chosen {
observations.append(MuseCodeSessionObservation(
sessionId: sessionId,
snapshotId: chosen.snapshotId ?? "",
modelId: chosen.segment.modelId,
totalTokens: chosen.segment.totalTokens,
segmentKey: chosen.segment.sourceFirstId ?? "",
observedAt: chosen.segment.observedAt))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug high

Missing source ranges collapse Muse segment identities

When sourceFirstId is absent, segmentKey becomes empty for every snapshot, so MuseCodeDeltaPlanner.plan treats a new segment as the previous one and silently drops its reset delta. Use sourceFirstId when present and fall back to snapshotId otherwise, so segment transitions remain distinguishable and new usage is posted.

Prompt for LLM
File Sources/QuotaCore/MuseCodeSessionReader.swift, lines 236-244:

Missing source ranges collapse Muse segment identities

`segmentKey: chosen.segment.sourceFirstId ?? ""` gives every snapshot without a `sourceRange` the same empty segment key. `MuseCodeDeltaPlanner.plan` (MuseCodeSessionIngest.swift:94-100) treats an unchanged key plus unchanged model as "same segment", so when a session rolls into a new segment whose snapshots carry no `sourceRange` the delta becomes `newTotal - oldTotal` (often negative) and is silently dropped — those tokens are never posted to Usage Monitor and the baseline is rebaselined upward, losing the new segment's burn entirely. Derive a distinct key when `sourceFirstId` is missing (for example from the snapshot id) so a segment reset stays detectable.

Suggested code:

if let chosen {
    observations.append(MuseCodeSessionObservation(
        sessionId: sessionId,
        snapshotId: chosen.snapshotId ?? "",
        modelId: chosen.segment.modelId,
        totalTokens: chosen.segment.totalTokens,
        segmentKey: chosen.segment.sourceFirstId ?? chosen.snapshotId ?? "",
        observedAt: chosen.segment.observedAt))
}

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +30 to +33
public var dedupeKey: String {
[sourceFirstId ?? "", sourceLastId ?? "", modelId, String(totalTokens)]
.joined(separator: "\u{1}")
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug medium

Growing segment snapshots are double-counted as new burn

Because dedupeKey includes totalTokens, a cumulative segment that grows from 100 to 250 produces two keys, and aggregate sums both as 350. Dedupe by sessionId, sourceFirstId, sourceLastId, and modelId, then retain the largest totalTokens for each range so MuseCodeBurnMonitor.evaluateBurn receives actual burn rather than phantom tokens.

Prompt for LLM
File Sources/QuotaCore/MuseCodeSessionReader.swift, lines 30-33:

Growing segment snapshots are double-counted as new burn

`dedupeKey` includes `totalTokens`, but the same file documents `tokenUsage.totalTokens` as "cumulative for its current segment" (lines 93-96) and the ingest contract repeats it. A segment whose source range is unchanged but whose cumulative total grows between snapshots therefore yields two different dedupe keys, so `aggregate` (line 315) keeps both and sums them: a segment that grew from 100 to 250 tokens is counted as 350, inflating `MuseCodeWindowUsage.totalTokens` — the exact value `MuseCodeBurnMonitor.evaluateBurn` compares against the threshold, so the burn alert can fire on phantom burn. Dedupe on (sessionId, sourceFirstId, sourceLastId, modelId) and keep the largest total per range instead of summing every distinct total.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +218 to +230
let snapshots = dated
.filter { $0.url.lastPathComponent.hasPrefix("snapshot-")
&& $0.url.pathExtension == "json" && $0.modified >= cutoff }
.sorted { $0.modified < $1.modified }
.prefix(Self.maxSnapshotsPerSession)
var parsed: [(snapshotId: String?, segment: MuseCodeTokenSegment)] = []
for snapshot in snapshots {
if let segment = Self.segment(sessionId: sessionId, url: snapshot.url,
modified: snapshot.modified, size: snapshot.size) {
segments.append(segment)
parsed.append((Self.snapshotId(from: snapshot.url), segment))
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Performance medium

Unchanged Muse snapshots are reparsed on every read

The one-minute refreshMuseCodePlugin cycle repeatedly reads and JSON-parses the entire 90-minute snapshot window, including as many as Self.maxSnapshotsPerSession unchanged files per session, each up to Self.maxSnapshotBytes. Cache parsed segments by path, size, and modification time, and reparse only entries whose metadata changed so recurring refreshes scale with new snapshots.

Prompt for LLM
File Sources/QuotaCore/MuseCodeSessionReader.swift, lines 218-230:

Unchanged Muse snapshots are reparsed on every read

`read()` re-reads and re-parses every `snapshot-*.json` modified in the last 90 minutes on every call, with no caching of previously parsed segments. `refreshMuseCodePlugin` (MonitorModel.swift:3119) runs from `rebuildLocalState`, which the one-minute session-file timer drives (MonitorModel.swift:1535-1537, cadence default `.one`), so the whole window is re-read and re-JSON-parsed every minute; the design bound is 512 sessions x 512 snapshots, each read whole via `Data(contentsOf:)` and parsed with `JSONSerialization` up to `maxSnapshotBytes` (32 MB) per file. Cache parsed segments by (path, size, mtime) and only parse files whose content changed since the previous read, so the per-minute cost scales with new snapshots rather than with the whole 90-minute window.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +218 to +222
let snapshots = dated
.filter { $0.url.lastPathComponent.hasPrefix("snapshot-")
&& $0.url.pathExtension == "json" && $0.modified >= cutoff }
.sorted { $0.modified < $1.modified }
.prefix(Self.maxSnapshotsPerSession)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Bug medium

Snapshot cap discards the newest snapshots

When a session exceeds Self.maxSnapshotsPerSession, sorting ascending and applying .prefix(Self.maxSnapshotsPerSession) retains the oldest snapshots and discards the newest, leaving segments and the latest observation with stale totals and models. Sort descending before applying .prefix(Self.maxSnapshotsPerSession), or retain .suffix(Self.maxSnapshotsPerSession) with the ascending order, to keep the newest snapshots.

Prompt for LLM
File Sources/QuotaCore/MuseCodeSessionReader.swift, lines 218-222:

Snapshot cap discards the newest snapshots

The per-session snapshot cap keeps the OLDEST snapshots instead of the newest: the list is sorted ascending by modification date and then truncated with `.prefix(Self.maxSnapshotsPerSession)`, so when a session has more than 512 snapshots inside the 90-minute window (the reader's own comment says the store "rotate[s] snapshots aggressively"), every recent snapshot is discarded. That makes `segments` miss the newest segment (the 90-minute totals under-count) and makes the "latest observation" fallback at line 235 (`parsed.max { observedAt }`) pick the 512th-oldest snapshot, so the bridge posts a stale cumulative total and the standard-session detector sees a stale model. The sibling cap for session directories (lines 200-203) sorts descending and correctly keeps the newest 512. Fix: sort descending and keep the newest 512, or keep the ascending order and take `.suffix(Self.maxSnapshotsPerSession)`.

Suggested code:

let snapshots = dated
    .filter { $0.url.lastPathComponent.hasPrefix("snapshot-")
        && $0.url.pathExtension == "json" && $0.modified >= cutoff }
    .sorted { $0.modified > $1.modified }
    .prefix(Self.maxSnapshotsPerSession)

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

Comment on lines +117 to +126
for observation in observations {
guard let modelId = observation.modelId, !modelId.isEmpty else { continue }
let previous = lastKnownModels[observation.sessionId]
let wasContributor = previous.map { Self.isContributor(modelId: $0) } ?? false
if Self.isStandard(modelId: modelId), previous == nil || wasContributor {
events.append(MuseCodeStandardSessionEvent(
sessionId: observation.sessionId, modelId: modelId,
observedAt: observation.observedAt))
}
lastKnownModels[observation.sessionId] = modelId

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

kody code-review Performance medium

Detector state grows unbounded and is rewritten every evaluation

The persisted lastKnownModels blob grows with every session ever observed and is JSON-encoded and rewritten on every detector evaluation, including each one-minute refresh. Cap lastKnownModels by tracking observation recency and evicting the oldest sessions, using MuseCodeDeltaPlanner.maxTrackedSessions as the bound, and call saveMuseCodeDetectorState only when the state changes.

Prompt for LLM
File Sources/QuotaCore/MuseCodeStandardSessionDetector.swift, lines 117-126:

Detector state grows unbounded and is rewritten every evaluation

`lastKnownModels` grows without bound: every session id ever observed is written into the map and no session is ever evicted, including sessions that have disappeared from the store. MonitorModel.swift:3191 then calls `saveMuseCodeDetectorState()` on EVERY evaluation — i.e. on each ~1-minute session-file refresh and each 5-minute provider refresh — JSON-encoding the whole dictionary and rewriting it to UserDefaults each time. The persisted blob therefore grows without limit over months of use and is re-serialized and rewritten every minute. The same PR bounds session tracking elsewhere (`MuseCodeDeltaPlanner.maxTrackedSessions = 1024` in MuseCodeSessionIngest.swift:84), so the omission here looks unintended. Fix: cap the tracked sessions (evict the oldest observations) the way the delta planner does, and persist the detector state only when it actually changed.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

@swu-rob
swu-rob Bot marked this pull request as ready for review November 9, 2026 05:39
Comment on lines +3264 to 3274
}

private func saveMuseCodeIngestState(_ state: [String: MuseCodeSessionObservation]) {
if let data = try? JSONEncoder().encode(state) {
defaults.set(data, forKey: "museCodeIngestObservations")
}
}

private func appendRunawayAlert(_ record: RunawayAlertRecord) {
var list = runawayAlertHistory
list.insert(record, at: 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Unguarded concurrent postMuseCodeBridge tasks can race across async suspensions, leading to baseline regression or double-counted token usage deltas.
Severity: MEDIUM

Suggested Fix

Serialize ingest updates by keeping an in-flight Task handle or using a serial queue/actor for postMuseCodeBridge, ensuring subsequent tasks wait or skip until preceding posts and baseline updates finish.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/CodeCaps/MonitorModel.swift#L3110-L3274

Potential issue: In `MonitorModel.swift`, `applyMuseCodeResult` launches an
uncoordinated, unguarded asynchronous `Task` calling `postMuseCodeBridge` on each
reading. Because `MonitorModel` is bound to `@MainActor`, `postMuseCodeBridge` yields
across suspension points (such as token reads and network publishing). If multiple timer
events or manual refreshes trigger back-to-back readings, concurrent posts can load the
same baseline ingest state. If posts complete out of order or land across new snapshots,
older completed tasks overwrite newer baseline states with stale `plan.updated` data, or
generate non-deduplicatable event IDs that cause token delta double-counting.

Did we get this right? 👍 / 👎 to inform future reviews.

Comment on lines 129 to 138
case .quotaReset, .vendorReset: enabled = resetEnabled
case .anomaly, .runaway: enabled = runawayEnabled
case .quotaExhaustion: enabled = false
// The Muse monitor is the feature these kinds exist for, so
// they ship enabled; the owner can turn either off in
// Alerts & Alarms without touching the other.
case .museCodeBurn, .museCodeStandardSession: enabled = true
}
result[kind] = UsageAlertOption(enabled: enabled, sound: resetSound)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Defaulting Muse alert kinds to enabled causes the iOS companion app to unexpectedly prompt for notification permissions without user opt-in.
Severity: LOW

Suggested Fix

Ensure museCodeBurn and museCodeStandardSession alert options default to disabled, or filter out unsupported platform alert kinds on iOS before evaluating whether to request notification permissions.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/QuotaCore/UsageAlertPreferences.swift#L129-L138

Potential issue: In `UsageAlertPreferences.load(...)`, `museCodeBurn` and
`museCodeStandardSession` are initialized with `enabled: true` and default to
notification delivery enabled on both fresh installs and preference backfills. In
`CompanionQuotaModel`, any assignment to `alertPreferences` after initialization checks
if any alert kind is enabled with notifications and prompts for system notification
permissions via `requestNotificationPermission()`. Because
`synchronizeRemoteAlertChoices()` runs after initial snapshot loading, the iOS companion
requests notification permissions without user interaction for alert kinds that iOS
cannot generate or receive.

Did we get this right? 👍 / 👎 to inform future reviews.

Comment on lines +95 to +105
prior.modelId == observation.modelId {
delta = observation.totalTokens - prior.totalTokens
} else {
// First observation of the session, a segment reset, or a
// model switch: the current segment's total is the delta.
delta = observation.totalTokens
}
if delta > 0 {
events.append(MuseCodePlannedEvent(observation: observation, delta: delta))
}
updated[observation.sessionId] = observation

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Retrying failed batch publishes after new snapshot arrival generates new event IDs covering previously posted deltas, leading to token double-counting.
Severity: MEDIUM

Suggested Fix

Persist incremental baselines per successfully published batch rather than all-or-nothing, or construct event IDs that reflect explicit start and end token offsets.

Prompt for AI Agent
Review the code at the location below. A potential bug has been identified by an AI
agent. Verify if this is a real issue. If it is, propose a fix; if not, explain why it's
not valid.

Location: Sources/QuotaCore/MuseCodeSessionIngest.swift#L92-L105

Potential issue: `MuseCodeDeltaPlanner.plan` calculates token deltas relative to
`prior.totalTokens` and formats an event ID tied solely to the snapshot identifier
rather than the token range. If publishing fails across sequential batches,
`postMuseCodeBridge` leaves the persisted baseline untouched. If a newer snapshot
arrives prior to retry, a larger delta covering already-posted tokens is submitted under
a new event ID, preventing server-side deduplication and causing double-counted usage.

Also affects:

  • Sources/QuotaCore/MuseCodeSessionReader.swift:30~33

Did we get this right? 👍 / 👎 to inform future reviews.

@swu-gb-designer

swu-gb-designer Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

[GB-DESIGNER 📁CC]

UI pass on the Muse Code plugin page, tip f83d825631: nits (the copy nits from #357 carried over).

  • "Plugin unavailable" should be "Plugin Unavailable".
  • "Two alert kinds: museCodeBurn fires when…" shows internal names.  Suggested: "Burn Alert warns you when usage passes the threshold while a session uses a standard model."
  • "Deterministic monitoring of Muse token burn…" reads better as "Tracks Muse token use and standard-model sessions on this Mac."
  • "Contributor Share (90 minutes)" should be "(90 Minutes)" to match "Last 90 Minutes".
  • "…as muse-code token events." exposes an event name; "…as Muse Code usage." says the same thing in plain words.
  • The all-caps "WARNING" badge shouts next to Title Case headings; "Warning" in the existing badge style would match.
  • Good: the ingest-token controls are gone from this page, which leaves the bridge section much simpler.

None of these block merge.  Not runtime-verified.

@kody-ai

kody-ai Bot commented Nov 9, 2026

Copy link
Copy Markdown

Automatic approval held

Kody's assessment:

This commit was reviewed without a risk assessment; Kody assesses the next commit.

@swu-wise

swu-wise Bot commented Nov 10, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded after a full preservation check against main (e7fca82).

Preservation matrix - all 11 findings verified against current main:

Fixed on main already:

  • Overlapping bridge tasks double-counting Muse tokens (MonitorModel)
  • Muse ingest token never saved (TokenStore)
  • Missing source ranges collapsing segment identities (MuseCodeSessionReader)
  • Growing snapshots double-counted as new burn (MuseCodeSessionReader)
  • Snapshot cap discarding the newest snapshots (MuseCodeSessionReader)
  • Concurrent postMuseCodeBridge baseline race (MonitorModel)
  • Retry double-counting after new snapshot arrival (MuseCodeSessionIngest)

Still real on main, fixed in #462:

  • Standard-session alert hidden behind burn alert (MuseCodePluginView): both alerts now render independently, pinned by a test
  • Detector state growing unbounded (MuseCodeStandardSessionDetector): 24h TTL eviction + 512-session cap, backward-compatible decode for legacy blobs

Remains tracked:

No action:

  • Default-enabled Muse alert kinds (UsageAlertPreferences): matches documented product intent, left unchanged

This branch is stale; the remaining real fixes continue under #462 through the normal review gates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant