diff --git a/README.md b/README.md index 25860160..5136daef 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,9 @@ It works particularly well in: exact `INPUT NEEDED` and `APPROVAL NEEDED` states. Without it, a completed open turn is definite `INPUT NEEDED`; an otherwise active session with no rollout activity for three minutes is cautiously labelled `CHECK SESSION`. + For a root with linked agents, fresh activity from any member suppresses that + uncertain fallback; definite input or approval signals still propagate from + the member that raised them. - An opt-in deterministic coding benchmark comparing every visible Codex model and supported reasoning effort by correctness, elapsed time, token use, and estimated standard API-equivalent cost. @@ -435,7 +438,11 @@ matches reroute and token-usage events to rollout calls by thread ID, turn ID, cumulative token checkpoint, and the complete response token breakdown. For a subscribed thread, costing waits for one refresh when that exact match is not yet available; a matching notification uses the resolved model, otherwise the -call safely returns to requested-model pricing. Late attachment, disconnects, +call safely returns to requested-model pricing. A call awaiting that decision +is kept in a separate pending count and does not enter the cumulative priced or +unpriced totals. This makes finalized accounting monotonic; a quota observation +that overlaps pending or newly finalized accounting is deferred instead of +silently moving its learning baseline. Late attachment, disconnects, ordinary non-daemon clients, and already historical reroutes also retain requested-model pricing rather than being guessed; these remaining coverage limits are one reason confidence never rises above Medium. Ordinary input, cached input, @@ -452,12 +459,16 @@ Benchmark view and making stale compiled pricing conspicuous wherever a priced figure appears. Each refresh brackets the account quota request with local accounting reads. -If their cost or call counters differ, `OBSERVATION DEFERRED` is shown and no -sample is taken, preventing a response completed during the request from being -paired with the wrong quota snapshot. Learning starts with a stable quota -percentage and cumulative local API-equivalent cost anchor. Once the same -window advances by at least five displayed percentage points without a reset -or an unpriced call, a sample is calculated: +If their cost, finalized-call, or pending-call counters differ—or a call is +still pending—`OBSERVATION DEFERRED` is shown and no sample is taken, preventing +a response completed during the request from being paired with the wrong quota +snapshot. Learning starts with a stable quota percentage and cumulative local +API-equivalent cost anchor. A pause in activity does not expire or reduce clean +movement. The backend may revise an upcoming rolling-window reset timestamp; +Codexometer retains the earliest observed boundary and does not restart merely +because that future timestamp moved. Once the same window advances by at least +five displayed percentage points without a reset or an unpriced call, a sample +is calculated: ```text central 100% estimate = observed API-equivalent cost × 100 / percentage-point movement @@ -475,12 +486,16 @@ Confidence is intentionally capped at Medium because local telemetry cannot prove that no other machine, cloud task, unobserved client, or server-side model reroute outside the shared-daemon subscription also affected the account quota. -An interval is discarded and re-anchored if the window resets, the counters +An interval is discarded and re-anchored if its earliest reset boundary passes, +used quota falls, the account or window definition changes, finalized counters regress, the quota moves five points without any matching priced local call, or -an unknown/unpriced model occurs. `LOCAL COVERAGE GAP` signals the unmatched -movement. Even a valid estimate can still vary with reasoning effort, model -mix, caching, prompt shape, and backend quota weighting, so compare ranges and -sample counts rather than treating the midpoint as a fixed entitlement. +an unknown/unpriced model occurs. The learning readout retains the reason, for +example `RESTARTED: WINDOW RESET`, `WINDOW DEFINITION CHANGED`, `LOCAL +ACCOUNTING REBASED`, `UNPRICED MODEL MIX`, or `LOCAL COVERAGE GAP`, while new +clean movement accumulates. It never silently returns to `0/5PP`. Even a valid +estimate can still vary with reasoning effort, model mix, caching, prompt +shape, and backend quota weighting, so compare ranges and sample counts rather +than treating the midpoint as a fixed entitlement. Samples remain process-local and are never written to the preferences file, so evidence cannot leak from one login into another on a later run. During a run, @@ -562,7 +577,8 @@ The other top-level views are: `APPROVAL NEEDED` and `INPUT NEEDED`. If no shared server is available, an otherwise active open session with no new token or rollout activity for three minutes receives `CHECK SESSION`: a deliberately uncertain prompt that can - also mean a long-running local tool. Any subsequent activity clears it. + also mean a long-running local tool. Subsequent activity from the root or any + linked agent clears the uncertain group-level warning. Codexometer never guesses `APPROVAL NEEDED` from inactivity. Closing the CLI releases its per-thread writer lock and clears every attention badge. A session already included in the current Monitor recording can remain as an @@ -650,7 +666,10 @@ Monitor does not retain the input question, approval text, response, or conversation content. A linked child's attention state is folded into its root so one remote Monitor row identifies the CLI session that needs intervention. A definite approval signal takes precedence, then definite input, then the -inferred check state when linked members have mixed states. +inferred check state when linked members have mixed states. Because `CHECK +SESSION` is only an inactivity inference, fresh activity anywhere in the group +suppresses a stale sibling's check; definite input and approval are never +suppressed this way. `CALLS` counts upstream model-response cycles observed after Monitor Start, not complete user turns. A single Codex turn can make several calls while using @@ -997,9 +1016,9 @@ need Go or Codexometer's source dependencies. ## Versioning Codexometer follows semantic versioning; the current source version is -`v0.7.3`. The Git tag is the release source of truth. Go automatically embeds +`v0.7.4`. The Git tag is the release source of truth. Go automatically embeds that tag in binaries built with -`go install github.com/merefield/codexometer@v0.7.3`; direct source builds fall +`go install github.com/merefield/codexometer@v0.7.4`; direct source builds fall back to the maintained value in `internal/version/version.go`. Both forms report the embedded version and exit without starting the interface: @@ -1012,7 +1031,7 @@ codexometer --version Release automation can override the source-build fallback without editing code: ```sh -go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.7.3" . +go build -ldflags="-s -w -X github.com/merefield/codexometer/internal/version.Fallback=0.7.4" . ``` ## How refresh works diff --git a/internal/codex/live_usage.go b/internal/codex/live_usage.go index 82d40f08..dc46f1f2 100644 --- a/internal/codex/live_usage.go +++ b/internal/codex/live_usage.go @@ -24,8 +24,10 @@ const ( fallbackAttentionAfter = 3 * time.Minute ) -// LiveUsageSnapshot is a process-local, monotonically increasing count built -// from token-count events appended to locally persisted Codex rollouts. +// LiveUsageSnapshot is a process-local accounting view built from token-count +// events appended to locally persisted Codex rollouts. Finalized API-equivalent +// totals increase monotonically; APIEqPendingCalls is an instantaneous count +// kept separate until daemon model resolution or requested-model fallback. type LiveUsageSnapshot struct { TotalTokens int64 LastActivity time.Time @@ -34,6 +36,7 @@ type LiveUsageSnapshot struct { APIEqUSD float64 APIEqPricedCalls int64 APIEqUnpricedCalls int64 + APIEqPendingCalls int64 } // LiveUsageSession is one independently started local Codex session. Token @@ -74,6 +77,7 @@ type LiveModelCall struct { Model string APIEqUSD float64 APIEqKnown bool + apiEqFinalized bool } // LiveTurnTiming contains the persisted latency measurement for one completed @@ -350,6 +354,7 @@ func (r *LiveUsageReader) fetchTokenUsage(ctx context.Context, forceFullDiscover SessionCount: activeSessions, Sessions: sessions, APIEqUSD: r.apiEqUSD, APIEqPricedCalls: r.apiEqPricedCalls, APIEqUnpricedCalls: r.apiEqUnknownCalls, + APIEqPendingCalls: int64(len(r.pendingModelResolutions)), }, nil } @@ -568,23 +573,26 @@ func (r *LiveUsageReader) consume(path string, cursor *rolloutCursor) error { model, pricingUsage, resolved = observation.Model, observation.Usage, true } } + resolutionDeferred := usageMatchesDelta && resolutionPending && !resolved call := LiveModelCall{ Sequence: r.nextEventSequence, At: record.at, OutputTokens: record.outputTokens, OutputAvailable: record.outputKnown, Model: model, } if usageMatchesDelta && (!resolutionPending || resolved) { if cost, known, _ := EstimateStandardAPIEqCost(model, pricingUsage); known { - call.APIEqUSD, call.APIEqKnown = cost, true + call.APIEqUSD, call.APIEqKnown, call.apiEqFinalized = cost, true, true r.apiEqUSD += cost r.apiEqPricedCalls++ } else { + call.apiEqFinalized = true r.apiEqUnknownCalls++ } - } else { + } else if !resolutionDeferred { + call.apiEqFinalized = true r.apiEqUnknownCalls++ } cursor.modelCalls = appendBounded(cursor.modelCalls, call, telemetryHistoryMax) - if usageMatchesDelta && resolutionPending && !resolved { + if resolutionDeferred { r.pendingModelResolutions = append(r.pendingModelResolutions, pendingModelResolution{ callSequence: call.Sequence, threadID: cursor.threadID, turnID: cursor.currentTurnID, usage: record.usage, cumulativeTotal: record.total, @@ -639,33 +647,24 @@ func (r *LiveUsageReader) ingestResolvedModelObservations(observations []resolve func (r *LiveUsageReader) reconcilePendingModelResolutions() { for _, pending := range r.pendingModelResolutions { - observation, ok := r.takeResolvedModelObservation(pending.threadID, pending.turnID, pending.usage, pending.cumulativeTotal) - if !ok { - call := r.modelCall(pending.callSequence) - if call != nil { - r.apiEqUnknownCalls-- - call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(call.Model, pending.usage) - if call.APIEqKnown { - r.apiEqUSD += call.APIEqUSD - r.apiEqPricedCalls++ - } else { - r.apiEqUnknownCalls++ - } - } - continue - } call := r.modelCall(pending.callSequence) if call == nil { + // The call aged out of the bounded per-session history before it + // could be finalized. Preserve fail-closed monotonic accounting. + r.apiEqUnknownCalls++ continue } - if call.APIEqKnown { - r.apiEqUSD -= call.APIEqUSD - r.apiEqPricedCalls-- - } else { - r.apiEqUnknownCalls-- + if call.apiEqFinalized { + continue } - call.Model = observation.Model - call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(observation.Model, observation.Usage) + observation, ok := r.takeResolvedModelObservation(pending.threadID, pending.turnID, pending.usage, pending.cumulativeTotal) + pricingUsage := pending.usage + if ok { + call.Model = observation.Model + pricingUsage = observation.Usage + } + call.APIEqUSD, call.APIEqKnown, _ = EstimateStandardAPIEqCost(call.Model, pricingUsage) + call.apiEqFinalized = true if call.APIEqKnown { r.apiEqUSD += call.APIEqUSD r.apiEqPricedCalls++ @@ -1088,12 +1087,15 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string } groups := make(map[string]*LiveUsageSession) + groupHasFreshActivity := make(map[string]bool) for _, cursor := range r.files { - active := now.Sub(cursor.lastModified) <= 5*time.Minute + quietFor := now.Sub(cursor.lastModified) + active := quietFor <= 5*time.Minute _, writerActive := liveWriters[cursor.threadID] exactStatus, exact := exactStatuses[cursor.threadID] - attention := sessionAttention(cursor.attention, writerActive, writerLocksSupported, now.Sub(cursor.lastModified), exactStatus, exact) - if !active && attention == SessionAttentionNone && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { + exactWorking := exact && exactStatus == sessionRuntimeWorking + attention := sessionAttention(cursor.attention, writerActive, writerLocksSupported, quietFor, exactStatus, exact) + if !active && !exactWorking && attention == SessionAttentionNone && cursor.observedTokens == 0 && len(cursor.modelCalls) == 0 && len(cursor.turnTimings) == 0 { continue } rootID, unattributed := rolloutRoot(cursor, byID) @@ -1105,8 +1107,13 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string group.TotalTokens += cursor.observedTokens group.ModelCalls = append(group.ModelCalls, cursor.modelCalls...) group.TurnTimings = append(group.TurnTimings, cursor.turnTimings...) - group.Active = group.Active || active || attention != SessionAttentionNone + group.Active = group.Active || active || exactWorking || attention != SessionAttentionNone group.Attention = mergeSessionAttention(group.Attention, attention) + // CHECK SESSION is only an inactivity inference. A freshly writing + // member—or an authoritatively working daemon thread—means the grouped + // root is demonstrably active, even if a linked child was left quiet + // overnight. Definite input and approval signals still propagate. + groupHasFreshActivity[rootID] = groupHasFreshActivity[rootID] || quietFor < fallbackAttentionAfter || exactWorking if cursor.lastModified.After(group.LastActivity) { group.LastActivity = cursor.lastModified } @@ -1127,6 +1134,9 @@ func (r *LiveUsageReader) sessionSnapshots(now time.Time, liveWriters map[string sessions := make([]LiveUsageSession, 0, len(groups)) activeCount := 0 for _, session := range groups { + if session.Attention == SessionAttentionCheck && groupHasFreshActivity[session.ID] { + session.Attention = SessionAttentionNone + } sort.Slice(session.ModelCalls, func(i, j int) bool { return session.ModelCalls[i].Sequence < session.ModelCalls[j].Sequence }) sort.Slice(session.TurnTimings, func(i, j int) bool { return session.TurnTimings[i].Sequence < session.TurnTimings[j].Sequence }) if session.Active { diff --git a/internal/codex/live_usage_test.go b/internal/codex/live_usage_test.go index cfd0f786..1a074dba 100644 --- a/internal/codex/live_usage_test.go +++ b/internal/codex/live_usage_test.go @@ -520,6 +520,52 @@ func TestSessionAttentionMergePrefersDefiniteSignals(t *testing.T) { } } +func TestSessionSnapshotsSuppressesQuietChildCheckWhileGroupIsActive(t *testing.T) { + now := time.Now() + reader := &LiveUsageReader{files: map[string]*rolloutCursor{ + "root": { + threadID: "root", lastModified: now, attention: sessionAttentionWorking, + }, + "child": { + threadID: "child", parentThreadID: "root", nonRoot: true, + lastModified: now.Add(-8 * time.Hour), attention: sessionAttentionWorking, + }, + }} + writers := map[string]struct{}{"root": {}, "child": {}} + + sessions, active := reader.sessionSnapshots(now, writers, true, nil) + if len(sessions) != 1 || active != 1 { + t.Fatalf("grouped sessions = %#v, active %d; want one active root", sessions, active) + } + if got := sessions[0].Attention; got != SessionAttentionNone { + t.Fatalf("fresh root inherited quiet child's uncertain attention = %v", got) + } +} + +func TestSessionSnapshotsExactWorkingStatusSuppressesGroupedFallback(t *testing.T) { + now := time.Now() + old := now.Add(-8 * time.Hour) + reader := &LiveUsageReader{files: map[string]*rolloutCursor{ + "root": { + threadID: "root", lastModified: old, attention: sessionAttentionWorking, + }, + "child": { + threadID: "child", parentThreadID: "root", nonRoot: true, + lastModified: old, attention: sessionAttentionWorking, + }, + }} + writers := map[string]struct{}{"root": {}, "child": {}} + statuses := map[string]sessionRuntimeStatus{"root": sessionRuntimeWorking} + + sessions, active := reader.sessionSnapshots(now, writers, true, statuses) + if len(sessions) != 1 || active != 1 { + t.Fatalf("daemon-working group = %#v, active %d; want one active root", sessions, active) + } + if got := sessions[0].Attention; got != SessionAttentionNone { + t.Fatalf("daemon-working root inherited quiet child's fallback = %v", got) + } +} + func TestLiveUsageReaderUsesPerThreadExactStatuses(t *testing.T) { home := t.TempDir() now := time.Now() @@ -576,7 +622,8 @@ func TestLiveUsageReaderCorrectsRequestedModelFromDelayedDaemonReroute(t *testin } _, requestedKnown, _ := EstimateStandardAPIEqCost("gpt-5.6-sol", usage) if call := first.Sessions[0].ModelCalls[0]; call.Model != "gpt-5.6-sol" || - !requestedKnown || call.APIEqKnown || call.APIEqUSD != 0 || first.APIEqUnpricedCalls != 1 { + !requestedKnown || call.APIEqKnown || call.APIEqUSD != 0 || call.apiEqFinalized || + first.APIEqUnpricedCalls != 0 || first.APIEqPendingCalls != 1 { t.Fatalf("pending reroute call = %#v snapshot %#v", call, first) } @@ -593,7 +640,8 @@ func TestLiveUsageReaderCorrectsRequestedModelFromDelayedDaemonReroute(t *testin if call.Model != "gpt-5.6-terra" || !resolvedKnown || !call.APIEqKnown || call.APIEqUSD != resolvedCost { t.Fatalf("reroute-corrected call = %#v", call) } - if corrected.APIEqUSD != resolvedCost || corrected.APIEqPricedCalls != 1 || corrected.APIEqUnpricedCalls != 0 { + if corrected.APIEqUSD != resolvedCost || corrected.APIEqPricedCalls != 1 || + corrected.APIEqUnpricedCalls != 0 || corrected.APIEqPendingCalls != 0 { t.Fatalf("reroute-corrected aggregate = %#v", corrected) } } @@ -604,7 +652,6 @@ func TestLiveUsageReaderRerouteCorrectionFailsClosedOnUnpriceableUsage(t *testin files: map[string]*rolloutCursor{"rollout": {modelCalls: []LiveModelCall{{ Sequence: 1, Model: "gpt-5.6-sol", }}}}, - apiEqUnknownCalls: 1, pendingModelResolutions: []pendingModelResolution{{ callSequence: 1, threadID: "thread", turnID: "turn", usage: usage, cumulativeTotal: 130, }}, @@ -631,7 +678,6 @@ func TestLiveUsageReaderFinalizesRequestedModelWhenDaemonHasNoReroute(t *testing files: map[string]*rolloutCursor{"rollout": {modelCalls: []LiveModelCall{{ Sequence: 1, Model: "gpt-5.6-sol", }}}}, - apiEqUnknownCalls: 1, pendingModelResolutions: []pendingModelResolution{{ callSequence: 1, threadID: "thread", turnID: "turn", usage: usage, cumulativeTotal: 110, }}, @@ -682,6 +728,48 @@ func TestLiveUsageReaderPropagatesWaitingAgentToRoot(t *testing.T) { } } +func TestLiveUsageReaderClearsQuietChildFallbackWhenRootResumes(t *testing.T) { + home := t.TempDir() + now := time.Now() + idleSince := now.Add(-8 * time.Hour) + rootPath := testRolloutPath(t, home, idleSince, "resumed-root") + childPath := testRolloutPath(t, home, idleSince, "quiet-child") + writeRollout(t, rootPath, + sessionMetaLine("resumed-root", `"cli"`, "/work/root", nil)+"\n"+ + attentionEventLine(idleSince, "task_started", nil)+"\n") + writeRollout(t, childPath, + sessionMetaLine("quiet-child", threadSpawnSource("resumed-root"), "/work/root", nil)+"\n"+ + attentionEventLine(idleSince, "task_started", nil)+"\n") + for _, path := range []string{rootPath, childPath} { + if err := os.Chtimes(path, idleSince, idleSince); err != nil { + t.Fatal(err) + } + } + locks := filepath.Join(home, "thread-writer-locks") + if err := os.MkdirAll(locks, 0o755); err != nil { + t.Fatal(err) + } + releaseRoot := holdTestFileLock(t, filepath.Join(locks, "resumed-root.lock")) + defer releaseRoot() + releaseChild := holdTestFileLock(t, filepath.Join(locks, "quiet-child.lock")) + defer releaseChild() + + reader, err := NewLiveUsageReader(home) + if err != nil { + t.Fatal(err) + } + usage, err := reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionCheck { + t.Fatalf("idle grouped session = %#v, %v; want cautious check", usage, err) + } + + appendRollout(t, rootPath, attentionEventLine(now, "task_started", nil)+"\n") + usage, err = reader.FetchTokenUsage(context.Background()) + if err != nil || len(usage.Sessions) != 1 || usage.Sessions[0].Attention != SessionAttentionNone { + t.Fatalf("resumed grouped session = %#v, %v; want stale child check cleared", usage, err) + } +} + func TestLiveUsageReaderKeepsExplicitInputRequestVisibleBeyondRecentActivity(t *testing.T) { home := t.TempDir() now := time.Now() diff --git a/internal/ui/model.go b/internal/ui/model.go index 0c259ab6..92c9798d 100644 --- a/internal/ui/model.go +++ b/internal/ui/model.go @@ -1010,7 +1010,7 @@ func (m Model) fetch() tea.Cmd { message.usageErr = beforeErr case afterErr != nil: message.usageErr = afterErr - case !quotaAPIAccountingEqual(before, after): + case !quotaAPIAccountingEqual(before, after) || after.APIEqPendingCalls > 0: message.usageErr = errQuotaObservationChanged default: message.usage = after diff --git a/internal/ui/model_test.go b/internal/ui/model_test.go index 3edcfd7e..9879d25d 100644 --- a/internal/ui/model_test.go +++ b/internal/ui/model_test.go @@ -156,6 +156,14 @@ func TestQuotaFetchRequiresStableAccountingBracket(t *testing.T) { if model.quotaAPITelemetryIssue != "OBSERVATION DEFERRED" { t.Fatalf("deferred issue = %q", model.quotaAPITelemetryIssue) } + + pending := changed + pending.APIEqPendingCalls = 1 + fetcher.usages = []codex.LiveUsageSnapshot{pending, pending} + message = model.fetch()().(fetchedMsg) + if !errors.Is(message.usageErr, errQuotaObservationChanged) { + t.Fatalf("pending quota accounting was accepted: %#v", message) + } fetcher.usages = []codex.LiveUsageSnapshot{changed, changed} message = model.fetch()().(fetchedMsg) updated, _ = model.Update(message) diff --git a/internal/ui/quota_api_eq.go b/internal/ui/quota_api_eq.go index da4b50b7..f080080f 100644 --- a/internal/ui/quota_api_eq.go +++ b/internal/ui/quota_api_eq.go @@ -21,7 +21,8 @@ var errQuotaObservationChanged = fmt.Errorf("local accounting changed during quo func quotaAPIAccountingEqual(left, right codex.LiveUsageSnapshot) bool { return left.APIEqUSD == right.APIEqUSD && left.APIEqPricedCalls == right.APIEqPricedCalls && - left.APIEqUnpricedCalls == right.APIEqUnpricedCalls + left.APIEqUnpricedCalls == right.APIEqUnpricedCalls && + left.APIEqPendingCalls == right.APIEqPendingCalls } // quotaAPISample is process-local and content-free. Its key contains only an @@ -43,8 +44,18 @@ type quotaAPIAnchor struct { costUSD float64 pricedCalls int64 unpricedCalls int64 + restartReason string } +const ( + quotaAPIRestartAccountChanged = "ACCOUNT CHANGED" + quotaAPIRestartAccountingRebased = "LOCAL ACCOUNTING REBASED" + quotaAPIRestartCoverageGap = "LOCAL COVERAGE GAP" + quotaAPIRestartUnpricedModel = "UNPRICED MODEL MIX" + quotaAPIRestartWindowChanged = "WINDOW DEFINITION CHANGED" + quotaAPIRestartWindowReset = "WINDOW RESET" +) + type quotaAPIEstimate struct { currentLow float64 currentHigh float64 @@ -62,7 +73,8 @@ func (m *Model) observeQuotaAPIEq(snapshot codex.Snapshot, usage codex.LiveUsage if account == "" { return } - if m.quotaAPIAccount != "" && m.quotaAPIAccount != account { + accountChanged := m.quotaAPIAccount != "" && m.quotaAPIAccount != account + if accountChanged { m.quotaAPIAnchors = make(map[string]quotaAPIAnchor) m.quotaAPIEvidence = nil m.quotaAPIIssues = make(map[string]string) @@ -74,6 +86,10 @@ func (m *Model) observeQuotaAPIEq(snapshot codex.Snapshot, usage codex.LiveUsage if m.quotaAPIIssues == nil { m.quotaAPIIssues = make(map[string]string) } + priorAnchorKeys := make(map[string]struct{}, len(m.quotaAPIAnchors)) + for key := range m.quotaAPIAnchors { + priorAnchorKeys[key] = struct{}{} + } m.quotaAPIEvidence = validQuotaAPISamples(m.quotaAPIEvidence, at) for _, meter := range snapshot.Meters() { if !quotaAPIMeterEligible(snapshot, meter) { @@ -86,16 +102,42 @@ func (m *Model) observeQuotaAPIEq(snapshot codex.Snapshot, usage codex.LiveUsage pricedCalls: usage.APIEqPricedCalls, unpricedCalls: usage.APIEqUnpricedCalls, } anchor, exists := m.quotaAPIAnchors[key] - if !exists || anchor.resetAt != current.resetAt || current.usedPercent < anchor.usedPercent || - current.costUSD < anchor.costUSD || current.pricedCalls < anchor.pricedCalls || + if !exists { + switch { + case accountChanged: + current.restartReason = quotaAPIRestartAccountChanged + case quotaAPIHasRelatedPriorAnchor(priorAnchorKeys, snapshot, meter): + current.restartReason = quotaAPIRestartWindowChanged + } + m.quotaAPIAnchors[key] = current + m.quotaAPIIssues[key] = "" + continue + } + if quotaAPIWindowReset(anchor, current, at) { + current.restartReason = quotaAPIRestartWindowReset + m.quotaAPIAnchors[key] = current + m.quotaAPIIssues[key] = "" + continue + } + if current.costUSD < anchor.costUSD || current.pricedCalls < anchor.pricedCalls || current.unpricedCalls < anchor.unpricedCalls { + current.restartReason = quotaAPIRestartAccountingRebased m.quotaAPIAnchors[key] = current m.quotaAPIIssues[key] = "" continue } + // The backend may revise an upcoming rolling-window reset timestamp + // without starting a new quota window. Preserve the earliest known + // boundary so a later observation can still detect that it passed, + // while retaining the clean movement and accounting baselines now. + if current.resetAt > 0 && (anchor.resetAt == 0 || current.resetAt < anchor.resetAt) { + anchor.resetAt = current.resetAt + m.quotaAPIAnchors[key] = anchor + } if current.unpricedCalls > anchor.unpricedCalls { + current.restartReason = quotaAPIRestartUnpricedModel m.quotaAPIAnchors[key] = current - m.quotaAPIIssues[key] = "UNPRICED MODEL MIX" + m.quotaAPIIssues[key] = "" continue } deltaPercent := current.usedPercent - anchor.usedPercent @@ -104,8 +146,9 @@ func (m *Model) observeQuotaAPIEq(snapshot codex.Snapshot, usage codex.LiveUsage } deltaCost := current.costUSD - anchor.costUSD if deltaCost <= 0 || current.pricedCalls == anchor.pricedCalls { + current.restartReason = quotaAPIRestartCoverageGap m.quotaAPIAnchors[key] = current - m.quotaAPIIssues[key] = "LOCAL COVERAGE GAP" + m.quotaAPIIssues[key] = "" continue } capacity := deltaCost * 100 / float64(deltaPercent) @@ -122,6 +165,28 @@ func (m *Model) observeQuotaAPIEq(snapshot codex.Snapshot, usage codex.LiveUsage } } +func quotaAPIHasRelatedPriorAnchor(priorKeys map[string]struct{}, snapshot codex.Snapshot, meter codex.Meter) bool { + wantedAccount := strings.TrimSpace(snapshot.AccountFingerprint) + wantedLimit := strings.ToLower(strings.TrimSpace(meter.LimitID)) + for key := range priorKeys { + parts := strings.Split(key, "|") + if len(parts) == 4 && parts[0] == wantedAccount && parts[2] == wantedLimit { + return true + } + } + return false +} + +func quotaAPIWindowReset(anchor, current quotaAPIAnchor, observedAt time.Time) bool { + if current.usedPercent < anchor.usedPercent { + return true + } + if anchor.resetAt <= 0 || current.resetAt <= anchor.resetAt { + return false + } + return !observedAt.Before(time.Unix(anchor.resetAt, 0)) +} + func quotaAPIMeterEligible(snapshot codex.Snapshot, meter codex.Meter) bool { return meter.Kind == codex.MeterQuotaWindow && snapshot.AccountFingerprint != "" && strings.EqualFold(strings.TrimSpace(meter.LimitID), "codex") @@ -307,6 +372,17 @@ func (m Model) quotaAPILine(meter codex.Meter, width int) string { progress := 0 if anchor, ok := m.quotaAPIAnchors[key]; ok { progress = min(max(meter.Window.UsedPercent-anchor.usedPercent, 0), quotaAPIMinimumDelta) + if anchor.restartReason != "" { + shortReason := shortQuotaAPIRestartReason(anchor.restartReason) + switch { + case width >= 72: + return fmt.Sprintf("API-EQ LEARNING // %d/%dPP CLEAN MOVEMENT // RESTARTED: %s", progress, quotaAPIMinimumDelta, anchor.restartReason) + case width >= 44: + return fmt.Sprintf("API-EQ %d/%dPP // RESTARTED: %s", progress, quotaAPIMinimumDelta, shortReason) + default: + return fmt.Sprintf("EQ %d/%dPP // %s", progress, quotaAPIMinimumDelta, shortReason) + } + } } if width < 44 { return fmt.Sprintf("API-EQ LEARNING %d/%dPP", progress, quotaAPIMinimumDelta) @@ -314,6 +390,25 @@ func (m Model) quotaAPILine(meter codex.Meter, width int) string { return fmt.Sprintf("API-EQ LEARNING // %d/%dPP CLEAN MOVEMENT", progress, quotaAPIMinimumDelta) } +func shortQuotaAPIRestartReason(reason string) string { + switch reason { + case quotaAPIRestartAccountChanged: + return "ACCOUNT" + case quotaAPIRestartAccountingRebased: + return "REBASED" + case quotaAPIRestartCoverageGap: + return "COVERAGE GAP" + case quotaAPIRestartUnpricedModel: + return "UNPRICED" + case quotaAPIRestartWindowChanged: + return "WINDOW CHANGED" + case quotaAPIRestartWindowReset: + return "RESET" + default: + return reason + } +} + func formatAPIRange(low, high float64) string { left, right := formatUSD(low), formatUSD(high) if left == right { diff --git a/internal/ui/quota_api_eq_test.go b/internal/ui/quota_api_eq_test.go index 3b326bf6..6e57fd5b 100644 --- a/internal/ui/quota_api_eq_test.go +++ b/internal/ui/quota_api_eq_test.go @@ -94,6 +94,92 @@ func TestQuotaAPIEstimatorResetsAnchorAndCapsConfidence(t *testing.T) { } } +func TestQuotaAPIEstimatorPreservesProgressAcrossUpcomingResetTimeRevisionAndInactivity(t *testing.T) { + now := time.Now().Truncate(time.Second) + reset := now.Add(4 * time.Hour).Unix() + model := New(nil, time.Minute) + initial := apiEqSnapshot(10, reset) + model.snapshot = initial + model.observeQuotaAPIEq(initial, codex.LiveUsageSnapshot{}, now) + + advanced := apiEqSnapshot(12, reset+1) + usage := codex.LiveUsageSnapshot{APIEqUSD: 1, APIEqPricedCalls: 1} + model.snapshot = advanced + model.observeQuotaAPIEq(advanced, usage, now.Add(2*time.Hour)) + key := quotaAPIKey(advanced, advanced.Meters()[0]) + anchor := model.quotaAPIAnchors[key] + if anchor.usedPercent != 10 || anchor.resetAt != reset || anchor.restartReason != "" { + t.Fatalf("benign reset-time revision moved anchor = %#v", anchor) + } + if line := model.quotaAPILine(advanced.Meters()[0], 100); !strings.Contains(line, "2/5PP CLEAN MOVEMENT") || strings.Contains(line, "RESTARTED") { + t.Fatalf("progress after reset-time revision = %q", line) + } + + model.observeQuotaAPIEq(advanced, usage, now.Add(3*time.Hour)) + if line := model.quotaAPILine(advanced.Meters()[0], 100); !strings.Contains(line, "2/5PP CLEAN MOVEMENT") { + t.Fatalf("inactivity changed progress = %q", line) + } +} + +func TestQuotaAPIEstimatorRestartsWhenPreviousResetBoundaryPassed(t *testing.T) { + now := time.Now().Truncate(time.Second) + reset := now.Add(time.Minute).Unix() + model := New(nil, time.Minute) + initial := apiEqSnapshot(10, reset) + model.observeQuotaAPIEq(initial, codex.LiveUsageSnapshot{}, now) + + rolled := apiEqSnapshot(10, reset+int64((7*24*time.Hour).Seconds())) + model.snapshot = rolled + model.observeQuotaAPIEq(rolled, codex.LiveUsageSnapshot{}, now.Add(2*time.Minute)) + key := quotaAPIKey(rolled, rolled.Meters()[0]) + anchor := model.quotaAPIAnchors[key] + if anchor.usedPercent != 10 || anchor.resetAt != *rolled.Meters()[0].Window.ResetsAt || + anchor.restartReason != quotaAPIRestartWindowReset { + t.Fatalf("rolled-window anchor = %#v", anchor) + } + if line := model.quotaAPILine(rolled.Meters()[0], 100); !strings.Contains(line, "RESTARTED: WINDOW RESET") { + t.Fatalf("rolled-window reason = %q", line) + } +} + +func TestQuotaAPIEstimatorExplainsAccountingRebase(t *testing.T) { + now := time.Now().Truncate(time.Second) + reset := now.Add(4 * time.Hour).Unix() + model := New(nil, time.Minute) + initial := apiEqSnapshot(10, reset) + model.observeQuotaAPIEq(initial, codex.LiveUsageSnapshot{APIEqUSD: 2, APIEqPricedCalls: 2}, now) + + advanced := apiEqSnapshot(12, reset) + model.snapshot = advanced + model.observeQuotaAPIEq(advanced, codex.LiveUsageSnapshot{APIEqUSD: 1, APIEqPricedCalls: 1}, now.Add(time.Minute)) + line := model.quotaAPILine(advanced.Meters()[0], 100) + if !strings.Contains(line, "0/5PP CLEAN MOVEMENT") || !strings.Contains(line, "RESTARTED: LOCAL ACCOUNTING REBASED") { + t.Fatalf("accounting rebase line = %q", line) + } + if compact := model.quotaAPILine(advanced.Meters()[0], 40); len(compact) > 40 || + !strings.Contains(compact, "0/5PP") || !strings.Contains(compact, "REBASED") { + t.Fatalf("compact accounting rebase line = %q", compact) + } +} + +func TestQuotaAPIEstimatorExplainsWindowDefinitionChange(t *testing.T) { + now := time.Now().Truncate(time.Second) + reset := now.Add(4 * time.Hour).Unix() + model := New(nil, time.Minute) + initial := apiEqSnapshot(10, reset) + model.observeQuotaAPIEq(initial, codex.LiveUsageSnapshot{}, now) + + changed := apiEqSnapshot(12, reset) + plan := "business" + changed.RateLimits.PlanType = &plan + model.snapshot = changed + model.observeQuotaAPIEq(changed, codex.LiveUsageSnapshot{APIEqUSD: 1, APIEqPricedCalls: 1}, now.Add(time.Minute)) + line := model.quotaAPILine(changed.Meters()[0], 100) + if !strings.Contains(line, "0/5PP CLEAN MOVEMENT") || !strings.Contains(line, "RESTARTED: WINDOW DEFINITION CHANGED") { + t.Fatalf("window-definition line = %q", line) + } +} + func TestQuotaAPIEstimatorKeepsDivergentSamplesAtLowConfidence(t *testing.T) { now := time.Now() snapshot := apiEqSnapshot(25, now.Add(4*time.Hour).Unix()) @@ -182,6 +268,11 @@ func TestQuotaAPIAccountingBracketRequiresStableCounters(t *testing.T) { if quotaAPIAccountingEqual(left, right) { t.Fatal("changed accounting was accepted") } + right = left + right.APIEqPendingCalls++ + if quotaAPIAccountingEqual(left, right) { + t.Fatal("pending accounting was accepted") + } } func TestQuotaAPITelemetryIssueTakesPrecedenceOverOldEstimate(t *testing.T) { diff --git a/internal/version/version.go b/internal/version/version.go index 0ea708a6..c867436e 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -11,7 +11,7 @@ import ( // checkout. Release automation may override it with: // // -X github.com/merefield/codexometer/internal/version.Fallback=1.2.3 -var Fallback = "0.7.3" +var Fallback = "0.7.4" // Current returns the module version embedded by Go for tagged installs, or // Fallback for ordinary source builds. The leading tag prefix is omitted so diff --git a/internal/version/version_test.go b/internal/version/version_test.go index d02872df..1a8e4779 100644 --- a/internal/version/version_test.go +++ b/internal/version/version_test.go @@ -4,8 +4,8 @@ import "testing" func TestCurrentReportsMaintainedFallbackForSourceBuild(t *testing.T) { got := Current() - if got != "0.7.3" { - t.Fatalf("Current() = %q, want 0.7.3", got) + if got != "0.7.4" { + t.Fatalf("Current() = %q, want 0.7.4", got) } } diff --git a/main_test.go b/main_test.go index 64a12d4f..1607c8c5 100644 --- a/main_test.go +++ b/main_test.go @@ -16,7 +16,7 @@ func TestRunVersion(t *testing.T) { for _, flag := range []string{"-v", "--version"} { var stdout, stderr bytes.Buffer code := run([]string{flag}, &stdout, &stderr, dependencies{}) - if code != 0 || stdout.String() != "codexometer v0.7.3\n" || stderr.Len() != 0 { + if code != 0 || stdout.String() != "codexometer v0.7.4\n" || stderr.Len() != 0 { t.Errorf("flag=%s code=%d stdout=%q stderr=%q", flag, code, stdout.String(), stderr.String()) } } @@ -101,7 +101,8 @@ func TestRunStartsDemoWithSelectedOptions(t *testing.T) { func sameDemoAccounting(left, right codex.LiveUsageSnapshot) bool { return left.APIEqUSD == right.APIEqUSD && left.APIEqPricedCalls == right.APIEqPricedCalls && - left.APIEqUnpricedCalls == right.APIEqUnpricedCalls + left.APIEqUnpricedCalls == right.APIEqUnpricedCalls && + left.APIEqPendingCalls == right.APIEqPendingCalls } func TestRunReportsUIError(t *testing.T) {