> For the complete documentation index, see [llms.txt](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase21-session01-pricing-daily-activity-accuracy/spec.md).

# Session Specification

**Session ID**: `phase21-session01-pricing-daily-activity-accuracy` **Phase**: 21 - Non-Hermes v2.3 Usage Accuracy **Status**: Not Started **Created**: 2026-06-02

***

## 1. Session Overview

This session starts Phase 21 by porting the low-risk, high-trust usage accuracy fixes from v2.3 into AI OS without importing stale v2.3 pricing. It adds robust Claude model pricing lookup, keeps AI OS's current Opus 4.8 era rates as the source of truth, and treats genuinely unknown models as uncounted instead of silently reporting zero-dollar spend.

The session also replaces daily activity session heuristics with real per-day unique session counts. The script scanner will track daily session identity while preserving existing token, message, and cost totals; aggregate output will emit `daily[].sessions`; and the home transforms will prefer that real count while keeping the old message-based fallback for legacy generated data.

This work fits before the remaining Phase 21 sessions because Session 02 changes adjacent aggregate project and ROI shapes, and Session 03 changes the Claude usage-window contract. Getting pricing and daily activity accurate first keeps those later sessions from layering on top of misleading base metrics.

***

## 2. Objectives

1. Add a pricing helper that supports exact current AI OS model rows, Claude family fallback, explicit Claude 3.x rows, and `null` for unknown models.
2. Route spend calculation and pricing-status checks through the helper so fallback-priced Claude variants are counted and true unknowns stay excluded.
3. Track and emit real per-day unique session counts in generated `daily[]` data while preserving token, message, and cost behavior.
4. Extend the browser live-data contract and home transforms so daily activity prefers `daily[].sessions` and safely falls back for old payloads.

***

## 3. Prerequisites

### Required Sessions

* [x] `phase15-session03-aggregate-orchestration-refactor` - Provides the modular aggregate script architecture that this session must extend.
* [x] `phase20-session02-cleanup-parity-signoff` - Confirms Phase 20 is closed and Phase 21 can begin.

### Required Tools/Knowledge

* Bun 1.3.14 project commands from `package.json`.
* Current AI OS pricing table in `scripts/lib/session-scanner.ts`.
* v2.3 source anchors under `/home/aiwithapex/projects/claudeos/claude-os-v2.3/`.
* Existing scanner, aggregate, validation, and home-transform test patterns.

### Environment Requirements

* AI OS repo checked out at `/home/aiwithapex/projects/aios`.
* v2.3 source checkout available for reference only.
* No live Claude credentials or generated private live data are required.

***

## 4. Scope

### In Scope (MVP)

* An AI OS maintainer can compute spend for exact current 4.x model names using the current AI OS pricing table - keep current rates as authoritative.
* An AI OS maintainer can compute spend for Claude 3.x rows and date-suffixed or variant Claude family names - add explicit rows and family fallback.
* An AI OS maintainer can distinguish genuinely unknown model pricing - return `null` from lookup and exclude unknown spend while keeping warning metadata.
* An AI OS maintainer can trust `daily[].sessions` as a real unique session count - track per-day session sets in the scanner and emit set sizes.
* A browser consumer can read daily session counts from typed live data - extend the contract, validator compatibility, and fallback example/fixtures.
* The home dashboard can show daily activity from real session counts - prefer `daily[].sessions` and retain the old messages heuristic for legacy data.

### Out of Scope (Deferred)

* Changing AI OS's current Opus 4.8 prices to v2.3's Opus prices - Reason: Phase 21 explicitly preserves the newer AI OS pricing table.
* Replacing the modular `scripts/lib/` aggregate architecture with the v2.3 monolith - Reason: Phase 15 established the current architecture.
* Correcting `recentProjects`, adding `allProjects`, or changing skill ROI defaults - Reason: Phase 21 Session 02 owns those adjacent changes.
* Adding Claude OAuth `/usage` reads or usage-panel live badges - Reason: Phase 21 Session 03 owns that sensitive credential and network path.
* Redesigning the home UI - Reason: this session changes data semantics and transforms only.

***

## 5. Technical Approach

### Architecture

Keep the implementation in the existing AI OS script and browser contract layers. `scripts/lib/session-scanner.ts` remains the owner of JSONL scanning, model token aggregation, daily buckets, and pricing calculation. The helper can live in that file to avoid premature abstraction, unless implementation proves a focused helper module removes real complexity.

