diff --git a/AGENTS.md b/AGENTS.md index fce30c2..38a9324 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,7 +33,8 @@ and states its assumption that the unpriced requests resemble the priced ones. through the recommendations and offers to apply each one, editing a settings file only after showing the change and getting a yes. Machine-readable output for other tools, such as quest's session export, lives in other commands and -never shapes `doctor`. +never shapes `doctor`. A change to `doctor`'s questions reruns +`assets/demo/walk.tape`, since no check runs it. - Never edit a transcript, and never print or keep prompt or reply text. - The README is for someone deciding whether to run the tool. Per-check diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5b3f3b2..bf636dd 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ PRs into `main` land by squash through GitHub's merge queue, which tests each entry against the current `main` with the required `Check` job -(`nix develop --command just check`, plus the macOS and Windows tests, or +(`just check` in the Nix dev shell, plus the macOS and Windows tests, or only `quest check` when nothing outside `quest/` and the agent docs changed). A branch only behind `main` needs no merge; merge `main` only when the PR conflicts or the queue refuses its head. diff --git a/README.md b/README.md index c2f6912..05e81ea 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ That is 1,190,393 Claude Code, Codex and T3 Code requests at public API prices. The savings are what `token-max doctor --defaults` finds for a user with no settings files on the same history: every change it would make, 8% of the spend. Most of it is a 1h subagent cache; the rest is a 1h main-agent -cache on usage credits, auto memory and unused skills and tools. +cache on usage credits, auto memory and unused or costly skills and tools. - **Subagents: a 1h prompt cache cost ~17% less than the default 5m**, ~$3,940/mo of those savings. Every Claude Code user's subagents get 5m. The setting is @@ -114,7 +114,7 @@ token-max doctor --help | Tools, skills and MCP servers | What each cost to send with every request, and how often it was used | | Instruction files | What each CLAUDE.md or AGENTS.md cost, beside the provider's size guidance | | Fast mode | What the premium cost; recommended off | -| Main-session effort | What each model and effort cost, beside the provider's guidance; `max` recommended down to `xhigh`, `low` worth considering raising | +| Main-session effort | What each model and effort cost, beside the provider's guidance; `max` recommended down to `xhigh` (or `high` where a model lacks it), `low` worth considering raising | | Auto memory | What loading, reading and writing it cost, and how often it was used; worth considering off | | Prompt suggestions, recaps, check-ins | What each background feature cost, where it can be estimated | | Bash timeout cap | Whether long foreground waits let the cache expire | diff --git a/assets/demo/walk.tape b/assets/demo/walk.tape index 50f7f20..f1a83ee 100644 --- a/assets/demo/walk.tape +++ b/assets/demo/walk.tape @@ -27,6 +27,11 @@ Show Type "token-max doctor" Sleep 500ms Enter +Sleep 2s +# How the profile pays: usage credits, so its main agent's default cache is 5m. +Type "a" +Sleep 300ms +Enter Sleep 4s Type "y" Sleep 300ms diff --git a/docs/reference.md b/docs/reference.md index d8fb5dd..1deb994 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -48,12 +48,12 @@ once, as a diff. A change whose saving was not measured, such as raising an effort, comes after the measured ones and says so. A change saving $5/mo or more is its own question. A smaller one joins a group -of its kind and reason: never used, no use recorded where the window cannot -rule one out, over `--max-cost-per-use` per use, or a redundant copy of a -Codex catalog skill whose most-used copy stays, such as never-used skills -or MCP servers over $1 per use. Each reason is its own group, so one yes never -covers a feature in use. A group is one question ranked by its combined saving, -which names every member and takes `y` for all, `n` for none or `o` to go +of its kind and reason, such as never-used skills or MCP servers over $1 per +use. The reasons are never used, no use recorded where the window cannot rule +one out, over `--max-cost-per-use` per use, and a redundant copy of a Codex +catalog skill whose most-used copy stays. Each reason is its own group, so a yes to +never-used features never also removes one in use. A group is one question ranked by its combined saving, +which names every member and takes `y` for all, `n` for none, `q` to quit or `o` to go through them one at a time; a group of one is asked as that change. Features whose savings were not measured, such as Codex catalog skills, are grouped the same way after the measured questions. A group saving under $1/mo in total, @@ -299,7 +299,7 @@ changes it, and the list ends with the source: | --- | --- | | Main-agent prompt cache TTL, while unset | Claude Code [requests 1h](https://code.claude.com/docs/en/prompt-caching#which-ttl-each-request-gets) for the main conversation on a Claude plan within its included usage, and 5m once usage credits or an API key pay for it. When `doctor` asked how the profile pays, the line shows that default, such as `1h (default)`, and prices against it alone. Otherwise token-max can't tell which applies, so the line shows `unset` and names both. When the replay picks a winner, setting it is the cheaper choice either way, so the line recommends `unset -> 1h` (or `5m`) and `doctor` offers to set it; it shows the replay's gap as "saves up to", saved only while the other default would apply. | | Claude fast mode | A Claude plan [pays fast mode only from usage credits](https://code.claude.com/docs/en/fast-mode#requirements), at its API rates, even with plan usage left. | -| Codex fast mode | A ChatGPT plan [counts Fast at 2.5x and Ultrafast at 8x](https://learn.chatgpt.com/docs/pricing) standard against included usage, and 2x and 6x on credits. The API premium priced is 2x for Fast on GPT-6 and GPT-5.6 and 6x for Ultrafast, so included usage can draw faster than it shows. | +| Codex fast mode | A ChatGPT plan [counts Fast at 2.5x and Ultrafast at 8x](https://learn.chatgpt.com/docs/pricing) standard against included usage, and 2x and 6x on credits. The API premium priced is the [documented API rate](semantics.md#speed-controls-and-premiums), which can be lower, so included usage can draw faster than it shows. | | Prompt suggestions | Claude Code [skips them](https://code.claude.com/docs/en/costs#background-token-usage) while a plan is near its usage limit, which the estimate, run on every eligible turn, cannot see. | | Fable weekly use | Anthropic [caps Fable models](https://support.claude.com/en/articles/15424964-claude-fable-models-on-your-plan) at up to half the weekly usage limit on Max, Ultra and Team and seat-based Enterprise premium seats, drawing it faster than other models, runs them on usage credits on Pro and Team and seat-based Enterprise standard seats, and bills them at API rates on usage-based Enterprise. The line shows weekly API-price spend and no share of the cap, as [Fable weekly use](#fable-weekly-use) explains. | | Codex compaction window and keepalive pings | ChatGPT credits [charge cache writes as ordinary input](https://learn.chatgpt.com/docs/pricing), while API prices from GPT-5.6 on charge 1.25x for a 30-minute write, so a replay that trades writes for reads can come out differently on credits. | @@ -386,11 +386,12 @@ The kinds of claim are: keepalive pings, background generation, tool output caps, and every tool, skill and MCP server, with subagent types and context no setting turns off. - **Official**: the provider's own guidance beside what the transcripts show: - CLAUDE.md length and the AGENTS.md byte budget, MCP tool loading, and - Fable's weekly use beside the plan rule. A Claude + CLAUDE.md length and the AGENTS.md byte budget, MCP tool loading, + main-session effort, and Fable's weekly use beside the plan rule. A Claude subagent type's evidence also cites Anthropic's model guide. - **Opinion**: the maintainer's preference, beside whatever was measured: fast - mode off and auto memory off. + mode off, auto memory off, raising a `low` effort, and lowering a Codex + `max` effort. The lines come in two groups. **Changes** come first: every line recommended (red, exit 1) or worth considering (yellow, exit 0), ranked together by what @@ -705,8 +706,7 @@ the verdict in its color, the saving green, and labels dim. `NO_COLOR` disables color, and `--plain` also disables decorative Unicode, and either puts the verdict word back in place of the dot. Evidence cards keep their verdict words and only add color, and each names its claim. Redirected output -is plain, and progress appears only on interactive stderr. SIGINT or SIGTERM ends -with exit 2 and no success report. +is plain, and progress appears only on interactive stderr. Unicode decorations require a UTF-8 locale. Progress is one line that shows each phase in turn, never an invented percent, and clears itself before the report. @@ -718,9 +718,10 @@ as the session export below. IDs in the report are opaque hashes. Shared histories are read once, and a request whose profile is ambiguous counts once on the line its profiles share -(see [Profiles](#profiles)). Independent check savings must not be summed; the -walk's running total and the [savings against the defaults](#savings-against-the-defaults) -are the only sums, and each says that overlapping settings may save less. +(see [Profiles](#profiles)). Independent check savings must not be summed; +every total the report gives, such as the walk's running total or the +[savings against the defaults](#savings-against-the-defaults), says that +overlapping changes may save less. ## Session export @@ -988,7 +989,7 @@ connection that then runs the audit: runs the first installed `token-max` whose `--version` matches, on the non-interactive `PATH`, then in the release installers' directory (the first of `$XDG_BIN_HOME`, `$XDG_DATA_HOME/../bin` and `~/.local/bin`), - then in `~/.cargo/bin`. With neither, the destination downloads the + then in `$CARGO_HOME/bin` (default `~/.cargo/bin`). With neither, the destination downloads the release from GitHub and checks it against its published checksum, which needs `curl`, `tar` and `xz` there. Matching the version is not matching the build, so a destination whose build differs from this one fails, @@ -1021,9 +1022,8 @@ too small. Any failed host, connection or stream before the reports are printed fails the whole run with exit 2 and no report, and Ctrl-C then stops every destination. After the reports, a failure during the walk, a Ctrl-C during its questions, or a -Ctrl-C after the yes that leaves a host unwritten also exits 2, as -[On SSH hosts](#on-ssh-hosts) describes. On a terminal, `doctor` walks through every -host's changes and writes each on its own host, as +Ctrl-C after the yes that leaves a host unwritten also exits 2. On a terminal, +`doctor` walks through every host's changes and writes each on its own host, as [On SSH hosts](#on-ssh-hosts) describes. Each host's percents are of that host's own spend, and the total's of the hosts' spend together. @@ -1052,8 +1052,8 @@ activity, and their metadata does not establish whether they are keepalive pings The maintainer's cost preference is fast mode off for both harnesses. The `fast-mode` check names the current effective local preference, its owner and the standard-speed replacement: Claude `fastMode: false`, or Codex -`service_tier = "default"`. Use `/fast off` for an active session. No settings -are edited. A justified current premium preference causes exit 1 even without +`service_tier = "default"`, which `doctor` offers to make when the profile's +own file owns the setting. Use `/fast off` for an active session. A justified current premium preference causes exit 1 even without historical usage or prices. Standard current settings never receive a change because of historical premium sessions. diff --git a/docs/releasing.md b/docs/releasing.md index f0fccff..1685b8b 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -34,7 +34,7 @@ Each release carries, per target, `token-max-.tar.xz` (a `token-max-/` directory holding the binary, README and LICENSE) or, on Windows, a flat `token-max-.zip`, each with a `.sha256` file; `token-max-installer.sh` and `token-max-installer.ps1`, which install into -the first of `$XDG_BIN_HOME`, `$XDG_DATA_HOME/../bin` and `~/.local/bin`; `source.tar.gz`; and `sha256.sum` over the archives. Every +the first of `$XDG_BIN_HOME`, `$XDG_DATA_HOME/../bin` and `~/.local/bin`; `source.tar.gz` with its `.sha256`; and `sha256.sum` over the archives. Every asset gets a GitHub build provenance attestation, which `gh attestation verify --repo kixel-ai/token-max` checks. `[package.metadata.binstall]` in `Cargo.toml` points `cargo binstall` at the diff --git a/docs/results.md b/docs/results.md index 6caf2c5..00575c6 100644 --- a/docs/results.md +++ b/docs/results.md @@ -48,10 +48,11 @@ Against the maintainer's current settings, the changes doctor still offers save ~$781/mo. Their settings already save ~$4,452/mo against the defaults, as each report's "Compared with defaults" line gives it: the 1h caches the plan profiles set, less the small cost of the 1h subagent cache on the usage -credits profiles. +credits profiles. Each figure adds up changes measured one at a time against +a different baseline, so together they need not equal the ~$5,653/mo above. -doctor asked how each Claude profile pays, and each answer came from the -profile's account (`oauthAccount.billingType` in its `.claude.json`): every +doctor asked how each Claude profile pays, and the maintainer answered from +the profile's account (`oauthAccount.billingType` in its `.claude.json`): every machine's `~/.claude` is on a plan, and the usage credits profiles, plus an archived profile with no account, were answered as API. Every offered change was declined, and no settings file changed. @@ -71,7 +72,7 @@ The plan profiles' subagent line is now priced, so its ~$3,940/mo is in the savings above. The previous snapshot left it out as "not enough evidence": T3 Code shares those profiles' histories, and doctor could not tell whether a T3 session ran under the profile's setting. It now reads the shared settings file -for the controls T3 leaves alone. [How context is priced](reference.md#how-context-is-priced) +for the controls T3 leaves alone. [T3 Code](reference.md#t3-code) describes the rule. On the usage credits profiles, whose main agent gets 5m unless set, 1h is the ~$518/mo in the savings; on their few subagent requests 5m was cheaper, by ~$3.63 over the window. diff --git a/docs/semantics.md b/docs/semantics.md index 74afe0c..363b587 100644 --- a/docs/semantics.md +++ b/docs/semantics.md @@ -26,9 +26,9 @@ The report counts skipped lines, and `--details` the files with a deferred final Records whose timestamp proves they precede `--since` stay outside selected billing and usage coverage. Claude requests and compaction boundaries are retained -separately in `scan.cacheContext` for predecessor, bracket and summary-link evidence, +separately in `Scan.cache_context` for predecessor, bracket and summary-link evidence, and user prompts for per-session thresholds such as a recap's three turns. -`scan.since` records the billing selection; checks inherit it, and a comparison +`Scan.since` records the billing selection; checks inherit it, and a comparison cannot expand an already filtered scan to an earlier billing window. Invalid pre-window usage becomes an unknown cache state, never a billed estimate or silently discarded attempt; it does not fail selected billing validation. Selected @@ -100,8 +100,8 @@ shared history stay unknown. Historical spend is never assigned to all aliases. OpenAI input includes cached reads and writes; output includes reasoning. On GPT-5.6 and later GPT families, recorded writes replace ordinary input at total -rates of 1.25x for 30m and 2.5x for Responses-only 12h. Missing write counters stay -unknown. An unsplit recorded write count uses an explicit default-30m assumption; +rates of 1.25x for 30m and 2.5x for Responses-only 12h. Missing write counters, or a split +that names only one lifetime, stay unknown. An unsplit recorded write count uses an explicit default-30m assumption; 12h attribution is unknown, not derived from the catalog's single write field. Earlier GPT models have no additional write charge. ChatGPT credits charge no separate cache write ([Codex pricing](https://learn.chatgpt.com/docs/pricing), @@ -109,8 +109,8 @@ checked 2026-11-14); replays keep the API write rate, and Codex compaction and keepalive lines say so. The [OpenAI caching guide](https://developers.openai.com/api/docs/guides/prompt-caching), checked 2026-11-07, documents the subset and lifetime rules. For catalog entries -with the legacy `context_over_200k` field, supported GPT-5.4/5.5/5.6 and GPT-6 models -use the documented 272,000-input threshold, including reads and writes. A +with the legacy `context_over_200k` field, the GPT models `threshold` in +`src/prices.rs` lists use the documented 272,000-input threshold, including reads and writes. A contradictory explicit tier fails pricing. The full request is repriced when a counterfactual crosses a tier. See [OpenAI pricing](https://developers.openai.com/api/docs/pricing). @@ -120,7 +120,7 @@ one-hour writes derive the documented 2x ordinary-input rate. US inference uses the documented 1.1x multiplier. Supported fast Opus rates use the documented 2x factor across the full context window; other speed/tier combinations remain unknown. Absent geography and the older `not_available` sentinel use the labelled -global API-equivalent assumption, without claiming an observed region. Server web search adds its public per-search fee. Web fetch has no extra +global API-equivalent assumption, without claiming an observed region. Server web search adds its public per-search fee on the Anthropic provider; elsewhere the fee is unknown, so the request is unpriced. Web fetch has no extra fee. Code-execution charges remain unknown without runtime, tool version, and free-allowance evidence. Client-side calls add no separate server-tool charge. These rules and Haiku 5.5's 100,000-input threshold are from @@ -233,8 +233,9 @@ the selected window. Sensitivity does not veto the aggregate estimate. Unsupport remain unknown and block only their affected comparison. No attempt is silently excluded or assigned observed zero billing. -Current TTL resolution follows force-5m, bucket environment, bucket setting, -enable-1h, then defaults. Shell overrides apply only to the active config root; +Current TTL resolution follows disabled caching (no TTL), force-5m, bucket +environment, bucket setting, enable-1h, then defaults: 5m for subagents, and for +a main bucket on Bedrock, Vertex or Foundry. Shell overrides apply only to the active config root; each profile's settings environment is read separately. Whether a main request is within a Claude plan's included usage or paid by usage credits is not inferred from credential files, so its unset default is unknown, and the line @@ -332,7 +333,7 @@ value and the capped window. A capped user or managed global window is owned by the model's `modelSettings` row, the only setting that changes it alone; a capped environment or T3 window applies to every model, so it stays advisory. Either owner then names what caps it, the variable and value or the cap itself. -Per-model controls require v2.1.288; environment suffixes require +Window controls require v2.1.288; environment suffixes (`k`, `m`) require v2.1.304. Project, launch and per-agent overrides remain an explicit limitation of the observed-file analysis. See [Claude model configuration](https://code.claude.com/docs/en/model-config#context-window-and-auto-compaction) and [settings reference](https://code.claude.com/docs/en/settings-reference#modelsettings), @@ -401,8 +402,8 @@ compaction on/off policy is evaluated afterward as described below. `idle-compaction` compares on/off at current TTL/window settings and again after applicable TTL/window changes. Each owning idle toggle gets an aggregate delta, on cost minus off cost, across request gaps and final observation periods. -Negative favors on, positive favors off, and exact zero retains the current -value. Only the latter configuration decides the toggle. Independent savings +Negative favors on, positive favors off, and exact zero is evidence for +neither, so the line stays advisory. Only the latter configuration decides the toggle. Independent savings are not additive. Dollars are API-price equivalents, not invoices. Current idle controls resolve user, project, local and managed settings, with @@ -516,8 +517,8 @@ include summary-only final periods. ## Keepalive pings `keepalive` replays each session sequentially for no pings and every candidate -cap. Pings fire every five sixths of the cache lifetime after a main request: -50 minutes under a 1h TTL, below the estimated native idle-compaction trigger at +cap. Pings fire every five sixths of the cache lifetime after a main request, +such as 50 minutes under a 1h TTL, below the estimated native idle-compaction trigger at 54 minutes, and 25 minutes under Codex's documented 30-minute minimum. Each ping uses the preceding main request's pricing metadata, reads its accumulated context, and adds a prompt and reply. Prompt size is the median growth between compatible @@ -556,8 +557,9 @@ by final pings are included in their cost and removed in the closed sensitivity. Codex periods are priced only for models with billed 30-minute writes, whose lifetime is documented and refreshed by reads ([OpenAI prompt caching](https://developers.openai.com/api/docs/guides/prompt-caching), -checked 2026-11-08). Recorded uniform 12-hour writes keep their actual write -rate and long coverage; a 30-minute ping preserves that existing expiry. +checked 2026-11-08). Codex pings every 25 minutes whatever the write lifetime. Recorded uniform +12-hour writes keep their actual write rate and long coverage, and the ping +merely preserves that existing expiry. Mixed write lifetimes leave prefix geometry unresolved. Older models' retention is a range. Every cap compares the same fully priced sessions, and every dollar figure is extrapolated from them to @@ -574,7 +576,7 @@ Neither harness has a native mechanism for capped idle pings. ## Shared component measurements -`scan.exposure` adds historical component revisions, request views, and invocation +`Scan.exposure` adds historical component revisions, request views, and invocation evidence. Components retain Unicode character counts, opaque identities and fingerprints, source locations, one owner (`skills` or `context`), and a server/namespace attribution key, or a plugin key where the record explicitly @@ -605,7 +607,7 @@ inherited; conflicting copied histories leave exposure unknown. Current effectiv enablement remains separately unresolved. No installed/current file size is used to establish historical exposure. -`report.exposure` publishes empirical calibration samples only for linked, +`Report.exposure` publishes empirical calibration samples only for linked, measured, single-part, complete text-only inputs with a matching request/response model, grouped by harness, model and provider. Claude requests that record a shape and only known text message blobs are complete. A blob holding an image, @@ -619,7 +621,7 @@ primitive. Without matching calibration, output keeps characters and unknown tokens/dollars. Images, opaque blocks, deferred definitions, digest-only requests, and multi-iteration totals cannot calibrate partial text. -`report.context` prices each piece of recurring context. Claude requests +`Report.context` prices each piece of recurring context. Claude requests with a recorded `api-request-shape` or full parameters qualify: tool definitions, then the system prompt, lead the prompt in recorded order. Codex requests qualify through their candidate `world_state` and `additional_tools` @@ -645,7 +647,7 @@ falls in the same cache slot; otherwise it stays unpriced for that request. A row with any unpriced piece in a request, such as an MCP server whose tool is priced but whose instructions are not, is unpriced for that request. Each piece's calibrated tokens are charged at the slot they fall in: cached reads, then 1h writes, then -5m writes, then ordinary input, at the request's model, provider and context +5m writes (for Codex, its recorded 30m or 12h writes), then ordinary input, at the request's model, provider and context tier. A request whose calibrated pieces exceed its recorded input is left unpriced rather than clipped. A piece's cost covers priced requests only; its estimate scales that to every request that carried the piece and is unknown @@ -658,8 +660,8 @@ shares conserve the aggregate's priced charge without charging it twice. Each row scales only its own priced observations; estimates for changing membership can have different coverage and must not be summed as a catalog counterfactual. -MCP tools group by server. Each server also has `details`: `mcp-tool` rows -for individually recorded tool schemas and `mcp-discovery` rows for recorded +MCP tools group by server. Each server also has `details`: `ContextKind::McpTool` rows +for individually recorded tool schemas and `ContextKind::McpDiscovery` rows for recorded discovery text. Each schema occupies its input position once, while its charge also credits the server total. Parent coverage remains unpriced for a request with any opaque member even when some detail rows can be priced. Tool calls @@ -677,7 +679,7 @@ session has no request, and count on every row that shares a settings file with them. A request no selected profile owns, such as one of a T3 instance removed from settings, has no setting to change and prices no row; it stays in the bill. -Tool results are `tool-output` rows, one per tool and one per MCP server. A +Tool results are `ContextKind::ToolOutput` rows, one per tool and one per MCP server. A result stays in the conversation until it compacts: output the previous request held is carried, and output beyond it is new, under the bounds above. A result that is not plain text, such as an image, leaves its row unpriced for that @@ -723,17 +725,17 @@ transcript files. A copy cannot say which profile made a call, so it counts for every row of its tool that shares a profile with it; skill uses count only the model's Skill calls, since a hidden skill can still be typed, except where the switch removes the skill entirely, where typed requests count too. A piece still sent -today with a positive cost and no recorded use is recommended off (`verdict: -"off"`, exit 1), whatever the amount, when the first shaped request in the +today with a positive cost and no recorded use is recommended off (`Verdict::Off`, +exit 1), whatever the amount, when the first shaped request in the window of one of its profiles already carried it and none of its profiles' transcripts could hide a call to it. An unreadable line could if its bytes name the piece (see below), or if its transcript has a tool result whose id matches no parsed call, a sign that a record was cut off; so could a deferred line. One every profile first sent later, one whose profile's transcripts could hide a call, or a Codex catalog -skill, whose uses are only partly recorded, gets `"consider"`, an advisory that exits -0, since the window cannot rule out a use. A used piece whose `estimatedUsd` -divided by its uses (`costPerUseUsd`) exceeds `maxCostPerUseUsd` (default $1, -`--max-cost-per-use`) also gets `"consider"`; otherwise it is kept. The ratio +skill, whose uses are only partly recorded, gets `Verdict::Consider`, an advisory that exits +0, since the window cannot rule out a use. A used piece whose `estimated_usd` +divided by its uses (`cost_per_use_usd`) exceeds `Report.max_cost_per_use_usd` (default $1, +`--max-cost-per-use`) also gets `Verdict::Consider`; otherwise it is kept. The ratio does not depend on the window's length. A piece with no priced request or unresolved service-tier evidence gets no verdict. Duplicate Codex copies can still receive a path-based recommendation without dollars. The cost is gross: removing a piece leaves later @@ -753,7 +755,7 @@ file, the reader also hashes every tool result id and call id in the parsed records and the whole `tool_use_id`, `call_id` and, for an output with no `call_id`, `id` values in unreadable lines; an id cut off inside its value is not read. Results whose id matches no parsed call, anywhere in the file and not only -in the `--since` window, are `unmatchedResults`. Claude pairs `tool_use` blocks +in the `--since` window, are `Unreadable.unmatched_results`. Claude pairs `tool_use` blocks with `tool_use_id`; Codex pairs `*_call` and `*_call_output` response items by `call_id`. The id evidence cannot name the cut call's feature, so a file with unreadable lines and any @@ -778,7 +780,7 @@ never retained. Different paths sharing a name remain separate rows; repeated identical entries contribute all of their rendered characters to that path's row, with requests counted once. Replacing aliases also changes member identity. -`context[].skill` publishes the resolved path, requested and loaded evidence, +`ContextCost.skill` publishes the resolved path, requested and loaded evidence, ambiguous requests, duplicate entry count, and preferred retained path. `calls` counts distinct observed user turns per skill, coalescing requests and loads in that turn so they cannot inflate the cost-per-use denominator. @@ -915,7 +917,7 @@ keep once it is off, and never exits 1: notes the agent writes for itself skip the review that checked-in `CLAUDE.md` or `AGENTS.md` gets, which encourages slop, so the maintainer advises it off whatever it cost, as an opinion. `--max-cost-per-use` does not apply. The check reports the total cost, the reads and writes, and the setting -that turns it off; its `savingsUsd` is that total. Once memory is off, the line +that turns it off; its `savings_usd` is that total. Once memory is off, the line still shows what it cost and how often it was used earlier in the window. Requests that recorded no context keep the memory files they were measured to read back, and are assumed to have loaded memory as often as those that did, so @@ -942,7 +944,7 @@ unmeasured, and the check says how many did. Today's setting decides whether memory is on, as every other check reads today's settings. It is resolved at the working directory of the latest main-agent request, where the user worked most recently, including the project's `.claude/settings.json` and -`.claude/settings.local.json`, so `offFile` names the file that owns it. Claude +`.claude/settings.local.json`, so `off_file` names the file that owns it. Claude Code reads the setting when a session starts, so a session begun before a change keeps the old value until it restarts. When main-agent sessions in that directory disagree with the setting at their latest request with a recorded @@ -960,11 +962,11 @@ request whose reply made the call, using that model's calibrated token ratio; writes without one stay unpriced rather than zero. [Codex](https://developers.openai.com/codex/memories) memories are off unless -`features.memories = true`, or both `memories.use_memories = false` (which +`features.memories = true`, and stay off when both `memories.use_memories = false` (which keeps them out of the prompt) and `memories.generate_memories = false` (which stops new ones) are set. With each full context Codex 0.167.0 adds a developer message part tagged `memories.instructions` holding `memory_summary.md`, split into several -parts when long; earlier versions start it with `## Memory`. A full world +parts when long, its first part starting `## Memory`. A full world state leaves it in context. Compaction rebuilds it: the summary in the `compacted` record's `replacement_history` takes its place, and without one it is gone. The settings decide whether memory is on, resolved like Claude Code's @@ -985,8 +987,8 @@ extrapolated over, or leave the cost unknown, even with memories off now, since while memories were on. A missing summary shows nothing, since it appears only once one has been written. Uses are the dedicated `memories` tools (`list`, `read` and `search` as reads, -`add_ad_hoc_note` as a write priced like a Claude write, at the 4-characters-per-token -rule of thumb) and shell reads under `/memories/` or +`add_ad_hoc_note` as a write priced like a Claude write, falling back to the +4-characters-per-token rule of thumb without calibration) and shell reads under `/memories/` or `memories_v2/`. Dedicated tool output moves to the memory row; shell output stays on the shell's row. Extraction and consolidation run as requests Codex records only in telemetry, so their cost is not measured: wherever memories may @@ -1044,8 +1046,8 @@ response before the next user prompt, or the session's last response. Only interactive terminal turns count (`entrypoint` `cli`, `querySource` `repl_main_thread` or absent); SDK and desktop clients run suggestions only when they ask for them, which transcripts do not record, so those turns are counted -in the uncertainty instead. A suggestion follows a turn with at least two -responses whose last response sent and wrote at most 10,000 uncached tokens, +in the uncertainty instead. A suggestion follows any turn after the session's first +response when its last response sent and wrote at most 10,000 uncached tokens, the client's cold-cache cutoff. A recap follows a turn once the session has three user turns and the next prompt came at least three minutes later. Each later recap requires two new user turns after the preceding modeled recap. A final @@ -1066,15 +1068,15 @@ live prefix refreshes it at response completion, which can keep a later recap warm. A recap that reads a live prefix refreshes it at the recap's start. When turning a feature off expires the prefix before the other feature or the next recorded request reads it, the extra ordinary recap input or cache rewrite is -subtracted from the saving as `lostWarming`. Only reads +subtracted from the saving as `lost_warming`. Only reads on the same model, speed and provider count, up to the prefix the recap read. Turns without recorded usage are scaled from the priced ones, and with none priced the check is unknown. Uses (an accepted suggestion, a read recap) are not recorded, so nonuse is never proven and the check never recommends a change: a feature that cost more than -`--max-cost-per-use` over the window is worth considering off (`action: -"advisory"`, exit 0), and one that cost less is kept, since it cannot have cost +`--max-cost-per-use` over the window is worth considering off (`Action::Advisory`, +exit 0), and one that cost less is kept, since it cannot have cost more than that per use. Goal check-ins start ordinary-looking task notification turns and Codex does not record automatic recaps, so both report an unknown cost and stay advisory. Each line names where to turn the feature off: @@ -1089,14 +1091,14 @@ checked 2026-11-08. ## Speed controls and premiums -`checks` includes the `fast-mode` variant, using the same report, rendering, +`Report.checks` includes the `CheckResult::Speed` variant, using the same report, rendering, evidence, action and exit policy as the other checks. Its `current` and `recommended` values describe speed after known disabling controls; -`replacement` names the owning setting syntax. `observed.premium` is the selected +`replacement` names the owning setting syntax. `SpeedCheck.observed.premium` is the selected window's rate-only premium at present API rates, with known subtotal and unknown -total kept separate. `currentEstimate.premium` applies the current effective +total kept separate. `current_estimate.premium` applies the current effective speed preference to those tokens. Only the latter supplies this check's -`savingsUsd` when it recommends a change. It is a rate-only comparison, not net +`savings_usd` when it recommends a change. It is a rate-only comparison, not net of cache switching. A standard current preference keeps, regardless of old premium usage. No records means unknown dollars, not zero. @@ -1111,7 +1113,7 @@ Its local system/user files and requirements are inspected. Legacy new `NAME.config.toml` files require an unobserved `--profile` selection. Those scopes and project trust/launch selection stay advisory when unresolved. -Requested controls have their own `Request.requestedSpeed` metadata and never +Requested controls have their own `Request.requested_speed` metadata and never populate billed `BillingPart.tier`/`speed`. In particular the native [Codex TokenUsageRecord schema](https://github.com/openai/codex/blob/main/codex-rs/protocol/src/protocol.rs) contains no billed tier. Native Codex historical premiums therefore remain @@ -1122,9 +1124,10 @@ even where the general historical cost estimate labels a standard-speed assumption. Each sampling iteration keeps its own model and billing metadata. The [OpenAI API price table](https://developers.openai.com/api/docs/pricing), -checked 2026-11-07, gives supported GPT-6 and GPT-5.6 fast rates at 2x standard, -GPT-5.5 at 2.5x and GPT-5.4 at 2x below/equal 272K input. Verified ultrafast rates -for GPT-6 Astra and GPT-6.1 Sol are 6x across their context tiers. Older or +checked 2026-11-07, gives fast rates at 2x standard for GPT-6 and GPT-5.6 models, +and GPT-5.5 at 2.5x and GPT-5.4 at 2x, each only at or below 272K input; ultrafast +is 6x across context tiers. `premium_multiplier` in `src/prices.rs` lists the +verified models. Older or unsupported combinations remain unknown. These API rates differ from a ChatGPT plan's multipliers, Fast at 2.5x and Ultrafast at 8x standard against included usage and 2x and 6x on credits @@ -1234,16 +1237,20 @@ form, and anything else, zero or negative falls back to the default (600000 ms maximum, 120000 ms default timeout). The effective cap is the larger of the two, so lowering only the maximum cannot override a larger default; the replacement names both when needed. Project and local settings are not read for this check. +The recommended cap is 4 minutes under a 5m TTL and 55 minutes under 1h, leaving +room for the starting request's output and the reply (`safe_cap` in +`src/bash.rs`). The compared TTL is the main-agent TTL check's verdict when it has one, else the current `promptCacheTtl`, else the write lifetime of the latest selected -main-agent request; with none, the check is advisory. Claude Code 2.1.319 moves +main-agent request; with none, or when recorded projects set the main TTL +differently, the check is advisory. Claude Code 2.1.319 moves commands in async subagents with a 5m cache to the background after 3 minutes on its own, so the subagent TTL does not set the cap. The reader keeps three facts per Claude `Bash` call in `StructuralEvent.shell`: `background` from `run_in_background`, `polls` when the command's words include -`sleep`, `do` and a `while`, `until` or `for` loop, and `timedOut` when the +`sleep`, `do` and a `while`, `until` or `for` loop, and `timed_out` when the result's `toolUseResult.timedOutAfterMs` is a number and the message holds one tool result. The command and its output are never retained. A wait runs from the request that started the call to its result. It is long when it reaches the @@ -1286,10 +1293,10 @@ checked 2026-11-14, first match winning: A user-file top-level `effortLevel` is the older form, which Opus 5.5, Sonnet 5.5, Haiku 5.5 and Fable 5.2 ignore. Settings accept `low` to `xhigh`; any other value is an error. -4. The model's default: `medium` for Fable 5.2, Opus 5.5, Sonnet 5.5 and +4. The model's default (`claude_model` in `src/effort.rs`): `medium` for Fable 5.2, Opus 5.5, Sonnet 5.5 and Haiku 5.5, `xhigh` for Opus 4.7, `high` for the other models in the docs' - effort table. A model outside the table takes no level; an unknown model - leaves the line unknown. + effort table. Older models the table lists without effort support take no + level; a model it does not list leaves the line unknown. The level then runs at the highest level the model supports at or below it (`xhigh` runs as `high` on Opus 4.6 and Sonnet 4.6), lowered to the lowest @@ -1345,7 +1352,8 @@ A run's model source follows Claude Code 2.1.322: the Agent call's `model`, then the agent definition's `model:`, then `CLAUDE_CODE_SUBAGENT_MODEL`, then the main model. `CLAUDE_CODE_SUBAGENT_MODEL_FORCE` drops the call and definition models, so the line then names the variable as the setting to change. A user or project agent file with a built-in's name replaces it. Built-in -Explore and Plan say `inherit`, so the variable never reaches them; Explore is +Explore and Plan say `inherit`, so only `CLAUDE_CODE_SUBAGENT_MODEL_FORCE` lets +the variable reach them; Explore is capped at Opus on the first-party API when the main model ranks above it (Fable, Mythos), unless `CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP` is set, and ran on Haiku before @@ -1389,7 +1397,8 @@ as YAML scalars without trailing comments. The cheapest current model is, among the provider's catalog models that are not deprecated, call tools and reply in text, the newest of each family with the lowest output then input rate: the newest Haiku for Anthropic, the cheapest -current GPT for OpenAI. The reprice swaps only the model on each recorded part, +current GPT for OpenAI (`Catalog::cheapest` in `src/prices.rs`, which also needs +known input, output and cache-read rates). The reprice swaps only the model on each recorded part, keeping its tokens, cache categories, speed and geography, so it assumes the same turns. A type already on that model is not repriced. A lower effort changes the output tokens, so its cost is not measured. diff --git a/docs/t3.md b/docs/t3.md index 9ec05e9..a28b198 100644 --- a/docs/t3.md +++ b/docs/t3.md @@ -315,11 +315,11 @@ belongs to the native profiles unless its originator is `T3 Code` or missing, which keeps it shared. A subagent whose root session excluded T3 excludes it too. A session whose every T3 owner is an instance no longer in T3's settings ran under controls that no longer exist: its requests -stay in the bill under that instance, named on a `T3 removed` report line and -counted in `scan.t3[].removed`, and leave every current profile's checks and +stay in the bill under that instance, counted by instance on a `T3 removed` report +line, and leave every current profile's checks and context costs. An owner still in settings but under another home stays unresolved. Each request -that stays unresolved is counted under its cause in `scan.t3[].unresolved` and -on a `T3 unresolved` report line. A `--t3-dir`-only selection still selects configured native +that stays unresolved is counted under its cause on a `T3 unresolved` +report line. A `--t3-dir`-only selection still selects configured native history directories, not a proven T3-session-only filter; retained shared records keep a named advisory profile rather than becoming anonymous charges. diff --git a/quest/m1/audit-docs.md b/quest/m1/audit-docs.md deleted file mode 100644 index 6f0d086..0000000 --- a/quest/m1/audit-docs.md +++ /dev/null @@ -1,9 +0,0 @@ -# [M] Audit the docs - -## Goal - -Run the `docs` audit: `quest audit docs` prints what it checks, what each finding becomes, and how to plan its next run. - -## Audit - -- docs diff --git a/quest/m1/missing-docs.md b/quest/m1/missing-docs.md new file mode 100644 index 0000000..7184565 --- /dev/null +++ b/quest/m1/missing-docs.md @@ -0,0 +1,11 @@ +# [S] Gate missing docs on the library's exports + +## Goal + +Every item `src/lib.rs` exports has a one-line doc comment, and `#![warn(missing_docs)]` in `src/lib.rs` keeps new ones from landing, since CI's clippy runs with `-D warnings`. + +## Plan + +[kixel-ai/token-max#174](https://github.com/kixel-ai/token-max/pull/174) made the library's modules private and re-exports only what `src/main.rs` and `tests/` use, so the lint no longer reaches every field in `src/model.rs`. +Adding the lint to the merged code reports 48 items: 24 enum variants and 9 fields in `src/model.rs`, 7 fields in `src/cli.rs`, 4 in `src/discovery.rs`, 3 in `src/prices.rs` and 1 in `src/reader.rs`. +Document each in one plain line, then add the lint. diff --git a/quest/m2/audit-docs.md b/quest/m2/audit-docs.md new file mode 100644 index 0000000..08e2831 --- /dev/null +++ b/quest/m2/audit-docs.md @@ -0,0 +1,25 @@ +# [M] Audit the docs + +## Goal + +Run the `docs` audit: `quest audit docs` prints what it checks, what each finding becomes, and how to plan its next run. + +## Plan + +- Baseline: the m1 run read `309b526`. Start from `git diff 309b526 -- README.md docs site src/cli.rs`, then read the pages no change touched. +- Check first: `docs/semantics.md` against `src/`, and the README and site figures against `docs/results.md`. Those had the most stale claims in the m1 run. +- `assets/demo/walk.tape` breaks whenever `doctor` adds a question. Run it and look at the frames, since nothing in CI runs it. +- Scope excludes `quest/` and the vendored `.agents/` and `.claude/` skills, which quest ships. +- `help.openai.com` answers 403 to scripted requests; check it in a browser. + +## Audit + +- docs + +## Required + +- [m1](/quest/m1/README.md) - runs once per milestone + +## Scheduled + +- 2026-11-27 - so a fast milestone does not rerun the audit at once diff --git a/site/public/index.html b/site/public/index.html index 87ea462..c6452d7 100644 --- a/site/public/index.html +++ b/site/public/index.html @@ -49,7 +49,7 @@

On the maintainer's last 30 days, across four machines

prices. The savings are every change token-max doctor --defaults would make for a user with no settings files, 8% of the spend: most of it the subagent cache, the rest the main agent's cache on usage credits, auto memory and - unused skills and tools.

+ unused or costly skills and tools.

Subagent cache, 1h instead of 5m

@@ -83,8 +83,9 @@

How it knows

cached, when it was written and whether it had expired by the next one, then plays the same sessions again under the other setting.
  • Prices both. At public API prices from models.dev, its only - download. What it can't price stays unknown, never zero. Then it offers each - change, shows the edit and backs the file up first.
  • + network request unless you name other machines with --ssh. What it + can't price stays unknown, never zero. Then it offers each change, shows the + edit and backs the file up first unless git already keeps it. diff --git a/site/public/walk.gif b/site/public/walk.gif index cdf2303..be3c3d4 100644 Binary files a/site/public/walk.gif and b/site/public/walk.gif differ diff --git a/src/cli.rs b/src/cli.rs index 74870c5..b598665 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -206,7 +206,7 @@ fn enter(phase: Phase) { *PHASE.lock().unwrap_or_else(PoisonError::into_inner) = phase; } -/// Parsed flags, as `node:util` `parseArgs` would return them in strict mode. +/// The parsed flags: each string option's value, every value of a repeatable one, and each switch. #[derive(Debug, Default, PartialEq)] struct Values { since: Option, @@ -274,7 +274,7 @@ impl Values { } } -/// Parse like strict `parseArgs`: no positionals, no unknown options, no inline values for +/// Parse strictly: no positionals, no unknown options, no inline values for /// booleans, and a dash-led separate value is rejected as ambiguous. fn parse(args: &[String]) -> Option { let mut values = Values::default(); @@ -368,8 +368,8 @@ fn since(value: &str) -> Result { Ok(midnight + time) } -/// Milliseconds after UTC midnight for `THH:mm[:ss[.fff]]` and `Z` or `+HH:mm`, as V8's ISO -/// parser reads it: 24:00 is the next midnight, seconds stop at 59, extra fraction digits drop. +/// Milliseconds after UTC midnight for `THH:mm[:ss[.fff]]` and `Z` or `+HH:mm`: +/// 24:00 is the next midnight, seconds stop at 59, extra fraction digits drop. fn iso_time(b: &[u8]) -> Option { let two = |at: usize, max: i64| -> Option { let digits = b.get(at..at + 2)?; @@ -435,7 +435,7 @@ fn env(name: &str) -> Option { std::env::var_os(name).map(|v| v.to_string_lossy().into_owned()) } -/// An environment variable that is set and not empty, as JavaScript `||` treats it. +/// An environment variable that is set and not empty; an empty one reads as unset. fn env_nonempty(name: &str) -> Option { env(name).filter(|v| !v.is_empty()) } @@ -484,7 +484,8 @@ fn help(text: &str) -> String { .join("\n") } -/// Numbers print as JavaScript's `JSON.stringify` prints them, such as `1` rather than `1.0`. +/// Numbers print in their shortest round-trip form, integers without a fraction, such as `1` +/// rather than `1.0`. struct JsFormatter; impl JsFormatter { @@ -526,7 +527,7 @@ impl Formatter for JsFormatter { } } -/// Stream a value as one compact JavaScript-compatible JSON line. +/// Stream a value as one compact JSON line, numbers formatted by `JsFormatter`. fn write_json(writer: impl Write, value: &impl Serialize) -> io::Result<()> { let mut writer = io::BufWriter::new(writer); let mut serializer = serde_json::Serializer::with_formatter(&mut writer, JsFormatter); @@ -686,7 +687,7 @@ pub fn render(scan: Scan, options: Render<'_>) -> Result { }) } -/// The `--since` bound; an empty value is absent, as JavaScript treats a falsy option. +/// The `--since` bound; an empty value is absent. fn window(values: &Values) -> Result, ScanError> { match values.since.as_deref() { None | Some("") => Ok(None), diff --git a/src/compaction.rs b/src/compaction.rs index 716d73f..3169506 100644 --- a/src/compaction.rs +++ b/src/compaction.rs @@ -415,7 +415,7 @@ pub fn compaction_samples<'a>( summaries: &[CompactionCharge], ) -> CompactionSamples<'a> { let mut result = Vec::new(); - // Later duplicates win, like a JavaScript Map built from the array. + // Later duplicates win. let by_id: HashMap<&str, &'a Request> = requests.iter().map(|r| (&*r.id, *r)).collect(); // Later records of an event win too, since they carry its final state. let last: HashMap<&Id, &'a StructuralEvent> = events.iter().map(|e| (&e.id, *e)).collect(); @@ -697,9 +697,8 @@ impl<'r, 'o> Simulator<'r, 'o> { } None => source, }; - // `state` stands for the JavaScript object in the session map: one taken from the map - // is written back even when a part bails out, while a fresh one replaces the map entry - // only once a part completes. + // A state taken from the session map is written back even when a part bails out, while + // a fresh one replaces the map entry only once a part completes. let (key, previous) = match self.states.remove_entry(&req.session) { Some((key, state)) => (key, Some(state)), None => (req.session.clone(), None), @@ -2363,7 +2362,7 @@ mod tests { r.parts[0].usage = writes(150000); requests.push(r); } - // Coverage and snapshot times match the TypeScript fixture, which the text report prints. + // Coverage and snapshot times are fixed because the text report prints them. let n = requests.len() as u64; Scan { subagents: vec![], @@ -2515,7 +2514,7 @@ mod tests { } } - /// The synthetic scans of the TypeScript compaction tests, called without TTL checks. + /// The synthetic scans the compaction tests share, called without TTL checks. fn scenario(name: &str) -> Scan { match name { "base" => data(4), @@ -2758,7 +2757,6 @@ mod tests { assert!((actual - expected).abs() < 1e-10, "{actual} != {expected}"); } - /// Recommendations and savings the TypeScript implementation reports for the same scans. #[test] fn unset_windows_take_the_latest_observed_trigger_else_the_documented_default() { let mut scan = data(4); @@ -4409,7 +4407,7 @@ mod tests { assert!(samples_of(&requests, &events, &[]).samples.is_empty()); } - /// A direct transliteration of the TypeScript scan, quadratic but obviously first-match. + /// A naive scan to check the real one against, quadratic but obviously first-match. fn naive_samples( requests: &[&Request], events: &[&StructuralEvent], @@ -4646,7 +4644,7 @@ mod tests { assert_eq!(skipped_lines(&s, &["other".into()]), 0); } - /// Matches the TypeScript replayWindows on the same scan, including an inert first window. + /// Includes an inert first window. #[test] fn replay_windows_applies_estimates_in_the_first_pass_and_chains_later_ones() { let mut scan = scenario("attempt"); @@ -4724,7 +4722,7 @@ mod tests { assert_eq!(result.estimated_parts.len(), 3); } - /// The TypeScript compaction tests, each through `analyze` (with the TTL checks it runs) and the text report. + /// Compaction tests, each through `analyze` (with the TTL checks it runs) and the text report. mod end_to_end { use super::{at, controls, data, near, usage, writes}; use crate::controls::{CompactionSources, Env, compaction_controls, window_control}; @@ -4815,7 +4813,7 @@ mod tests { } } - // Ported from compaction.test.ts: "net window winner prices summary and new prefix once, retaining observed summaries". + // Net window winner prices summary and new prefix once, retaining observed summaries. #[test] fn net_window_winner_prices_summary_and_new_prefix_once_retaining_observed_summaries() { let report = report(&data(4)); @@ -4859,7 +4857,7 @@ mod tests { assert_eq!(check.ttls.main, Some(Ttl::FiveMinutes)); } - // Ported from compaction.test.ts: "window presentation keeps conditional baselines, every scenario and geometry evidence reachable". + // Window presentation keeps conditional baselines, every scenario and geometry evidence reachable. #[test] fn window_presentation_keeps_conditional_baselines_every_scenario_and_geometry_evidence() { let report = report(&data(4)); @@ -4926,7 +4924,7 @@ mod tests { )); } - // Ported from compaction.test.ts: "summary overhead can lose, sensitivity cannot veto a positive aggregate estimate". + // Summary overhead can lose, sensitivity cannot veto a positive aggregate estimate. #[test] fn summary_overhead_can_lose_and_sensitivity_cannot_veto_a_positive_aggregate() { let one = check(&data(1)); @@ -4944,7 +4942,7 @@ mod tests { assert!(loss.scenarios[0].savings_usd.unwrap() < 0.0); } - // Ported from compaction.test.ts: "current smaller window is the comparison baseline, rather than old larger history". + // Current smaller window is the comparison baseline, rather than old larger history. #[test] fn current_smaller_window_is_the_comparison_baseline() { let mut s = data(4); @@ -4960,7 +4958,7 @@ mod tests { ); } - // Ported from compaction.test.ts: "unsupported affected usage is unpriced; unknown unchanged output cancels with provenance". + // Unsupported affected usage is unpriced; unknown unchanged output cancels with provenance. #[test] fn unsupported_affected_usage_is_unpriced_and_unknown_unchanged_output_cancels() { let mut s = data(4); @@ -4983,7 +4981,7 @@ mod tests { assert_eq!(check(&no_sample).scenarios[0].savings_usd, None); } - // Ported from compaction.test.ts: "historical-only or unsupported client controls remain advisory, including unknown candidates". + // Historical-only or unsupported client controls remain advisory, including unknown candidates. #[test] fn historical_only_or_unsupported_client_controls_remain_advisory() { let mut s = data(4); @@ -5007,7 +5005,7 @@ mod tests { assert!(check(&unsupported).scenarios[0].margin.is_some()); } - // Ported from compaction.test.ts: "Codex standalone compaction uses linked billed summary and cold prefix at the full context tier". + // Codex standalone compaction uses linked billed summary and cold prefix at the full context tier. #[test] fn codex_standalone_compaction_uses_linked_billed_summary_and_cold_prefix() { let mut s = data(4); @@ -5086,7 +5084,7 @@ mod tests { assert_eq!(u.scenarios[0].savings_usd, None); } - // Ported from compaction.test.ts: "bracketed Claude model controls scan safely and unresolved aliases stay advisory". + // Bracketed Claude model controls scan safely and unresolved aliases stay advisory. #[test] fn bracketed_claude_model_controls_scan_safely_and_unresolved_aliases_stay_advisory() { let w = Workspace::new(); @@ -5140,7 +5138,7 @@ mod tests { ); } - // Ported from compaction.test.ts: "discovery retains only whitelisted compaction controls and malformed selected limits fail". + // Discovery retains only whitelisted compaction controls and malformed selected limits fail. #[test] fn discovery_retains_only_whitelisted_compaction_controls_and_malformed_limits_fail() { let w = Workspace::new(); @@ -5190,7 +5188,7 @@ mod tests { ); } - // Ported from compaction.test.ts: "window replay uses TTL recommendations and never inherits old-prefix external warming". + // Window replay uses TTL recommendations and never inherits old-prefix external warming. #[test] fn window_replay_uses_ttl_recommendations_and_never_inherits_external_warming() { let mut s = data(2); @@ -5231,7 +5229,7 @@ mod tests { assert_eq!(s.requests[2].parts[0].usage.read, Some(0)); } - // Ported from compaction.test.ts: "changing a message prefix preserves unchanged billed compaction iterations". + // Changing a message prefix preserves unchanged billed compaction iterations. #[test] fn changing_a_message_prefix_preserves_unchanged_billed_compaction_iterations() { let mut s = data(2); @@ -5253,7 +5251,7 @@ mod tests { assert_eq!(s.requests, before); } - // Ported from compaction.test.ts: "window estimates reuse bracketed attempt inputs and retain missing historical billing". + // Window estimates reuse bracketed attempt inputs and retain missing historical billing. #[test] fn window_estimates_reuse_bracketed_attempt_inputs_and_retain_missing_billing() { let mut s = data(2); @@ -5291,7 +5289,7 @@ mod tests { assert_eq!(s.requests[2].parts[0].usage.input, None); } - // Ported from compaction.test.ts: "pre-window summary linkage calibrates selected work without charging old generation". + // Pre-window summary linkage calibrates selected work without charging old generation. #[test] fn pre_window_summary_linkage_calibrates_selected_work_without_charging_old_generation() { let mut s = data(4); @@ -5326,7 +5324,7 @@ mod tests { near(check.base.savings_usd, 1.96); } - // Ported from compaction.test.ts: "an unsupported smaller window does not veto another candidate's positive aggregate". + // An unsupported smaller window does not veto another candidate's positive aggregate. #[test] fn an_unsupported_smaller_window_does_not_veto_another_candidates_positive_aggregate() { let mut s = data(4); @@ -5341,7 +5339,7 @@ mod tests { assert!(check.base.savings_usd.unwrap() > 0.0); } - // Ported from compaction.test.ts: "shared Claude controls produce one aggregate recommendation for all affected models". + // Shared Claude controls produce one aggregate recommendation for all affected models. #[test] fn shared_claude_controls_produce_one_aggregate_recommendation_for_all_models() { for environment in [false, true] { @@ -5408,7 +5406,7 @@ mod tests { } } - // Ported from compaction.test.ts: "small unknown iterations cancel while truly missing input leaves only its own session unpriced". + // Small unknown iterations cancel while truly missing input leaves only its own session unpriced. #[test] fn small_unknown_iterations_cancel_while_missing_input_leaves_only_its_session_unpriced() { let mut s = data(4); @@ -5428,7 +5426,7 @@ mod tests { assert!(scenario.margin.is_some()); } - // Ported from compaction.test.ts: "each added summary is its own pair, so a few unpriced sessions cannot outweigh many small differences". + // Each added summary is its own pair, so a few unpriced sessions cannot outweigh many small differences. // Unpriced sessions are now extrapolated over rather than bounded. #[test] fn each_added_summary_is_its_own_pair_so_unpriced_sessions_are_extrapolated_over() { @@ -5470,7 +5468,7 @@ mod tests { assert_eq!(check.base.action, Action::Change); } - // Ported from compaction.test.ts: "a window that changes no request is a keep, not missing evidence". + // A window that changes no request is a keep, not missing evidence. #[test] fn a_window_that_changes_no_request_is_a_keep_not_missing_evidence() { let mut s = data(0); @@ -5492,8 +5490,7 @@ mod tests { assert!(!text.contains("could not confirm"), "{text}"); } - // Ported from compaction.test.ts: "unreadable lines count as unknown parts, so many of them block a recommendation". - // They are now extrapolated over like any unpriced part. + // Unreadable lines count as unknown parts, extrapolated over like any unpriced part. #[test] fn unreadable_lines_count_as_unknown_parts_extrapolated_over() { let mut s = data(4); @@ -5517,7 +5514,7 @@ mod tests { assert!(extrapolated.base.margin.is_some()); } - // Ported from compaction.test.ts: "Claude historical window differences and structured TTL window alignment remain visible". + // Claude historical window differences and structured TTL window alignment remain visible. #[test] fn claude_historical_window_differences_remain_visible() { let mut s = data(4); @@ -5539,7 +5536,7 @@ mod tests { assert_eq!(check.base.action, Action::Change); } - // Ported from compaction.test.ts: "added summaries require billed output and do not confuse postTokens with output". + // Added summaries require billed output and do not confuse postTokens with output. #[test] fn added_summaries_require_billed_output_and_do_not_confuse_post_tokens_with_output() { let mut s = data(4); diff --git a/src/context.rs b/src/context.rs index cbc234e..621c17d 100644 --- a/src/context.rs +++ b/src/context.rs @@ -54,7 +54,7 @@ pub fn setting_text(path: &[String], value: Value, append: bool, harness: Harnes .expect("JSON values serialize"); let pretty = String::from_utf8(pretty).expect("JSON is UTF-8"); // One line: each newline and its indentation become a single space, then - // brackets close up. Like the TypeScript, this also applies inside strings. + // brackets close up. This also applies inside strings, which only affects display. let mut flat = String::with_capacity(pretty.len()); let mut chars = pretty.chars().peekable(); while let Some(c) = chars.next() { @@ -603,7 +603,7 @@ fn pieces( None, ), Category::PluginInstructions => { - // Each UTF-16 unit outside the allowed set becomes one underscore, as in JavaScript. + // Each UTF-16 unit outside the allowed set becomes one underscore. let mut server = String::with_capacity(name.len()); for c in name.chars() { if c.is_ascii_alphanumeric() || c == '_' || c == '-' { diff --git a/src/controls.rs b/src/controls.rs index cadb39f..e301250 100644 --- a/src/controls.rs +++ b/src/controls.rs @@ -51,13 +51,14 @@ pub(crate) fn members(value: Option<&Value>) -> &Map { object(value.unwrap_or(&Value::Null)) } -/// A number that JavaScript's `Number.isSafeInteger` accepts, including integral floats. +/// An integral number, float or not, of magnitude at most 2^53 - 1. fn safe_integer(value: &Value) -> Option { let n = value.as_f64()?; (n.fract() == 0.0 && n.abs() <= MAX_SAFE_INTEGER as f64).then_some(n as i64) } -/// JavaScript's `String(value)`, where `None` is `undefined`. +/// A value as text: absent is "undefined", arrays join with commas and nulls in them as empty, +/// objects are "[object Object]". pub(crate) fn js_string(value: Option<&Value>) -> String { match value { None => "undefined".into(), @@ -2436,7 +2437,7 @@ mod tests { ); } - // Ported from compaction.test.ts: "effective per-model controls honor managed scope, environment ownership and dated IDs". + // Effective per-model controls honor managed scope, environment ownership and dated IDs. #[test] fn per_model_controls_honor_managed_scope_environment_and_dated_ids() { let user = map(json!({ @@ -2486,7 +2487,7 @@ mod tests { assert_eq!(&*error.location.unwrap().file, "managed.json"); } - // Ported from compaction.test.ts: "bracketed Claude model controls scan safely and unresolved aliases stay advisory". + // Bracketed Claude model controls scan safely and unresolved aliases stay advisory. #[test] fn bracketed_model_controls_and_unresolved_aliases() { let user = map(json!({ @@ -2646,7 +2647,7 @@ mod tests { assert!(!codex_premium_model("gpt-6.1-sol-2026-1-02", false)); } - // Ported from fast.test.ts: "Claude disabling controls and unsupported models suppress saved fast preferences, with exact owners". + // Claude disabling controls and unsupported models suppress saved fast preferences, with exact owners. #[test] fn claude_disabling_controls_suppress_saved_fast_preferences() { let c = json!({ "model": "claude-opus-5-5", "fastMode": true }); @@ -2729,7 +2730,7 @@ mod tests { ); } - // Ported from fast.test.ts: "Codex gates are independent, support ultrafast and keep unsupported tiers unknown". + // Codex gates are independent, support ultrafast and keep unsupported tiers unknown. #[test] fn codex_gates_are_independent_and_unsupported_tiers_stay_unknown() { let codex = |config: Value| speed(Harness::Codex, config, json!({}), &[]); @@ -2783,7 +2784,7 @@ mod tests { ); } - // Ported from fast.test.ts: "invalid speed controls name the effective source file including Windows drive letters". + // Invalid speed controls name the effective source file including Windows drive letters. #[test] fn invalid_speed_controls_name_the_effective_source_file() { let system = Map::new(); diff --git a/src/discovery.rs b/src/discovery.rs index 111ca6f..a016ea5 100644 --- a/src/discovery.rs +++ b/src/discovery.rs @@ -27,7 +27,7 @@ pub struct DiscoveryOptions { pub env: Env, pub claude_dirs: Vec, pub codex_dirs: Vec, - /// Explicit T3 state directories containing settings.json and statev2.sqlite. + /// Explicit T3 state directories: settings.json, and statev2.sqlite when it exists. pub t3_dirs: Vec, /// The system managed Claude settings file; overridable for host adapters and synthetic tests. pub managed_settings_file: String, @@ -450,7 +450,7 @@ fn collation_weight(c: char) -> Option { } } -/// JavaScript's default `localeCompare` (ICU root collation) for printable ASCII paths: +/// ICU root collation for printable ASCII paths: /// punctuation before digits before letters, then lowercase before uppercase. pub(crate) fn locale_compare(a: &str, b: &str) -> Ordering { let primary = |s: &str| s.chars().filter_map(collation_weight).collect::>(); @@ -465,12 +465,12 @@ pub(crate) fn locale_compare(a: &str, b: &str) -> Ordering { .then_with(|| tertiary(a).cmp(&tertiary(b))) } -/// Convert TOML into the JSON shapes JavaScript's TOML parser yields. +/// Convert TOML into JSON: a date becomes an empty object, a non-finite float null. fn toml_json(value: toml::Value) -> Option { Some(match value { toml::Value::String(s) => Value::String(s), toml::Value::Integer(n) => { - // Integers JavaScript cannot represent exactly are a parse error there. + // An integer outside a double's safe-integer range fails the parse. if n.unsigned_abs() > crate::safe::MAX_SAFE_INTEGER as u64 { return None; } @@ -2127,7 +2127,7 @@ impl Walk { }; entries.push((name.to_string_lossy().into_owned(), kind)); } - // JavaScript's default sort compares UTF-16 code units. + // Names sort by UTF-16 code units. entries.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16())); for (name, kind) in entries.into_iter().rev() { stack.push((join(&[&canonical, &name]), kind)); @@ -2965,7 +2965,7 @@ mod tests { ); } - // Ported from reader.test.ts: "current environment overrides are scoped to the active config root". + // Current environment overrides are scoped to the active config root. #[test] fn environment_overrides_are_scoped_to_the_active_root() { let w = Workspace::new(); @@ -3185,7 +3185,7 @@ mod tests { } } - // Ported from reader.test.ts: "managed TTL controls retain the managed owner and API-key presence leaves billing unknown". + // Managed TTL controls retain the managed owner and API-key presence leaves billing unknown. #[test] fn managed_ttl_controls_keep_the_managed_owner() { let w = Workspace::new(); @@ -3213,7 +3213,7 @@ mod tests { assert_eq!(claude(&data).ttl.subagent.value, Some(Ttl::FiveMinutes)); } - // Ported from reader.test.ts: "automatic discovery ignores a symlinked Claude config file". + // Automatic discovery ignores a symlinked Claude config file. #[cfg(unix)] #[test] fn symlinked_config_files_are_not_profiles() { @@ -3230,7 +3230,7 @@ mod tests { assert_eq!(error.message, "selected root is missing or inaccessible"); } - // Ported from reader.test.ts: "managed file locations match the supported host platforms". + // Managed file locations match the supported host platforms. #[test] fn managed_file_locations_match_platforms() { assert_eq!( @@ -3247,7 +3247,7 @@ mod tests { ); } - // Ported from the discovery half of reader.test.ts: "shared directories are read once, preserve profile aliases, and include nested subagents". + // Shared directories are read once, preserve profile aliases, and include nested subagents. #[cfg(unix)] #[test] fn shared_directories_are_snapshotted_once_and_explicit_roots_exclude_others() { @@ -3279,7 +3279,7 @@ mod tests { assert_eq!(selected.profiles[0].ttl.main.value, Some(Ttl::OneHour)); } - // Ported from the discovery halves of reader.test.ts: "all lengths freeze before reading" and "a shrunk snapshot fails". + // All lengths freeze before reading, and a shrunk snapshot fails. #[test] fn lengths_freeze_at_discovery_and_missing_explicit_roots_fail() { let w = Workspace::new(); @@ -3345,7 +3345,7 @@ mod tests { assert_eq!(error.message, "cannot snapshot selected history"); } - // Ported from compaction.test.ts: "discovery retains only whitelisted compaction controls and malformed selected limits fail". + // Discovery retains only whitelisted compaction controls and malformed selected limits fail. #[test] fn discovery_keeps_whitelisted_compaction_controls_and_rejects_malformed_limits() { let w = Workspace::new(); @@ -3390,7 +3390,7 @@ mod tests { assert_eq!(error.message, "invalid per-model settings"); } - // Ported from the discovery half of fast.test.ts: "active-profile environment, managed policy and current project ownership suppress stale preferences". + // Active-profile environment, managed policy and current project ownership suppress stale preferences. #[test] fn environment_managed_policy_and_project_ownership_suppress_fast_preferences() { let w = Workspace::new(); @@ -3436,7 +3436,7 @@ mod tests { assert_eq!(directory.owner, format!("{}:fastMode", text(&local))); } - // Ported from fast.test.ts: "Codex legacy/named profiles and project selection stay advisory; local requirements can block premium". + // Codex legacy/named profiles and project selection stay advisory; local requirements can block premium. #[test] fn codex_named_profiles_stay_advisory_and_requirements_block_premium() { let w = Workspace::new(); @@ -3483,7 +3483,7 @@ mod tests { assert_eq!(error.message, "invalid required speed feature"); } - // Ported from the discovery half of fast.test.ts: "known distinct project controls get separate cards and nearest Codex scope remains advisory owner". + // Known distinct project controls get separate cards and nearest Codex scope remains advisory owner. #[test] fn nearest_codex_project_scope_owns_speed() { let w = Workspace::new(); @@ -3518,7 +3518,7 @@ mod tests { assert_eq!(directory.replacement, profile.speed.unwrap().replacement); } - // Ported from the discovery half of reader.test.ts: "a custom ANTHROPIC_BASE_URL proxy is priced as the public Anthropic API". + // A custom ANTHROPIC_BASE_URL proxy is priced as the public Anthropic API. #[test] fn an_answered_billing_sets_only_an_unset_main_ttl_on_the_anthropic_api() { let w = Workspace::new(); @@ -4308,7 +4308,7 @@ mod tests { assert!(settled(&[&plain, &off]).ttl.main.varies); } - // Ported from the discovery half of idle.test.ts: "native informational notices are the only parsed idle attribution; project owners and threshold floor resolve". + // Native informational notices are the only parsed idle attribution; project owners and threshold floor resolve. #[test] fn project_owners_and_threshold_floor_resolve_at_recorded_directories() { let w = Workspace::new(); diff --git a/src/doctor.rs b/src/doctor.rs index 3d9624f..339138f 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -509,7 +509,7 @@ fn outranking(profile: &Profile, edit: &Edit, defaults: bool) -> Result bool { let edit = Edit::from(control); // Claude's deny rules from every file apply together. diff --git a/src/exposure.rs b/src/exposure.rs index 011124c..0c44b5b 100644 --- a/src/exposure.rs +++ b/src/exposure.rs @@ -137,7 +137,7 @@ pub struct ExposureCollector { invocations: IndexMap, observations: HashMap, file: Option, - // Active revision and category by component key, in JavaScript `Map` insertion order. + // Active revision and category by component key, in insertion order. active: IndexMap, pending_removed: IndexSet, session: Text, @@ -323,9 +323,9 @@ impl Placed { /// What a component's size and fingerprint are measured from. enum Content<'a> { Text(&'a str), - /// The `JSON.stringify` text of a value. + /// The compact JSON text of a value. Json(&'a Value), - /// `JSON.stringify(undefined)`, which is not text. + /// No value at all, which has no text. Missing, /// A value whose rendered size is unknown; only its serialized identity is kept. Opaque(&'a Value), @@ -1921,7 +1921,7 @@ impl ExposureCollector { .as_ref() .and_then(|items| self.message_characters(items)); if let Some(messages) = messages { - // A shape without a system prompt counts it as zero, as JavaScript adds null. + // A shape without a system prompt counts it as zero. complete = Some( messages + shape.system.size.characters.unwrap_or(0) @@ -2735,7 +2735,7 @@ fn reasons( /// a content-level thinking block's opaque signature is dropped; every other /// field, tool input included, counts. fn blob_characters(message: Option<&Value>) -> Result, ScanError> { - // JSON.stringify(undefined) is not text; the TypeScript failed here too. + // A missing message has no text to count, so it is an error rather than zero. let message = message.ok_or_else(|| ScanError::new("invalid context object"))?; let mut sink = Chars(0); match message { @@ -2853,13 +2853,13 @@ fn complete_text(params: &Map) -> Result { } // --------------------------------------------------------------------------- -// Raw record access, mirroring JavaScript's view of parsed JSON. +// Raw record access, where a missing key reads as null. fn field<'a>(map: &'a Map, key: &str) -> &'a Value { map.get(key).unwrap_or(&Value::Null) } -/// JavaScript's `??` treats null like a missing key. +/// The value, treating null like a missing key. fn present(value: Option<&Value>) -> Option<&Value> { value.filter(|v| !v.is_null()) } @@ -2898,7 +2898,7 @@ fn id(value: Option<&Value>) -> Result { safe::id(value.unwrap_or(&Value::Null)) } -/// JavaScript's default string sort compares UTF-16 code units. +/// Compare strings by UTF-16 code units. fn js_cmp(a: &str, b: &str) -> std::cmp::Ordering { a.encode_utf16().cmp(b.encode_utf16()) } @@ -2944,9 +2944,9 @@ fn kind_name(kind: InvocationKind) -> &'static str { } // --------------------------------------------------------------------------- -// Patterns, matched exactly as the JavaScript regular expressions they replace. +// Patterns over transcript text, matched by hand. -/// JavaScript's `\s`. +/// Whitespace: ASCII and Unicode spaces, line and paragraph separators, and the byte order mark. pub(crate) fn js_space(c: char) -> bool { matches!( c, @@ -2961,7 +2961,7 @@ pub(crate) fn js_space(c: char) -> bool { ) } -/// Where JavaScript's multiline `^` may match, and what `.` excludes. +/// A line terminator: where a line may start, and what never belongs to a line. fn line_terminator(c: char) -> bool { matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}') } @@ -3308,7 +3308,8 @@ fn script_references(code: &str) -> Vec<(usize, &str)> { } // --------------------------------------------------------------------------- -// JSON.stringify, byte for byte, into a string, a character count or a hash. +// Compact JSON, written into a string, a character count or a hash, so sizes and +// fingerprints never depend on how a value was parsed. trait Sink { fn put(&mut self, text: &str); @@ -3320,7 +3321,7 @@ impl Sink for String { } } -/// Counts code points, as iterating a JavaScript string does. +/// Counts code points. struct Chars(usize); impl Sink for Chars { @@ -3363,7 +3364,7 @@ fn json(value: &Value, sink: &mut S) { } } -/// Write an object in JavaScript property order, optionally without one key. +/// Write an object in `js_entries` order, optionally without one key. fn write_object( map: &Map, sink: &mut S, @@ -3396,14 +3397,14 @@ fn write_object( sink.put("}"); } -/// Object entries in JavaScript order: array indices ascending, then insertion order. +/// Object entries with array-index keys first, ascending, then the rest in insertion order. pub(crate) fn js_entries(map: &Map) -> Vec<(&str, &Value)> { let mut entries: Vec<(&str, &Value)> = map.iter().map(|(k, v)| (k.as_str(), v)).collect(); entries.sort_by_key(|(k, _)| array_index(k).map_or((1, 0), |n| (0, n))); entries } -/// A canonical array index property name, which JavaScript enumerates first. +/// A key that is a canonical array index: no leading zero, below 2^32 - 1. fn array_index(key: &str) -> Option { let b = key.as_bytes(); if b.is_empty() @@ -3417,7 +3418,7 @@ fn array_index(key: &str) -> Option { (n < u64::from(u32::MAX)).then_some(n as u32) } -/// JSON.stringify's string escaping: quotes, backslashes and control characters only. +/// Quote a JSON string, escaping only quotes, backslashes and control characters. fn quote(text: &str, sink: &mut S) { sink.put("\""); let mut start = 0; @@ -3445,7 +3446,8 @@ fn quote(text: &str, sink: &mut S) { sink.put("\""); } -/// JavaScript's `Number.prototype.toString` for a parsed JSON number. +/// A parsed JSON number in shortest round-trip form: exponent form below 1e-6 or from 1e21 +/// in magnitude, and integers beyond 2^53 as the nearest double. pub(crate) fn number(n: &Number) -> String { const SAFE: u64 = 1 << 53; if let Some(u) = n.as_u64() @@ -3462,7 +3464,7 @@ pub(crate) fn number(n: &Number) -> String { if value == 0.0 { return "0".into(); } - // Shortest round-trip digits, then ECMAScript's choice of plain or exponential form. + // Shortest round-trip digits, then plain or exponential form by magnitude. let sign = if value < 0.0 { "-" } else { "" }; let scientific = format!("{:e}", value.abs()); let (mantissa, exponent) = scientific.split_once('e').expect("exponent"); diff --git a/src/exposure/scan_tests.rs b/src/exposure/scan_tests.rs index 843f1ba..a91ffd1 100644 --- a/src/exposure/scan_tests.rs +++ b/src/exposure/scan_tests.rs @@ -102,7 +102,7 @@ fn assistant(second: u32, content: Value) -> Value { }) } -/// Merge `fields` into a copy of the object `base`, like a JavaScript spread. +/// A copy of the object `base` with `fields` set over it. fn with(base: Value, fields: Value) -> Value { let mut merged = base; let object = merged.as_object_mut().unwrap(); @@ -116,7 +116,7 @@ fn jsonl(records: &[Value]) -> String { records.iter().map(|r| format!("{r}\n")).collect() } -/// JSON text length in UTF-16 units, like JavaScript's `JSON.stringify(v).length`. +/// Compact JSON text length in UTF-16 units. fn length(value: &Value) -> usize { serde_json::to_string(value).unwrap().encode_utf16().count() } diff --git a/src/fast.rs b/src/fast.rs index b567c90..fec540e 100644 --- a/src/fast.rs +++ b/src/fast.rs @@ -622,7 +622,7 @@ mod tests { ); } - /// The TypeScript fast-mode tests that read real settings files through `scan`, then `speed_checks` or `analyze`. + /// Fast-mode tests that read real settings files through `scan`, then `speed_checks` or `analyze`. mod end_to_end { use super::super::{SpeedInput, speed_checks}; use crate::controls::{Env, SettingsScope, speed_controls}; @@ -652,7 +652,7 @@ mod tests { std::fs::write(path, contents).unwrap(); } - /// The TypeScript `workspace().options`: this home, no environment, a checkout-local managed file. + /// This home, no environment, a checkout-local managed file. fn options(w: &Workspace) -> DiscoveryOptions { DiscoveryOptions { home: text(&w.home), @@ -704,7 +704,7 @@ mod tests { }) } - /// The TypeScript `control(harness, config)`: a user scope over an empty managed scope. + /// A user scope over an empty managed scope. fn control(harness: Harness, config: Value) -> SpeedControl { let config = config.as_object().cloned().unwrap(); let managed = serde_json::Map::new(); @@ -751,7 +751,7 @@ mod tests { } } - // Ported from fast.test.ts: "rate-only premium preserves Claude 5m/1h reads/writes, geography and fixed fees". + // Rate-only premium preserves Claude 5m/1h reads/writes, geography and fixed fees. #[test] fn rate_only_premium_preserves_claude_cache_lifetimes_geography_and_fixed_fees() { let w = Workspace::new(); @@ -870,7 +870,7 @@ mod tests { assert!(standard.observed.premium.total_usd.unwrap().to_f64() > 0.0); } - // Ported from fast.test.ts: "current-setting warning survives missing billing metadata; historical unknowns and prices stay unknown". + // Current-setting warning survives missing billing metadata; historical unknowns and prices stay unknown. #[test] fn current_setting_warning_survives_missing_billing_metadata() { let w = Workspace::new(); @@ -914,7 +914,7 @@ mod tests { assert_eq!(empty.base.savings_usd, None); } - // Ported from fast.test.ts: "active-profile environment, managed policy and current project ownership suppress stale preferences". + // Active-profile environment, managed policy and current project ownership suppress stale preferences. #[test] fn active_profile_environment_managed_policy_and_project_ownership_suppress_stale_preferences() { @@ -971,7 +971,7 @@ mod tests { assert_eq!(result.base.owner, format!("{}:fastMode", text(&local))); } - // Ported from fast.test.ts: "Codex legacy/named profiles and project selection stay advisory; local requirements can block premium". + // Codex legacy/named profiles and project selection stay advisory; local requirements can block premium. #[test] fn codex_legacy_named_profiles_stay_advisory_and_local_requirements_block_premium() { let w = Workspace::new(); @@ -1005,7 +1005,7 @@ mod tests { assert_eq!(speed().value.as_deref(), Some("standard")); } - // Ported from fast.test.ts: "unknown speeds, price gaps and explicit windows never turn missing premiums into zero". + // Unknown speeds, price gaps and explicit windows never turn missing premiums into zero. #[test] fn unknown_speeds_price_gaps_and_explicit_windows_never_turn_missing_premiums_into_zero() { let w = Workspace::new(); @@ -1036,7 +1036,7 @@ mod tests { assert_eq!(unknown.base.action, Action::Change); } - // Ported from fast.test.ts: "unsupported Opus history has no hypothetical premium and unknown iteration ownership stays unpriced". + // Unsupported Opus history has no hypothetical premium and unknown iteration ownership stays unpriced. #[test] fn unsupported_opus_history_has_no_hypothetical_premium_and_unknown_ownership_stays_unpriced() { @@ -1076,7 +1076,7 @@ mod tests { ); } - // Ported from fast.test.ts: "known distinct project controls get separate cards and nearest Codex scope remains advisory owner". + // Known distinct project controls get separate cards and nearest Codex scope remains advisory owner. #[test] fn known_distinct_project_controls_get_separate_cards_and_nearest_codex_scope_owns() { let w = Workspace::new(); @@ -1178,7 +1178,7 @@ mod tests { assert_eq!(cards, [(Action::Change, 1), (Action::Keep, 1)]); } - // Ported from fast.test.ts: "managed blocks survive named/legacy alternatives while a separately allowed premium remains unresolved". + // Managed blocks survive named/legacy alternatives while a separately allowed premium remains unresolved. #[test] fn managed_blocks_survive_named_alternatives_while_an_allowed_premium_stays_unresolved() { let w = Workspace::new(); @@ -1217,7 +1217,7 @@ mod tests { assert_eq!(speed().value.as_deref(), Some("standard")); } - // Ported from fast.test.ts: "partially priced premium retains covered categories as subtotal while its total remains unknown". + // Partially priced premium retains covered categories as subtotal while its total remains unknown. #[test] fn partially_priced_premium_retains_covered_categories_as_a_subtotal() { let w = Workspace::new(); diff --git a/src/idle.rs b/src/idle.rs index 87dc9ff..e5d5681 100644 --- a/src/idle.rs +++ b/src/idle.rs @@ -151,7 +151,7 @@ fn difference(after: &Cost, before: &Cost) -> Cost { } } -/// JavaScript's `Math.sign`. +/// 1 for a positive `value`, -1 for a negative one, else `value` itself (zero or NaN). fn sign(value: f64) -> f64 { if value > 0.0 { 1.0 @@ -557,7 +557,7 @@ impl Period<'_> { /// Known-on cohorts by version, client and flag state. type Cohorts<'r> = IndexMap<(&'r str, &'r str, &'static str), ActivationCohort>; -/// The first window owning each (owner, model), as `find` would return. +/// The first window owning each (owner, model); later duplicates never win. fn window_lookup(windows: &[ScenarioWindow]) -> HashMap<(&str, Option<&str>), Option> { let mut lookup = HashMap::default(); for w in windows { @@ -885,8 +885,7 @@ enum Tick<'r> { /// A total replay order for a tick at `position` in the list of requests, then boundaries, /// then idle triggers: time, then boundaries first, then list order. /// -/// The TypeScript comparator calls any tied boundary smaller, even against another boundary, -/// which its engine's stable merge sort resolves by reversing tied boundaries. +/// Tied boundaries replay in reverse list order. fn tick_key(time: Millis, boundary: bool, position: usize) -> (Millis, u8, i64) { let position = position as i64; if boundary { @@ -904,7 +903,7 @@ struct Session<'r> { /// Charges shared by every profile. struct Summaries<'a> { - /// The last charge for each event, like a JavaScript Map built from the array. + /// The last charge for each event. by_event: HashMap<&'a Id, &'a CompactionCharge>, requests: HashSet<&'a str>, } diff --git a/src/model.rs b/src/model.rs index 60913ea..d7f84d7 100644 --- a/src/model.rs +++ b/src/model.rs @@ -267,7 +267,9 @@ impl Billing { } impl Ttl { + /// Both TTLs, shortest first. pub const ALL: [Ttl; 2] = [Ttl::FiveMinutes, Ttl::OneHour]; + /// The serialized name, such as "5m". pub fn as_str(self) -> &'static str { match self { Ttl::FiveMinutes => "5m", @@ -284,12 +286,14 @@ pub struct PerTtl { } impl PerTtl { + /// The value for `ttl`. pub fn get(&self, ttl: Ttl) -> &T { match ttl { Ttl::FiveMinutes => &self.five_minutes, Ttl::OneHour => &self.one_hour, } } + /// The mutable value for `ttl`. pub fn get_mut(&mut self, ttl: Ttl) -> &mut T { match ttl { Ttl::FiveMinutes => &mut self.five_minutes, @@ -306,12 +310,14 @@ pub struct PerBucket { } impl PerBucket { + /// The value for `bucket`. pub fn get(&self, bucket: Bucket) -> &T { match bucket { Bucket::Main => &self.main, Bucket::Subagent => &self.subagent, } } + /// The mutable value for `bucket`. pub fn get_mut(&mut self, bucket: Bucket) -> &mut T { match bucket { Bucket::Main => &mut self.main, @@ -328,7 +334,9 @@ pub enum Bucket { } impl Bucket { + /// Both buckets, main first. pub const ALL: [Bucket; 2] = [Bucket::Main, Bucket::Subagent]; + /// The serialized name, such as "subagent". pub fn as_str(self) -> &'static str { match self { Bucket::Main => "main", @@ -379,6 +387,7 @@ impl Usage { } } +/// What a billed part was sampled for. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum PartKind { @@ -399,6 +408,7 @@ pub struct BillingPart { pub geo: Option, } +/// Whether a request's usage was recorded, estimated or missing. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum RequestEvidence { @@ -407,6 +417,7 @@ pub enum RequestEvidence { Unknown, } +/// Whether a request came from the main conversation or a sub-agent. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum Agent { @@ -415,6 +426,7 @@ pub enum Agent { Unknown, } +/// Which provider API a request used. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum Api { @@ -520,6 +532,7 @@ pub enum Few { pub type Origins = Few; impl Few { + /// Adds `item` to the end. pub fn push(&mut self, item: T) { *self = match std::mem::take(self) { Few::None => Few::One(item), @@ -633,6 +646,7 @@ impl Serialize for Few { } } +/// What a structural event marks in a session. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "kebab-case")] pub enum EventKind { @@ -646,6 +660,7 @@ pub enum EventKind { IdleNotice, } +/// What tied an idle period to its cause, when anything did. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum IdleAttribution { @@ -1319,6 +1334,7 @@ pub struct BackgroundControl { pub off_file: Option, } +/// Whether a transcript root was read, and why not. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum RootState { @@ -1328,6 +1344,7 @@ pub enum RootState { Inaccessible, } +/// Where a transcript root's path came from. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum RootOrigin { @@ -1516,6 +1533,7 @@ pub struct CompactionCharge { pub assumptions: Vec, } +/// Whether a usage estimate has a basis. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EstimateEvidence { Estimated, @@ -1534,6 +1552,7 @@ pub struct UsageEstimate { pub assumptions: Vec, } +/// Whether a cache predecessor's state is known, estimated or unknown. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum KnownState { Known, @@ -1541,6 +1560,7 @@ pub enum KnownState { Unknown, } +/// Whether a cached prefix size was measured or estimated. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PrefixEvidence { Measured, @@ -1560,6 +1580,7 @@ pub struct CachePredecessor { pub reason: &'static str, } +/// Whether a request's replayed cache geometry is exact, rests on an estimate, or is unknown. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ReplayOutcome { Invariant, @@ -1579,6 +1600,7 @@ pub struct CacheReplayEvidence { pub reason: &'static str, } +/// What a check recommends doing with its setting. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Action { Change, @@ -1689,6 +1711,7 @@ pub struct CheckBase { pub sources: Vec, } +/// What chose the TTL comparison's window: `--since`, the last TTL change, or all available history. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum WindowBasisKind { Explicit, @@ -1696,12 +1719,14 @@ pub enum WindowBasisKind { Available, } +/// TTL costs under alternative assumptions for requests with no linked cache history. #[derive(Clone, Debug, PartialEq)] pub struct UnlinkedSensitivity { pub no_billed_attempt: PerTtl, pub cold_cache: PerTtl, } +/// How sensitive the TTL comparison is to cold caches and unlinked requests. #[derive(Clone, Debug, PartialEq)] pub struct TtlSensitivity { pub cold_prefix1h_usd: Option, @@ -1750,6 +1775,7 @@ pub struct AddedCompaction { pub prefix_cost: Cost, } +/// How sensitive a compaction window's savings are to summary size and re-reads. #[derive(Clone, Debug, PartialEq)] pub struct WindowSensitivity { pub larger_summary_savings_usd: Option, @@ -1862,6 +1888,7 @@ impl Change { } } +/// The fast-mode premium measured on responses that recorded their speed. #[derive(Clone, Debug, PartialEq)] pub struct ObservedPremium { pub premium_parts: u64, @@ -1871,6 +1898,7 @@ pub struct ObservedPremium { pub monthly_premium_usd: Option, } +/// The fast-mode premium the current setting would add, at rate-card prices. #[derive(Clone, Debug, PartialEq)] pub struct CurrentPremium { pub premium: Cost, @@ -2017,6 +2045,7 @@ pub struct BashCapCheck { pub waits: BashWaits, } +/// Whether an idle period could have triggered the idle policy. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PeriodStatus { Eligible, @@ -2025,6 +2054,7 @@ pub enum PeriodStatus { Censored, } +/// When the user returned after an idle period, relative to cache expiry. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ReturnTiming { BeforeExpiry, @@ -2033,6 +2063,7 @@ pub enum ReturnTiming { Final, } +/// Whether the idle policy was seen acting on a period. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PeriodOutcome { Applied, @@ -2096,6 +2127,7 @@ pub struct OnOff { pub off: T, } +/// A compaction window in effect for one owner and its models. #[derive(Clone, Debug, PartialEq)] pub struct ScenarioWindow { pub owner: String, @@ -2103,6 +2135,7 @@ pub struct ScenarioWindow { pub value: Option, } +/// The idle policy's cost difference for periods of one context size. #[derive(Clone, Debug, PartialEq)] pub struct ContextDelta { pub tokens: Option, @@ -2110,6 +2143,7 @@ pub struct ContextDelta { pub delta_usd: Option, } +/// How often the idle policy applied, for one client version and flag state. #[derive(Clone, Debug, PartialEq)] pub struct ActivationCohort { pub version: Text, @@ -2120,6 +2154,7 @@ pub struct ActivationCohort { pub fraction: f64, } +/// How sensitive the idle policy's cost difference is to its assumptions. #[derive(Clone, Debug, PartialEq)] pub struct IdleSensitivity { pub closed_delta: Option, @@ -2293,6 +2328,7 @@ impl CheckResult { // --------------------------------------------------------------------------- // Exposure: recurring context components and how they were used. +/// What kind of recurring context a component is. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)] #[serde(rename_all = "kebab-case")] pub enum Category { @@ -2344,6 +2380,7 @@ pub struct Size { pub fingerprint: Id, } +/// Which check reports a component: skills or context. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum Owner { @@ -2351,6 +2388,7 @@ pub enum Owner { Context, } +/// Whether a component is one item or an aggregate of several. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum Scope { @@ -2405,6 +2443,7 @@ pub enum Current { Unresolved, } +/// What kind of use an invocation records. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "kebab-case")] pub enum InvocationKind { @@ -2418,6 +2457,7 @@ pub enum InvocationKind { ScriptReference, } +/// How far an invocation got. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum InvocationStatus { @@ -2428,6 +2468,7 @@ pub enum InvocationStatus { Reference, } +/// How an invocation was made: typed, mentioned, by a tool, and so on. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum Via { @@ -2461,6 +2502,7 @@ pub struct Invocation { pub profiles: Vec, } +/// How a request's components were tied to it: on the wire, by time order, or not at all. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "lowercase")] pub enum Linkage { @@ -2469,6 +2511,7 @@ pub enum Linkage { Unknown, } +/// Whether a request's text was recorded in full. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)] #[serde(rename_all = "kebab-case")] pub enum TextCoverage { @@ -2477,6 +2520,7 @@ pub enum TextCoverage { Unknown, } +/// A request's component identifiers, sharing a prefix with an earlier request's. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub struct References { pub base: Option, @@ -2567,9 +2611,11 @@ impl Ids { let tail = ids[keep..].iter().cloned().collect(); Self::new(like.map(|like| (like, keep)), tail) } + /// How many identifiers there are. pub fn len(&self) -> usize { self.0.len } + /// Whether there are no identifiers. pub fn is_empty(&self) -> bool { self.0.len == 0 } @@ -2779,6 +2825,7 @@ pub struct MemoryUse { pub request: Option, } +/// One request's character and token counts, for calibrating estimates. #[derive(Clone, Debug, PartialEq)] pub struct CalibrationSample { pub request: Text, @@ -2815,6 +2862,7 @@ pub struct Control { pub append: bool, } +/// What kind of context an item adds to requests. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum ContextKind { Tool, @@ -2831,6 +2879,7 @@ pub enum ContextKind { Other, } +/// What a context check recommends for one item. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Verdict { /// Never used across a window that would have recorded a use: a recommended change. @@ -3058,6 +3107,7 @@ pub struct CacheContext { pub prompts: Vec, } +/// How much of the scan could be read and priced. #[derive(Clone, Debug, Default, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct ScanCoverage { @@ -3101,6 +3151,7 @@ pub struct Scan { pub defaults: bool, } +/// Where prices came from and when. #[derive(Clone, Debug, PartialEq)] pub struct PriceSource { pub source: String, @@ -3108,6 +3159,7 @@ pub struct PriceSource { pub offline: bool, } +/// What one bucket of requests cost at API prices. #[derive(Clone, Debug, PartialEq)] pub struct HistoricalCost { pub bucket: String, @@ -3131,6 +3183,7 @@ pub struct TierScenario { pub cost: Cost, } +/// Calibrations and assumptions behind exposure estimates. #[derive(Clone, Debug, PartialEq)] pub struct ExposureSummary { pub calibration: Vec, diff --git a/src/prices.rs b/src/prices.rs index eea6b39..e71d0eb 100644 --- a/src/prices.rs +++ b/src/prices.rs @@ -255,7 +255,7 @@ fn model_price(value: &Value) -> Result { } tiers.sort_by(|a, b| a.size.partial_cmp(&b.size).expect("finite tier sizes")); let legacy = match fields.get("context_over_200k") { - // JavaScript truthiness decides whether a legacy tier field is present. + // A legacy tier field counts only when set: not null, false, zero or an empty string. Some(value) if truthy(Some(value)) => Some(rates(value)?), _ => None, }; @@ -2160,7 +2160,7 @@ mod tests { ); } - // Ported from fast.test.ts: "OpenAI fast and ultrafast API repricing preserves long context and billed write lifetimes". + // OpenAI fast and ultrafast API repricing preserves long context and billed write lifetimes. #[test] fn openai_fast_and_ultrafast_repricing_preserves_long_context_and_billed_write_lifetimes() { let catalog = prices(); @@ -2324,7 +2324,7 @@ mod tests { } } - // Ported from fast.test.ts: "plain GPT-5.6 alias has verified fast rates without substituting catalog model prices". + // Plain GPT-5.6 alias has verified fast rates without substituting catalog model prices. #[test] fn plain_gpt_5_6_alias_has_verified_fast_rates_without_substituting_catalog_prices() { let mut c = prices(); diff --git a/src/reader.rs b/src/reader.rs index b857f34..edbd29c 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -54,12 +54,12 @@ fn nested<'a>(map: &'a Map, key: &str) -> &'a Map object(member(map, key)) } -/// JavaScript's `a ?? b`: a null or absent `a` falls through to `b`. +/// `a`, or `b` when `a` is null or absent. fn coalesce<'a>(a: Option<&'a Value>, b: Option<&'a Value>) -> Option<&'a Value> { a.filter(|v| !v.is_null()).or(b) } -/// A member that is a string, like `typeof value === "string"`. +/// A member that is a string. fn string<'a>(map: &'a Map, key: &str) -> Option<&'a str> { map.get(key).and_then(Value::as_str) } @@ -521,14 +521,14 @@ impl Iterator for Records<'_> { } } -/// Parse one line like a fatal `TextDecoder` followed by `JSON.parse`; non-objects are unreadable. +/// Parse one line as strict UTF-8 JSON; non-objects are unreadable. fn parse(line: &[u8]) -> Option> { - // The decoder drops a leading byte order mark before JSON.parse sees the text. + // A leading byte order mark is not part of the JSON. let line = line.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(line); let value = match serde_json::from_slice(line) { Ok(value) => value, Err(_) => { - // JSON.parse accepts escaped lone surrogates, which JavaScript writers emit for + // Escaped lone surrogates are accepted, since JavaScript writers emit them for // truncated text. U+FFFD is what hashing such a string in UTF-8 sees anyway. let text = std::str::from_utf8(line).ok()?; serde_json::from_str(&replace_lone_surrogates(text)?).ok()? diff --git a/src/replay.rs b/src/replay.rs index b2a27f1..668b2ad 100644 --- a/src/replay.rs +++ b/src/replay.rs @@ -41,7 +41,7 @@ fn in_bucket(r: &Request, p: &BillingPart, selected: Bucket) -> bool { cache_bucket(r, p).is_none_or(|b| b == selected) } -/// JavaScript's `toFixed(1)`, which rounds exact binary halves away from zero. +/// One decimal place, rounding exact binary halves away from zero. fn to_fixed1(value: f64) -> String { // An exact tie at one decimal is an odd multiple of 1/4; Rust would round it to even. let quarters = value.abs() * 4.0; @@ -893,7 +893,7 @@ pub fn analyze(options: AnalyzeOptions) -> Result { let mut groups: IndexMap> = IndexMap::default(); for r in &scan.requests { let mut profiles: Vec<&str> = r.profiles.iter().map(String::as_str).collect(); - // JavaScript's default sort compares UTF-16 code units. + // Profiles sort by UTF-16 code units. profiles.sort_by(|a, b| a.encode_utf16().cmp(b.encode_utf16())); groups.entry(profiles.join(":")).or_default().push(r); } diff --git a/src/report.rs b/src/report.rs index ed18f7e..22c9d58 100644 --- a/src/report.rs +++ b/src/report.rs @@ -49,7 +49,7 @@ pub struct Host<'a> { const DAY: f64 = 86_400_000.0; -/// JavaScript's `Number.prototype.toString`. +/// Shortest round-trip digits, with `NaN`, `Infinity` and `-Infinity` for non-finite values. fn js_number(value: f64) -> String { match serde_json::Number::from_f64(value) { Some(n) => crate::exposure::number(&n), @@ -59,7 +59,7 @@ fn js_number(value: f64) -> String { } } -/// JavaScript's `Math.round`: halves round up, toward positive infinity. +/// Round to the nearest integer, halves toward positive infinity. fn js_round(value: f64) -> f64 { let floor = value.floor(); if value - floor >= 0.5 { @@ -69,13 +69,13 @@ fn js_round(value: f64) -> f64 { } } -/// JavaScript's `toFixed(2)` for a non-negative value, which rounds exact binary halves up. +/// Two decimal places for a non-negative value, rounding exact binary halves up. fn to_fixed2(value: f64) -> String { if !value.is_finite() || value >= 1e21 { return js_number(value); } // A value whose exact binary expansion ends in a half cent is an odd multiple - // of 1/8. Rust rounds those to even; JavaScript picks the larger. + // of 1/8. Rust rounds those to even; this picks the larger. let eighths = value * 8.0; if eighths.fract() == 0.0 && eighths % 2.0 == 1.0 { let cents = (value * 100.0).floor() as u64 + 1; @@ -139,7 +139,7 @@ fn approx_estimate(value: Option) -> String { value.map_or_else(|| "unknown".into(), |e| approx_usd(e.usd, e.margin)) } -/// A whole number grouped like `toLocaleString("en-US")`. +/// A whole number with commas between groups of three digits. fn count(value: impl Into) -> String { let value = value.into(); let digits = value.unsigned_abs().to_string(); @@ -7228,7 +7228,7 @@ mod tests { #[test] fn numbers_format_like_javascript() { - // toFixed rounds exact binary halves up; Rust's formatter rounds them to even. + // Exact binary halves round up, where Rust's formatter rounds them to even. assert_eq!(usd(0.125), "$0.13"); assert_eq!(usd(0.625), "$0.63"); assert_eq!(usd(2.675), "$2.67"); diff --git a/src/safe.rs b/src/safe.rs index 7433527..db0c5b9 100644 --- a/src/safe.rs +++ b/src/safe.rs @@ -89,7 +89,7 @@ pub fn hex(bytes: &[u8]) -> String { out } -/// JavaScript's `Number.MAX_SAFE_INTEGER`, the largest integer an f64 holds exactly. +/// The largest integer an f64 holds exactly along with both its neighbors, 2^53 - 1. pub const MAX_SAFE_INTEGER: i64 = 9_007_199_254_740_991; /// Preserve absent counts as unknown and reject corrupt counts. @@ -116,7 +116,7 @@ pub fn count(value: Option<&Value>) -> Result, ScanError> { } } -/// JavaScript truthiness of an optional JSON member. +/// Whether an optional JSON member is set: not absent, null, false, zero or an empty string. pub fn truthy(value: Option<&Value>) -> bool { match value { None | Some(Value::Null) => false, @@ -132,7 +132,7 @@ pub fn timestamp(value: &Value) -> Option { parse_instant(value.as_str()?) } -/// Parse an ISO date-time like JavaScript's `Date.parse`, local time when no offset is given. +/// Parse an ISO date-time, as local time when no offset is given. pub fn parse_instant(text: &str) -> Option { let b = text.as_bytes(); let shape = b.len() > 10 @@ -153,7 +153,7 @@ pub fn parse_instant(text: &str) -> Option { Some(zoned.timestamp().as_millisecond()) } -/// Format an instant like JavaScript's `Date.prototype.toISOString`. +/// Format an instant as UTC with milliseconds, such as `2026-11-01T00:00:00.000Z`. pub fn iso(millis: Millis) -> String { let ts = jiff::Timestamp::from_millisecond(millis).expect("instant in range"); ts.strftime("%Y-%m-%dT%H:%M:%S%.3fZ").to_string() diff --git a/src/terminal.rs b/src/terminal.rs index ba27e4d..b65208e 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -435,7 +435,7 @@ mod tests { } } - // Ported from report.test.ts: narrow output never exceeds its width. + // Narrow output never exceeds its width. #[test] fn every_row_fits_its_width() { let text = "Change claude-cache-ttl for /home/user/.claude/projects/very-long-directory-name 漢字😀 to 1h; saves $12.34 per month."; diff --git a/src/test_support.rs b/src/test_support.rs index 3b9234c..89091fd 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -202,8 +202,8 @@ impl Drop for Workspace { } } -/// One synthetic Claude transcript of `profile` with `skipped` unreadable lines, which hold -/// `lines` and leave `unmatched` tool results without a parsed call. +/// One synthetic Claude transcript of `profile` whose unreadable lines are `lines`, which +/// leave `unmatched` tool results without a parsed call. pub fn make_snapshot(profile: &str, lines: &[&str], unmatched: u64) -> Snapshot { let mut unreadable = crate::unreadable::Unreadable::default(); for line in lines { diff --git a/src/wire.rs b/src/wire.rs index ac7712c..8e8e2cf 100644 --- a/src/wire.rs +++ b/src/wire.rs @@ -184,6 +184,7 @@ pub struct Stream { } impl Stream { + /// Reads values from `reader`. pub fn new(reader: R) -> Self { Self { json: serde_json::Deserializer::from_reader(reader), diff --git a/tests/cli.rs b/tests/cli.rs index 08bfe1a..50ee9d0 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -730,7 +730,7 @@ fn sessions_prints_one_json_line_per_session_and_only_takes_its_options() { assert!(help.contains("\n sessions "), "{help}"); } -/// Floats print as JavaScript prints them: integers without a fraction, no `1.0`. +/// Floats print in shortest form: integers without a fraction, no `1.0`. #[test] fn session_numbers_print_like_javascript() { let w = Workspace::new(); @@ -999,7 +999,7 @@ fn a_relocated_binary_runs_from_any_directory_with_relative_paths() { assert!(!stderr.contains("SYNTHETIC_PRIVATE")); } -// Ported from fast.test.ts: "built CLI warns from current settings alone, remains read-only and skips unreadable lines". +// Built CLI warns from current settings alone, remains read-only and skips unreadable lines. #[test] fn warns_from_current_fast_settings_alone_stays_read_only_and_skips_unreadable_lines() { let w = Workspace::new();