`scripts/lib/aggregate-orchestration.ts` should continue to own emitted live data assembly, rounding, sorting, pricing warnings, and validation before generated writes. Browser consumers should stay behind `src/lib/live-data-types.ts`, `src/lib/validate-live-data.ts`, and `src/lib/home-transforms.ts`.

### Design Patterns

* Extract pure functions, then test, then wire: Add pricing and transform tests before wiring the helper through aggregate output.
* Typed degradation over throws: Unknown pricing becomes an explicit uncounted state, not an aggregate failure.
* Additive live-data contract: `daily[].sessions` is optional so old generated payloads continue to validate and render.
* Deterministic output: Daily rows remain sorted and capped as before, with the new session count carried alongside existing fields.

### Technology Stack

* Bun 1.3.14 project runtime and test runner.
* TypeScript for script and browser code.
* Vitest for focused script, validation, and transform tests.
* Existing aggregate validation and generated-data write boundaries.

***

## 6. Deliverables

### Files to Create

| File                                                                                           | Purpose                                               | Est. Lines |
| ---------------------------------------------------------------------------------------------- | ----------------------------------------------------- | ---------- |
| `.spec_system/specs/phase21-session01-pricing-daily-activity-accuracy/implementation-notes.md` | Baseline notes, changes made, commands, residual gaps | \~120      |
| `.spec_system/specs/phase21-session01-pricing-daily-activity-accuracy/security-compliance.md`  | Pricing and generated-data privacy sign-off           | \~80       |

### Files to Modify

| File                                                    | Changes                                                        | Est. Lines |
| ------------------------------------------------------- | -------------------------------------------------------------- | ---------- |
| `scripts/lib/session-scanner.ts`                        | Pricing helper, compute-cost routing, daily session sets       | \~90       |
| `scripts/lib/aggregate-orchestration.ts`                | Daily session emission and pricing-status handling             | \~30       |
| `src/lib/live-data-types.ts`                            | Optional `daily[].sessions` contract support                   | \~10       |
| `src/lib/validate-live-data.ts`                         | Additive validation/default compatibility for daily sessions   | \~20       |
| `src/data/live-data.example.json`                       | Example payload compatibility for the daily session field      | \~10       |
| `src/lib/home-transforms.ts`                            | Prefer daily session counts with legacy message fallback       | \~30       |
| `scripts/lib/__tests__/session-scanner.test.ts`         | Pricing and per-day unique-session regression coverage         | \~100      |
| `scripts/lib/__tests__/aggregate-orchestration.test.ts` | Aggregate daily emission and pricing-warning coverage          | \~60       |
| `src/lib/__tests__/home-transforms.test.ts`             | Daily activity and usage-daily session fallback coverage       | \~50       |
| `src/lib/__tests__/nested-validation.test.ts`           | Validator compatibility coverage for new and legacy daily rows | \~30       |

***

## 7. Success Criteria

### Functional Requirements

* [ ] Exact current AI OS model rows still compute the same spend as before.
* [ ] Claude 3.x model rows compute with explicit prices.
* [ ] Date-suffixed or variant Claude Opus, Sonnet, and Haiku names fall back to current AI OS family rates.
* [ ] Unknown models return `null` from pricing lookup or an equivalent uncounted state, and aggregate output warns without counting spend.
* [ ] `daily[].sessions` is emitted from a unique per-day session set.
* [ ] Home daily activity and usage-daily rows prefer `daily[].sessions` and fall back to the old message heuristic only for legacy data.

### Testing Requirements

* [ ] Scanner pricing and daily session tests are written and passing.
* [ ] Aggregate emission tests prove daily session counts and unknown pricing warnings.
* [ ] Home transform and validation tests prove new and legacy payload behavior.
* [ ] Typecheck and script typecheck pass.

### Non-Functional Requirements

* [ ] No new client bundle dependency is added.
* [ ] Aggregate output remains available on unknown models, malformed JSONL rows, missing timestamps, and old generated daily data.
* [ ] Generated browser-visible data stays sanitized and does not expose raw prompts, transcripts, credentials, command output, or private paths.

### Quality Gates

* [ ] All files ASCII-encoded.
* [ ] Unix LF line endings.
* [ ] Code follows project conventions.

***

## 8. Implementation Notes

### Key Considerations

* Do not copy v2.3 Opus `$15/$75` rates. Family fallback rates must derive from the current AI OS table, including the current Opus 4.8 era `$5/$25` rate.
* Unknown model handling should preserve token/message visibility while excluding spend from totals and surfacing a clear pricing warning.
* Daily session tracking should count unique sessions per day without inflating counts for multiple assistant messages in the same JSONL session.
* `daily[].sessions` must be additive and optional so existing generated data continues to validate and render.

### Potential Challenges

* Pricing fallback can overmatch unrelated model names: Use Claude-family parsing only and keep unknown non-Claude names unpriced.
* Daily session counts can drift if the key is unstable: Prefer JSONL file path as the v2.3-compatible session key unless implementation proves an existing row session ID is more reliable for AI OS data.
* Validation may already preserve unknown daily fields: Still add contract and tests so the new field is intentional and protected.

### Relevant Considerations

* \[P01] **Bundle budget watch on 3D vendor chunks**: This session should add no client dependency and should keep home transform changes lightweight.
* \[P02] **Typed degradation over throws**: Unknown pricing and malformed JSONL rows should degrade locally instead of blocking aggregate output.
* \[P05] **Script-only runtime boundary**: Pricing and scan logic belong under `scripts/lib/`; browser code should consume validated generated data only.
* \[P08] **Local agent privacy/readiness boundary**: Browser output must remain sanitized metadata and must not expose raw paths, prompts, logs, or credentials.
* \[P15] **Full aggregate remains the compatibility command**: Keep `bun run aggregate` behavior compatible while adding daily sessions.

### Behavioral Quality Focus

Checklist active: Yes Top behavioral risks for this session:

* Unknown model pricing silently reports zero spend instead of an explicit uncounted state.
* Daily activity overcounts messages as sessions or double-counts multiple assistant turns from the same JSONL file.
* New `daily[].sessions` contract breaks old generated data or fixture-backed home rendering.

***

## 9. Testing Strategy

### Unit Tests

* Test exact current AI OS pricing rows, Claude 3.x rows, Claude-family fallback variants, cache token pricing, missing token fields, and unknown model handling in `scripts/lib/__tests__/session-scanner.test.ts`.
* Test per-day session counting with multiple assistant messages in one file, multiple JSONL files on one day, missing timestamps, malformed rows, and unknown model rows.
* Test `computeDailyActivity` and `deriveUsageDaily` prefer `daily.sessions` while preserving the legacy messages fallback.

### Integration Tests

* Extend aggregate orchestration tests to prove emitted `daily[]` rows include `sessions`, cost rounding remains stable, ordering remains deterministic, and unknown pricing warnings remain scoped to true unknown models.
* Extend validation tests to prove new daily rows and legacy daily rows both validate safely.

### Manual Testing

* Run focused Vitest files for scanner, aggregate orchestration, validation, and home transforms.
* Run app and script typecheck.
* Optionally run `bun run aggregate` only if the operator wants to refresh local generated data; do not commit generated private `src/data/live-data.json`.

### Edge Cases

* Unknown non-Claude model with tokens.
* Date-suffixed Claude family model missing an exact row.
* Claude 3.x model with explicit row.
* Empty JSONL directory.
* Malformed JSONL line.
* Assistant usage row without timestamp.
* Existing generated daily row without `sessions`.
* Daily row with `sessions: 0`.

***

## 10. Dependencies

### External Libraries

* None new.

### Internal Modules

* `scripts/lib/session-scanner.ts`
* `scripts/lib/aggregate-orchestration.ts`
* `scripts/lib/output-assembly.ts`
* `src/lib/live-data-types.ts`
* `src/lib/validate-live-data.ts`
* `src/lib/home-transforms.ts`

### Other Sessions

* Depends on: `phase15-session03-aggregate-orchestration-refactor`, `phase20-session02-cleanup-parity-signoff`
* Depended by: `phase21-session02-project-windows-skill-roi-defaults`, `phase21-session03-authoritative-claude-usage-oauth`, Phase 22 Antigravity usage consumers

***

## Next Steps

Run the implement workflow step to begin AI-led implementation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://ai-os-and-trend-finder.gitbook.io/ai-os-and-trend-finder-docs/.spec_system/archive/sessions/phase21-session01-pricing-daily-activity-accuracy/spec.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
