diff --git a/.github/scripts/vsixPolicy.mjs b/.github/scripts/vsixPolicy.mjs index bfe9b1ff..5564194e 100644 --- a/.github/scripts/vsixPolicy.mjs +++ b/.github/scripts/vsixPolicy.mjs @@ -18,6 +18,10 @@ const FORBIDDEN_ENTRY_PATTERNS = [ /^extension\/node_modules(?:\/|$)/i, /^extension\/issue87-.*\.cjs$/i, /^extension\/out\/claudeIncrementalPrototype\.js$/i, + /^extension\/out\/adviceEffectiveness\/(?:evidencePreparation|feedback|legacyBridge|legacyPersonalization|modelExperiment)\.js$/i, + /^extension\/out\/(?:adviceDemoSample|adviceSummary)\.js$/i, + /^extension\/(?:AI-ADVICE-.*V2\.3\.1|V2\.3\.1-CANDIDATE-CONTRACT(?:\.zh-CN)?)\.md$/i, + /^extension\/CLAUDE-COLD-AB-V2\.3\.1(?:\.zh-CN)?\.md$/i, /(?:^|\/)\.env(?:\.|$)/i, /\.(?:pem|key|p12|pfx)$/i, ]; diff --git a/.github/scripts/vsixPolicy.test.mjs b/.github/scripts/vsixPolicy.test.mjs index 8b95bf91..0fbc97b9 100644 --- a/.github/scripts/vsixPolicy.test.mjs +++ b/.github/scripts/vsixPolicy.test.mjs @@ -73,6 +73,26 @@ test('VSIX policy rejects internal Superpowers review material', () => { ); }); +test('VSIX policy rejects dormant v2.3.1 preparation seams and review documents', () => { + for (const entry of [ + 'extension/out/adviceEffectiveness/evidencePreparation.js', + 'extension/out/adviceEffectiveness/feedback.js', + 'extension/out/adviceEffectiveness/legacyBridge.js', + 'extension/out/adviceEffectiveness/legacyPersonalization.js', + 'extension/out/adviceEffectiveness/modelExperiment.js', + 'extension/out/adviceDemoSample.js', + 'extension/out/adviceSummary.js', + 'extension/AI-ADVICE-INTEGRATION-V2.3.1.md', + 'extension/V2.3.1-CANDIDATE-CONTRACT.zh-CN.md', + ]) { + assert.throws( + () => assertSafeVsixEntries([...minimalEntries, entry]), + /forbidden VSIX entry/, + entry, + ); + } +}); + test('VSIX policy rejects unsafe or non-canonical archive paths', () => { for (const entry of [ '/extension/out/extra.js', diff --git a/.vscodeignore b/.vscodeignore index ec2a3674..ce7fa89c 100644 --- a/.vscodeignore +++ b/.vscodeignore @@ -20,6 +20,16 @@ CONTRIBUTING.md probe-*.mjs issue87-*.cjs out/claudeIncrementalPrototype.js +out/adviceEffectiveness/evidencePreparation.js +out/adviceEffectiveness/feedback.js +out/adviceEffectiveness/legacyBridge.js +out/adviceEffectiveness/legacyPersonalization.js +out/adviceEffectiveness/modelExperiment.js +out/adviceDemoSample.js +out/adviceSummary.js +AI-ADVICE-*V2.3.1*.md +CLAUDE-COLD-AB-V2.3.1*.md +V2.3.1-CANDIDATE-CONTRACT*.md docs/** .gitignore diff --git a/AGENTS.md b/AGENTS.md index eab08c5f..3ed71d86 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -213,3 +213,6 @@ Co-authored-by: OpenAI Codex <215057067+openai-codex[bot]@users.noreply.github.c ``` - Keep controlled comment-only first-pass automation separate from the privileged maintainer-only mention workflow. + +## Codex 工具適配 +瀏覽器操作使用當前 Codex browser/computer-use 工具;原文的 Claude MCP 工具名稱只描述操作意圖,不能直接呼叫。提問依目前模式使用可用工具;Git 操作仍需當次明確授權。 diff --git a/AGENTS.zh-CN.md b/AGENTS.zh-CN.md index 524e0cab..86e2e667 100644 --- a/AGENTS.zh-CN.md +++ b/AGENTS.zh-CN.md @@ -177,3 +177,9 @@ Co-authored-by: OpenAI Codex <215057067+openai-codex[bot]@users.noreply.github.c ``` - comment-only 的受控 first-pass automation 与 maintainer-only 的高权限 mention workflow 必须保持分离。 + +## Codex 工具适配 + +浏览器操作使用当前可用的 Codex browser/computer-use 工具;原文中的 Claude MCP +工具名称只描述操作意图,不能直接调用。提问按当前模式使用可用工具;Git 操作仍须 +获得当次明确授权。 diff --git a/ARCHITECTURE-zh-CN.md b/ARCHITECTURE-zh-CN.md index d293b4e6..cca2e1c4 100644 --- a/ARCHITECTURE-zh-CN.md +++ b/ARCHITECTURE-zh-CN.md @@ -3,11 +3,16 @@ > 本文简要说明扩展的 provider 边界、数据流与用量语义。模块职责或 > provider 行为变化时必须同步更新。英文版见 > [`ARCHITECTURE.md`](ARCHITECTURE.md)。 +> 持久数据清单、保留、迁移、清除和网络边界的规范来源是双语 +> [`v2.3.1 本地数据契约`](docs/superpowers/specs/2026-09-02-v2.3.1-local-data-contract.zh-CN.md)。 ## 产品边界 **Claude Code Usage** 继续保持 local-first、无 runtime dependency 和 read-mostly。 v2.3.0 保留完整 Claude 体验,并增加 provider-specific 的 Codex Beta 用量与优化视图。 +v2.3.1 候选在不改变 provider 计量口径的前提下,增加一套默认关闭、 +local-first 的建议有效性闭环、唯一的显式 BYOK 请求边界、可持久的历史任务状态、 +Codex 有界的本地每周重置观测历史,以及滚动 30 天的日期→小时投影。 - Claude:精确的本地 token bucket、模型成本估算和 Anthropic OAuth 5 小时/每周配额。 - Codex Beta:本地 processed/fresh/cache/output/reasoning 指标、模型与 effort 拆分、 @@ -25,19 +30,25 @@ Opt-in GitHub 认证和跨设备聚合同步延后到 v2.4.x,届时单独做 | `extension.ts` | 激活、命令、设置、provider 生命周期、刷新编排、watcher、状态栏/webview 接线和匿名诊断。 | | `dataLoader.ts` | 为精确兼容保留的 Claude 解析、校验、归因和内容分析 primitive。 | | `claudeIncrementalIndex.ts` | 生产环境 Claude 内存 per-file 索引:append-tail 解析、精确跨文件 response 去重、受影响 group 聚合、内容分析 contribution 和已物化 dashboard row。 | +| `adviceEffectiveness/contract.ts`、`adapters.ts`、`payload.ts` | 严格的观察/证据/建议/行动/结果契约,隐私重建型 provider adapter,以及 canonical 聚合/个性化 payload。 | +| `adviceEffectiveness/preparedRequest.ts` / `remoteAdvice.ts` | host 持有的唯一完整 HTTP Prepared 对象、精确 preview/send bytes、BYOK-only 授权、取消与严格结构化解析。 | +| `adviceEffectiveness/comparisonPairing.ts`、`comparisonResult.ts`、`versionedPersistence.ts` | 净化的可比任务配对、冻结的 measurement-version envelope 与有界的本地反馈/比较存储。 | +| `optimizerRequest.ts` | 仅用户粘贴草稿通过同一 Prepared 与严格发送边界;不回退到 advice 证据 parser。 | +| `backgroundWorkState.ts` / `resourceOwnership.ts` | 可持久的 progress/backoff/pause 状态,以及供测试核对 timer、watcher、worker、network 和 backfill 创建者/停止/真实销毁的 registry。 | | `providers/providerTypes.ts` | Provider-neutral token、event、confidence、outcome、coverage 和 limit contract。 | | `providers/claudeProvider.ts` | 薄兼容 adapter,不改变既有 Claude 聚合结果。 | | `providers/codex/codexSchema.ts` | 最小安全 JSON guard,不展开或返回 message/command/tool body。 | | `providers/codex/codexParser.ts` | Codex 精确单次请求解析及 cumulative high-water 回退、伪名 lineage metadata、结构计数、quality flag 和 last-observed limit。 | | `providers/codex/codexManifest.ts` | Codex 允许目录发现、HMAC file key、fingerprint 和 manifest diff。 | -| `providers/codex/codexIndex.ts` | schema-3 的 per-file 数字聚合与重放证据持久化、有界 cold/tail parse、独立 aggregate/period/current-day coverage 和原子存取。 | +| `providers/codex/codexIndex.ts` | schema-3 的 per-file 数字聚合与重放证据持久化、有界 cold/tail parse、独立 aggregate/period/滚动 30 天小时 coverage 和原子存取。 | +| `providers/codex/codexQuotaHistory.ts` | 小型、账户中性的每周重置观测缓存;压缩重复本地样本,不保留凭据、账户名或原始标签。 | | `providers/codex/codexIndexWorker.ts` / `codexIndexClient.ts` | 后台协调器、recent-first progress、cancel、resume、checkpoint 持久化和 single-flight client。 | | `providers/codex/codexFilePassPool.ts` / `codexFilePassWorker.ts` | 未完成回填期间,用于独立 main、lineage、period、current-day 和 identity per-file pass 的自适应受限本地 pool。 | | `providers/codex/codexProvider.ts` | 面向 extension 的 Codex snapshot facade 与 partial/unavailable/error outcome。 | | `providers/codex/codexUsage.ts` | Codex 自然日 Today/小时、7 天、30 天、月度、task 与项目 view model 聚合,以及精确模型 API 等效成本。 | | `providers/codex/codexInsights.ts` | 确定性的结构用量建议,不读 prompt/body。 | | `codexView.ts` / `codexViewComponents.ts` | Codex 本地化文案与默认 provider contract;不负责 HTML renderer、client script 或 CSS。 | -| `settings.ts` | 权威 `SETTINGS` catalog 和 `SettingsStore`;不得散落直接读取。 | +| `settings.ts` | 权威 `SETTINGS` catalog 和 `SettingsStore`;普通值进入 configuration/globalState,BYOK 凭证只进入 SecretStorage,且绝不进入 Webview snapshot。不得散落直接读取。 | | `statusBar.ts` / `codexStatus.ts` | Provider-specific 状态展示和通用 Claude 配额格式化。 | | `webview.ts` | Claude/Codex 唯一一套 provider-aware dashboard shell、共享 render function、共享 client 行为、provider tab 与 Compare 展示。 | | `i18n.ts` | 八个 UI locale 的全部用户可见文案。 | @@ -60,13 +71,20 @@ Claude JSONL ──> manifest metadata ──> background worker ──> schema guard + 精确单次请求 parser(lineage high-water 回退) - ──> per-file 数字聚合索引 + 定向的当日小时 sidecar + ──> per-file 数字聚合索引 + 有界账户中性的每周重置历史 + ──> 滚动稀疏 30 天小时 sidecar ──> CodexProviderSnapshot ──> Codex scope + insight ──> Codex 状态栏 + provider-aware dashboard render input Claude aggregate + Codex scope ──> 同一套 `webview.ts` dashboard render stack Claude aggregate + Codex scope ──> 并列 Compare(不跨 provider 求和) + +已物化 provider snapshot + ──> 隐私重建型 advice adapter + ──> 本地证据 + 确定性建议 + ──> 可选 host-owned Prepared 请求 ──> 预览 ──> 显式 BYOK 发送 + ──> 本地反馈 ──> 净化可比 pair ──> 冻结 comparison envelope ``` 任一 provider unavailable 或 partial 时,不清空另一 provider 最近验证的 snapshot。 @@ -79,7 +97,8 @@ provider 都已有真实数据时才显示「对比」。worker 启动前先装 选中 Codex 时才重绘 Webview;refresh 返回后仍会用已验证 snapshot 做最后一次渲染。 Codex 的「今天」指配置时区中的当前自然日,而不是最近任务。汇总来自该日已验证的 period slice; -精确小时行来自下文所述的独立当日 sidecar。小时、每日与每月主图默认使用 API 等效成本,Token 构成图 +精确小时行与 30 天日期下钻来自下文的独立滚动 sidecar。点击已渲染日期只展开这份投影, +不要求 host 读取 JSONL。小时、每日与每月主图默认使用 API 等效成本,Token 构成图 仍独立展示。未知模型计入 Token 分母但保持未定价,因此定价 coverage 始终可见。Claude 与 Codex 的 时间序列布局使用对齐的响应式宽度,较密集的图表和表格在各自可键盘聚焦的区域内滚动。 @@ -106,7 +125,10 @@ output 与 reasoning component 是精确的单次请求归因。`last_token_usag parent baseline,因此该路径按 component 与 lineage 维护 high-water。Unknown parent、counter regression 和 schema drift 产生 quality flag,不生成负用量或伪造精度。 -本地日志中的 Codex `rate_limits.primary` 只是 last-observed snapshot,到 reset 时间后隐藏。 +本地日志中的 Codex `rate_limits` 只是 last-observed snapshot,到 reset 时间后隐藏。 +v2.3.1 候选还会保留一份有界、账户中性的 account-wide 每周观测历史:同一重置边界的 +重复样本只保留一个代表,真正不同的重置时刻则分别保留。这份历史用于对齐和复核每周 +估算,不是账户注册表;如果某次重置从未出现在本地日志行里,插件也无法凭空发现它。 v2.3.0 不读 Codex credential,也不发网络请求刷新它。 ## 隐私与持久化 @@ -118,9 +140,19 @@ Codex 发现仅限: - 默认 `$CODEX_HOME`:`~/.codex` 绝不读取 `auth.json`、SQLite、config secret、keychain、浏览器状态或未知文件。 -Raw path/session/parent ID 只留在本地 worker 的短期内存。磁盘只持久化 machine-salted 伪名 key -和按 day/model/effort/session 聚合的数字,绝不存 prompt、response、command、tool arguments、 -raw line 或 raw path。 +Raw path/session/parent ID 只留在本地 worker 的短期内存。磁盘只持久化 machine-salted 伪名 key、 +按 day/model/effort/session 聚合的数字,以及上面所述的有界账户中性额度历史;绝不存 prompt、 +response、command、tool arguments、raw line、raw path、账户名、凭据或原始 provider label。 + +Advice 只消费已物化聚合,不重读 JSONL,也不重遍历保留的 records。远程默认为 +aggregate-only;prompt sample 与可选 user context 需单独明确同意,并必须原样出现在精确请求预览中。 +host 保管 Prepared 对象和 API key;webview 只拿到预览与不透明 handle。第二次点击才把同一 bytes 对象 +发给用户配置的 BYOK endpoint。Feedback、comparable pair 与 comparison envelope 全部保持本地, +不接受 prompt、response、path、session、title、endpoint 或 credential 字段。 + +Advice 同意变更会立即作废 Prepared handle。host 的 pending-write 计数器在全部排队同意 +写入结束前阻止新预览与发送;持久化失败保持关闭。聚合或提示授权撤回还会通过既有 network +owner 取消在途建议请求,与仅含用户草稿的 Optimizer 请求隔离。取消不能追回已传出的字节。 Machine salt 存在 VS Code `globalState`,不写入索引。Worker progress/result/error 与 diagnostics 只含匿名计数与时间,不含 path 或 ID。 @@ -150,10 +182,10 @@ aggregate;按日的期间切片则独立晋升,因此 partial migration 不 all-time 的状态。7 天与 30 天只累加自然日内发生的 event;不会因为 Session 的最后活动落在范围内, 就把该 Session 的整段较早历史吸收进来。 -当日小时索引是 schema 3 的增量 sidecar,不是第三份 all-time 事实来源。只有经重复分类选为 canonical, -且已验证 period slice 已包含 `asOfDay` 的文件才会进入候选集。每个文件的小时晋升状态与处理中 cursor -都会写入 checkpoint,因此取消后可从已验证 offset 续传。日期或时区变化时会丢弃过期 sidecar,改为 -目标新自然日;该路径既不使主 aggregate 失效,也不会触发全历史重建。 +滚动 30 天小时索引是 schema 3 的增量 sidecar,不是第三份 all-time 事实来源。只有经重复分类选为 +canonical,且已验证 period slice 与配置自然日窗口相交的文件才会进入候选集。每个文件的小时晋升状态与 +处理中 cursor 都会写入 checkpoint,因此取消后可从已验证 offset 续传。窗口前移时淘汰第 31 天; +时区改变只请求一次定向迁移。该路径既不使主 aggregate 失效,也不会触发无关的全历史重建。 Identity 同样是一份 coverage 契约。Git 的 SCP 形式 SSH URL 与 HTTPS URL 在 host/path 一致时 会规范化为同一个 repository identity。Root title 采用可信的最新 `updated_at` title;subagent @@ -192,17 +224,31 @@ Codex 按多 GiB 本地历史设计: 数十 MB snapshot 主导高速回填耗时; - 只有可能改变 lineage 的阶段才重新 reconcile;period 和稳定阶段复用已验证关系, 不再反复扫描完整索引; -- 当日小时任务仅处理 period slice 已证明包含 `asOfDay` 的 canonical 文件;它独立 checkpoint/续传, - 不会重置主索引; +- 滚动 30 天小时任务仅处理 period slice 已证明与配置自然日窗口相交的 canonical 文件; + 它独立 checkpoint/续传,滚动淘汰第 31 天,不会重置主索引; - append refresh 只读新 tail;未完成行只留在 scanner 的短期内存,从 safe cursor 重试,绝不写入 v3; - truncate/replacement 只重解析受影响文件; - cancel checkpoint 会原子保存 per-file contribution 与 migration progress,下一轮从已验证 cursor resume; - 并发 refresh 共享同一 worker run。 -每周 API 等效价值历史只从已经聚合的 Token 用量生成。有真实每周重置观测时,七天窗口按该重置 -对齐;没有时,仅已用历史按 UTC 周一至周一的自然周分组。Token 日志能够证明已用价值,但不能证明 -历史订阅总额度,因此总额度与未用额度仅在存在真实额度用量比例观测时生成。Codex 的仅已用历史可能 -合并同一 home 中的多个登录,而额度推算行仍绑定其实际观测的重置序列。 +额度历史由同一批 JSONL 解析流程顺便填充。旧的完整索引最多接受一次基于已保存 +last-observed limit 的 metadata-only 播种;不会增加第二套额度扫描器、timer、网络轮询或凭据读取。 +播种完成后,未变化的 warm refresh 仍然读取 0 字节用量正文。 + +历史任务还使用一份精简的可持久控制状态:measurement version、reason、progress、 +failure streak、next eligible time 和 pause reason。成功后立即继续,不人为等待;失败或无进展后 +进入 backoff,普通 refresh/watch/focus 事件不能重启同一停滞迁移。Resource registry 记录每个 timer、 +watcher、worker、network request 与 backfill 的创建者,只在真实 stop callback 完成后释放 lease。 +为降低首次可用延迟,有界的首次索引可在失焦后继续;但 extension dispose、provider 关闭或显式取消 +仍对其终止负责。 + +每周 API 等效价值历史只从已经聚合的 Token 用量生成。最新有效的重置观测用于锚定互不重叠的七天 +展示窗口;没有观测时,仅已用历史按 UTC 周一至周一的自然周分组。真实的额度用量比例观测可以支持 +历史窗口的总额度近似,而不只支持当前窗口。Codex 的 account-wide `codex` series 会纳入同一 home +中所有符合条件的本地文件,因为文件键不是账号身份。重置时间如果偏离七天网格,则按观测时间映射到 +对应展示窗口;来源不确定、重置漂移或日切片跨边界时降低可信度并标注为近似。真正不同的 quota +series 仍仅显示已用值;当前周期不显示未用值,历史周期只有在同时存在总额度近似时才显示未用值。 +每条用量仍只进入一个窗口。 v2.3.0 不推断 20、100 或 200 美元的订阅档位。本地 Codex 日志没有可靠的账号与套餐身份, 后续比较必须采用用户明确选择的 opt-in 账号映射,不能猜测后绑定价格。 @@ -213,6 +259,7 @@ v2.3.0 不推断 20、100 或 200 美元的订阅档位。本地 Codex 日志没 和安装 VSIX smoke test。 - 用户可见字符串覆盖 `en`、`de-DE`、`zh-TW`、`zh-CN`、`ja`、`ko`、`pt-BR`、`id`; 七份 README 同步。 +- dormant 的 preparation/experiment 模块与仅供评审的 v2.3.1 文档必须保持不可从生产 command graph 到达,并排除出 VSIX。 - 不手工修改 `package.json` 版本。发布已审阅的 Release Drafter draft 后才创建 tag, publish workflow 再从 tag 写入包版本。 - 通过合并贡献者原 PR,或经授权先修改该 PR 分支再合并,保留贡献归属。 diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index baf4852b..164abf04 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -4,12 +4,19 @@ > semantics. Update it whenever module ownership or provider behavior changes. > A faithful Simplified-Chinese companion lives in > [`ARCHITECTURE-zh-CN.md`](ARCHITECTURE-zh-CN.md). +> The normative persistent-data inventory, retention, migration, clearing, and +> network boundaries live in the bilingual +> [`v2.3.1 local data contract`](docs/superpowers/specs/2026-09-02-v2.3.1-local-data-contract.md). ## Product boundary **Claude Code Usage** remains local-first, dependency-free, and read-mostly. v2.3.0 preserves the complete Claude experience and adds Codex Beta as a provider-specific usage and optimization view. +The v2.3.1 candidate adds a default-off, local-first advice-effectiveness loop, +a single explicit BYOK request boundary, durable historical-work state, a +bounded local history of Codex weekly reset observations, and a rolling 30-day +Codex date/hour projection without changing provider accounting. - Claude: exact local token buckets, model pricing estimates, and Anthropic OAuth 5-hour/weekly quota. @@ -32,19 +39,25 @@ aggregate sync are deferred to v2.4.x after a separate privacy review. | `extension.ts` | Activation, commands, settings, provider lifecycle, refresh orchestration, watchers, status/webview wiring, and anonymous diagnostics. | | `dataLoader.ts` | Claude parsing, validation, attribution, and content-analysis primitives retained for exact compatibility. | | `claudeIncrementalIndex.ts` | Production in-memory per-file Claude index: append-tail parsing, exact cross-file response deduplication, affected-group aggregation, content-analysis contributions, and materialized dashboard rows. | +| `adviceEffectiveness/contract.ts`, `adapters.ts`, and `payload.ts` | Strict observation/evidence/recommendation/action/result contracts, privacy-rebuilding provider adapters, and canonical aggregate/personalization payloads. | +| `adviceEffectiveness/preparedRequest.ts` and `remoteAdvice.ts` | One host-owned full HTTP request object, exact preview/send bytes, BYOK-only authorization, cancellation, and strict structured-advice parsing. | +| `adviceEffectiveness/comparisonPairing.ts`, `comparisonResult.ts`, and `versionedPersistence.ts` | Sanitized comparable-task pairing, frozen measurement-version envelopes, and bounded local feedback/comparison storage. | +| `optimizerRequest.ts` | User-draft-only projection through the same prepared-request and strict-send boundary; no advice-evidence parser fallback. | +| `backgroundWorkState.ts` / `resourceOwnership.ts` | Durable progress/backoff/pause state and the testable creator/stop/disposal registry for timers, watchers, workers, network calls, and backfills. | | `providers/providerTypes.ts` | Provider-neutral token, event, confidence, outcome, coverage, and limit contracts. | | `providers/claudeProvider.ts` | Thin compatibility adapter that exposes existing Claude aggregates without changing their results. | | `providers/codex/codexSchema.ts` | Minimal safe JSON guards; never flattens or returns message/command/tool bodies. | | `providers/codex/codexParser.ts` | Codex exact-request parsing with cumulative high-water fallback, pseudonymous lineage metadata, structural counters, quality flags, and last-observed limits. | | `providers/codex/codexManifest.ts` | Allowlisted Codex directory discovery, HMAC file keys, fingerprints, and manifest diffing. | -| `providers/codex/codexIndex.ts` | Schema-3 persistent per-file numeric aggregates and replay evidence, bounded cold/tail parsing, independent aggregate/period/current-day coverage, and atomic save/load. | +| `providers/codex/codexIndex.ts` | Schema-3 persistent per-file numeric aggregates and replay evidence, bounded cold/tail parsing, independent aggregate/period/rolling-30-day-hour coverage, and atomic save/load. | +| `providers/codex/codexQuotaHistory.ts` | Small account-neutral weekly reset-observation cache; compacts repeated local samples without retaining credentials, account names, or raw labels. | | `providers/codex/codexIndexWorker.ts` / `codexIndexClient.ts` | Background coordinator, recent-first progress, cancellation, resume, checkpoint persistence, and single-flight client. | | `providers/codex/codexFilePassPool.ts` / `codexFilePassWorker.ts` | Adaptive bounded local pool for independent per-file main, lineage, period, current-day, and identity passes during incomplete backfills. | | `providers/codex/codexProvider.ts` | Extension-facing Codex snapshot facade and partial/unavailable/error outcomes. | | `providers/codex/codexUsage.ts` | Codex calendar-Today/hourly, 7-day, 30-day, monthly, task, and project view-model aggregation with exact-model API-equivalent cost. | | `providers/codex/codexInsights.ts` | Deterministic structural usage guidance; no prompt/body inspection. | | `codexView.ts` / `codexViewComponents.ts` | Codex localized-copy and default-provider contracts; no HTML renderer, client script, or CSS ownership. | -| `settings.ts` | Canonical `SETTINGS` catalog and `SettingsStore`; do not scatter direct reads. | +| `settings.ts` | Canonical `SETTINGS` catalog and `SettingsStore`; ordinary values use configuration/globalState, while BYOK credentials use SecretStorage and never enter Webview snapshots. Do not scatter direct reads. | | `statusBar.ts` / `codexStatus.ts` | Provider-specific status presentation and generic Claude quota formatting. | | `webview.ts` | Single provider-aware Claude/Codex dashboard shell, shared render functions, shared client behavior, provider tabs, and Compare presentation. | | `i18n.ts` | All user-facing copy for all eight UI locales. | @@ -68,13 +81,20 @@ allowlisted Codex JSONL ──> manifest metadata ──> background worker ──> schema guard + exact-request parser with lineage high-water fallback - ──> per-file numeric aggregate index + targeted current-day hourly sidecar + ──> per-file numeric aggregate index + bounded neutral weekly-reset history + ──> rolling sparse 30-day hourly sidecar ──> CodexProviderSnapshot ──> Codex scopes + insights ──> Codex status + provider-aware dashboard render inputs Claude aggregates + Codex scopes ──> one `webview.ts` dashboard render stack Claude aggregates + Codex scopes ──> side-by-side Compare (no cross-provider totals) + +materialized provider snapshots + ──> privacy-rebuilding advice adapters + ──> local evidence + deterministic recommendations + ──> optional host-owned Prepared request ──> preview ──> explicit BYOK send + ──> local feedback ──> sanitized comparable pairs ──> frozen comparison envelope ``` One provider may be unavailable or partial without clearing the other @@ -93,7 +113,9 @@ still gets a final render when the refresh returns. Codex Today is the current civil day in the configured timezone, not the most recent task. Its summary uses that day's verified period slice; exact hourly -rows come from the independent current-day sidecar described below. Hourly, +rows and 30-day drill-downs come from the independent rolling sidecar described +below. Clicking an already-rendered date only reveals that projection and does +not ask the host to read JSONL. Hourly, daily, and monthly primary charts use API-equivalent cost by default, while the token-composition chart remains a separate view. Unknown models contribute to the token denominator but remain unpriced, so pricing coverage stays visible. @@ -127,9 +149,14 @@ fallback and may include an inherited parent baseline. That path uses per-component, per-lineage high-water marks. Unknown parents, regressions, and schema drift produce quality flags rather than negative or fabricated usage. -Codex `rate_limits.primary` found in local logs is a last-observed snapshot only. -It is hidden once its reset time passes. v2.3.0 does not read Codex credentials -or make a network call to refresh it. +Codex `rate_limits` found in local logs is a last-observed snapshot only. It is +hidden once its reset time passes. The v2.3.1 candidate also keeps a bounded, +account-neutral history of account-wide weekly observations: repeated samples +for one reset boundary collapse to one representative, while genuinely +different reset times remain separate. This history is evidence for aligning +and auditing weekly estimates; it is not an account registry and cannot reveal +a reset that never appears in a local log line. v2.3.0 does not read Codex +credentials or make a network call to refresh it. ## Privacy and persistence @@ -141,9 +168,25 @@ Codex discovery is restricted to: It never reads `auth.json`, SQLite databases, config secrets, keychains, browser state, or unknown files. Raw paths/session/parent IDs stay in short-lived local -worker memory. Disk persistence contains machine-salted pseudonymous keys and -numeric per-day/model/effort/session aggregates only—never prompt, response, -command, tool-argument, raw-line, or raw-path content. +worker memory. Disk persistence contains machine-salted pseudonymous keys, +numeric per-day/model/effort/session aggregates, and the bounded neutral quota +history described above—never prompt, response, command, tool-argument, +raw-line, raw-path, account name, credential, or raw provider-label content. + +Advice starts from materialized aggregates rather than rereading JSONL or +walking retained records. Aggregate-only is the remote default. Prompt samples +and optional user context have a separate explicit consent and must appear in +the exact request preview. The host keeps the prepared object and API key; the +webview receives only the preview and an opaque handle. A second click sends the +same byte object to the configured BYOK endpoint. Feedback, comparable pairs, +and comparison envelopes remain local and accept no prompt, response, path, +session, title, endpoint, or credential field. + +Advice consent changes invalidate prepared handles immediately. A host-side +pending-write counter blocks new previews and sends until every queued consent +write settles; failed persistence stays closed. Aggregate/prompt revocation also +cancels active advice transports through the existing network owner, separately +from user-draft Optimizer calls. Cancellation cannot recall transmitted bytes. The machine salt lives in VS Code `globalState`, not in the index file. Worker progress/results/errors and diagnostics contain anonymous counts and timings, @@ -187,13 +230,14 @@ states. The 7/30-day views sum events in their natural calendar days; they do not pull an entire older session into a range merely because the session's last activity falls inside it. -The current-day hourly index is an additive schema-3 sidecar, not a third source -of all-time truth. A file becomes eligible only after duplicate classification -selects it as canonical and its verified period slice already contains -`asOfDay`. Per-file hourly promotion and in-progress cursors are checkpointed, -so cancellation resumes from the verified offset. A day or timezone change -discards the stale sidecar and targets the new civil day. This path neither -invalidates the primary aggregate nor triggers a full-history reindex. +The rolling 30-day hourly index is an additive schema-3 sidecar, not a third +source of all-time truth. A file becomes eligible only after duplicate +classification selects it as canonical and its verified period slice intersects +the configured civil-day window. Per-file hourly promotion and in-progress +cursors are checkpointed, so cancellation resumes from the verified offset. +Day 31 is evicted as the window advances. A timezone change requests one +targeted migration. This path neither invalidates the primary aggregate nor +triggers an unrelated full-history reindex. Identity is also a coverage contract. Git SCP-style SSH and HTTPS repository URLs are canonicalized to the same repository identity where their host/path @@ -247,9 +291,10 @@ Codex history is designed for multi-gigabyte local corpora: - derived lineage is reconciled only in stages that can change it; period and stable stages reuse the verified relationship instead of repeatedly scanning the complete index; -- current-day hourly work is limited to canonical files already known from - period slices to contain `asOfDay`; its own checkpoints resume independently - and do not reset the primary index; +- rolling 30-day hourly work is limited to canonical files already known from + period slices to intersect the configured civil-day window; its own + checkpoints resume independently, evicts day 31, and does not reset the + primary index; - append refresh reads only the new tail; an incomplete line stays only in the scanner's short-lived memory and is retried from the safe cursor, never in v3; - truncation/replacement reparses only the affected file; @@ -257,13 +302,34 @@ Codex history is designed for multi-gigabyte local corpora: progress, so the next run resumes from the verified cursor; - concurrent refresh requests share one worker run. +Quota history is populated opportunistically by those same JSONL passes. An +older complete index may receive one metadata-only seed from its already saved +last-observed limit, but there is no second quota scanner, timer, network poll, +or credential lookup. Once that seed is present, an unchanged warm refresh +continues to read zero usage-record bodies. + +Historical work also has a small durable control state: measurement version, +reason, progress, failure streak, next eligible time, and pause reason. Progress +continues immediately after success. Failure or no progress applies backoff, so +ordinary refresh/watch/focus events cannot restart the same stalled migration. +The resource registry records who created every timer, watcher, worker, network +request, and backfill, and releases a lease only after its real stop callback +finishes. A bounded first-index backfill may continue after focus loss for +first-use latency, but extension disposal, provider disable, or explicit +cancellation still owns its termination. + Weekly API-equivalent history is derived from already-aggregated token usage. -Observed weekly resets align seven-day buckets; otherwise usage-only history -uses Monday-to-Monday UTC calendar weeks. A token log can prove used value, but -not an historical subscription capacity: full and unused estimates are emitted -only where a real quota-utilization sample exists. Codex usage-only history may -combine multiple sign-ins in one home, while quota-derived rows remain bound to -their observed reset series. +The newest valid reset observation anchors non-overlapping seven-day display +buckets; without one, usage-only history uses Monday-to-Monday UTC calendar +weeks. A real utilization sample can support a full-window estimate, including +for historical buckets. For Codex, the account-wide `codex` series is allowed to +use all eligible local files in the same home because file keys are not account +identities. A reset that drifts from the seven-day grid is mapped by observation +time to the corresponding display bucket; source uncertainty, reset drift, and +daily slices crossing a boundary lower confidence and are rendered as an +approximation. A genuinely different quota series remains usage-only. Current +unused value is withheld, while historical unused value is shown only alongside +a full estimate. Each usage row still contributes to exactly one bucket. v2.3.0 does not infer a $20, $100, or $200 subscription tier. Local Codex logs do not expose a reliable account-and-plan identity, so a future comparison must @@ -275,6 +341,8 @@ use an explicit opt-in account mapping rather than attaching prices by guess. VSIX smoke test are required in proportion to the change. - User-visible strings cover `en`, `de-DE`, `zh-TW`, `zh-CN`, `ja`, `ko`, `pt-BR`, and `id`; all seven README editions move together. +- Dormant preparation/experiment modules and review-only v2.3.1 documents stay + unreachable from the production command graph and are excluded from VSIX. - `package.json` is not manually version-bumped. Publishing the reviewed Release Drafter draft creates the tag; the publish workflow stamps that tag version. - Contributor PR attribution is preserved by merging the contributor's original diff --git a/CHANGELOG.md b/CHANGELOG.md index dce931ae..075e06ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,223 @@ All notable changes to this fork compared to upstream [`ClaudeCodeUsage/ClaudeCodeUsage`](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage) (last upstream release: 1.0.8). Format follows [Keep a Changelog](https://keepachangelog.com). +## [2.3.1] — Unreleased + +### Added +- **GPT-6 Astra and Claude Fable 5.1 pricing** — exact model IDs now use their + current official Standard API rates and context windows: `gpt-6-astra` + (1.05M context) and `claude-fable-5-1` / `claude-mythos-5-1` (1M context). + Fable 5.1's model-specific cache-read rate is `$0.25 / MTok`; historical + Fable 5 pricing remains unchanged. GPT-6 requests above 272K input receive a + request-wide surcharge from OpenAI, but local aggregate logs cannot prove + that per-request boundary, so the API-equivalent estimate deliberately uses + the standard short-context rate and keeps the existing request-level-pricing + disclaimer. +- **AWS Bedrock in-region Claude pricing (#95)** — an opt-in Claude pricing + backend covers Opus 4.5–5, Sonnet 4.5–5, and Haiku 4.5 with separate + 5-minute/1-hour cache-write and cache-read rates. Switching backends + invalidates cached Claude cost aggregates so unchanged local logs are + repriced immediately. Sonnet 5 uses the standard in-region rate that applies + after its launch promotion ended on 2026-08-31. Thanks to + [@akapti](https://github.com/akapti) for the contribution. +- **Combined activity heatmap and private sharing** — Compare now leads with a + Claude + Codex calendar heatmap built from the existing provider daily + aggregates. Its preview-first share studio exports deterministic local SVG, a + privacy-safe card, and a copyable Markdown snippet with configurable title, + 30/90-day or yearly range, and an explicit privacy preview. The default + Academic Violet ramp follows the project-profile visual reference, quantile + bands keep isolated peaks from flattening ordinary days, and the mapping can + be switched locally between quantile, logarithmic, and linear modes. Four + curated or one custom accent palette can be selected. Claude-only and + Codex-only histories remain useful; no second log scan or statistics cache is + introduced. +- **Durable quota observation history** — versioned, atomically written, + bounded observations keep provider, machine-local anonymous account epoch, + observation/reset time, used/remaining fraction, window identity, source, + confidence, and quality flags. Window-ID changes, reset-time changes, and + significant usage rollbacks preserve irregular and same-day reset events. +- **Observed weekly allowance estimates** — every valid observation in a + coherent window contributes `priced used equivalent / used fraction`; robust + aggregation weights price/log coverage, boundary quality, attribution, and + recency. Total estimates never fall below confirmed usage, unused estimates + never go negative, and a coherent current or completed window exposes both as + a subscription-durability estimate. If later logs overrun a stale observation, + the full value remains a low-confidence lower bound while unused is withheld + instead of showing a false zero. Unattributed or approximate windows are + labelled low confidence. Even when local Codex quota series overlap, the + current period uses the latest real observation for a clearly labelled + low-confidence blended total/unused estimate; ambiguous completed periods + stay used-only. +- **Evidence-backed advice loop** — the default-off feature keeps local + observations, evidence, recommendations, actions, local helpful/not-helpful/ + applied feedback, and guarded comparable-task results in one surface. When + reliable comparable work is unavailable, it says that the evidence is + insufficient instead of manufacturing an improvement claim. +- **Exact BYOK preview and explicit send** — aggregate-only is the default. + Prompt personalization has separate consent. The complete Anthropic or + OpenAI-compatible request body is prepared once, previewed with its byte count + and SHA-256, and only the same canonical bytes can be sent after a second user + click. Claude Code OAuth credentials are never used for generative requests. +- **Versioned local comparison evidence** — sanitized task pairs and frozen + comparison-result envelopes retain only coarse provider, cohort, metric, + quality, coverage, and version fields. Prompt text, response text, paths, + session identifiers, and task bodies have no persistence field. +- **Bounded local advice snooze** — each recommendation can be paused for seven + days (up to thirty days), moved out of the default summary, and shown again + on demand or after expiry; ratings and applied feedback remain independent. +- **Thirty-day Codex hourly drill-down** — every populated date in the rolling + 30-day view can expand from the already-indexed sparse date/hour sidecar. + Clicking a date reads zero JSONL bodies; the 31st day is evicted, and Claude + and Codex use the configured timezone and shared `HH:00` labels. + +### Changed +- **Refreshed release documentation** — all seven README editions now show the + current Claude Today, Codex overview, collapsed weekly details, and vertical + sharing studio. Captures use the production renderer with disclosed synthetic + fixtures; a repeatable capture script keeps screenshot provenance explicit. +- **Shared dashboard system** — Claude and Codex now reuse the same density, + headings, disclosure controls, chart/table framing, empty states, focus + treatment, responsive navigation, and light/dark design tokens while keeping + provider-specific metric labels and meanings. Dashboard figures use the VS + Code UI font again; monospace remains limited to code and copyable snippets. +- **Preview-first sharing layout** — the combined heatmap now occupies the full + reading width and Card settings sit directly below it. Weekly period tables + are collapsed by default so the trend chart remains primary. The sharing + workspace is enabled by default and one Settings toggle hides all sharing UI. +- **Concise plugin settings** — the verbose local-data inventory and destructive + privacy-control panel no longer renders inside the dashboard. The authoritative + inventory, retention boundaries, and clear paths remain in the repository's + `LOCAL-DATA.md` files. +- **Aligned Codex status bar** — the main Codex item now uses configured-zone + Today instead of Recent task. Its compact quota percentage means remaining + allowance; the tooltip and warning colour continue to use observed utilisation + with Claude's progress bars, thresholds, reset columns, and line wrapping. +- **Chronological month views** — Codex monthly charts and tables render + oldest-first in every range. +- **Explicit Codex uncached composition** — the Token composition summary now + surfaces uncached usage (uncached input + output) while retaining the + non-overlapping uncached-input / cached-input / output stack; reasoning stays + a disclosed subset of output. +- **System-reminder prompt filtering remains intentional** — framework reminder + messages are excluded from user-input counts; token and cost totals are unchanged. +- **One AI request boundary** — the former Get AI Advice command and Usage + Optimizer now enter the same preview, explicit-send, cancellation, strict + response parsing, and local-state boundary. The optimizer still sends only + the draft pasted by the user and keeps its copyable result format. +- **Resumable Codex historical work** — first-use and migration work records its + progress, failure streak, next eligible time, and pause reason. Successful + work continues without an artificial delay; failure or no progress cannot be + hot-looped by ordinary refreshes, and restart resumes from a safe checkpoint. +- **Unified resource ownership** — timers, watchers, workers, network requests, + and backfills expose their creator, stop conditions, and actual disposal to + lifecycle tests. A bounded first-index exception may finish after focus loss, + but disable, explicit cancellation, and extension disposal still stop it. +- **Safer Codex rolling totals and reset history** — recent 7/30-day views no + longer trust an inflated or still-rebuilding period sidecar; they use the + verified daily aggregate until the configured-zone projection catches up. + The existing index pass also captures compact quota observations without + polling, credentials, or a second scanner. + +### Fixed +- **One-time v2.3.0 Codex token-semantics migration** — the per-file parser + state now carries a new semantics version. Existing schema-3 indexes request + one bounded, resumable rebuild instead of retaining pre-fix request + attribution indefinitely; completed files survive partial checkpoints. +- **Account-aware quota confidence** — a reset boundary may remain useful for + deterministic weekly alignment across anonymous Codex epochs, but crossing + an account/profile fingerprint can no longer erase `account-ambiguous`. + Current-window total and unused estimates remain available at low confidence. +- **Deterministic scroll debounce test** — continuous-scroll coverage now emits + one synchronous gesture and advances only the fake clock, removing a race + between animation frames and the 180 ms persistence timer. +- **Immediate advice-consent revocation** — withdrawing aggregate or prompt + consent immediately invalidates prepared previews and cancels active advice + requests, without waiting for local storage. New previews/sends stay blocked + until all consent writes settle; persistence failures stay closed. Unrelated + user-draft Optimizer requests are not cancelled. Already transmitted bytes + cannot be recalled. +- **Claude watcher failures fall back safely** — asynchronous `fs.watch` + errors (for example, an exhausted watch-handle limit) are now handled after + registration, close the owned watcher cleanly, and leave normal polling + active instead of escaping through the Extension Host. +- **Timezone-stable chart date labels** — daily and monthly usage keys no + longer roll back a day or month when a chart metric changes or a drill-down + renders in a Webview host/configured timezone west of UTC. Bare monthly keys + also render as the intended month instead of `Invalid Date`. +- **Configured-zone advice snooze dates** — Advice and Optimizer now format a + snooze expiry with the selected UI locale and configured timezone instead of + whichever timezone happens to host the Extension process. +- **Configured-zone rolling ranges** — the Claude provider heatmap now ends on + today in the configured timezone. Share Card 7-day, 30-day, and yearly scopes, + plus Usage tracking and AI-advice 7-day/30-day attribution, use exact + civil-date windows instead of fixed millisecond cutoffs. Claude and Codex + session range filters now follow those same Today/7-day/30-day date keys. + Claude session, project, branch, and workflow timestamps also use the + configured timezone for their clock and Today/Yesterday/year labels. + Activity near UTC boundaries is no longer omitted or pulled from an adjacent + local day. +- **Complete Share studio localization** — the active Compare sharing workspace + now carries complete German, Japanese, Korean, Brazilian Portuguese, and + Indonesian copy instead of silently falling back to English. A repository + coverage guard keeps all eight supported locales aligned when copy fields + change. +- **Hardened Codex thread-title path redaction** — runtime titles now mask POSIX + absolute paths even when a path is attached directly to a colon or other + punctuation (for example, `3:/Users/name`), preventing local usernames and + filesystem locations from reaching dashboard text or screenshots. +- **Claude chart drill-down reload parity** — expanded day-to-hour and + month-to-day rows now survive a Webview reload, re-request their lazy detail + data, and retain selected/ARIA state. Chart controls derive their drill-down + kind from their own tab instead of whichever tab happened to be active while + the page initialized; an intentional tab switch still clears expansions. +- **Claude rolling-range regression** — Claude's middle dashboard tab now uses + Today plus the preceding 29 configured-zone calendar dates instead of the + current calendar month. The Workflows summary now uses the same rolling range, + classifies runs by their configured-zone start date, and compares against the + matching 30-day total. The monthly-cost status-bar option remains a calendar + month, and an empty Today view identifies the latest recent activity date. +- **Reconciled 30-day Codex statistics** — “Last 30 days” is the configured + timezone's current calendar date plus the preceding 29 dates. The view is + projected from verified daily aggregates, so Today ≤ Last 30 days ≤ All time, + daily/monthly/model/effort totals reconcile, and repeated refresh/reindex does + not accumulate duplicate thread or historical-file usage. +- **Reasoning-effort normalization** — current, legacy, nested, missing, and + invalid structured variants are normalized without guessing from a model + name. Non-zero unknown usage is visible with an explanation; zero-value + unknown rows are omitted. +- **Duplicate share rows fail safely** — identical provider/date rows are + idempotent, conflicting duplicates block export, and absent dates render as + zero in the selected range. +- **Smooth Codex dashboard scrolling** — scroll position is persisted once + after a gesture instead of serializing Webview state on every animation + frame. Live first-index progress now patches its status text in place rather + than rebuilding the complete dashboard DOM every 250 ms, so active indexing + no longer interrupts scrolling or disclosure state. +- **Per-model API-equivalent headlines** — Codex model disclosures now follow + Claude's visual meaning: the green value is an exact-model API-equivalent + price with pricing-coverage help. Unknown models remain visibly unpriced, and + effort disclosures keep their uncached-token value in neutral text. +- **OpenAI reasoning-effort requests** — OpenAI-compatible request bodies now + send `reasoning_effort` without the unsupported top-level `thinking` + parameter, fixing [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94). + Thanks to [@aaroncvan](https://github.com/aaroncvan) for the report and + [@Alex668866](https://github.com/Alex668866) for the precise diagnosis. + +### Privacy and packaging +- Disabled or unconsented advice adds no timer, watcher, worker, network request, + log scan, or hidden Webview render relative to v2.3.0. There are no default or + background AI requests. +- Combined exports contain only title, date range, daily aggregate totals, + provider labels, and caveats—never accounts, fingerprints, projects, threads, + paths, prompts, or log content. Local SVG/Markdown needs no account permission. +- Direct GitHub publication remains an explicit, exact-destination action. It + requests only `public_repo`, verifies a public repository and default branch, + previews create/overwrite, and stores owner/repository/path only after success. + Release validation uses mocks and performs no real repository write. +- Dormant migration/experiment modules and internal v2.3.1 review documents are + explicitly excluded from the VSIX. The human-controlled publish workflow + stamps package metadata from the reviewed `v2.3.1` release tag. + ## [2.3.0] — Unreleased ### Fixed @@ -19,16 +236,19 @@ upstream release: 1.0.8). Format follows [Keep a Changelog](https://keepachangel - **Weekly API-equivalent periods no longer overlap or double-count usage** — the newest valid official reset observation anchors one sequence of unique `[start, reset)` weekly buckets, so each local usage event contributes to - exactly one period. Any overlapping, non-aligned future reset is treated as a - conflict even when its series name differs; it cannot create an additional + exactly one period. A genuinely different quota series with an overlapping, + non-aligned future reset is treated as a conflict; same-series observations + remain one low-confidence series rather than creating an additional "current" row. Codex usage is persisted in daily slices, so a slice that crosses an official intraday reset remains counted once but marks the affected - period as a boundary approximation and suppresses total / unused allowance - inference. This display-only correction does not change the index schema or - trigger a rebuild. Historical Codex periods are always used-value-only; only - the newest current period may infer a total when its reset is unambiguous and - its indexed usage can be attributed to one observation source. Current unused - value remains withheld, and ambiguous multi-sign-in usage stays used-only. + period as a boundary approximation and lowers confidence on any full + allowance estimate. Drifted reset observations are mapped by observation time + to the corresponding display bucket. This display-only correction does not + change the index schema or trigger a rebuild. Same-series Codex observations + can estimate historical as well as current full values from all eligible local + files; current unused value remains withheld, historical unused value requires + a full estimate, and genuinely different quota series or missing evidence stays + used-only. - **Claude changed-file refreshes no longer reread the full corpus (#87)** — the production refresh path now keeps an exact in-memory per-file index, reads only a verified append tail, and rebuilds only affected files for @@ -91,10 +311,12 @@ upstream release: 1.0.8). Format follows [Keep a Changelog](https://keepachangel views now calculate historical used API-equivalent value directly from local token logs. One valid observed reset anchors unique, non-overlapping weekly buckets; without one, usage-only rows use Monday-to-Monday UTC calendar weeks. - Codex historical periods, boundary-approximate daily slices, conflicting reset - sequences, and usage that cannot be assigned to one observed sign-in remain - used-value-only. Only an unambiguous newest current period with single-source - attribution may infer a total allowance; its unused value is still withheld. + Codex account-wide observations can decorate historical and current buckets; + reset drift is mapped by observation time, while source ambiguity and boundary + slices lower confidence. Genuinely conflicting quota series and periods with + no usable observation remain used-value-only. Current unused value is still + withheld, while historical unused value is shown only when a full estimate is + available. Current official API prices are applied consistently and each period includes model-price coverage. This remains an estimate, not a bill or an official subscription price. The panel is enabled by default and can be hidden with diff --git a/LOCAL-DATA.md b/LOCAL-DATA.md new file mode 100644 index 00000000..c8a50812 --- /dev/null +++ b/LOCAL-DATA.md @@ -0,0 +1,116 @@ +# Local data and privacy + +Claude Code Usage is local-first. It reads provider-owned usage logs, stores +only bounded derived state needed for fast refresh and reset-aware estimates, +and never treats API-equivalent cost as a bill. + +This page is the user-facing inventory for v2.3.1. The normative field-level +contract is in +[`docs/superpowers/specs/2026-09-02-v2.3.1-local-data-contract.md`](docs/superpowers/specs/2026-09-02-v2.3.1-local-data-contract.md). + +## What the extension reads and retains + +| Data class | Source | What is retained by the extension | Retention and clearing | Remote interaction | +|---|---|---|---|---| +| Claude usage records | Claude Code's local `projects/**/*.jsonl` | Runtime usage records and an in-memory per-file index; bounded prompt samples only when content analysis is enabled | Released on window reload/exit. Data controls never touch source logs; the separately opt-in Session Actions feature may move one exactly confirmed log to the OS trash (recoverable) | None unless the user separately previews and sends an advice request | +| Codex usage records | `$CODEX_HOME/sessions/**/*.jsonl` and `archived_sessions/**/*.jsonl` | A versioned incremental index of pseudonymous file keys, offsets, numeric usage, dates, model/effort, and sanitized structural aggregates | Until rebuild, explicit clear, schema replacement, or host removal | None | +| Codex titles | Exactly `$CODEX_HOME/session_index.jsonl` | `id → thread_name` is streamed for runtime display; titles are not written to the index | Runtime only | None | +| Quota observations | Claude's official quota response or structured Codex rate-limit events | Provider, machine-local anonymous account epoch, observed/reset time, period, used/remaining fraction, anonymous window identity, source, confidence, and quality flags | At most 180 days and 512 observations per provider/account/period after boundary-preserving compaction; clear separately or with all derived data | Claude quota lookup contacts Anthropic when enabled; Codex quota evidence is local | +| Settings and UI preferences | User choices | Typed extension settings, selected tab/filters, bounded background-work state, heatmap title/range/privacy preview | Until reset, clear, or uninstall; ordinary VS Code settings may participate in Settings Sync | No extension-initiated transfer | +| Share destination | User-entered GitHub target | Optional `owner/repository/path`; no GitHub credential | Until sharing preferences are reset | Only after an explicit publish action and exact destination confirmation | +| Advice evidence | Derived local aggregates and explicit feedback | Coarse observations, recommendations, ratings, snoozes, comparable-task metrics, coverage, and versions | Bounded local ledger; clear independently | Nothing by default; only the exact previewed request is sent after a separate action | +| Advice API key | User-provided secret | Secret value in VS Code SecretStorage only | Until the key or all derived data is cleared | Used only as the authorization credential for the explicitly configured endpoint | + +## What is never cached + +- OAuth access or refresh tokens, cookies, authorization headers, or GitHub + credentials. +- API keys outside VS Code SecretStorage. +- Full account identifiers, email addresses, display names, or subscription + names. Account continuity uses a machine-local HMAC fingerprint or an + isolated unattributed epoch. +- Raw prompt/response bodies, tool arguments, commands, complete CLI output, + absolute source-log paths, repository remotes, or persistent thread titles. + +Different anonymous account fingerprints are not merged. If local Codex logs +cannot establish one coherent account/window, the dashboard shows only used +API-equivalent value and explains why it cannot claim an account-level unused +allowance. + +## Combined heatmap and exports + +The Compare heatmap reuses daily provider aggregates; it does not scan logs +again or create another statistics cache. + +```text +Claude processed = input + cache creation + cache read + output +Codex processed = input total + output total +Combined activity = Claude processed + Codex processed +``` + +Codex cached input is already part of input total, and reasoning is already +part of output total, so neither is added again. Combined activity is local +token volume—not productivity, billing, model capability, or provider +equivalence. + +Local SVG and Markdown exports contain only a bounded title, selected date +range, daily Claude/Codex/combined aggregates, labels, and caveats. They do not +contain accounts, projects, thread titles, paths, prompts, or log content. + +Direct GitHub publication is optional and never runs in the background. v2.3.1 +requests `public_repo`, verifies the repository is public and resolves its +default branch, then asks the user to confirm the exact +`owner/repository/branch/path` and whether the file will be created or replaced. +Private repositories use local SVG plus Markdown instead of silently requesting +broader access. + +## Clear and migration behavior + +Separate Command Palette actions rebuild the Codex derived index, clear quota +history, clear advice data, reset UI or sharing preferences, and remove the BYOK +secret. “Clear all extension-derived data” first lists its targets. These +maintenance actions stay out of the dashboard Settings tab so it remains +concise. None of them deletes Claude or Codex source logs or provider-owned +credentials. + +Clearing all quota history atomically replaces the quota store with one valid +empty schema-2 document and removes only its exact quarantine/interrupted-write +siblings under the same cross-process lease. A provider/account-only clear +fails closed when quarantined data or an unresolved legacy migration cannot be +assigned safely; the user may then explicitly choose the all-history clear. + +Clear All deletes an exact catalog of released setting/state names, not every +key beginning with `ccu.setting.`. Unknown or future keys are preserved. Before +any mutation it checks all currently visible configuration scopes; an +unregistered legacy setting that VS Code cannot safely update blocks the whole +operation, leaves existing data intact, and is reported for manual removal. +Queued activation writes are drained before deletion and exact postconditions +are verified afterward. If the Webview cannot acknowledge its allowlisted +browser-state reset, a value-free pending action marker is retried on the next +panel open instead of reporting a false success. + +This clearing boundary is separate from the opt-in Session Actions feature. +That feature can move one user-selected Claude session log to the OS trash only +after its own modal confirmation; it never participates in Clear All. + +v2.3.1 validates and atomically migrates known legacy quota/config state before +removing the legacy copy. Corrupt or future-schema files fail closed; an old +valid file is not overwritten until the replacement validates. Uninstall may +leave host-managed extension storage behind, so the explicit clear command is +the reliable deletion route. + +VS Code only lets the running extension inspect Global, the current Workspace, +and currently open Workspace Folder configuration scopes. A legacy value that +exists only in a closed workspace remains there until that workspace is opened +and the clear control is run again (or the setting is removed manually). + +## Known limits + +- A reset that never appears in an official response or local structured event + cannot be reconstructed. Day-only Codex evidence lowers boundary confidence. +- Local Codex histories may include several sign-ins. Ambiguous overlap remains + used-only; the extension never invents an account split. +- API-equivalent values use currently known public API prices and pricing + coverage. They are estimates, not provider bills or subscription prices. +- Retention of source logs is controlled by Claude Code and Codex, not this + extension. diff --git a/LOCAL-DATA.zh-CN.md b/LOCAL-DATA.zh-CN.md new file mode 100644 index 00000000..6fb06ea5 --- /dev/null +++ b/LOCAL-DATA.zh-CN.md @@ -0,0 +1,93 @@ +# 本地数据与隐私 + +Claude Code Usage 采用本地优先设计。插件只读取供应商拥有的本地用量日志, +并保留快速刷新、重置识别和额度估算所必需的有界派生状态;API 等效成本始终 +只是估算,不是账单。 + +本文是 v2.3.1 面向用户的数据清单。字段级规范见 +[`docs/superpowers/specs/2026-09-02-v2.3.1-local-data-contract.zh-CN.md`](docs/superpowers/specs/2026-09-02-v2.3.1-local-data-contract.zh-CN.md)。 + +## 插件读取和保留什么 + +| 数据类别 | 来源 | 插件保留的内容 | 保留与清除 | 远程交互 | +|---|---|---|---|---| +| Claude 用量记录 | Claude Code 本地 `projects/**/*.jsonl` | 运行时用量记录和内存中的逐文件索引;仅在启用内容分析时保留有界提示样本 | 窗口重载/退出即释放。本地数据控制绝不触碰源日志;另行启用的“会话操作”可把一个精确确认的日志移入系统回收站(可恢复) | 默认无;只有用户另行预览并发送建议请求时才可能包含获准内容 | +| Codex 用量记录 | `$CODEX_HOME/sessions/**/*.jsonl` 与 `archived_sessions/**/*.jsonl` | 版本化增量索引:匿名文件键、偏移量、数值用量、日期、模型/effort 和已净化结构聚合 | 保留到重建、明确清除、schema 替换或宿主移除 | 无 | +| Codex 标题 | 仅 `$CODEX_HOME/session_index.jsonl` | 流式读取 `id → thread_name` 供运行时显示;标题不写入索引 | 仅运行时 | 无 | +| 额度观测 | Claude 官方额度响应或 Codex 结构化 rate-limit 事件 | 供应商、本机匿名账号 epoch、观测/重置时间、周期、已用/剩余比例、匿名窗口标识、来源、可信度和质量标志 | 保留不超过 180 天;边界保护压缩后每个供应商/账号/周期最多 512 条;可单独或随全部派生数据清除 | 启用时 Claude 额度查询会访问 Anthropic;Codex 额度证据只来自本地 | +| 设置与 UI 偏好 | 用户选择 | 类型化设置、标签页/筛选、有限后台任务状态、热力图标题/范围/隐私预览 | 保留到重置、清除或卸载;普通 VS Code 设置可能参与 Settings Sync | 插件不主动传输 | +| 分享目标 | 用户输入的 GitHub 目标 | 可选 `owner/repository/path`;不保存 GitHub 凭据 | 保留到重置分享偏好 | 仅在用户明确发布并确认精确目标后发生 | +| 建议证据 | 本地派生聚合与明确反馈 | 粗粒度观察、建议、评分、暂停、可比任务指标、覆盖率和版本 | 有界本地台账;可独立清除 | 默认不发送;只有单独确认后才发送精确预览过的请求 | +| 建议 API Key | 用户自备密钥 | 仅存于 VS Code SecretStorage | 保留到清除密钥或全部派生数据 | 只作为用户明确配置端点的授权凭据 | + +## 绝不缓存什么 + +- OAuth access/refresh token、cookie、authorization header 或 GitHub 凭据。 +- VS Code SecretStorage 之外的 API key。 +- 完整账号标识、邮箱、显示名或订阅名称。账号连续性只用本机 HMAC + fingerprint 或隔离的未归属 epoch。 +- 原始提示/响应正文、工具参数、命令、完整 CLI 输出、源日志绝对路径、 + 仓库 remote 或持久化线程标题。 + +不同匿名账号 fingerprint 不会合并。如果本地 Codex 日志无法证明属于同一账号 +和同一窗口,仪表盘只显示已用 API 等效价值,并说明为何不能声称账号级未用额度。 + +## 综合热力图与导出 + +“对比”热力图直接复用供应商日聚合,不会再次扫描日志,也不会新增第二套统计缓存。 + +```text +Claude processed = input + cache creation + cache read + output +Codex processed = input total + output total +综合活动量 = Claude processed + Codex processed +``` + +Codex 的 cached input 已包含在 input total 中,reasoning 已包含在 output total 中, +因此均不得重复相加。综合活动量只代表本地 Token 活动,不代表生产率、账单、模型能力 +或两个供应商的能力等价。 + +本地 SVG 与 Markdown 导出只含有界标题、所选日期范围、每日 Claude/Codex/综合聚合、 +标签和免责声明;不含账号、项目、线程标题、路径、提示或日志内容。 + +直接发布到 GitHub 是可选动作,且绝不在后台运行。v2.3.1 仅请求 `public_repo`, +先验证仓库公开性和默认分支,再要求用户确认精确的 +`owner/repository/branch/path` 以及创建或覆盖动作。私有仓库应改用本地 SVG + +Markdown,不会静默索取更宽权限。 + +## 清除与迁移 + +命令面板提供独立维护动作:重建 Codex 派生索引、清除额度历史、清除建议数据、重置 +UI 或分享偏好、移除 BYOK 密钥。“清除全部扩展派生数据”会先列出精确目标。这些动作 +不进入仪表盘设置页,以保持插件设置简洁;同时均不删除 Claude/Codex 源日志或供应商 +拥有的凭据。 + +清除全部额度历史时,插件会在同一个跨进程 lease 内把额度存储原子替换为一个合法的 +空 schema-2 文档,并只删除该文件族中精确匹配的隔离/中断写入文件。若隔离数据或尚未 +完成的旧版迁移无法安全归属到 provider/账号,范围清除会安全拒绝;用户可再明确选择 +清除全部额度历史。 + +“清除全部”按已发布的精确 setting/state 名称清单删除,不会泛删所有 +`ccu.setting.*`;未知或未来键会保留。任何修改之前,插件先检查当前可见配置作用域; +若发现 VS Code 已无法安全更新的未注册旧设置,整个操作会在零删除状态下停止,并提示 +手动移除。激活期排队写入会先排空,删除后再验证精确后置条件。若 Webview 未能确认其 +白名单浏览器状态已清除,插件会保存一个不含数据值的待重试动作,在下次打开面板时重放, +而不会误报成功。 + +这个清除边界与另行选择启用的“会话操作”相互独立。后者只有在用户针对单个 Claude +会话日志完成模态确认后,才会把它移入系统回收站(可恢复);它不会参与“清除全部”。 + +v2.3.1 会先验证并原子迁移已知旧版额度/配置状态,成功后才移除旧副本。损坏或未来 +schema 会安全失败;替代文件通过验证前不会覆盖旧的有效文件。卸载后宿主可能保留 +扩展存储,因此明确的清除命令才是可靠删除路径。 + +VS Code 只允许当前运行的插件检查 Global、当前 Workspace 及当前已打开的 Workspace +Folder 配置作用域。只存在于关闭工作区中的旧值会继续保留,直到打开该工作区后再次 +运行清除控制(或手动删除该设置)。 + +## 已知限制 + +- 从未出现在官方响应或本地结构化事件中的重置无法重建;只有日粒度的 Codex 证据 + 会降低边界可信度。 +- 同一 Codex home 可能包含多个登录。归属重叠不清时只显示已用值,绝不虚构账号拆分。 +- API 等效价值按当前已知公开 API 单价和定价覆盖率估算,不是供应商账单或订阅价格。 +- 源日志保留期由 Claude Code 和 Codex 控制,不由本插件控制。 diff --git a/README-en.md b/README-en.md index 043b98d1..ab665cea 100644 --- a/README-en.md +++ b/README-en.md @@ -10,7 +10,7 @@ > > **What it is _not_:** a billing tool. All amounts are estimates based on public per-million-token rates. Refer to your Anthropic account for actual charges. -> Screenshots are from the English UI. See the [main README](README.md) for the full feature reference. +> Screenshots include English and Simplified Chinese. See the [main README](README.md) for the full feature reference. ## Screenshots @@ -26,24 +26,67 @@ Hover the quota indicator for a breakdown: ![Dashboard](images/v2-dashboard-en.png) +### v2.3.1 Codex and Compare + +![Claude Today, Simplified Chinese, dark theme](images/v2.3.1/claude-today-zh-CN-dark.png) + +![Codex overview, Simplified Chinese, dark theme](images/v2.3.1/codex-overview-zh-CN-dark.png) + +![Codex weekly allowance estimate, English, dark theme](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +![Combined Claude and Codex heatmap, English, light theme](images/v2.3.1/compare-heatmap-en-light.png) + +These four v2.3.1 captures use the production renderer, synthetic fixtures, and VS Code Light+/Dark+ theme variables—not personal usage or billing evidence. Native VSIX installation is checked separately. + +- Codex shows **Today token usage** and separate **remaining quota**: 36% used means `wk 64%`. Hover shows utilisation bars, resets, and wrapped notes. Quota is last-observed local evidence, not a live balance. +- Period details start collapsed; sharing settings sit below the preview. Sharing is on by default with an off switch and quantile, logarithmic, or linear intensity. +- CLI calls count only when persistent sessions leave usage-bearing logs. Non-persisted calls cannot be backfilled; Today and Last 30 days use the configured timezone. + ## Features - **Status bar** — today's cost, current-session cost, and real 5-hour / weekly quota (`5h:N% wk:N%`) read from Claude Code's own OAuth session. Zero configuration. -- **Dashboard tabs** — Today / This Month / All Time, plus **Sessions / Projects / Content / Branches**, all sortable. +- **Dashboard tabs** — Today / Last 30 Days / All Time, plus **Sessions / Projects / Content / Branches**, all sortable. - **Stacked cost-composition charts** with a Y-axis and reference lines — see at a glance how much of each day / month went to input, output, cache-write and cache-read. - **Content tab** — estimates which content consumes your tokens (your prompts vs. tool results vs. assistant output / thinking). -- **AI advice** (opt-in) — sends a usage summary plus a sample of your prompts to an OpenAI-compatible API (DeepSeek V4 Pro by default) and suggests concrete rewrites. Bring your own key, or preview a static demo first. +- **AI advice** (opt-in) — starts with local evidence and explainable actions. Optional BYOK personalisation defaults to aggregates only; prompt samples require separate consent. The exact full request is previewed before a separate Send action, and helpful / not-helpful / applied feedback stays local. Recommendations can be snoozed for a bounded period and return after expiry or on demand. + Withdrawing advice consent immediately invalidates previews and cancels active advice requests; already transmitted bytes cannot be recalled. - **Multi-vendor pricing** — Opus 4.x / Sonnet 4.x / Haiku 4.5 verified against Anthropic's public pricing; reference rates for OpenAI / Gemini / DeepSeek / Kimi / GLM / Qwen with family-aware fallback. `Refresh Token Pricing` pulls live LiteLLM data. - **Personalisation** — language, timezone, decimal places, compact numbers, project grouping, dashboard auto-refresh toggle. +## What's new in v2.3.1 + +- Exact pricing and context metadata now cover **GPT-6 Astra** + (`gpt-6-astra`, 1.05M context) and **Claude Fable 5.1 / Mythos 5.1** + (`claude-fable-5-1` / `claude-mythos-5-1`, 1M context). Fable 5.1 uses its + model-specific `$0.25 / MTok` cache-read rate without changing historical + Fable 5 data. GPT-6 API-equivalent values use the official Standard + short-context rates; the request-wide surcharge above 272K input is excluded + because aggregate local logs cannot establish that per-request threshold. +- Claude estimates can optionally use direct Anthropic or AWS Bedrock in-region + on-demand rates for current Opus, Sonnet, and Haiku families. Switching the + backend reprices unchanged logs immediately; Sonnet 5 uses the standard rate + after its launch promotion ended on 31 August 2026. +- Last 30 days is the configured-timezone current date plus the preceding 29 dates. Today ≤ Last 30 days ≤ All time, repeated refresh/reindex is stable, all breakdowns reconcile, and months run oldest-first. Claude's Workflows summary uses the same rolling range and assigns each run by its configured-zone start date. Chart metric switches and drill-down labels render daily/monthly usage keys without host-timezone rollback; Advice and Optimizer snooze dates also use the configured timezone and UI locale. +- Structured reasoning-effort variants normalize without model-name guessing. Non-zero unknown is explained; zero unknown is hidden. +- Bounded anonymous quota observations preserve irregular and same-day resets. Every valid same-window used fraction contributes to labelled total and unused subscription-durability estimates, including the current window. Approximate or unattributed evidence is low confidence. If local Codex quota series overlap, the current window uses the latest real observation for a low-confidence blended estimate; ambiguous completed windows remain used-only. Unused value never becomes negative. +- Compare now leads with a combined Claude + Codex activity heatmap that reuses daily aggregates, works with either provider alone, and keeps both components in every tooltip. +- The preview-first share studio supports deterministic local SVG, a combined card, copyable Markdown, title/range controls, a privacy preview, and curated/custom colors. It is on by default and can be hidden with one Settings switch. Academic Violet is the default; intensity can use quantile (default), logarithmic, or linear mapping. Optional public-GitHub publication is separately confirmed at the exact destination. +- Codex Token composition now shows **uncached usage** (uncached input + output) above the non-overlapping uncached-input / cached-input / output stack; reasoning remains a subset of output. +- Codex scrolling stays smooth while indexing: scroll state is saved once after a gesture and live index progress patches text without rebuilding the page. Per-model green headlines now show exact-model API-equivalent price with coverage help; unknown models show `—`, while effort headlines retain neutral uncached-token values. +- OpenAI-compatible optimizer requests now send `reasoning_effort` without the unsupported top-level `thinking` parameter, resolving [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94). +- Claude and Codex now share dashboard density, hierarchy, disclosure, focus, ARIA, narrow-width, and light/dark design tokens while retaining provider-specific metric meanings. +- Get AI Advice and Usage Optimizer share one exact-preview and explicit-send boundary. There is no default or background AI request, and local evidence/feedback remains bounded. + +The reviewed draft is `v2.3.1`; the human-controlled publish workflow stamps package metadata from that release tag. + ## Codex Beta in v2.3 - Codex usage records are discovered only from `sessions/**/*.jsonl` and `archived_sessions/**/*.jsonl`; credential, database, and unknown files remain excluded. Separately, the extension streams exactly `$CODEX_HOME/session_index.jsonl` to map `id` to `thread_name` for truthful thread titles. Absolute paths are redacted and titles remain memory-only. Usage-record JSONL lines are streamed and temporarily parsed only to extract allowlisted usage and structural metadata; prompt, response, command, and tool-argument fields are not inspected or used for analysis, and are never retained or persisted. - **Processed** means input + output, **uncached usage** means uncached input + output, **cached input** remains a subset of input, and reasoning remains a subset of output. The overview also shows input cache hit rate as cached input / input. Codex billing cost is not shown. Its first summary card is a clearly labelled API-equivalent cost estimate for the selected scope, and the All-time view shows the weekly trend on the same pricing basis; Claude / Codex / Compare keep each provider's accounting separate. -- Codex **Today** means the current calendar day in the configured timezone. It adds exact hourly API-equivalent cost beside a separate token-composition view; daily and monthly primary charts also default to API-equivalent cost while token composition stays separately visible. Only exact known-model prices contribute, so unknown models remain unpriced and pricing coverage stays visible. The additive, schema-3-compatible hourly sidecar processes only canonical files already known to contain today, is checkpointed and resumable, and does not force a full-history reindex. +- Codex **Today** means the current calendar day in the configured timezone. It adds exact hourly API-equivalent cost beside a separate token-composition view; daily and monthly primary charts also default to API-equivalent cost while token composition stays separately visible. Only exact known-model prices contribute, so unknown models remain unpriced and pricing coverage stays visible. The additive, schema-3-compatible hourly sidecar keeps sparse buckets for the rolling last 30 days, is checkpointed and resumable, evicts day 31, and serves date expansion without reading JSONL on click. Codex monthly charts and tables list months oldest-first. - Request-level attribution prefers valid `last_token_usage` components; its `total_tokens` is active-context size, not request usage. A full numeric total-plus-last signature suppresses only proven replay from the same pseudonymous rate-limit source or an immediately adjacent duplicate. Missing last snapshots fall back to cumulative lineage high-water. Upgrading triggers one automatic reindex, while the indexed subtotal remains visible throughout the pass. -- Claude and Codex All-time / Compare views calculate historical used equivalents directly from local token logs. The newest valid official reset observation anchors one sequence of unique, non-overlapping weekly periods, so each usage event is counted once; without a usable observation, usage-only rows fall back to Monday-to-Monday UTC calendar weeks. Any overlapping, non-aligned future reset is a conflict even when its series name differs; it cannot create another current period, and period ranges are shown separately from reset times. Codex usage is stored in daily slices: when one crosses an official intraday reset, its tokens are still counted once, the affected period is labelled a boundary approximation, and only used equivalent is shown. This display rule does not change the index schema or trigger a rebuild. Codex historical periods are always used-value-only. Only the newest current period may infer a total when the reset is unambiguous and indexed usage can be attributed to one observation source; current unused value remains withheld. Multi-sign-in usage that cannot be attributed reliably also stays used-only, without inventing an account split. Current official API rates are applied consistently across history. This is a proxy, not a bill or an official subscription price. The panel is enabled by default and can be hidden in Settings with `showWeeklyEquivalentValue`. Claude records profile-scoped quota observations from this release onward. -- Switching to Codex keeps the established Today / Month / All time / Sessions / Projects / Content / Settings structure, relabelled where Codex semantics differ. Both providers use the same render functions, HTML classes, charts, tables, spacing, and responsive rules; their time-series charts stay width-aligned while dense content scrolls inside its own region. Codex recommendations use indexed 30-day structural evidence. +- Claude and Codex All-time / Compare views calculate historical used equivalents directly from local token logs. The newest valid official reset observation anchors one sequence of unique, non-overlapping weekly periods, so each usage event is counted once; without a usable observation, usage-only rows fall back to Monday-to-Monday UTC calendar weeks. A genuinely different quota series with an overlapping, non-aligned future reset is a conflict; same-series observations remain one series and may be shown as a low-confidence approximation. It cannot create another current period, and period ranges are shown separately from reset times. Codex usage is stored in daily slices, and an account-wide `codex` observation may decorate both historical and current buckets. If an observed reset drifts from the seven-day grid, the sample is mapped to the display period containing its observation time; file-source uncertainty, reset drift, and daily boundary crossings lower confidence and are labelled approximate. File keys are not account identities, so eligible local files in one home are included together. If local quota series overlap, the current period uses the latest real observation for a low-confidence blended estimate; ambiguous completed periods, or periods without a usable observation, stay used-only rather than inventing an account split. Any coherent observed window—including the current one—can show total and unused durability estimates; attribution or boundary uncertainty lowers confidence instead of silently replacing the values with dashes. This display rule does not change the index schema or trigger a rebuild. Current official API rates are applied consistently across history. This is a proxy, not a bill, official balance, or official subscription price. The panel is enabled by default and can be hidden in Settings with `showWeeklyEquivalentValue`. Claude records profile-scoped quota observations from this release onward. +- Switching to Codex keeps the established Today / Last 30 days / All time / Sessions / Projects / Content / Settings structure, relabelled where Codex semantics differ. Both providers use the same render functions, HTML classes, charts, tables, spacing, and responsive rules; their time-series charts stay width-aligned while dense content scrolls inside its own region. Codex recommendations use indexed 30-day structural evidence. - Root tasks use the latest real thread title after path redaction. Child rows prefer their own real thread title; when it is missing, they use the reported nickname and display the parent/root title; if those are also missing, they receive a localized neutral fallback. Project names use the Git repository name, or the directory basename outside Git. The extension does not invent Branches or Workflows that cannot be measured reliably. - Rolling 7-day and 30-day values use exact event-day slices in the configured timezone. During an incomplete migration or rebuild, every Codex card, table, project, session, recommendation, and status value is visibly an **indexed subtotal**; unverified legacy totals are excluded. Once a Codex home is detected, its provider tab appears immediately; the page shows exact indexed-file, percentage, and byte progress during the first build, while Compare waits until both providers have real data. After the first atomic checkpoint, the complete subtotal dashboard stays usable while indexing continues; progress never replaces its cards or tables. A selected Codex home is account-agnostic, so logs left by multiple sign-ins in that same home are combined. Local logs expose no reliable account identity, so limit cards remain **last-observed** and are never summed. - Each recommendation presents an observation, readable evidence, and a conditional action only when the indexed 30-day structural aggregates support it; no evidence means no generic advice. @@ -69,15 +112,41 @@ Open Settings (`Ctrl+,`) and search for **`Claude Code Usage`**. All settings ar - `usageLimitTracking` — show the real 5h / weekly quota indicator. - `showCost` / `showContext` — toggle the cost item and the context-window fill indicator (like `/context`) in the status bar. - Each of these status-bar items is opt-out — set `usageLimitTracking`, `showCost`, or `showContext` to `false` to hide just that one. -- `advice.apiKey` — API key for the AI advice feature (OpenAI-compatible). +- `advice.apiKey` — bring-your-own key shared by AI Advice and the Usage Optimizer (Anthropic or OpenAI-compatible endpoint). - `pauseDashboardRefresh` — pause dashboard auto-refresh (also toggleable in the dashboard header). See the [full settings table in the main README](README.md#configuration). +## Local data, privacy, and known limits + +See [Local data and privacy](LOCAL-DATA.md) for the complete inventory, +retention, migration, clearing, and remote-interaction contract. + +| Data | Local retention | Remote behavior | +|---|---|---| +| Source logs | Provider-owned, read-only; never copied wholesale | None by default | +| Codex index | Bounded pseudonymous numeric/structural aggregates | None | +| Quota history | Bounded anonymous window observations; no raw account ID | Claude quota lookup only when enabled; Codex evidence stays local | +| UI/share state | Filters plus optional title/range and GitHub destination strings | Publish only after exact explicit confirmation | +| Advice state/key | Bounded aggregate evidence; key only in SecretStorage | Exact previewed request only after a separate Send action | + +A reset absent from official/local structured evidence cannot be reconstructed. +Ambiguous multi-login Codex history uses the latest real observation for a +low-confidence current-period blend; ambiguous completed periods remain used-only. API-equivalent values +depend on visible pricing coverage and are not bills. Source-log retention is +controlled by Claude Code and Codex; explicit clear controls are the reliable +way to remove extension-derived state. + ## Troubleshooting **"No Claude Code Data"** — make sure Claude Code is installed and used at least once; check the `dataDirectory` setting (auto-detection looks at `~/.claude/projects`). +**One-shot Claude CLI activity is missing** — calls made with +`--no-session-persistence` can leave prompt history but no project transcript or +token `usage` fields. The extension does not invent token/cost totals from that +history. Run future audited calls without the flag if they should appear; past +unpersisted token usage cannot be reconstructed locally. + **Quota shows `5h:--% wk:--%`** — log in to the active Claude profile once. Credentials follow explicit `dataDirectory`, then the first valid `CLAUDE_CONFIG_DIR`, then `~/.claude`; the global macOS Keychain item is used diff --git a/README-id.md b/README-id.md index 942600be..603ef099 100644 --- a/README-id.md +++ b/README-id.md @@ -10,7 +10,7 @@ > **ini _Bukanlah_:** alat billing. Semua angka adalah estimasi berdasarkan tarif publik per-juta-token. Rujuk ke akun Anthropic Anda untuk biaya yang sebenarnya. -> Screenshot berasal dari UI berbahasa Inggris. Lihat [README utama](README.md) untuk referensi fitur lengkap. +> Screenshot mencakup UI bahasa Inggris dan Tionghoa Sederhana. Lihat [README utama](README.md) untuk referensi lengkap. ## Screenshot @@ -26,24 +26,67 @@ Arahkan kursor ke indikator kuota untuk melihat rinciannya: ![Dashboard](images/v2-dashboard-en.png) +### Codex dan Perbandingan v2.3.1 + +![Claude hari ini, Tionghoa Sederhana, tema gelap](images/v2.3.1/claude-today-zh-CN-dark.png) + +![Ringkasan Codex, Tionghoa Sederhana, tema gelap](images/v2.3.1/codex-overview-zh-CN-dark.png) + +![Estimasi batas mingguan Codex, Inggris, tema gelap](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +![Heatmap gabungan Claude dan Codex, Inggris, tema terang](images/v2.3.1/compare-heatmap-en-light.png) + +Empat gambar v2.3.1 ini menggunakan renderer produksi, data sintetis, dan variabel tema VS Code Light+/Dark+, bukan bukti penggunaan pribadi atau tagihan. Instalasi VSIX native diverifikasi secara terpisah. + +- Codex menampilkan **token terpakai hari ini** dan **sisa kuota** secara terpisah: penggunaan mingguan 36% berarti `wk 64%`. Tooltip tetap menampilkan bilah penggunaan, waktu reset, dan catatan berbaris. Kuota berasal dari pengamatan lokal terakhir, bukan saldo langsung. +- Detail periode tertutup secara default; pengaturan berbagi berada di bawah pratinjau. Berbagi aktif secara default dan dapat dimatikan, dengan intensitas kuantil, logaritmik, atau linear. +- Panggilan CLI dihitung hanya jika sesi persisten menyimpan log dengan usage. Panggilan tanpa log tidak dapat dipulihkan; Hari ini dan 30 hari terakhir memakai zona waktu yang dikonfigurasi. + ## Fitur - **Status bar** — biaya hari ini, biaya sesi saat ini, dan kuota 5-jam / mingguan yang sebenarnya (`5h:N% wk:N%`) dibaca dari sesi OAuth Claude Code sendiri. Tanpa konfigurasi. -- **Tab dashboard** — Hari Ini / Bulan Ini / Sepanjang Waktu, plus **Sesi / Proyek / Konten / Branch**, semuanya bisa diurutkan. +- **Tab dashboard** — Hari Ini / 30 Hari Terakhir / Sepanjang Waktu, plus **Sesi / Proyek / Konten / Branch**, semuanya bisa diurutkan. - **Grafik komposisi biaya bertumpuk** dengan sumbu Y dan garis referensi — lihat sekilas berapa banyak dari tiap hari / bulan yang terpakai untuk masukan, keluaran, cache-write, dan cache-read. - **Tab Konten** — memperkirakan konten mana yang menghabiskan token Anda (prompt Anda vs. hasil tool vs. output / pemikiran asisten). -- **Saran AI** (opsional) — mengirim ringkasan penggunaan plus sampel prompt Anda ke API yang kompatibel dengan OpenAI (DeepSeek V4 Pro secara default) dan menyarankan penulisan ulang yang konkret. Gunakan API key Anda sendiri, atau pratinjau demo statis terlebih dahulu. +- **Saran AI** (opsional) — dimulai dari bukti lokal dan tindakan yang dapat dijelaskan. Personalisasi BYOK opsional hanya memakai agregat secara default; sampel prompt memerlukan persetujuan terpisah. Permintaan lengkap dipratinjau secara persis sebelum tindakan Kirim yang terpisah, dan umpan balik berguna / tidak berguna / diterapkan tetap lokal. Saran dapat ditunda untuk waktu terbatas dan muncul kembali setelah kedaluwarsa atau secara manual. + Pencabutan persetujuan langsung membatalkan pratinjau dan permintaan saran yang sedang berjalan; data yang sudah terkirim tidak dapat ditarik kembali. - **Harga multi-vendor** — Opus 4.x / Sonnet 4.x / Haiku 4.5 diverifikasi terhadap harga publik Anthropic; tarif referensi untuk OpenAI / Gemini / DeepSeek / Kimi / GLM / Qwen dengan fallback berbasis family model. `Refresh Token Pricing` menarik data LiteLLM langsung. - **Personalisasi** — bahasa, zona waktu, angka desimal, angka ringkas, pengelompokan proyek, toggle penyegaran otomatis dashboard. +## Yang baru di v2.3.1 + +- Metadata harga dan konteks yang tepat kini mencakup **GPT-6 Astra** + (`gpt-6-astra`, konteks 1,05 juta token) serta **Claude Fable 5.1 / Mythos + 5.1** (`claude-fable-5-1` / `claude-mythos-5-1`, konteks 1 juta token). + Fable 5.1 memakai tarif baca cache khusus `$0.25 / juta token` tanpa mengubah + riwayat Fable 5. Nilai ekuivalen API GPT-6 memakai tarif Standard resmi untuk + konteks pendek. Biaya tambahan untuk seluruh permintaan di atas 272K input + tidak disertakan karena log agregat lokal tidak dapat memastikan ambang per + permintaan tersebut. +- Estimasi Claude dapat memakai tarif langsung Anthropic atau tarif on-demand + AWS Bedrock in-region untuk keluarga Opus, Sonnet, dan Haiku saat ini. + Mengganti backend langsung menghitung ulang log yang tidak berubah; Sonnet 5 + memakai tarif standar setelah promosi peluncurannya berakhir 31 Agustus 2026. +- 30 hari terakhir berarti hari ini dan 29 tanggal sebelumnya dalam zona waktu konfigurasi. Total dapat direkonsiliasi, refresh berulang stabil, dan bulan tampil dari lama ke baru. Ringkasan Workflows Claude memakai rentang bergulir yang sama dan memasukkan setiap eksekusi berdasarkan tanggal mulai di zona waktu konfigurasi. Saat metrik grafik diganti atau label drill-down dirender, kunci penggunaan harian/bulanan tidak lagi mundur sehari atau sebulan akibat zona waktu host. Tanggal berakhirnya penundaan Saran AI dan Usage Optimizer juga memakai zona waktu konfigurasi dan bahasa UI. +- Reasoning effort terstruktur tidak ditebak dari nama model. `unknown` bukan nol dijelaskan; nilai nol disembunyikan. +- Pengamatan kuota anonim yang terbatas mempertahankan reset tidak teratur dan pada hari yang sama. Fraksi valid dalam satu jendela menghasilkan estimasi total dan sisa daya tahan langganan, termasuk periode berjalan. Bukti perkiraan atau tanpa atribusi diberi keyakinan rendah. Jika series kuota Codex lokal tumpang tindih, periode berjalan memakai pengamatan nyata terbaru untuk estimasi gabungan berkeyakinan rendah; periode selesai yang atribusinya ambigu tetap hanya menampilkan nilai terpakai. +- Perbandingan menampilkan heatmap aktivitas gabungan Claude + Codex dari agregat harian yang sudah ada dan tetap berfungsi dengan satu penyedia. +- Studio berbagi yang mengutamakan pratinjau mencakup SVG lokal deterministik, kartu, Markdown, judul/rentang, pratinjau privasi, dan warna yang dapat disesuaikan. Academic Violet menjadi default; pemetaan intensitas dapat memakai kuantil (default), logaritmik, atau linear. Publikasi GitHub publik mengonfirmasi tujuan tepat secara terpisah. +- Komposisi Token Codex sekarang menampilkan **penggunaan tanpa cache** (input tanpa cache + output) di atas stack input tanpa cache / input cache / output yang tidak tumpang tindih; reasoning tetap merupakan bagian dari output. +- Codex tetap dapat digulir dengan mulus saat pengindeksan: status gulir disimpan sekali setelah gerakan selesai dan progres indeks langsung hanya memperbarui teks tanpa membangun ulang halaman. Ringkasan hijau per model kini mengikuti makna Claude, yaitu harga ekuivalen API untuk model yang cocok tepat beserta cakupan harga. Model tak dikenal menampilkan `—`, sedangkan effort tetap memakai nilai Token tanpa cache berwarna netral. +- Permintaan Optimizer yang kompatibel dengan OpenAI kini hanya mengirim `reasoning_effort` tanpa parameter tingkat atas `thinking` yang tidak didukung, menyelesaikan [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94). +- Claude/Codex berbagi token desain untuk kepadatan, hierarki, fokus, ARIA, lebar sempit, serta tema terang/gelap tanpa menyamakan arti metrik. + +Draft Release yang ditinjau adalah `v2.3.1`; alur publikasi manual menetapkan versi paket dari tag tersebut. + ## Codex Beta di v2.3 - Catatan penggunaan Codex hanya ditemukan dari `sessions/**/*.jsonl` dan `archived_sessions/**/*.jsonl`; file kredensial, database, dan file tak dikenal tetap dikecualikan. Secara terpisah, ekstensi hanya melakukan streaming terhadap `$CODEX_HOME/session_index.jsonl` untuk memetakan `id` ke `thread_name` bagi judul thread yang sebenarnya. Jalur absolut dalam judul disamarkan dan judul hanya disimpan di memori. Setiap baris JSONL penggunaan di-stream dan diparse sementara hanya untuk mengambil metadata penggunaan dan struktur dalam daftar izin; field prompt, respons, perintah, dan argumen alat tidak diperiksa atau dipakai untuk analisis, serta tidak pernah disimpan atau dipersistenkan. - **Diproses** = input + output, **Penggunaan tanpa cache** = Input tanpa cache + output, **cached input** tetap bagian dari input, dan reasoning bagian dari output. Ringkasan juga menampilkan tingkat hit cache input sebagai cached input / input. Biaya tagihan Codex tidak ditampilkan. Kartu ringkasan pertama menampilkan estimasi biaya ekuivalen API untuk cakupan terpilih dengan label yang jelas, sedangkan tampilan Sepanjang Waktu menunjukkan tren mingguan dengan dasar harga yang sama. Claude / Codex / Compare tetap memisahkan makna tiap penyedia. -- **Hari Ini** pada Codex berarti hari kalender saat ini dalam zona waktu yang dikonfigurasi. Tampilan ini menambahkan biaya ekuivalen API per jam yang tepat di samping tampilan komposisi Token yang terpisah. Grafik utama harian dan bulanan juga memakai biaya ekuivalen API sebagai default, sementara komposisi Token tetap tersedia secara terpisah. Hanya harga model yang dikenal dan cocok tepat yang dihitung; model tak dikenal tetap tanpa harga dan cakupan harga selalu terlihat. Sidecar per jam yang bersifat tambahan dan kompatibel dengan schema 3 hanya memproses file canonical yang sudah diketahui memuat penggunaan hari ini, dapat dilanjutkan dari checkpoint, dan tidak memicu pengindeksan ulang seluruh riwayat. +- **Hari Ini** pada Codex berarti hari kalender saat ini dalam zona waktu yang dikonfigurasi. Tampilan ini menambahkan biaya ekuivalen API per jam yang tepat di samping tampilan komposisi Token yang terpisah. Grafik utama harian dan bulanan juga memakai biaya ekuivalen API sebagai default, sementara komposisi Token tetap tersedia secara terpisah. Hanya harga model yang dikenal dan cocok tepat yang dihitung; model tak dikenal tetap tanpa harga dan cakupan harga selalu terlihat. Sidecar per jam yang bersifat tambahan dan kompatibel dengan schema 3 menyimpan bucket tanggal / jam yang jarang untuk 30 hari bergulir, mendukung checkpoint dan resume, membuang hari ke-31, dan membuka tanggal tanpa membaca JSONL. Grafik dan tabel bulanan Codex menampilkan bulan dari yang paling lama ke yang terbaru. - Atribusi Token per permintaan memprioritaskan component `last_token_usage` yang valid; `total_tokens` di dalamnya adalah ukuran konteks aktif, bukan penggunaan permintaan. Signature numerik lengkap total-plus-last hanya menghapus replay yang terbukti berasal dari sumber rate-limit pseudonim yang sama atau record yang tepat bersebelahan. Jika last snapshot tidak ada, parser kembali ke cumulative lineage high-water. Setelah upgrade, indeks dibangun ulang otomatis satu kali dan subtotal terindeks tetap terlihat selama prosesnya. -- Tampilan Sepanjang Waktu / Perbandingan Claude dan Codex menghitung ekuivalen terpakai historis langsung dari log Token lokal. Pengamatan reset resmi terbaru yang valid menjadi satu jangkar bagi rangkaian periode mingguan yang unik dan tidak tumpang tindih, sehingga setiap peristiwa penggunaan hanya dihitung dalam satu periode. Jika tidak ada pengamatan yang dapat dipakai, riwayat khusus pemakaian kembali ke minggu kalender UTC Senin-ke-Senin. Reset masa depan yang tumpang tindih tetapi tidak selaras dianggap konflik meskipun nama series berbeda; reset itu tidak dapat membuat periode berjalan kedua. Rentang periode dan waktu reset ditampilkan terpisah. Penggunaan Codex disimpan sebagai irisan harian. Bila suatu irisan melewati reset resmi di tengah hari, Token tetap dihitung satu kali, periode terdampak diberi label 「perkiraan batas」, dan hanya ekuivalen terpakai yang ditampilkan tanpa menyimpulkan total batas atau sisa. Aturan tampilan ini tidak mengubah schema indeks dan tidak memicu pembangunan ulang. Periode historis Codex selalu hanya menampilkan nilai terpakai. Hanya periode berjalan terbaru yang boleh memperkirakan total batas bila reset tidak berkonflik dan penggunaan terindeks dapat diatribusikan dengan andal ke satu sumber pengamatan; nilai sisa periode berjalan tetap tidak ditampilkan sebagai kesimpulan. Penggunaan dari beberapa login yang tidak dapat diatribusikan juga tetap hanya menampilkan nilai terpakai tanpa mengarang pemisahan akun. Harga API resmi saat ini diterapkan konsisten pada riwayat. Ini proksi, bukan tagihan atau harga langganan resmi. Panel ini aktif secara default dan dapat disembunyikan di Settings dengan `showWeeklyEquivalentValue`. Claude mulai merekam pengamatan batas per profil sejak rilis ini. -- Beralih ke Codex tetap memakai struktur Hari Ini / Bulan Ini / Sepanjang Waktu / Sesi / Proyek / Konten / Settings yang sudah ada, dengan label yang disesuaikan pada makna Codex. Kedua penyedia memakai render function, HTML class, grafik, tabel, jarak, dan aturan responsif yang sama; grafik deret waktunya tetap sejajar lebarnya, sedangkan konten padat hanya bergulir di areanya sendiri. Rekomendasi Codex memakai bukti struktural 30 hari yang telah diindeks. +- Tampilan Sepanjang Waktu / Perbandingan Claude dan Codex menghitung ekuivalen terpakai historis langsung dari log Token lokal. Pengamatan reset resmi terbaru yang valid menjadi jangkar bagi rangkaian periode mingguan yang unik dan tidak tumpang tindih, sehingga setiap peristiwa penggunaan hanya dihitung dalam satu periode. Jika tidak ada pengamatan yang dapat dipakai, riwayat khusus pemakaian kembali ke minggu kalender UTC Senin-ke-Senin. Pengamatan dari series yang sama tetap menjadi satu series dan dapat ditampilkan sebagai perkiraan berkeyakinan rendah tanpa membuat periode berjalan kedua. Pengamatan account-wide `codex` dapat menghias periode historis dan berjalan; pergeseran reset, ketidakpastian sumber file, atau batas irisan harian menurunkan keyakinan. Kunci file bukan identitas akun, sehingga file lokal yang memenuhi syarat dalam satu home dipakai bersama. Jika series kuota lokal tumpang tindih, periode berjalan memakai pengamatan nyata terbaru untuk estimasi gabungan berkeyakinan rendah. Periode selesai yang atribusinya ambigu atau periode tanpa pengamatan tetap hanya menampilkan ekuivalen terpakai tanpa mengarang pemisahan akun. Setiap periode teramati yang konsisten, termasuk periode berjalan, dapat menampilkan estimasi total dan sisa daya tahan; ketidakpastian atribusi atau batas menurunkan keyakinan alih-alih menyembunyikan nilainya. Aturan tampilan ini tidak mengubah schema indeks dan tidak memicu pembangunan ulang. Harga API resmi saat ini diterapkan konsisten pada riwayat. Ini proksi, bukan tagihan, saldo resmi, atau harga langganan resmi. Panel ini aktif secara default dan dapat disembunyikan di Settings dengan `showWeeklyEquivalentValue`. Claude mulai merekam pengamatan batas per profil sejak rilis ini. +- Beralih ke Codex tetap memakai struktur Hari Ini / 30 Hari Terakhir / Sepanjang Waktu / Sesi / Proyek / Konten / Settings yang sudah ada, dengan label yang disesuaikan pada makna Codex. Kedua penyedia memakai render function, HTML class, grafik, tabel, jarak, dan aturan responsif yang sama; grafik deret waktunya tetap sejajar lebarnya, sedangkan konten padat hanya bergulir di areanya sendiri. Rekomendasi Codex memakai bukti struktural 30 hari yang telah diindeks. - Tugas utama memakai judul thread nyata terbaru setelah jalur disamarkan. Baris tugas anak memprioritaskan judul thread nyatanya sendiri; jika tidak ada, baris memakai nama panggilan yang dilaporkan sambil menampilkan judul induk / tugas utama. Jika informasi itu juga tidak ada, baris memakai nama pengganti netral yang dilokalkan. Nama proyek memakai nama repositori Git, atau nama folder di luar Git. Ekstensi tidak mengarang Branches atau Workflows yang tidak dapat dihitung secara andal. - Nilai 7 dan 30 hari memakai irisan tepat berdasarkan hari peristiwa di zona waktu yang dikonfigurasi. Saat migrasi atau pembangunan ulang belum selesai, setiap kartu, tabel, proyek, sesi, rekomendasi, dan nilai status Codex ditandai sebagai **subtotal terindeks**, sementara total lama yang belum diverifikasi dikecualikan. Setelah Codex home terdeteksi, tab penyedianya langsung ditampilkan; selama indeks pertama dibuat, jumlah file terindeks yang tepat, persentase, dan progres kapasitas tampil langsung di halaman, sedangkan Perbandingan menunggu hingga kedua penyedia memiliki data nyata. Setelah checkpoint atomik pertama dibuat, seluruh dasbor subtotal tetap dapat digunakan saat pengindeksan berlanjut; indikator progres tidak menggantikan kartu atau tabel. Codex home yang dipilih tidak membedakan akun, jadi log dari beberapa login di home yang sama digabung. Log lokal tidak memiliki identitas akun yang andal; kartu batas tetap **terakhir diamati** dan tidak dijumlahkan. - Setiap rekomendasi hanya menampilkan pengamatan, bukti yang mudah dibaca, dan tindakan bersyarat bila agregat struktural 30 hari yang telah diindeks mendukungnya. Tanpa bukti, tidak ada saran umum. @@ -68,11 +111,30 @@ Buka Settings (`Ctrl+,`) dan cari **`Claude Code Usage`**. Semua pengaturan bers - `usageLimitTracking` — tampilkan indikator kuota 5 jam / mingguan yang sebenarnya. - `showCost` / `showContext` — nyalakan/matikan item biaya dan indikator pengisian jendela konteks (seperti `/context`) di status bar. - Setiap item status bar ini bisa dimatikan sendiri — atur `usageLimitTracking`, `showCost`, atau `showContext` ke `false` untuk menyembunyikan salah satunya saja. -- `advice.apiKey` — API key untuk fitur saran AI (kompatibel dengan OpenAI). +- `advice.apiKey` — API key milik pengguna yang dipakai bersama oleh Saran AI dan Usage Optimizer (endpoint Anthropic atau kompatibel OpenAI). - `dashboardAutoRefresh` — nyalakan/matikan penyegaran otomatis dashboard (bisa juga di-toggle di header dashboard). Lihat [tabel pengaturan lengkap di README utama](README.md#configuration). +## Data lokal, privasi, dan batasan + +Lihat [Local data and privacy](LOCAL-DATA.md) untuk inventaris lengkap, +retensi, migrasi, penghapusan, dan batas interaksi jarak jauh. + +| Data | Retensi lokal | Perilaku jarak jauh | +|---|---|---| +| Log sumber | Milik penyedia, hanya-baca, tidak disalin utuh | Tidak ada secara default | +| Indeks Codex | Agregat numerik/struktur pseudonim yang terbatas | Tidak ada | +| Riwayat kuota | Pengamatan jendela anonim terbatas, tanpa ID akun mentah | Hanya kuota Claude saat aktif; Codex tetap lokal | +| UI/berbagi | Filter serta judul/rentang/tujuan GitHub opsional | Publikasi hanya setelah konfirmasi tepat | +| Saran/kunci | Bukti agregat terbatas; kunci hanya di SecretStorage | Hanya permintaan yang dipratinjau persis setelah tindakan Kirim terpisah | + +Reset tanpa bukti terstruktur tidak dapat direkonstruksi. Riwayat beberapa login +yang ambigu memakai pengamatan nyata terbaru untuk estimasi gabungan periode berjalan +berkeyakinan rendah; periode selesai tetap hanya menampilkan nilai terpakai. Nilai ekuivalen API bukan +tagihan. Retensi log sumber dikelola Claude Code/Codex; kontrol hapus eksplisit +adalah cara andal menghapus state turunan ekstensi. + ## Pemecahan masalah **"No Claude Code Data"** — pastikan Claude Code sudah terpasang dan pernah dipakai minimal sekali; periksa pengaturan `dataDirectory` (deteksi otomatis mencari di `~/.claude/projects`). diff --git a/README-ja.md b/README-ja.md index ede16bdd..5ec8ebd9 100644 --- a/README-ja.md +++ b/README-ja.md @@ -10,7 +10,7 @@ > > **これは何ではないか**:請求ツールではありません。表示される金額はすべて公開のトークン単価に基づく見積もりです。実際の請求は Anthropic アカウントをご確認ください。 -> スクリーンショットは英語 UI のものです。全機能の詳細は[メイン README](README.md) を参照してください。 +> スクリーンショットには英語と簡体字中国語を使用しています。詳細は[メイン README](README.md) を参照してください。 ## スクリーンショット @@ -26,24 +26,67 @@ ![ダッシュボード](images/v2-dashboard-en.png) +### v2.3.1 Codex と比較 + +![Claude 本日、簡体字中国語、ダークテーマ](images/v2.3.1/claude-today-zh-CN-dark.png) + +![Codex 概要、簡体字中国語、ダークテーマ](images/v2.3.1/codex-overview-zh-CN-dark.png) + +![Codex 週間枠推定、英語、ダークテーマ](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +![Claude と Codex の統合ヒートマップ、英語、ライトテーマ](images/v2.3.1/compare-heatmap-en-light.png) + +上の4枚は本番ダッシュボードのレンダラー、合成データ、VS Code Light+/Dark+ のテーマ変数から生成しています。個人の使用量や請求の証拠ではありません。ネイティブ VSIX のインストールは別途検証します。 + +- Codex は**本日の使用済みトークン**と**残りクォータ**を別表示します。週の使用率が36%なら `wk 64%`。ツールチップには使用率バー、リセット時刻、折り返した説明を表示します。クォータは最後のローカル観測であり、リアルタイム残高ではありません。 +- 期間詳細は初期状態で折りたたみ、共有設定はプレビューの下に配置。共有は既定で有効、無効化も可能です。色の強度は分位数・対数・線形から選択できます。 +- CLI の計上には usage を含む永続セッションログが必要です。未保存の呼び出しは復元できません。本日と過去30日は設定タイムゾーンを使用します。 + ## 主な機能 - **ステータスバー** — 本日のコスト、現在のセッションのコスト、そして Claude Code 自身の OAuth セッションから読み取る実際の 5 時間 / 週間クォータ(`5h:N% wk:N%`)。設定不要。 -- **ダッシュボードタブ** — 今日 / 今月 / 全期間 に加え、**Sessions / Projects / Content / Branches**。すべて並べ替え可能。 +- **ダッシュボードタブ** — 今日 / 直近 30 日 / 全期間 に加え、**Sessions / Projects / Content / Branches**。すべて並べ替え可能。 - **積み上げコスト構成チャート**(Y 軸と参照線付き)— 各日 / 各月のコストが入力・出力・キャッシュ書き込み・キャッシュ読み取りにどれだけ使われたか一目で分かります。 - **Content タブ** — どの内容がトークンを消費しているか(あなたのプロンプト vs ツール結果 vs アシスタント出力 / 思考)を推定。 -- **AI アドバイス**(任意)— 使用量サマリーと最近のプロンプトのサンプルを OpenAI 互換 API(デフォルト DeepSeek V4 Pro)に送り、具体的な書き換えを提案。キーは自分で用意、または静的デモを先にプレビュー可能。 +- **AI アドバイス**(任意)— まずローカルの根拠と説明可能な行動を示します。BYOK による任意のパーソナライズは集計値のみが既定で、プロンプト例には別の同意が必要です。完全なリクエストを正確にプレビューしてから、別の送信操作を行います。有用 / 不要 / 適用済みのフィードバックはローカルだけに残り、提案は期間限定で保留して期限後または手動で再表示できます。 + 同意を撤回するとプレビューは直ちに無効となり、実行中のアドバイス要求をキャンセルします。送信済みのデータは取り戻せません。 - **マルチベンダー価格** — Opus 4.x / Sonnet 4.x / Haiku 4.5 は Anthropic 公式価格で検証済み。OpenAI / Gemini / DeepSeek / Kimi / GLM / Qwen の参考価格(ファミリー認識フォールバック付き)。`Refresh Token Pricing` で LiteLLM の最新価格を取得。 - **パーソナライズ** — 言語、タイムゾーン、小数点桁数、コンパクト数値、プロジェクトのグループ化、ダッシュボード自動更新の切り替え。 +## v2.3.1 の新機能 + +- 正確な料金とコンテキスト情報が **GPT-6 Astra**(`gpt-6-astra`、 + 105 万トークン)および **Claude Fable 5.1 / Mythos 5.1** + (`claude-fable-5-1` / `claude-mythos-5-1`、100 万トークン)に対応しました。 + Fable 5.1 は専用のキャッシュ読み取り料金 `$0.25 / 100 万トークン` を使い、 + 従来の Fable 5 履歴は変更しません。GPT-6 の API 相当額には公式 Standard + の短コンテキスト料金を使用します。ローカル集計ログでは各リクエストが + 272K 入力を超えたか判定できないため、その場合のリクエスト全体への追加料金は + 含めません。 +- Claude の見積もりでは、Anthropic 直接料金または AWS Bedrock の in-region + オンデマンド料金を選択でき、現行の Opus・Sonnet・Haiku 系列を対象にします。 + 切り替えると未変更のログも直ちに再計算され、Sonnet 5 には 2026 年 8 月 31 日の + 開始記念価格終了後の標準料金を使用します。 +- 直近 30 日は設定タイムゾーンの今日と過去 29 日です。合計は照合可能で、再更新は安定し、月は古い順に表示します。Claude の Workflows サマリーも同じローリング範囲を使い、設定タイムゾーンでの開始日に基づいて各実行を集計します。チャート指標の切り替えやドリルダウンラベルの表示でも、日/月の使用量キーがホストのタイムゾーンによって前日・前月へずれることはありません。AI アドバイスと Usage Optimizer の保留期限も、設定タイムゾーンと UI 言語で表示します。 +- 構造化 reasoning effort をモデル名から推測しません。非ゼロの `unknown` は理由を示し、ゼロは表示しません。 +- 上限付き匿名クォータ観測が不規則・同日リセットを保持します。有効な同一ウィンドウの割合から、現在期間を含む総枠と未使用分の耐久性推定を表示します。近似・未帰属は低信頼度です。ローカルの Codex クォータ系列が重複していても、現在期間は最新の実測値による低信頼度の混合推定を表示し、帰属が曖昧な完了期間だけを使用済み表示に留めます。 +- 比較タブは既存の日次集計から Claude + Codex 統合活動ヒートマップを表示し、単一プロバイダーでも機能します。 +- プレビュー優先の共有スタジオは、決定的ローカル SVG、共有カード、Markdown、タイトル/範囲、プライバシープレビュー、調整可能な色に対応します。Academic Violet が既定で、強度マッピングは分位数(既定)、対数、線形から選べます。公開 GitHub 送信は正確な宛先を別途確認します。 +- Codex の Token 構成は、重複しない「非キャッシュ入力 / キャッシュ入力 / 出力」スタックの上に **非キャッシュ使用量**(非キャッシュ入力 + 出力)を明示します。推論は引き続き出力の部分集合です。 +- Codex はインデックス作成中も滑らかにスクロールします。スクロール状態は操作後に一度だけ保存され、ライブ進捗はページ全体を再構築せずテキストだけを更新します。モデル別の緑色サマリーは Claude と同じ意味になり、完全一致モデルの API 等価コストと価格カバレッジを表示します。未知モデルは `—`、effort は中立色の非キャッシュ Token 表示です。 +- OpenAI 互換の Optimizer リクエストは `reasoning_effort` のみを送り、未対応のトップレベル `thinking` を送信しないため、[#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94) を解決します。 +- Claude/Codex は密度、階層、フォーカス、ARIA、狭幅、明暗テーマの token を共有しつつ、指標の意味は分離します。 + +レビュー済み Release ドラフトは `v2.3.1` です。手動公開ワークフローが、その tag からパッケージ版を設定します。 + ## v2.3 Codex Beta - Codex の使用量レコードは `sessions/**/*.jsonl` と `archived_sessions/**/*.jsonl` からだけ検出し、認証情報、DB、未知のファイルは対象外です。これとは別に、`$CODEX_HOME/session_index.jsonl` だけをストリームで読み込み、実際のスレッド名に使う `id` → `thread_name` の対応を取得します。名前に含まれる絶対パスは伏せ、名前はメモリ内だけに保持します。使用量 JSONL の各行は、許可リスト内の使用量・構造メタデータを抽出するためだけにストリーム処理で一時解析します。プロンプト、応答、コマンド、ツール引数の各フィールドは参照も分析利用もせず、保持・永続化もしません。 - **処理済み** = 入力 + 出力、**非キャッシュ使用量** = 非キャッシュ入力 + 出力、**キャッシュ入力**は入力の部分集合、reasoning は出力の部分集合です。概要には「キャッシュ入力 / 入力」による入力キャッシュヒット率も表示します。Codex の請求コストは表示しません。先頭のサマリーカードには選択範囲の API 等価コスト推定を明示し、全期間ビューには同じ単価基準の週間推移を表示します。Claude / Codex / Compare は各プロバイダーの集計方法を分けて扱います。 -- Codex の**今日**は、設定したタイムゾーンの現在の暦日です。正確な時間別 API 等価コストを表示し、Token 構成は独立したビューとして残します。日別・月別のメインチャートも API 等価コストを既定表示にし、Token 構成は別に確認できます。正確に一致する既知モデルだけを価格計算に含めるため、未知モデルは価格未設定のままで、価格カバレッジは常に表示されます。schema 3 と互換性のある追加型の時間別 sidecar は、今日の使用を含むことが既に分かっている canonical ファイルだけを対象とし、checkpoint 保存と再開に対応します。全履歴の再インデックスは発生させません。 +- Codex の**今日**は、設定したタイムゾーンの現在の暦日です。正確な時間別 API 等価コストを表示し、Token 構成は独立したビューとして残します。日別・月別のメインチャートも API 等価コストを既定表示にし、Token 構成は別に確認できます。正確に一致する既知モデルだけを価格計算に含めるため、未知モデルは価格未設定のままで、価格カバレッジは常に表示されます。schema 3 と互換性のある追加型の時間別 sidecar は、直近 30 日の疎な日付 / 時間バケットを保持し、checkpoint 保存と再開、31 日目の削除に対応します。日付を展開しても JSONL は読みません。Codex の月別チャートと表は古い月から順に表示します。 - リクエスト単位の Token 帰属では、有効な `last_token_usage` の各 component を優先します。その `total_tokens` はアクティブなコンテキスト量であり、リクエスト使用量ではありません。total と last の完全な数値署名により、同じ仮名化 rate-limit ソースまたは直前の隣接レコードの再生を証明できる場合だけ除外します。last snapshot がない場合は cumulative lineage high-water にフォールバックします。アップグレード後はインデックスを一度自動再構築し、その間もインデックス済み小計を表示します。 -- Claude と Codex の全期間 / 比較ビューは、ローカル Token ログから過去の使用済み等価値を直接計算します。最新の有効な公式リセット観測を基準に、一意で重複しない週間期間の列を作り、各使用イベントは一つの期間にだけ数えます。利用できる観測がなければ、使用分のみの履歴を UTC の月曜から月曜の暦週にフォールバックします。系列名が異なっていても、重複して整合しない将来リセットは競合として扱い、二つ目の「現在の期間」を作りません。期間範囲とリセット時刻は分けて表示します。Codex の使用量は日単位のスライスで保存されます。スライスが公式の日中リセットをまたぐ場合も Token は一度だけ数え、影響する期間を「境界近似」と表示し、使用済み等価値だけを示して総上限や未使用分を逆算しません。この表示規則はインデックス schema を変更せず、再構築も発生させません。Codex の過去期間は常に使用済み値だけを表示します。最新の現在期間に限り、リセット競合がなく、インデックス済み使用量を単一の観測元へ確実に帰属できる場合だけ総上限を推定でき、現在の未使用値は結論として示しません。帰属できない複数ログインの使用量も使用済み値だけとし、架空のアカウント分割は行いません。履歴には現在の公式 API 単価を一貫して適用します。これは請求額や公式のサブスクリプション価格ではなく代理推定です。このパネルは既定で有効で、設定の `showWeeklyEquivalentValue` から非表示にできます。Claude はこのリリースからプロファイル別に上限観測を記録します。 -- Codex に切り替えても、既存の今日 / 今月 / 全期間 / セッション / プロジェクト / コンテンツ / 設定の構成を維持し、Codex の意味に合わせてラベルだけを調整します。両プロバイダーは同じ render function、HTML class、チャート、表、余白、レスポンシブルールを使います。時系列チャートの幅は揃い、密な内容だけが各領域内でスクロールします。Codex の提案はインデックス済み 30 日間の構造的根拠を使います。 +- Claude と Codex の全期間 / 比較ビューは、ローカル Token ログから過去の使用済み等価値を直接計算します。最新の有効な公式リセット観測を基準に、一意で重複しない週間期間の列を作り、各使用イベントは一つの期間にだけ数えます。利用できる観測がなければ、使用分のみの履歴を UTC の月曜から月曜の暦週にフォールバックします。同じ quota series の観測は一つの series のまま、低信頼度の近似として表示でき、二つ目の「現在の期間」は作りません。Codex の account-wide `codex` 観測は過去と現在の期間の両方を装飾でき、リセット時刻のずれ、ファイルソース、日次境界越えは信頼度を下げます。ファイルキーはアカウント ID ではないため、同じ home の対象ファイルをまとめて扱います。ローカルの quota series が重複していても、現在期間は最新の実測値による低信頼度の混合推定を表示します。帰属が曖昧な完了期間、または観測のない期間は使用済み等価値だけを表示し、アカウント分割を作りません。一貫した観測期間は現在期間を含めて総枠と未使用分の耐久性推定を表示でき、帰属や境界が不確かな場合は値を隠さず信頼度を下げます。この表示規則はインデックス schema を変更せず、再構築も発生させません。履歴には現在の公式 API 単価を一貫して適用します。これは請求額、公式残高、公式のサブスクリプション価格ではなく代理推定です。このパネルは既定で有効で、設定の `showWeeklyEquivalentValue` から非表示にできます。Claude はこのリリースからプロファイル別に上限観測を記録します。 +- Codex に切り替えても、既存の今日 / 直近 30 日 / 全期間 / セッション / プロジェクト / コンテンツ / 設定の構成を維持し、Codex の意味に合わせてラベルだけを調整します。両プロバイダーは同じ render function、HTML class、チャート、表、余白、レスポンシブルールを使います。時系列チャートの幅は揃い、密な内容だけが各領域内でスクロールします。Codex の提案はインデックス済み 30 日間の構造的根拠を使います。 - ルートタスクには、絶対パスを伏せた最新の実際のスレッド名を使います。子タスクは自身の実際のスレッド名を優先し、ない場合は報告されたニックネームを使って親 / ルートタスク名も表示します。それらもない場合はローカライズ済みの中立的な代替名を表示します。プロジェクト名は Git リポジトリ名、Git 外ではフォルダー名です。信頼できる集計ができない Branches や Workflows は作り上げません。 - 過去 7 日 / 30 日は、設定したタイムゾーンでイベント発生日を正確に区切ります。移行または再構築中は、Codex のカード、表、プロジェクト、セッション、提案、ステータス値を**インデックス済み小計**として明示し、未検証の旧集計値を除外します。Codex home を検出するとプロバイダータブを直ちに表示し、初回インデックス中はページ内に正確なインデックス済みファイル数、割合、容量の進捗をリアルタイム表示します。「比較」は両プロバイダーに実データが揃ってから表示します。最初のアトミックチェックポイント生成後は、インデックス処理が続いていても小計ダッシュボード全体を利用でき、進捗表示がカードや表に置き換わることはありません。選択した Codex home はアカウントを区別しないため、同じ home に複数のログインが残したログは合算されます。ローカルログには信頼できるアカウント識別子がないため、上限カードは**最終観測**のままで合算しません。 - 各提案は、インデックス済み 30 日間の構造集計に根拠がある場合だけ、観測、読みやすい根拠、条件付きアクションを示します。根拠がなければ一般論を生成しません。 @@ -69,11 +112,27 @@ Cursor / Windsurf 向けに [Open VSX Registry](https://open-vsx.org/extension/G - `usageLimitTracking` — 実際の 5 時間 / 週間クォータ表示。 - `showCost` / `showContext` — ステータスバーのコスト表示と、コンテキストウィンドウ使用率(`/context` 風)の切り替え。 - これらのステータスバー項目は個別に非表示にできます。`usageLimitTracking` / `showCost` / `showContext` を `false` にすると、その項目だけ消えます。 -- `advice.apiKey` — AI アドバイス機能の API キー(OpenAI 互換)。 +- `advice.apiKey` — AI アドバイスと Usage Optimizer で共有する持ち込み API キー(Anthropic または OpenAI 互換エンドポイント)。 - `pauseDashboardRefresh` — ダッシュボードの自動更新を一時停止(ダッシュボードのヘッダーでも切り替え可能)。 設定の全一覧は[メイン README](README.md#configuration) を参照。 +## ローカルデータ、プライバシー、制限 + +完全な一覧、保持、移行、消去、通信境界は +[Local data and privacy](LOCAL-DATA.md)([中文](LOCAL-DATA.zh-CN.md))を参照してください。 + +| データ | ローカル保持 | リモート動作 | +|---|---|---| +| ソースログ | プロバイダー所有・読み取り専用、丸ごと複製しない | 既定なし | +| Codex インデックス | 上限付き仮名化数値/構造集計 | なし | +| クォータ履歴 | 上限付き匿名ウィンドウ観測、元アカウント ID なし | 有効時の Claude クォータ取得のみ。Codex はローカル | +| UI/共有 | フィルター、任意のタイトル/範囲/GitHub 宛先文字列 | 正確な確認後だけ公開 | +| アドバイス/鍵 | 上限付き集計証拠。鍵は SecretStorage のみ | 別の送信操作後だけ正確にプレビューした要求 | + +構造化証拠にないリセットは復元できません。複数ログインの帰属が曖昧な場合、現在期間は最新の実測値による低信頼度の混合推定を表示し、完了期間は使用済みのみです。 +API 等価値は請求額ではありません。ソースログの保持は Claude Code/Codex が管理し、派生状態は明示消去が確実です。 + ## トラブルシューティング **「No Claude Code Data」** — Claude Code がインストールされ、少なくとも一度使用されていることを確認。`dataDirectory` 設定を確認(自動検出は `~/.claude/projects` を参照)。 diff --git a/README-ko.md b/README-ko.md index 0520408a..3e452860 100644 --- a/README-ko.md +++ b/README-ko.md @@ -10,7 +10,7 @@ > > **무엇이 아닌가**: 청구 도구가 아닙니다. 표시되는 모든 금액은 공개된 100만 토큰당 단가 기준 추정치입니다. 실제 청구는 Anthropic 계정을 확인하세요. -> 스크린샷은 영어 UI 기준입니다. 전체 기능 설명은 [메인 README](README.md)를 참고하세요. +> 스크린샷에는 영어와 중국어 간체 UI가 포함됩니다. 전체 기능 설명은 [메인 README](README.md)를 참고하세요. ## 스크린샷 @@ -26,24 +26,67 @@ ![대시보드](images/v2-dashboard-en.png) +### v2.3.1 Codex 및 비교 + +![Claude 오늘, 중국어 간체, 어두운 테마](images/v2.3.1/claude-today-zh-CN-dark.png) + +![Codex 개요, 중국어 간체, 어두운 테마](images/v2.3.1/codex-overview-zh-CN-dark.png) + +![Codex 주간 한도 추정, 영어, 어두운 테마](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +![Claude와 Codex 통합 히트맵, 영어, 밝은 테마](images/v2.3.1/compare-heatmap-en-light.png) + +위 4장은 실제 대시보드 렌더러, 합성 데이터, VS Code Light+/Dark+ 테마 변수로 생성했습니다. 개인 사용량이나 청구 증거가 아니며, 네이티브 VSIX 설치는 별도로 검증합니다. + +- Codex는 **오늘 사용한 토큰**과 **남은 쿼터**를 따로 표시합니다. 주간 사용률 36%이면 `wk 64%`입니다. 툴팁에는 사용률 막대, 초기화 시각, 줄바꿈 설명이 유지됩니다. 쿼터는 마지막 로컬 관측이며 실시간 잔액이 아닙니다. +- 기간 상세는 기본으로 접고 공유 설정은 미리보기 아래에 둡니다. 공유는 기본 활성화이며 끌 수 있고, 색 강도는 분위수·로그·선형 중 선택합니다. +- CLI 호출은 usage가 있는 영구 세션 로그를 남겨야 집계됩니다. 저장하지 않은 호출은 복원할 수 없습니다. 오늘과 최근 30일은 설정된 시간대를 사용합니다. + ## 기능 - **상태 표시줄** — 오늘 비용, 현재 세션 비용, 그리고 Claude Code 자체 OAuth 세션에서 읽는 실제 5시간 / 주간 쿼터(`5h:N% wk:N%`). 설정 불필요. -- **대시보드 탭** — 오늘 / 이번 달 / 전체 기간, 그리고 **Sessions / Projects / Content / Branches**. 모두 정렬 가능. +- **대시보드 탭** — 오늘 / 최근 30일 / 전체 기간, 그리고 **Sessions / Projects / Content / Branches**. 모두 정렬 가능. - **누적 비용 구성 차트**(Y축과 기준선 포함) — 각 일 / 월의 비용 중 입력·출력·캐시 쓰기·캐시 읽기가 차지하는 비율을 한눈에. - **Content 탭** — 어떤 콘텐츠가 토큰을 소비하는지 추정(내 프롬프트 vs 도구 결과 vs 어시스턴트 출력 / 사고). -- **AI 조언**(선택) — 사용량 요약과 최근 프롬프트 샘플을 OpenAI 호환 API(기본 DeepSeek V4 Pro)로 보내 구체적인 재작성을 제안. 키는 직접 준비하거나, 정적 데모를 먼저 미리보기. +- **AI 조언**(선택) — 먼저 로컬 근거와 설명 가능한 행동을 보여 줍니다. 선택형 BYOK 개인화는 기본적으로 집계만 포함하고 프롬프트 샘플에는 별도 동의가 필요합니다. 전체 요청을 정확히 미리 본 뒤 별도의 보내기 동작을 수행하며, 유용함 / 유용하지 않음 / 적용됨 피드백은 로컬에만 남습니다. 조언은 제한된 기간 동안 일시 중지할 수 있으며 만료되거나 수동으로 다시 표시됩니다. + 동의를 철회하면 미리보기가 즉시 무효화되고 진행 중인 조언 요청이 취소됩니다. 이미 전송된 데이터는 회수할 수 없습니다. - **멀티 벤더 가격** — Opus 4.x / Sonnet 4.x / Haiku 4.5는 Anthropic 공식 가격으로 검증. OpenAI / Gemini / DeepSeek / Kimi / GLM / Qwen 참고 가격(패밀리 인식 폴백 포함). `Refresh Token Pricing`으로 LiteLLM 최신 가격 가져오기. - **개인화** — 언어, 시간대, 소수 자릿수, 간략 숫자, 프로젝트 그룹화, 대시보드 자동 새로고침 토글. +## v2.3.1 새로운 기능 + +- 정확한 가격 및 컨텍스트 메타데이터가 **GPT-6 Astra**(`gpt-6-astra`, + 105만 토큰)와 **Claude Fable 5.1 / Mythos 5.1** + (`claude-fable-5-1` / `claude-mythos-5-1`, 100만 토큰)을 지원합니다. + Fable 5.1은 전용 캐시 읽기 요금인 `$0.25 / 백만 토큰`을 사용하며 기존 + Fable 5 기록은 바꾸지 않습니다. GPT-6 API 등가액은 공식 Standard 단기 + 컨텍스트 요금을 사용합니다. 로컬 집계 로그로는 개별 요청이 272K 입력을 + 넘었는지 확인할 수 없으므로 해당 요청 전체에 적용되는 추가 요금은 포함하지 + 않습니다. +- Claude 추정치는 Anthropic 직접 요금 또는 AWS Bedrock in-region 온디맨드 요금을 + 선택해 현재 Opus·Sonnet·Haiku 계열에 적용할 수 있습니다. 백엔드를 바꾸면 변경되지 + 않은 로그도 즉시 다시 계산하며, Sonnet 5에는 2026년 8월 31일 출시 프로모션 종료 + 이후의 표준 요금을 사용합니다. +- 최근 30일은 설정 시간대의 오늘과 이전 29일입니다. 합계가 대조되고 반복 새로고침이 안정적이며 월은 오래된 순서로 표시됩니다. Claude Workflows 요약도 같은 롤링 범위를 사용하고 설정 시간대의 시작일에 따라 각 실행을 집계합니다. 차트 지표를 전환하거나 드릴다운 레이블을 표시할 때도 일/월 사용량 키가 호스트 시간대 때문에 전날이나 전월로 밀리지 않습니다. AI 조언과 Usage Optimizer의 일시 중지 만료일도 설정 시간대와 UI 언어로 표시합니다. +- 구조화 reasoning effort를 모델 이름에서 추측하지 않습니다. 0이 아닌 `unknown`은 이유를 설명하고 0은 숨깁니다. +- 제한된 익명 쿼터 관측이 불규칙·당일 재설정을 보존합니다. 같은 창의 유효 비율로 현재 기간을 포함한 총한도와 미사용 내구성 추정치를 표시합니다. 근사·미귀속 증거는 낮은 신뢰도로 표시합니다. 로컬 Codex 쿼터 계열이 겹쳐도 현재 기간은 마지막 실제 관측으로 신뢰도 낮은 혼합 추정을 표시하고, 귀속이 모호한 완료 기간만 사용분 전용으로 유지합니다. +- 비교 탭은 기존 일별 집계로 Claude + Codex 통합 활동 히트맵을 표시하며 단일 공급자에서도 작동합니다. +- 미리보기 중심 공유 스튜디오는 결정적 로컬 SVG, 공유 카드, Markdown, 제목/기간, 개인정보 미리보기와 조절 가능한 색상을 지원합니다. Academic Violet이 기본이며 강도 매핑은 분위수(기본), 로그, 선형 중에서 선택할 수 있습니다. 공개 GitHub 전송은 정확한 대상을 별도로 확인합니다. +- Codex Token 구성은 겹치지 않는 「캐시되지 않은 입력 / 캐시 입력 / 출력」스택 위에 **캐시되지 않은 사용량**(캐시되지 않은 입력 + 출력)을 명확히 표시합니다. 추론은 계속 출력의 부분집합입니다. +- Codex는 인덱싱 중에도 부드럽게 스크롤됩니다. 스크롤 상태는 동작이 끝난 뒤 한 번만 저장되고 실시간 인덱스 진행률은 페이지 전체를 다시 만들지 않고 텍스트만 갱신합니다. 모델별 녹색 요약은 Claude와 같은 의미로 정확히 일치하는 모델의 API 등가 비용과 가격 적용 범위를 표시합니다. 알 수 없는 모델은 `—`, effort는 중립색의 캐시되지 않은 Token 값으로 유지합니다. +- OpenAI 호환 Optimizer 요청은 `reasoning_effort`만 보내고 지원되지 않는 최상위 `thinking`을 보내지 않아 [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94)를 해결합니다. +- Claude/Codex는 밀도, 계층, 포커스, ARIA, 좁은 폭, 밝고 어두운 테마 token을 공유하되 지표 의미는 분리합니다. + +검토된 Release 초안은 `v2.3.1`이며, 수동 게시 워크플로가 해당 tag에서 패키지 버전을 설정합니다. + ## v2.3 Codex Beta - Codex 사용량 레코드는 `sessions/**/*.jsonl`과 `archived_sessions/**/*.jsonl`에서만 찾으며 자격 증명, DB, 알 수 없는 파일은 제외합니다. 별도로 `$CODEX_HOME/session_index.jsonl` 하나만 정확히 스트리밍해 실제 스레드 제목에 사용할 `id` → `thread_name` 매핑을 가져옵니다. 제목 속 절대 경로는 가리고 제목은 메모리에만 유지합니다. 사용량 JSONL 각 줄은 허용 목록의 사용량·구조 메타데이터를 추출하기 위해서만 스트리밍 방식으로 일시 파싱합니다. 프롬프트, 응답, 명령, 도구 인수 필드는 검사하거나 분석에 사용하지 않으며 보관·영구 저장하지 않습니다. - **처리된** 값 = 입력 + 출력, **캐시되지 않은 사용량** = 캐시되지 않은 입력 + 출력, **캐시 입력**은 입력의 부분집합, reasoning은 출력의 부분집합입니다. 개요에는 캐시 입력 / 입력으로 계산한 입력 캐시 적중률도 표시합니다. Codex 청구 비용은 표시하지 않습니다. 첫 요약 카드에는 선택 범위의 API 등가 비용 추정치를 명확히 표시하고, 전체 기간 보기에는 같은 가격 기준의 주간 추이를 표시합니다. Claude / Codex / Compare는 공급자별 집계 의미를 분리합니다. -- Codex의 **오늘**은 설정한 시간대의 현재 달력 날짜를 뜻합니다. 정확한 시간별 API 등가 비용을 표시하고 Token 구성은 별도 보기로 유지합니다. 일별·월별 기본 차트도 API 등가 비용을 기본값으로 사용하며 Token 구성은 따로 볼 수 있습니다. 정확히 일치하는 알려진 모델만 가격 계산에 포함하므로 알 수 없는 모델은 가격을 매기지 않고 가격 적용 범위는 계속 표시합니다. schema 3과 호환되는 추가형 시간별 sidecar는 오늘 사용량이 있다고 이미 확인된 canonical 파일만 처리하고 checkpoint 저장과 재개를 지원하며, 전체 기록 재인덱싱을 유발하지 않습니다. +- Codex의 **오늘**은 설정한 시간대의 현재 달력 날짜를 뜻합니다. 정확한 시간별 API 등가 비용을 표시하고 Token 구성은 별도 보기로 유지합니다. 일별·월별 기본 차트도 API 등가 비용을 기본값으로 사용하며 Token 구성은 따로 볼 수 있습니다. 정확히 일치하는 알려진 모델만 가격 계산에 포함하므로 알 수 없는 모델은 가격을 매기지 않고 가격 적용 범위는 계속 표시합니다. schema 3과 호환되는 추가형 시간별 sidecar는 최근 30일의 희소한 날짜 / 시간 버킷을 보관하고 checkpoint 저장과 재개, 31일째 제거를 지원하며 날짜를 펼칠 때 JSONL을 읽지 않습니다. Codex 월별 차트와 표는 오래된 달부터 표시합니다. - 요청 단위 Token 귀속은 유효한 `last_token_usage` component를 우선 사용합니다. 그 안의 `total_tokens`는 활성 컨텍스트 크기이며 요청 사용량이 아닙니다. total과 last의 전체 숫자 서명이 동일한 가명 rate-limit 소스 또는 바로 인접한 레코드의 재생을 증명할 때만 중복을 제거합니다. last snapshot이 없으면 cumulative lineage high-water로 되돌아갑니다. 업그레이드 후 인덱스를 한 번 자동 재구축하며 그동안에도 인덱싱된 소계를 계속 표시합니다. -- Claude와 Codex의 전체 기간 / 비교 보기는 로컬 Token 로그에서 과거 사용 등가치를 직접 계산합니다. 가장 최근의 유효한 공식 재설정 관측 하나만 고유하고 겹치지 않는 주간 기간열의 기준이 되므로 각 사용 이벤트는 한 기간에만 집계됩니다. 사용할 수 있는 관측이 없으면 사용분 전용 기록만 UTC 월요일부터 월요일까지의 달력 주로 되돌아갑니다. series 이름이 달라도 겹치면서 정렬되지 않은 미래 재설정은 충돌로 처리하며 두 번째 「현재 기간」을 만들 수 없습니다. 기간 범위와 재설정 시각은 따로 표시합니다. Codex 사용량은 일별 슬라이스로 저장됩니다. 슬라이스가 공식 일중 재설정을 가로지르더라도 Token은 한 번만 집계하고, 영향을 받은 기간을 「경계 근사치」로 표시하며 사용된 등가치만 보여 주고 총한도나 미사용분을 역산하지 않습니다. 이 표시 규칙은 인덱스 schema를 변경하거나 재구축을 유발하지 않습니다. Codex 과거 기간은 항상 사용된 값만 표시합니다. 최신 현재 기간에 한해 재설정 충돌이 없고 인덱싱된 사용량을 단일 관측 출처에 안정적으로 귀속할 수 있을 때만 총한도를 추정할 수 있으며, 현재 미사용 값은 결론으로 제시하지 않습니다. 귀속할 수 없는 여러 로그인 사용량도 사용된 값만 표시하며 계정 분리를 만들어 내지 않습니다. 현재 공식 API 단가를 전체 기록에 일관되게 적용합니다. 이는 청구액이나 공식 구독 가격이 아닌 대리 추정치입니다. 이 패널은 기본으로 켜지며 설정의 `showWeeklyEquivalentValue`에서 끌 수 있습니다. Claude는 이 릴리스부터 프로필별 한도 관측을 기록합니다. -- Codex로 전환해도 기존 오늘 / 이번 달 / 전체 기간 / 세션 / 프로젝트 / 콘텐츠 / 설정 구조를 유지하고 Codex 의미에 맞게 레이블만 조정합니다. 두 공급자는 같은 render function, HTML class, 차트, 표, 간격 및 반응형 규칙을 사용합니다. 시계열 차트는 너비가 정렬되고 밀집된 콘텐츠만 각 영역 안에서 스크롤됩니다. Codex 제안은 인덱싱된 30일 구조 근거를 사용합니다. +- Claude와 Codex의 전체 기간 / 비교 보기는 로컬 Token 로그에서 과거 사용 등가치를 직접 계산합니다. 가장 최근의 유효한 공식 재설정 관측을 기준으로 고유하고 겹치지 않는 주간 기간열을 만들며 각 사용 이벤트는 한 기간에만 집계됩니다. 사용할 수 있는 관측이 없으면 사용분 전용 기록만 UTC 월요일부터 월요일까지의 달력 주로 되돌아갑니다. 같은 quota series의 관측은 하나의 series로 유지하고 낮은 신뢰도의 근사치로 표시할 수 있으며 두 번째 「현재 기간」을 만들지 않습니다. Codex의 account-wide `codex` 관측은 과거와 현재 기간 모두를 장식할 수 있고 재설정 이동, 파일 출처 또는 일별 경계 통과는 신뢰도를 낮춥니다. 파일 키는 계정 ID가 아니므로 같은 home의 대상 파일을 함께 사용합니다. 로컬 quota series가 겹쳐도 현재 기간은 마지막 실제 관측으로 신뢰도 낮은 혼합 추정을 표시합니다. 귀속이 모호한 완료 기간이나 관측이 없는 기간은 사용된 등가치만 표시하고 계정 분리를 만들어 내지 않습니다. 내부적으로 일관된 관측 기간은 현재 기간을 포함해 총한도와 미사용 내구성 추정치를 표시할 수 있으며, 귀속이나 경계가 불확실하면 값을 숨기지 않고 신뢰도를 낮춥니다. 이 표시 규칙은 인덱스 schema를 변경하거나 재구축을 유발하지 않습니다. 현재 공식 API 단가를 전체 기록에 일관되게 적용합니다. 이는 청구액, 공식 잔액 또는 공식 구독 가격이 아닌 대리 추정치입니다. 이 패널은 기본으로 켜지며 설정의 `showWeeklyEquivalentValue`에서 끌 수 있습니다. Claude는 이 릴리스부터 프로필별 한도 관측을 기록합니다. +- Codex로 전환해도 기존 오늘 / 최근 30일 / 전체 기간 / 세션 / 프로젝트 / 콘텐츠 / 설정 구조를 유지하고 Codex 의미에 맞게 레이블만 조정합니다. 두 공급자는 같은 render function, HTML class, 차트, 표, 간격 및 반응형 규칙을 사용합니다. 시계열 차트는 너비가 정렬되고 밀집된 콘텐츠만 각 영역 안에서 스크롤됩니다. Codex 제안은 인덱싱된 30일 구조 근거를 사용합니다. - 루트 작업은 절대 경로를 가린 최신 실제 스레드 제목을 사용합니다. 자식 작업은 자신의 실제 스레드 제목을 우선 사용하고, 제목이 없으면 보고된 닉네임을 사용하면서 부모 / 루트 작업 제목도 표시합니다. 이 정보도 없으면 현지화된 중립 대체 이름을 표시합니다. 프로젝트 이름은 Git 저장소 이름을, Git 외부에서는 폴더 이름을 사용합니다. 안정적으로 집계할 수 없는 Branches나 Workflows를 만들어 내지 않습니다. - 최근 7일 / 30일 값은 설정한 시간대에서 이벤트 발생일을 정확히 나눠 계산합니다. 마이그레이션이나 재구축이 진행 중이면 Codex 카드, 표, 프로젝트, 세션, 권장 사항 및 상태 값을 **인덱싱된 소계**로 명시하고 검증되지 않은 이전 합계를 제외합니다. Codex home이 감지되면 공급자 탭을 즉시 표시하고, 최초 인덱싱 중에는 페이지 안에 정확한 인덱싱 파일 수, 백분율, 용량 진행 상황을 실시간으로 표시합니다. 비교 탭은 두 공급자 모두 실제 데이터가 생긴 뒤에만 표시됩니다. 첫 원자적 체크포인트가 생성되면 인덱싱이 계속되는 동안에도 전체 소계 대시보드를 사용할 수 있으며 진행 표시가 카드나 표를 대체하지 않습니다. 선택한 Codex home은 계정을 구분하지 않으므로 같은 home에 여러 로그인이 남긴 로그는 합산됩니다. 로컬 로그에는 신뢰할 수 있는 계정 식별자가 없으므로 한도 카드는 **마지막 관측**만 유지하며 합산하지 않습니다. - 각 제안은 인덱싱된 30일 구조 집계에 근거가 있을 때만 관측, 읽기 쉬운 근거, 조건부 행동을 보여 줍니다. 근거가 없으면 일반적인 조언을 생성하지 않습니다. @@ -69,11 +112,27 @@ Cursor / Windsurf용으로 [Open VSX Registry](https://open-vsx.org/extension/Gr - `usageLimitTracking` — 실제 5시간 / 주간 쿼터 표시. - `showCost` / `showContext` — 상태 표시줄의 비용 항목과 컨텍스트 윈도우 사용률(`/context` 유사) 표시 전환. - 위 상태 표시줄 항목들은 개별적으로 끌 수 있습니다. `usageLimitTracking` / `showCost` / `showContext` 를 `false`로 설정하면 해당 항목만 숨겨집니다. -- `advice.apiKey` — AI 조언 기능용 API 키(OpenAI 호환). +- `advice.apiKey` — AI 조언과 Usage Optimizer가 함께 쓰는 사용자 제공 API 키(Anthropic 또는 OpenAI 호환 엔드포인트). - `pauseDashboardRefresh` — 대시보드 자동 새로고침 일시정지(대시보드 헤더에서도 토글 가능). 전체 설정 표는 [메인 README](README.md#configuration)를 참고하세요. +## 로컬 데이터, 개인정보 및 제한 + +전체 목록, 보존, 마이그레이션, 삭제 및 원격 경계는 +[Local data and privacy](LOCAL-DATA.md)([中文](LOCAL-DATA.zh-CN.md))를 참고하세요. + +| 데이터 | 로컬 보존 | 원격 동작 | +|---|---|---| +| 원본 로그 | 공급자 소유·읽기 전용, 전체 복사 안 함 | 기본 없음 | +| Codex 인덱스 | 제한된 가명 수치/구조 집계 | 없음 | +| 쿼터 기록 | 제한된 익명 창 관측, 원시 계정 ID 없음 | 활성화된 Claude 쿼터 조회만. Codex는 로컬 | +| UI/공유 | 필터와 선택형 제목/범위/GitHub 대상 문자열 | 정확한 확인 후에만 게시 | +| 조언/키 | 제한된 집계 근거, 키는 SecretStorage만 | 별도 보내기 후 정확히 미리 본 요청만 전송 | + +구조화 근거에 없는 재설정은 복원할 수 없습니다. 여러 로그인 귀속이 모호하면 현재 기간은 마지막 실제 관측으로 신뢰도 낮은 혼합 추정을 표시하고, 완료 기간은 사용분만 표시합니다. +API 등가 값은 청구액이 아닙니다. 원본 로그 보존은 Claude Code/Codex가 관리하며 파생 상태는 명시적 삭제가 가장 확실합니다. + ## 문제 해결 **"No Claude Code Data"** — Claude Code가 설치되어 최소 한 번 사용되었는지 확인하고, `dataDirectory` 설정을 확인하세요(자동 감지는 `~/.claude/projects`를 봅니다). diff --git a/README-zh-CN.md b/README-zh-CN.md index 04a341a4..c2884019 100644 --- a/README-zh-CN.md +++ b/README-zh-CN.md @@ -10,7 +10,7 @@ > > **它不是什么**:账单工具。所有金额均为估算值(基于公开的每百万 token 单价),实际费用请以 Anthropic 官方账单为准。 -> 截图取自英文界面。 +> 截图包含中英文界面;各图标明主题与范围。 --- @@ -35,40 +35,77 @@ *点击状态栏打开完整仪表板:堆叠 token 构成图、小时分布、缓存命中率、按 token 类型的成本构成,以及下方的按模型 / 按日表格。* +### v2.3.1 Codex 与对比 + +![Claude 今日,简体中文深色主题](images/v2.3.1/claude-today-zh-CN-dark.png) + +![Codex 概览,简体中文深色主题](images/v2.3.1/codex-overview-zh-CN-dark.png) + +![Codex 每周额度估算,英文深色主题](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +![Claude 与 Codex 综合热力图,英文浅色主题](images/v2.3.1/compare-heatmap-en-light.png) + +以上四张 v2.3.1 截图使用生产仪表板渲染器、合成夹具及 VS Code Light+/Dark+ 主题变量生成,不是个人用量或账单证据;原生 VSIX 安装单独验收。 + +- Codex 主状态项显示**今日已用 token**,周额度项显示**余量**:已用 36% 时为 `wk 64%`;悬浮卡保留已用进度条、重置时间和分行说明。额度来自本地最后观测,不是实时余额。 +- 周期详情默认折叠;分享设置位于图下方。分享工作台默认开启、可关闭;色阶可选分位数、对数或线性。 +- CLI 调用只有留下带 usage 的持久会话日志才能计入。未保存会话的历史调用不能回填;今日和最近 30 天都采用配置时区。 + ### Content 标签页:看清 token 究竟花在了哪里 ![Content 标签页](images/v2-content-en.png) *估算各类内容的 token 占比:你的提示词 vs 工具结果(按工具)vs 助手输出 / 思考。这是优化使用的切入点,范围为最近 30 天(`advice.promptWindowDays`)。* -### AI 建议:基于你真实用量的一份教练报告 +### AI 建议:先看本地证据,再决定是否发送 -AI 建议生成的是一份 **Markdown 文档**,用文字展示比截图更直观。配好 key(`advice.apiKey`),点击 **Get AI advice**(✨ 按钮,或 Content 标签页那张卡),选一个范围(全部项目,或某个项目),它会把你的用量汇总加上一份**你自己的**提示词样本发给你的模型,打开一份按优先级排好的报告。自备 key,默认使用 Anthropic(`/v1/messages`),也支持任意 OpenAI 兼容端点。 +**Get AI advice** 现在打开统一的建议有效性界面:先用已物化的本地聚合解释观察、证据和条件式行动;用户可记录「有用 / 无用 / 已应用」,并在存在可靠同类任务时查看版本化的前后比较。比较账本只保存粗粒度指标、质量、覆盖率和版本,不保存提示词、正文、路径或 session ID;没有可靠配对时会明确显示证据不足。单条建议可暂停有限时间,期间移出默认摘要,到期或手动恢复后重新出现。 -返回内容大致是这样(示意): +AI 个性化仍为可选项。自备 `advice.apiKey` 后,默认请求只含聚合数据;提示样本需要单独同意。界面会先展示将要发送的**完整请求及其规范字节**,随后必须另外点击「发送」才会调用配置的 Anthropic 或 OpenAI 兼容端点。密钥只进入请求头,不出现在预览中;没有默认、后台或订阅凭据请求。 -> **把指令写得更完整** -> - 有几条提示词只写了「修一下这个 bug」,没说是哪个文件、什么现象,于是第一轮要先去找。开头先点明文件 + 期望行为 vs 实际行为。 -> -> **在不牺牲清晰度的地方省 token** -> - 约 38% 的 token 花在 150k 上下文以上。不相关的任务之间用 `/clear`,每次请求都更省。 +撤回建议的数据授权会立即作废预览并取消在途建议请求,不等待本地存储写入;已经传出的字节无法追回。 ### 用量优化器 ![用量优化器卡片](images/v2-optimizer-en.png) -粘贴进一条粗略、没成形的需求,获得一条干净、**可直接粘贴**的提示词(纯文本、无 Markdown),并附上推荐的 effort / thinking / 模型(以小标签显示)。三个可选开关进一步微调(标出含糊指代 · 压缩长粘贴内容 · 建议风格方向)。实验性,默认关闭;**只发送你粘贴的文字**,不碰你的文件、不进终端,且首次有一次性同意确认。 +粘贴进一条粗略、没成形的需求,获得一条干净、**可直接粘贴**的提示词(纯文本、无 Markdown),并附上推荐的 effort / thinking / 模型(以小标签显示)。三个可选开关进一步微调(标出含糊指代 · 压缩长粘贴内容 · 建议风格方向)。实验性,默认关闭;**只发送你粘贴的文字**,不碰你的文件、不进终端。它与 AI 建议共用完整请求预览、单独发送、取消和严格响应解析边界。 --- +## v2.3.1 新功能 + +- 精确定价与上下文元数据现已覆盖 **GPT-6 Astra**(`gpt-6-astra`,105 万 + token 上下文)以及 **Claude Fable 5.1 / Mythos 5.1** + (`claude-fable-5-1` / `claude-mythos-5-1`,100 万 token 上下文)。 + Fable 5.1 使用其专属的 `$0.25 / 百万 token` 缓存读取价,既有 Fable 5 + 历史数据不变。GPT-6 的 API 等效值采用官方 Standard 短上下文费率;由于 + 本地聚合日志无法判定单次请求是否超过 272K 输入,因此不计入该阈值以上的 + 整个请求附加价。 +- Claude 估算可选用 Anthropic 直连或 AWS Bedrock in-region 按需费率,覆盖当前 + Opus、Sonnet 与 Haiku 系列;切换后端会立即按新费率重算未变化的本地日志。 + Sonnet 5 使用 2026 年 8 月 31 日上线促销结束后的标准费率。 +- 最近 30 天严格定义为配置时区中的今天及此前 29 个自然日;满足「今天 ≤ 最近 30 天 ≤ 全部时间」,重复刷新/重建不累加,所有分组可核对,月份从旧到新显示。Claude 的工作流摘要使用同一滚动范围,并按配置时区中的开始日期归入周期。切换图表指标或渲染下钻标签时,日/月用量键不会再受宿主时区影响而回退一天或一个月;AI 建议和用量优化器的暂停截止日期也统一使用配置时区与界面语言。 +- 兼容当前和旧版结构化 reasoning effort,不根据模型名猜测;非零 `unknown` 会解释原因,零值不会渲染。 +- 有界匿名额度观测可保留不规则、连续乃至同日重置。每个同窗有效已用比例都参与总额度和未用耐用度估算(包括当前周期);近似或未归属证据标为低可信度。即使本地 Codex 额度系列重叠,当前周期仍采用最后一次真实观测给出低可信度混合估算;归属不清的已结束周期保持仅已用值。未用估算不会为负。 +- 「对比」默认展示 Claude + Codex 综合活动热力图,直接复用日聚合、支持任一单供应商,并在 tooltip 中分别显示两侧数据。 +- 预览优先的分享工作台包含确定性本地 SVG、综合分享卡、可复制 Markdown、自定义标题/范围、隐私预览和可调配色。工作台默认开启,可在设置中用一个开关整体隐藏。默认采用 Academic Violet;色阶映射可选分位数(默认)、对数或线性;可选的公开 GitHub 发布需要另行确认精确目标。 +- Codex Token 构成现在会在互不重叠的「未缓存输入 / 缓存输入 / 输出」堆叠上方明确显示 **未缓存用量**(未缓存输入 + 输出);推理仍是输出的子集。 +- Codex 在索引期间也能顺畅滚动:滚动状态改为操作结束后只保存一次,实时索引进度只更新文字,不再重建整页。分模型折叠项的绿色摘要现在与 Claude 一致,显示精确模型的 API 等效价格并附定价覆盖说明;未知模型显示 `—`,推理强度仍以中性色显示未缓存 Token。 +- OpenAI 兼容的优化器请求现在只发送 `reasoning_effort`,不再附带不受支持的顶层 `thinking` 参数,解决 [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94)。 +- Claude/Codex 共用卡片密度、层级、折叠、焦点、ARIA、窄宽度和深浅主题 token,同时保持各供应商指标含义独立。 +- AI 建议与用量优化器共用精确预览和明确发送边界;没有默认/后台 AI 请求,本地证据与反馈保持有界。 + +已审阅的 Release 草稿为 `v2.3.1`;人工发布工作流会从该 tag 写入包版本。 + ## 2.3 Codex Beta - Codex 用量记录只会从 `sessions/**/*.jsonl` 与 `archived_sessions/**/*.jsonl` 中发现;凭据、数据库和未知文件仍明确排除。此外,插件会精确流式读取 `$CODEX_HOME/session_index.jsonl`,仅将 `id` 映射为 `thread_name`,用于真实线程标题。标题中的绝对路径会先脱敏,标题只保留在内存。用量 JSONL 会逐行流式、临时解析,以提取白名单内的用量与结构元数据;提示词、回复、命令和工具参数字段不会被检查或用于分析,也不会被保留或持久化。 - **已处理** = 输入 + 输出;**未缓存用量** = 未缓存输入 + 输出;**缓存输入**仍是输入的子集,reasoning 仍是输出的子集。概览还会按「缓存输入 / 输入」显示输入缓存命中率。Codex 不显示账单成本;首张汇总卡会针对当前范围显示明确标注的 API 等效成本估算,「全部时间」则按同一定价口径展示每周趋势。Claude / Codex / Compare 仍保持各供应商口径独立。 -- Codex 的**今天**指配置时区中的当前自然日。页面会显示精确的小时 API 等效成本,并把 Token 构成作为独立视图;每日与每月主图也默认显示 API 等效成本,Token 构成仍单独保留。只有精确匹配的已知模型才参与计价,未知模型保持未定价,定价覆盖率始终可见。这个兼容 schema 3 的增量小时 sidecar 仅处理已知包含今天用量的 canonical 文件,支持检查点与续传,且不会触发全历史重建。 +- Codex 的**今天**指配置时区中的当前自然日。页面会显示精确的小时 API 等效成本,并把 Token 构成作为独立视图;每日与每月主图也默认显示 API 等效成本,Token 构成仍单独保留。只有精确匹配的已知模型才参与计价,未知模型保持未定价,定价覆盖率始终可见。这个兼容 schema 3 的增量小时 sidecar 保存滚动最近 30 天的稀疏日期 / 小时桶,支持检查点与续传、淘汰第 31 天,并在展开日期时不读取 JSONL。Codex 按月图表和表格按月份从旧到新显示。 - 单次请求 Token 归因优先采用有效的 `last_token_usage` component;其中 `total_tokens` 表示活跃上下文大小,不是该请求的用量。只有完整的 total-plus-last 数字签名能证明同一伪名 rate-limit 来源或紧邻记录发生重放时才去重;缺少 last snapshot 时回退为 cumulative lineage high-water。升级后会自动重建一次索引,期间持续显示已索引小计。 -- Claude 与 Codex 的「全部时间」/「对比」会直接根据本地 Token 日志计算历史已用等价值。最新且有效的官方重置观测只会锚定一组唯一、互不重叠的每周周期,每条用量只计入一个周期;没有可用观测时,仅已用历史才回退到 UTC 周一至周一的自然周。任何重叠但未对齐的未来重置都会视为冲突,即使 series 名称不同,也不能再生成第二个「当前周期」;周期范围与重置时刻会分开表达。Codex 用量按日切片保存:若某个切片跨过官方日内重置,其 Token 仍只计一次,受影响周期会标为「边界近似」,并且只显示已用等价值,不反推总额度或未用额度。该显示规则不改变索引 schema,也不会触发重建。Codex 历史周期一律仅显示已用值;只有最新当前周期在重置无冲突、且已索引用量可可靠归属到单一观测来源时,才允许反推总额度,当前未用值仍不会作为结论。无法归属的多登录用量同样只显示已用值,不会虚构账号拆分。历史统一套用当前官方 API 单价;这是代理估算,不是账单或官方订阅价格。该面板默认开启,可在设置中通过 `showWeeklyEquivalentValue` 关闭。Claude 从此版本开始按本地 profile 记录额度观测。 -- 切换到 Codex 后仍沿用既有的今天 / 本月 / 全部时间 / 会话 / 项目 / 内容 / 设置结构,并按 Codex 语义调整标签。两个供应商复用同一组渲染函数、HTML class、图表、表格、间距和响应式规则;时间序列图保持宽度对齐,密集内容只在各自区域内滚动。Codex 建议使用已索引的 30 天结构化证据。 +- Claude 与 Codex 的「全部时间」/「对比」会直接根据本地 Token 日志计算历史已用等价值。最新且有效的官方重置观测会锚定一组唯一、互不重叠的每周周期,每条用量只计入一个周期;没有可用观测时,仅已用历史才回退到 UTC 周一至周一的自然周。只有真正不同 quota series 且其未来重置重叠、未对齐时才视为冲突;同一 series 的观测仍保持为一个 series,并可按低可信度近似显示,不会再生成第二个「当前周期」。周期范围与重置时刻会分开表达。Codex 的 account-wide `codex` 观测可以同时装饰历史和当前周期;如果重置时间偏离七天网格,就按观测时间映射到对应展示周期。文件来源、重置漂移或日切片跨边界时仍可给出总额度近似,但会降低可信度并标注为近似。文件键不是账号身份,因此同一 home 中符合条件的本地文件会一起参与;即使本地 quota series 重叠,当前周期仍采用最后一次真实观测给出低可信度混合估算;归属不清的已结束周期或没有可用观测的周期保持仅已用值,不会虚构账号拆分。任何内部一致且有观测的周期(包括当前周期)都可以显示总额度和未用耐用度估算;归属或边界不确定时降低可信度,而不是静默显示破折号。Codex 用量按日切片保存,Token 仍只计入一个周期;该显示规则不改变索引 schema,也不会触发重建。历史统一套用当前官方 API 单价;这是代理估算,不是账单、官方余额或官方订阅价格。该面板默认开启,可在设置中通过 `showWeeklyEquivalentValue` 关闭。Claude 从此版本开始按本地 profile 记录额度观测。 +- 切换到 Codex 后仍沿用既有的今天 / 最近 30 天 / 全部时间 / 会话 / 项目 / 内容 / 设置结构,并按 Codex 语义调整标签。两个供应商复用同一组渲染函数、HTML class、图表、表格、间距和响应式规则;时间序列图保持宽度对齐,密集内容只在各自区域内滚动。Codex 建议使用已索引的 30 天结构化证据。 - 根任务使用经过路径脱敏的最新真实线程标题;子任务优先使用自己的真实线程标题,缺失时使用其上报的昵称并显示父级 / 根任务标题;这些信息仍缺失时采用本地化的中性回退名称。项目名称使用 Git 仓库名,非 Git 目录则使用文件夹的末级名称。插件不会虚构无法可靠统计的 Branches 或 Workflows。 - 最近 7 天与 30 天按配置时区中的事件发生日精确切片。迁移或重建未完成时,Codex 的卡片、表格、项目、会话、建议与状态栏都会明确标为**已索引小计**,并排除未经验证的旧版总量。检测到 Codex home 后会立即显示供应商标签;首次建立索引期间在页面内实时显示精确的已索引文件数、百分比与容量进度,「对比」则等到两个供应商都有真实数据后才出现。生成首个原子检查点后,完整的小计仪表盘会在索引继续期间保持可用;进度提示不会替代卡片和表格。所选 Codex home 不区分账号,因此同一目录中多个登录账号留下的日志会合并统计;本地日志没有可靠的账号身份字段,额度卡只能保留**最后观测**,不会相加。 - 每条建议仅在已索引的 30 天结构聚合有证据时展示观测、易读证据和条件式行动;没有证据就不会生成泛化建议。 @@ -104,8 +141,8 @@ AI 建议生成的是一份 **Markdown 文档**,用文字展示比截图更直 实际返回的受限模型名称,例如 `fable 17%`;由 PR #38 ([@wheelbarrel00](https://github.com/wheelbarrel00))最初的 模型专属额度功能演进而来。 -- **AI 建议 2.0**:自备 key:默认 **Anthropic**(`/v1/messages`),也支持任意 OpenAI 兼容端点(`advice.apiFormat`)。引入新信号(运行、缓存命中率、归因、思考占比);可选 `advice.userContext` 会附上"针对本项目的个性化"一节;`advice.promptWindowDays`(默认 30)设定采样窗口。传输层加强了:超时、重试、curl 兜底。*(一个免 key 的"订阅"后端做过原型,但本版未上线 —— Anthropic 封禁用 Claude Code 的 OAuth token 直连 API;若日后放开会再启用。)* -- **用量优化器**(实验性,`advice.optimizer.enabled`,默认关闭):Content 标签页的一张卡,粘贴进粗略需求,返回一条精炼提示词,以**纯文本**形式(可直接粘贴、无 Markdown),并附推荐的 effort / thinking / 模型。三个可选微调项(标出含糊指代 · 压缩长粘贴内容 · 建议风格方向)。**只发送你粘贴的文字**,且首次有一次性同意确认。 +- **AI 建议 2.0 的兼容基础**:继续支持自备 key 的 Anthropic(`/v1/messages`)与 OpenAI 兼容端点(`advice.apiFormat`)、超时、重试和 curl 兜底;v2.3.1 将旧入口收敛到统一的本地证据、完整请求预览、明确发送和反馈边界。订阅凭据从不用于模型请求。 +- **用量优化器**(实验性,`advice.optimizer.enabled`,默认关闭):Content 标签页的一张卡,粘贴进粗略需求,返回一条精炼提示词,以**纯文本**形式(可直接粘贴、无 Markdown),并附推荐的 effort / thinking / 模型。三个可选微调项(标出含糊指代 · 压缩长粘贴内容 · 建议风格方向)。先生成包含所粘贴文字的精确请求预览;只有随后明确点击发送才会访问配置的 BYOK endpoint。 - **上下文窗口指示器**(实验性,默认关闭):在设置里开启后,状态栏显示当前 session 的上下文占用。`~` 表示窗口大小是猜测;代理 / 自定义模型可用 `contextWindowOverride` 手填真实窗口。 ## 2.0 新功能 @@ -113,7 +150,7 @@ AI 建议生成的是一份 **Markdown 文档**,用文字展示比截图更直 - **真实的 5 小时和每周配额** 显示在状态栏:OAuth 会话跟随当前窗口所选的 Claude profile,优先级为显式 `dataDirectory`、首个有效 `CLAUDE_CONFIG_DIR`、最后 `~/.claude`;macOS 钥匙串仅用于默认 profile。借鉴上游 [PR #9](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/pull/9)([@Dobidop](https://github.com/Dobidop))。 - **四个新标签页**:Sessions、Projects、Content、Branches,均可排序。 - **堆叠 token 构成图**,含 Y 轴和参考线。 -- **AI 建议命令**(默认 DeepSeek V4 Pro,`reasoning_effort=max`),未配置 key 时提供 demo 演示。 +- **AI 建议命令**现在转到统一的本地证据界面;没有自备 key 时请求保持未发送,不再打开另一套 demo 路径。 - **多厂商定价**:Opus 4.x、Sonnet 4.x、Haiku 4.5 对照 Anthropic 官方定价;OpenAI、Gemini、DeepSeek、Kimi、GLM、Qwen 等代理场景的参考价,含家族感知回退。`Refresh Token Pricing` 可拉取 LiteLLM 即时价格。 - **自定义时区** 用于日期显示(`claudeCodeUsage.timezone`)。 - **浅色主题标签可读性** 修复。 @@ -154,7 +191,7 @@ ext install GrowthJack.claude-code-usage |---|---|---| | `language` | `"auto"` | 界面语言:`auto` / `en` / `de-DE` / `zh-TW` / `zh-CN` / `ja` / `ko` / `pt-BR` / `id`。 | | `dataDirectory` | `""` | 自定义 Claude 数据目录;留空 = 自动检测。 | -| `advice.apiKey` | `""` | AI 建议 + 用量优化器的 API key(留空则 AI 建议会打开 demo)。 | +| `advice.apiKey` | `""` | AI 建议 + 用量优化器的自备 API key;留空时不能发送请求。 | 其余全部 —— 刷新间隔、状态栏各项、数字 / 日期格式、项目分组、内容分析,以及所有 AI 建议 / 优化器选项 —— 都在仪表板的 ⚙ 设置标签页里。升级不丢配置:首次启动会做一次性迁移,把你 `settings.json` 里已有的值搬过来。 @@ -180,9 +217,27 @@ ext install GrowthJack.claude-code-usage ## 隐私 +完整数据清单、保留期、迁移、清除和远程边界见 +[本地数据与隐私](LOCAL-DATA.zh-CN.md)([English](LOCAL-DATA.md))。 + +| 数据 | 本地保留 | 远程行为 | +|---|---|---| +| 源日志 | 供应商拥有、只读;不整份复制 | 默认无 | +| Codex 索引 | 有界匿名数值/结构聚合 | 无 | +| 额度历史 | 有界匿名窗口观测,不含原始账号 ID | 启用时仅 Claude 查询额度;Codex 证据留在本地 | +| UI/分享状态 | 筛选及可选标题/范围/GitHub 目标字符串 | 仅精确确认后发布 | +| 建议状态/密钥 | 有界聚合证据;密钥仅在 SecretStorage | 另行点击发送后才传输精确预览过的请求 | + - 所有 token / 成本 / session 分析都在**本地**进行,只读取你的 `~/.claude/projects/**/*.jsonl` 文件。 - 配额指示器用 Claude Code 现有的 OAuth token 调用 **`api.anthropic.com/api/oauth/usage`**,不发送任何额外凭证。 -- **AI 建议**和**用量优化器**是仅有的会调用模型的功能 —— 且只在**你**主动触发时。AI 建议发送的是你的用量汇总加上一份近期提示词样本;优化器**只发送你粘贴进去的文字**(不碰你的文件、不进终端),且首次有一次性同意确认。两者都发往 `advice.apiUrl` 指定的端点,用你自己的 `advice.apiKey`(默认 Anthropic `/v1/messages`,也支持任意 OpenAI 兼容端点)。**自备 key**;插件本身不附带任何密钥。 +- **AI 建议**和**用量优化器**是仅有的会调用模型的功能,而且只在你查看完整请求后再次主动点击「发送」时调用。AI 建议默认只发送聚合证据;提示样本与用户上下文需要独立同意,并完整出现在预览中。优化器只包含你粘贴的文字。两者仅使用 `advice.apiUrl` 与自备 `advice.apiKey`;密钥只进入请求头,插件不使用订阅凭据,也没有后台请求。 + +### 已知限制 + +- 从未出现在官方或本地结构化证据中的重置无法重建;只有日粒度时可信度会下降。 +- 一个 Codex home 可能包含多个登录;当前周期会用最后一次真实观测给出低可信度混合估算,归属不清的已结束周期保持仅已用值,不虚构账号拆分。 +- API 等效价值受当前公开单价与可见定价覆盖率影响,不是账单或订阅价格。 +- 源日志保留期由 Claude Code/Codex 控制;明确的清除控制才是移除插件派生状态的可靠方式。 --- @@ -192,6 +247,11 @@ ext install GrowthJack.claude-code-usage - 确认 Claude Code 已安装并至少使用过一次。 - 检查 `dataDirectory` 设置;自动检测会查 `~/.claude/projects` 和 `~/.config/claude/projects`。 +**一次性 Claude CLI 调用没有计入** +- 使用 `--no-session-persistence` 的调用可能只留下提示历史,不会写入项目转录, + 也没有 token `usage` 字段。插件不会根据提示历史虚构 token 或成本。希望后续 + 审计调用计入时,请不要使用该参数;过去未持久化的 token 用量无法在本地重建。 + **配额行显示 `5h:--% wk:--%`** - Claude Code 的 OAuth token 缺失或过期。请登录一次当前 Claude profile。凭证按显式 `dataDirectory`、首个有效 `CLAUDE_CONFIG_DIR`、最后 `~/.claude` 的顺序选择;全局 macOS 钥匙串条目不会替代已选中的自定义 profile。 @@ -201,8 +261,8 @@ ext install GrowthJack.claude-code-usage **`Get AI Usage Advice` 返回 404** - DeepSeek 当前端点**不**使用 `/v1` 前缀。请用 `https://api.deepseek.com/chat/completions`。扩展会自动剥除多余的 `/v1`。 -**`Get AI Usage Advice` 显示 demo 而非真实建议** -- AI 建议需要 key。若 `claudeCodeUsage.advice.apiKey` 为空,命令会打开一份手写 demo(文件名带 `…-DEMO-…`,顶部有醒目横幅)而不调用任何 API。在设置中填入 key 即可获得真实建议。 +**`Get AI Usage Advice` 无法发送** +- AI 个性化需要自备 key。若 `claudeCodeUsage.advice.apiKey` 为空,仍可查看本地证据,但发送按钮不可用且不会调用 API;在设置中填入 key 后,先核对完整请求预览,再单独点击发送。 **大历史下 CPU 占用高或刷新缓慢(包括 Linux)** - V2.2.1 移除了 active 状态下隐藏的 8 秒轮询覆盖,并限制首时间戳扫描。 diff --git a/README-zh-TW.md b/README-zh-TW.md index 222d1979..733caff0 100644 --- a/README-zh-TW.md +++ b/README-zh-TW.md @@ -10,7 +10,7 @@ > > **它不是什麼**:帳單工具。顯示金額均為估算值,實際費用請以官方帳單為準。 -> 截圖取自英文介面。完整功能說明請見[主 README](README.md)。 +> 截圖包含英文與簡體中文介面。完整功能說明請見[主 README](README.md)。 ## 截圖 @@ -26,24 +26,65 @@ ![儀表板](images/v2-dashboard-en.png) +### v2.3.1 Codex 與比較 + +![Claude 今日,簡體中文深色主題](images/v2.3.1/claude-today-zh-CN-dark.png) + +![Codex 概覽,簡體中文深色主題](images/v2.3.1/codex-overview-zh-CN-dark.png) + +![Codex 每週額度估算,英文深色主題](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +![Claude 與 Codex 綜合熱力圖,英文淺色主題](images/v2.3.1/compare-heatmap-en-light.png) + +以上四張 v2.3.1 影像使用正式儀表板渲染器、合成資料與 VS Code Light+/Dark+ 主題變數產生,不是個人用量或帳單證據;原生 VSIX 安裝另行驗證。 + +- Codex 狀態列分別顯示**今日已用 token**和**剩餘額度**:已用 36% 時顯示 `wk 64%`。提示卡保留使用進度條、重置時間與換行說明;額度是本地最後觀測,不是即時餘額。 +- 週期明細預設收合,分享設定位於預覽下方。分享工作台預設開啟、可關閉;色階可選分位數、對數或線性。 +- CLI 呼叫須留下帶 usage 的持久工作階段日誌才能計入。未保存的呼叫無法回填;今日與最近 30 天使用設定時區。 + ## 功能特色 - **狀態列** — 今日成本、當前 session 成本,以及真實的 5 小時 / 每週配額(`5h:N% wk:N%`),透過 Claude Code 自身的 OAuth 工作階段讀取,無需設定。 -- **儀表板分頁** — 今日 / 本月 / 全部時間,外加 **Sessions / Projects / Content / Branches**,皆可排序。 +- **儀表板分頁** — 今日 / 最近 30 天 / 全部時間,外加 **Sessions / Projects / Content / Branches**,皆可排序。 - **堆疊式成本構成圖**,含 Y 軸與參考線 —— 一眼看出每日 / 每月的成本中,輸入、輸出、快取寫入、快取讀取各佔多少。 - **Content 分頁** — 估算哪些內容消耗你的 token(你的提示 vs 工具結果 vs 助理輸出 / 思考)。 -- **AI 建議**(選用)— 將用量摘要加上你近期提示的樣本送往 OpenAI 相容 API(預設 DeepSeek V4 Pro),給出具體改寫建議。需自備 key,或先預覽靜態示範。 +- **AI 建議**(選用)— 先呈現本機證據與可解釋行動。可選的自備金鑰個人化預設只含聚合資料;提示樣本需要另行同意。完整請求會先精確預覽,再由你另外按下「傳送」;有用 / 無用 / 已套用回饋只留在本機。單一建議可暫停有限期間,期間會從摘要移除,期滿或手動恢復後再顯示。 + 撤回建議的資料授權會立即使預覽失效並取消進行中的建議請求;已傳出的位元組無法收回。 - **多廠商定價** — Opus 4.x / Sonnet 4.x / Haiku 4.5 對照 Anthropic 官方定價;OpenAI / Gemini / DeepSeek / Kimi / GLM / Qwen 參考價,含家族感知回退。`Refresh Token Pricing` 可拉取 LiteLLM 即時價格。 - **個人化** — 語言、時區、小數位數、精簡數字、專案分組、儀表板自動刷新開關。 +## v2.3.1 新功能 + +- 精確定價與上下文中繼資料現已涵蓋 **GPT-6 Astra**(`gpt-6-astra`,105 萬 + token 上下文)以及 **Claude Fable 5.1 / Mythos 5.1** + (`claude-fable-5-1` / `claude-mythos-5-1`,100 萬 token 上下文)。 + Fable 5.1 採用專屬的 `$0.25 / 百萬 token` 快取讀取價,既有 Fable 5 + 歷史資料不變。GPT-6 的 API 等效值採用官方 Standard 短上下文費率;由於 + 本機彙總日誌無法判定單次請求是否超過 272K 輸入,因此不計入該門檻以上的 + 整個請求附加價。 +- Claude 估算可選用 Anthropic 直連或 AWS Bedrock in-region 隨選費率,涵蓋目前 + Opus、Sonnet 與 Haiku 系列;切換後端會立即按新費率重算未變更的本機日誌。 + Sonnet 5 使用 2026 年 8 月 31 日上市優惠結束後的標準費率。 +- 最近 30 天是設定時區中的今天與前 29 個日期;總計可核對、重複重新整理穩定,月份由舊到新。Claude 的工作流程摘要使用同一滾動範圍,並依設定時區中的開始日期歸入週期。切換圖表指標或呈現下鑽標籤時,日/月用量鍵不會再受宿主時區影響而倒退一天或一個月;AI 建議與用量最佳化器的暫停截止日期也統一使用設定時區與介面語言。 +- 結構化 reasoning effort 不依模型名稱猜測;非零 `unknown` 會解釋,零值不顯示。 +- 有界匿名額度觀測保留不規則及同日重設;有效同窗比例可估算總額度與未用耐用度(包括目前週期)。近似或未歸屬證據標為低可信度。即使本機 Codex 額度系列重疊,目前週期仍採用最後一次真實觀測提供低可信度混合估算;歸屬不清的已結束週期維持僅已用值。 +- 「比較」預設顯示 Claude + Codex 綜合活動熱力圖,沿用日聚合,也支援單一供應商。 +- 預覽優先的分享工作台可匯出確定性本機 SVG、分享卡與 Markdown,並自訂標題/範圍、預覽隱私及調整配色。工作台預設開啟,可在設定用一個開關整體隱藏。預設 Academic Violet;色階映射可選分位數(預設)、對數或線性;GitHub 公開發佈另行確認精確目標。 +- Codex Token 構成現在會在互不重疊的「未快取輸入 / 快取輸入 / 輸出」堆疊上方明確顯示 **未快取用量**(未快取輸入 + 輸出);推理仍是輸出的子集。 +- Codex 在索引期間也能順暢捲動:捲動狀態改為操作結束後只儲存一次,即時索引進度只更新文字,不再重建整頁。各模型折疊項的綠色摘要現在與 Claude 一致,顯示精確模型的 API 等效價格並附定價涵蓋說明;未知模型顯示 `—`,推理強度仍以中性色顯示未快取 Token。 +- OpenAI 相容的最佳化器請求現在只傳送 `reasoning_effort`,不再附帶不受支援的頂層 `thinking` 參數,解決 [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94)。 +- Claude/Codex 共用密度、層級、焦點、ARIA、窄幅與深淺色設計 token,但不混淆指標語義。 + +已審閱的 Release 草稿為 `v2.3.1`;人工發佈工作流程會從該 tag 寫入套件版本。 + ## v2.3 Codex Beta - Codex 用量記錄只會從 `sessions/**/*.jsonl` 與 `archived_sessions/**/*.jsonl` 中發現;憑證、資料庫與未知檔案仍明確排除。此外,擴充功能會精確串流讀取 `$CODEX_HOME/session_index.jsonl`,僅將 `id` 對應到 `thread_name`,用於真實執行緒標題。標題中的絕對路徑會先去識別化,標題只保留在記憶體。用量 JSONL 會逐行串流並暫時解析,以擷取白名單內的用量與結構中繼資料;提示、回覆、命令和工具參數欄位不會被檢查或用於分析,也不會被保留或持久化。 - **已處理** = 輸入 + 輸出;**未快取用量** = 未快取輸入 + 輸出;**快取輸入**仍是輸入的子集,reasoning 仍是輸出的子集。概覽也會依「快取輸入 / 輸入」顯示輸入快取命中率。Codex 不顯示帳單成本;首張摘要卡會針對目前範圍顯示明確標示的 API 等效成本估算,「全部時間」則依同一定價口徑顯示每週趨勢。Claude / Codex / Compare 仍維持各供應商口徑獨立。 -- Codex 的**今天**指設定時區中的目前自然日。頁面會顯示精確的每小時 API 等效成本,並將 Token 構成保留為獨立檢視;每日與每月主圖也預設顯示 API 等效成本,Token 構成仍分開呈現。只有精確符合的已知模型才參與計價,未知模型維持未定價,定價涵蓋率始終可見。這個相容 schema 3 的增量小時 sidecar 只處理已知包含今天用量的 canonical 檔案,支援檢查點與續傳,且不會觸發完整歷史重建。 +- Codex 的**今天**指設定時區中的目前自然日。頁面會顯示精確的每小時 API 等效成本,並將 Token 構成保留為獨立檢視;每日與每月主圖也預設顯示 API 等效成本,Token 構成仍分開呈現。只有精確符合的已知模型才參與計價,未知模型維持未定價,定價涵蓋率始終可見。這個相容 schema 3 的增量小時 sidecar 會保留最近 30 天的稀疏日期 / 小時分桶,支援檢查點與續傳、淘汰第 31 天,並在展開日期時不讀取 JSONL。Codex 按月圖表與表格會按月份由舊到新顯示。 - 單次請求 Token 歸因優先採用有效的 `last_token_usage` component;其中 `total_tokens` 表示目前上下文大小,不是該次請求的用量。只有完整的 total-plus-last 數字簽名能證明同一假名化 rate-limit 來源或相鄰記錄發生重播時才去重;缺少 last snapshot 時回退為 cumulative lineage high-water。升級後會自動重建一次索引,期間持續顯示已索引小計。 -- Claude 與 Codex 的「全部時間」/「比較」會直接依本機 Token 日誌計算歷史已用等價值。最新且有效的官方重設觀測只會錨定一組唯一、互不重疊的每週週期,每筆用量只計入一個週期;沒有可用觀測時,僅已用歷史才回退到 UTC 週一至週一的自然週。任何重疊但未對齊的未來重設都會視為衝突,即使 series 名稱不同,也不能再建立第二個「目前週期」;週期範圍與重設時刻會分開呈現。Codex 用量按日切片保存:若某個切片跨過官方日內重設,其 Token 仍只計一次,受影響週期會標為「邊界近似」,並且只顯示已用等價值,不反推總額度或未用額度。此顯示規則不改變索引 schema,也不會觸發重建。Codex 歷史週期一律只顯示已用值;只有最新目前週期在重設無衝突,且已索引用量可可靠歸屬到單一觀測來源時,才允許反推總額度,目前未用值仍不作為結論。無法歸屬的多登入用量同樣只顯示已用值,不會虛構帳號拆分。歷史統一套用目前官方 API 單價;這是代理估算,不是帳單或官方訂閱價格。此面板預設開啟,可在設定中透過 `showWeeklyEquivalentValue` 關閉。Claude 從此版本開始依本機 profile 記錄額度觀測。 -- 切換到 Codex 後仍沿用既有的今天 / 本月 / 全部時間 / 工作階段 / 專案 / 內容 / 設定結構,並依 Codex 語義調整標籤。兩個供應商共用同一組 render function、HTML class、圖表、表格、間距與響應式規則;時間序列圖維持寬度對齊,密集內容只在各自區域內捲動。Codex 建議使用已索引的 30 天結構化證據。 +- Claude 與 Codex 的「全部時間」/「比較」會直接依本機 Token 日誌計算歷史已用等價值。最新且有效的官方重設觀測會錨定一組唯一、互不重疊的每週週期,每筆用量只計入一個週期;沒有可用觀測時,僅已用歷史才回退到 UTC 週一至週一的自然週。只有真正不同的 quota series 且其未來重設重疊、未對齊時才視為衝突;同一 series 的觀測仍維持為一個 series,並可按低可信度近似顯示,不會再建立第二個「目前週期」。週期範圍與重設時刻會分開呈現。Codex 的 account-wide `codex` 觀測可同時裝飾歷史與目前週期;若重設時間偏離七天網格,就依觀測時間映射到對應展示週期。檔案來源、重設漂移或日切片跨邊界時仍可給出總額度近似,但會降低可信度並標示為近似。檔案鍵不是帳號身分,因此同一個 home 中符合條件的本機檔案會一起參與;即使本機 quota series 重疊,目前週期仍採用最後一次真實觀測提供低可信度混合估算;歸屬不清的已結束週期或沒有可用觀測的週期維持僅已用值,不會虛構帳號拆分。任何內部一致且有觀測的週期(包括目前週期)都可顯示總額度與未用耐用度估算;歸屬或邊界不確定時降低可信度,而不是靜默顯示破折號。Codex 用量按日切片保存,Token 仍只計入一個週期;此顯示規則不改變索引 schema,也不會觸發重建。歷史統一套用目前官方 API 單價;這是代理估算,不是帳單、官方餘額或官方訂閱價格。此面板預設開啟,可在設定中透過 `showWeeklyEquivalentValue` 關閉。Claude 從此版本開始依本機 profile 記錄額度觀測。 +- 切換到 Codex 後仍沿用既有的今天 / 最近 30 天 / 全部時間 / 工作階段 / 專案 / 內容 / 設定結構,並依 Codex 語義調整標籤。兩個供應商共用同一組 render function、HTML class、圖表、表格、間距與響應式規則;時間序列圖維持寬度對齊,密集內容只在各自區域內捲動。Codex 建議使用已索引的 30 天結構化證據。 - 根任務使用經過路徑去識別化的最新真實執行緒標題;子任務優先使用自己的真實執行緒標題,缺少時使用其回報的暱稱並顯示父級 / 根任務標題;這些資訊仍缺少時採用本地化的中性回退名稱。專案名稱使用 Git 儲存庫名稱,非 Git 目錄則使用資料夾的末級名稱。擴充功能不會虛構無法可靠統計的 Branches 或 Workflows。 - 最近 7 天與 30 天依設定時區中的事件發生日精確切片。遷移或重建未完成時,Codex 的卡片、表格、專案、工作階段、建議與狀態列都會明確標為**已索引小計**,並排除未驗證的舊版總量。偵測到 Codex home 後會立即顯示供應商分頁;首次建立索引期間會在頁面內即時顯示精確的已索引檔案數、百分比與容量進度,「比較」則等到兩個供應商都有真實資料後才出現。產生第一個原子檢查點後,完整的小計儀表盤會在索引繼續期間保持可用;進度提示不會取代卡片和表格。所選 Codex home 不區分帳戶,因此同一目錄中多個登入帳戶留下的記錄會合併統計;本機記錄沒有可靠的帳戶身分欄位,額度卡只能保留**最後觀測**,不會相加。 - 每則建議只在已索引的 30 天結構聚合有證據時顯示觀測、易讀證據和條件式行動;沒有證據就不會產生泛化建議。 @@ -69,15 +110,36 @@ ext install GrowthJack.claude-code-usage - `usageLimitTracking` — 顯示真實的 5 小時 / 每週配額指示器。 - `showCost` / `showContext` — 切換狀態列的成本項目與上下文視窗佔用指示器(類似 `/context`)。 - 上述狀態列項目皆可個別隱藏:將 `usageLimitTracking` / `showCost` / `showContext` 設為 `false` 即可只隱藏該項。 -- `advice.apiKey` — AI 建議功能的 API key(OpenAI 相容)。 +- `advice.apiKey` — AI 建議與 Usage Optimizer 共用的自備 API key(Anthropic 或 OpenAI 相容 endpoint)。 - `pauseDashboardRefresh` — 暫停儀表板自動刷新(也可在儀表板標題列切換)。 完整設定表請見[主 README](README.md#configuration)。 +## 本機資料、隱私與限制 + +完整清單、保留期、遷移、清除及遠端邊界見 +[本機資料與隱私](LOCAL-DATA.zh-CN.md)([English](LOCAL-DATA.md))。 + +| 資料 | 本機保留 | 遠端行為 | +|---|---|---| +| 來源日誌 | 供應商擁有、唯讀,不整份複製 | 預設無 | +| Codex 索引 | 有界假名化數值/結構聚合 | 無 | +| 額度歷史 | 有界匿名窗口觀測,不含原始帳號 ID | 啟用時僅 Claude 查詢額度;Codex 證據留在本機 | +| UI/分享 | 篩選與可選標題/範圍/GitHub 目的字串 | 僅在精確確認後發佈 | +| 建議/金鑰 | 有界聚合證據;金鑰僅在 SecretStorage | 另行傳送精確預覽的請求 | + +未出現在結構化證據中的重設無法重建;多登入歸屬不清時,目前週期會用最後一次真實觀測提供低可信度混合估算,已結束週期維持僅已用值。 +API 等效價值不是帳單。來源日誌保留由 Claude Code/Codex 控制,明確清除才是移除擴充功能派生狀態的可靠方式。 + ## 疑難排解 **「無 Claude Code 資料」** — 確認 Claude Code 已安裝並至少使用過一次;檢查 `dataDirectory` 設定(自動偵測會查 `~/.claude/projects`)。 +**一次性 Claude CLI 呼叫沒有計入** — 使用 `--no-session-persistence` 的呼叫 +可能只留下提示歷史,不會寫入專案轉錄,也沒有 token `usage` 欄位。本擴充功能 +不會根據提示歷史虛構 token 或成本。希望之後的審計呼叫計入時,請不要使用該參數; +過去未持久化的 token 用量無法在本機重建。 + **配額顯示 `5h:--% wk:--%`** — 請登入目前的 Claude profile。憑證依序跟隨 明確設定的 `dataDirectory`、第一個有效的 `CLAUDE_CONFIG_DIR`、最後 `~/.claude`;全域 macOS 鑰匙圈項目只用於預設 profile。 diff --git a/README.md b/README.md index b8c0594c..5a888726 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,45 @@ the same data. ## Screenshots -### Status bar +### v2.3.1 Claude, Codex and Compare + +The four v2.3.1 images below are reproducible captures of the production dashboard +renderer with synthetic fixtures and VS Code Light+/Dark+ theme variables, not +personal usage or billing evidence. Native VSIX installation is verified separately. + +![Claude Today in Simplified Chinese, dark theme](images/v2.3.1/claude-today-zh-CN-dark.png) + +*Today and Last 30 days share the configured calendar timezone. CLI usage is +counted only when normal persistent sessions leave usage-bearing local logs; +calls made without session persistence cannot be reconstructed.* + +![Codex overview in Simplified Chinese, dark theme](images/v2.3.1/codex-overview-zh-CN-dark.png) + +*The corrected Codex overview uses one configured-timezone calendar model for +Today, Last 30 days, months, models, effort, and all-time totals.* + +![Codex weekly allowance estimate in English, dark theme](images/v2.3.1/codex-weekly-estimate-en-dark.png) + +*Observed quota windows retain reset evidence locally. A valid used fraction can +produce labelled total and unused subscription-durability estimates, including +for the current window. Approximate evidence remains visible with low confidence. +Period details start collapsed; expand them to inspect the numeric evidence.* + +![Combined Claude and Codex heatmap in English, light theme](images/v2.3.1/compare-heatmap-en-light.png) + +*Compare combines provider daily activity without double-counting Codex cached +input or reasoning. Its preview-first share studio offers an Academic Violet +default, curated/custom colors, deterministic local SVG, and privacy-safe +Markdown. It is enabled by default and can be hidden with the single sharing +workspace setting. Card settings sit below the preview; intensity can use quantile, +logarithmic, or linear scaling. The metric is activity volume, not productivity or billing.* + +### Claude status bar + +Codex uses a compact **Today token usage** item and a separate **remaining quota** +item: observed 36% weekly utilisation displays `wk 64%`. The hover card retains +utilisation progress bars, reset times, and wrapped explanations. Local Codex +quota is last-observed evidence, not a live account balance. ![Status bar](images/v2-status-bar-en.png) @@ -73,14 +111,24 @@ tool results (by tool) vs. assistant output / thinking. This is the lever for optimising your usage. Scoped to the last 30 days (`advice.promptWindowDays`).* -### AI advice — a coaching report from your real usage +### AI advice — evidence first, sending optional + +v2.3.1 keeps one readable path from a local observation to its +evidence, recommendation, action, feedback, and guarded result. It is off by +default. Local evidence appears before any model is involved; **Helpful**, **Not +helpful**, and **Applied** stay on this device. Once enough reliable, similar +before/after tasks exist, the card reports the frozen comparison result; +otherwise it says that the evidence is insufficient. + +Each recommendation can be snoozed for a bounded period; it leaves the default +summary and returns after expiry or when you choose to show it again. -AI advice writes you a **Markdown document**, so it reads better as text than as -a screenshot. Set a key (`advice.apiKey`), click **Get AI advice** (the ✨ button -or the card on the Content tab), pick a scope (all projects, or one), and it sends -your usage aggregates + a sample of *your own* prompts to your model and opens a -prioritised report. Bring your own key — Anthropic (`/v1/messages`) by default, or -any OpenAI-compatible endpoint. +AI personalisation is a separate choice. Aggregate-only is the default and +prompt samples remain off until separately allowed. The extension prepares the +complete request once and shows its exact JSON, byte count, and SHA-256. Preview +sends nothing; **Send this exact request** is a second explicit action, using the +same canonical bytes and your own configured key/endpoint. Claude Code OAuth +credentials are never used as a generative backend. A flavour of what it returns (illustrative): @@ -101,11 +149,94 @@ Paste a rough, half-formed request; get back one clean, **paste-ready** prompt (plain text, no Markdown) plus a recommended reasoning effort / thinking / model shown as chips. Three optional toggles refine it (flag vague references · condense long pastes · suggest a style direction). Experimental, off by default; **only the -text you paste is sent** — never your files or the terminal — behind a one-time -consent prompt. +text you paste is included** — never your files or the terminal. It now uses the +same full-request preview and separate explicit Send action as AI advice. --- +## What's new in v2.3.1 + +- **GPT-6 Astra and Fable 5.1 support** — exact pricing and context metadata now + cover `gpt-6-astra` (1.05M context) and `claude-fable-5-1` / + `claude-mythos-5-1` (1M context). Fable 5.1 uses its model-specific + `$0.25 / MTok` cache-read rate without changing historical Fable 5 data. + GPT-6 API-equivalent values use official Standard short-context rates; the + request-wide surcharge above 272K input is excluded because aggregate local + logs cannot establish that per-request threshold. +- **Optional AWS Bedrock pricing** — Claude estimates can use direct Anthropic + or AWS Bedrock in-region on-demand rates for current Opus, Sonnet, and Haiku + families. Switching the backend reprices unchanged logs immediately; Sonnet + 5 uses the standard rate after its launch promotion ended on 31 August 2026. +- **Correct, stable date ranges** — Last 30 days means today plus the preceding + 29 calendar dates in the configured timezone. Today ≤ Last 30 days ≤ All time, + provider totals reconcile, repeated refresh/reindex is idempotent, and Codex + monthly charts/tables run oldest-first. Claude's Workflows summary uses that + same rolling range and assigns each run by its configured-zone start date. + Chart metric switches and drill-down labels render daily/monthly usage keys + without host-timezone rollback; Advice and Optimizer snooze dates also use + the configured timezone and UI locale. +- **Truthful effort attribution** — legacy and current structured effort fields + normalize without guessing from model names. A non-zero `unknown` bucket is + explained; a zero bucket is not rendered. +- **Reset-aware weekly estimates** — bounded, atomically written quota + observations preserve reset-time/window changes and significant usage drops, + including consecutive and same-day resets. Every valid same-window used + fraction contributes an observed full-allowance estimate. Coherent current and + completed windows show total and unused durability estimates; approximate or + unattributed evidence is labelled low confidence. If local Codex series + overlap, the current window uses the latest real observation for a labelled + low-confidence blended estimate; ambiguous completed windows remain + usage-only. Unused value never goes negative. +- **Combined heatmap in Compare** — Claude and Codex daily processed volume is + merged with provider components visible in every tooltip. It works with both + providers or either provider alone and reuses existing aggregates instead of + scanning logs again. +- **Private share loop** — use the preview-first studio to customize title, + 30/90-day or yearly range, and heatmap colors. Academic Violet is the default; + choose quantile (default), logarithmic, or linear intensity mapping to suit + the activity distribution. Inspect the privacy preview, export deterministic + SVG, and copy a Markdown snippet. Optional public-GitHub publication is a + separate exact-destination confirmation; local export needs no account + permission. +- **Explicit Codex uncached composition** — Token composition shows uncached + usage (uncached input + output) above the non-overlapping uncached-input / + cached-input / output stack; reasoning remains a subset of output. +- **Smooth live Codex dashboard** — scroll state is saved once after a gesture, + and active index progress updates its text in place instead of rebuilding the + page. Per-model disclosure headlines now use Claude's green-money convention: + exact-model API-equivalent price with coverage help; unknown models show `—`, + while effort headlines keep neutral uncached-token values. +- **OpenAI reasoning compatibility** — OpenAI-compatible optimizer requests + send `reasoning_effort` without the unsupported top-level `thinking` + parameter, resolving [#94](https://github.com/ClaudeCodeUsage/ClaudeCodeUsage/issues/94). +- **Aligned dashboard interaction** — shared density, headings, disclosures, + charts, empty states, keyboard focus, ARIA behavior, narrow layout, and + light/dark design tokens keep Claude and Codex consistent without claiming + their metrics are semantically equivalent. +- **One advice loop** — local evidence, explainable recommendations, optional + exact BYOK preview/send, device-local feedback, and versioned comparable-task + results share one boundary. Get AI Advice opens this surface; the Optimizer + reuses its preview/send/cancel/strict-parse behavior instead of forming a + third network path. +- **No automatic AI traffic** — the feature is off by default, aggregate consent + and prompt-personalisation consent are separate, and a request crosses the + network only after the user previews it and clicks Send. + Withdrawing advice consent immediately invalidates previews and cancels active + advice requests; it cannot recall bytes already transmitted. +- **Resumable first-use work** — Codex history and the rolling 30-day hour + migration show why they are running, persist progress/failure/backoff state, + and do not restart equivalent work after completion or on every refresh. +- **Thirty-day hour drill-down** — any populated Codex day in the last 30 days + expands from the existing index with zero JSONL reads on click. Claude and + Codex use the configured timezone and the same `HH:00` labels. +- **Safe rolling totals and resumable indexing** — recent 7/30-day views reject + stale/inflated period projections and use verified daily aggregates until the + zone projection catches up. First-use work persists bounded progress and does + not hot-loop or repeat after completion. + +The reviewed draft is `v2.3.1`; the human-controlled publish workflow stamps +package metadata from that release tag. + ## What's new in 2.3 - **Codex Beta, enabled by default** — usage records are discovered only from @@ -130,8 +261,9 @@ consent prompt. API-equivalent cost while token composition stays separately visible. Only exact known-model prices contribute; unknown models remain unpriced and every row keeps pricing coverage visible. The schema-3-compatible hourly sidecar - processes only canonical files already known to contain today, is checkpointed - and resumable, and does not force a full-history reindex. + keeps sparse buckets for the rolling last 30 days, is checkpointed and + resumable, evicts day 31, and serves date expansion with zero JSONL reads on + click. Codex monthly charts and tables list months oldest-first. - **Request-level token attribution** — valid `last_token_usage` components are preferred, while its `total_tokens` remains an active-context measurement, not request usage. A full numeric total-plus-last signature suppresses only @@ -143,22 +275,31 @@ consent prompt. newest valid official reset observation anchors one sequence of unique, non-overlapping weekly periods, and each usage event belongs to exactly one period; without a usable observation, usage-only rows fall back to - Monday-to-Monday UTC calendar weeks. Any overlapping, non-aligned future reset - is a conflict even if its series name differs; it cannot create a second current - period, and period ranges are shown separately from reset times. Codex usage is + Monday-to-Monday UTC calendar weeks. A genuinely different quota series with + an overlapping, non-aligned future reset is a conflict; same-series observations + remain one series and may be shown as a low-confidence approximation. It cannot + create a second current period, and period ranges are shown separately from reset times. Codex usage is stored in daily slices: when one crosses an official intraday reset, its tokens are still counted once, the affected period is labelled a boundary - approximation, and only used equivalent is shown. This display rule neither - changes the index schema nor triggers a rebuild. Codex historical periods are - always used-value-only. Only the newest current period may infer a total when - the reset is unambiguous and indexed usage can be attributed to one observation - source; current unused value is still withheld. Multi-sign-in usage that cannot - be attributed reliably also remains used-only, without inventing an account - split. Current official API rates are applied consistently across history. This - is a proxy, not a bill or an official subscription price. The panel is enabled - by default and can be hidden in Settings with `showWeeklyEquivalentValue`. + approximation. Codex's account-wide `codex` observations can decorate both + historical and current buckets. If an observed reset drifts from the seven-day + grid, the sample is mapped to the display period containing its observation + time; file-source uncertainty, reset drift, and daily boundary crossings lower + confidence and are labelled as approximate. File keys are not account + identities, so eligible local files in one home are included together. A + current period still uses the latest real observation for a low-confidence + blended estimate when local quota series overlap. Ambiguous completed periods, + or periods without a usable observation, remain usage-only rather than + inventing an account split. Any coherent + observed window—including the current one—can show total and unused durability + estimates; attribution or boundary uncertainty lowers confidence instead of + silently replacing the values with dashes. + This display rule neither changes the index schema nor triggers a rebuild. + Current official API rates are applied consistently across history. This is a + proxy, not a bill or an official subscription price. The panel is enabled by + default and can be hidden in Settings with `showWeeklyEquivalentValue`. - **One dashboard render stack** — switching to Codex keeps the established - Today / Month / All time / Sessions / Projects / Content / Settings structure, + Today / Last 30 days / All time / Sessions / Projects / Content / Settings structure, relabelled where Codex semantics differ. The same render functions, HTML classes, charts, tables, spacing, and responsive rules are used for both providers. Claude and Codex time-series charts stay width-aligned while dense @@ -284,20 +425,19 @@ consent prompt. cap actually named by Anthropic, such as `fable 17%`; migrated from the original model-specific contribution in PR #38 by [@wheelbarrel00](https://github.com/wheelbarrel00). -- **AI advice 2.0** — bring your own key: **Anthropic** (`/v1/messages`) by - default, or any OpenAI-compatible endpoint (`advice.apiFormat`). Fed with the - new signals (runs, cache hit rates, attribution, thinking share); optional - `advice.userContext` adds a "Personalised for this project" section; - `advice.promptWindowDays` (default 30) sets the sampling window. Transport - hardened: timeout, retry, curl fallback. *(A keyless "subscription" backend - was prototyped but isn't shipped — Anthropic blocks calling the API with the - Claude Code OAuth token; it may return if that changes.)* +- **AI advice 2.0** — bring your own key for Anthropic or an OpenAI-compatible + endpoint (`advice.apiFormat`). v2.3.1 places local evidence and an exact full- + request preview before the separate Send action. Aggregate-only is the + default; prompt samples and `advice.userContext` require independent prompt- + personalisation consent and appear verbatim in the preview. The keyless + Claude Code subscription backend is not shipped and is unreachable. - **Usage Optimizer** (experimental, `advice.optimizer.enabled`, default off) — a Content-tab card where you paste a rough request and get back one tightened prompt as **plain text** (paste-ready, no Markdown) plus a recommended effort / thinking / model. Three optional lenses (flag ambiguous references · condense long pastes · suggest a style direction). **Only the text you paste - is sent**, behind a one-time consent prompt. + is included**, and the full provider request must be previewed and explicitly + sent. - **Context-window indicator** (experimental, off by default) — opt in via Settings to show the current session's context fill in the status bar. A "~" marks a guessed window; set `contextWindowOverride` for proxied/custom models. @@ -312,8 +452,9 @@ consent prompt. by [@Dobidop](https://github.com/Dobidop). - **Four new tabs**: Sessions, Projects, Content, Branches — all sortable. - **Token-composition stacked chart** with Y-axis and reference lines. -- **AI advice command** (DeepSeek V4 Pro default, `reasoning_effort=max`) - with a demo-mode fallback when no API key is configured. +- **AI advice command** — now routes to the unified local-evidence surface; a + missing API key leaves the request unsent instead of opening a separate demo + or transport path. - **Multi-vendor pricing**: Opus 4.x, Sonnet 4.x, Haiku 4.5 (verified against Anthropic's public pricing); reference rates for proxied setups (OpenAI, Gemini, DeepSeek, Kimi, GLM, Qwen) with family-aware fallback. @@ -372,7 +513,7 @@ for **`Claude Code Usage`**: | `language` | `"auto"` | UI language: `auto` / `en` / `de-DE` / `zh-TW` / `zh-CN` / `ja` / `ko` / `pt-BR` / `id`. | | `dataDirectory` | `""` | Custom Claude data dir; empty = auto-detect. | | `codex.dataDirectory` | `""` | Custom Codex home; empty = `CODEX_HOME` or `~/.codex`. | -| `advice.apiKey` | `""` | API key for AI advice + the Usage Optimizer (empty = advice opens a demo instead). | +| `advice.apiKey` | `""` | Bring-your-own key for AI advice + the Usage Optimizer; empty means no request can be sent. | Everything else — refresh interval, status-bar items, number/date formatting, project grouping, content analysis, and all the AI advice / Optimizer options — @@ -417,6 +558,17 @@ authoritative. ## Privacy +The complete user-facing inventory, retention rules, clearing behavior, and +remote boundaries are in [Local data and privacy](LOCAL-DATA.md) ([简体中文](LOCAL-DATA.zh-CN.md)). + +| Data | Stored locally | Remote behavior | Clear path | +|---|---|---|---| +| Claude/Codex source logs | Provider-owned and read-only; never copied wholesale | None by default | Managed by the provider tools, not deleted by this extension | +| Codex derived index | Bounded pseudonymous numeric/structural aggregates | None | Rebuild or clear derived index | +| Quota observations | Bounded anonymous window facts; no raw account ID | Claude quota fetch only when enabled; Codex evidence stays local | Clear by provider/account epoch or all | +| UI/share preferences | Tab/filter state plus optional title/range and GitHub destination strings | Publish only after exact explicit confirmation | Reset UI or sharing preferences independently | +| Advice data/key | Bounded aggregate evidence; key only in SecretStorage | Exact previewed request only after separate Send | Clear advice data and key independently | + - All **Claude** token / cost / session analysis runs locally by reading your `~/.claude/projects/**/*.jsonl` files. - Codex usage records are discovered only from `sessions/**/*.jsonl` and @@ -435,13 +587,25 @@ authoritative. - The quota indicator calls **`api.anthropic.com/api/oauth/usage`** using Claude Code's existing OAuth token. No additional credentials are sent. - **AI advice** and the **Usage Optimizer** are the only features that call a - model — and only when *you* trigger them. AI advice sends an aggregate - summary of your usage plus a sample of your recent prompts; the Optimizer - sends **only the text you paste into it** (never your files or the terminal), - behind a one-time consent prompt. Both send to the endpoint in `advice.apiUrl` - with your own `advice.apiKey` (Anthropic `/v1/messages` by default, or any - OpenAI-compatible endpoint). **Bring your own key**; nothing is shipped with - the extension. + model — and only after *you* preview and explicitly send a prepared request. + Advice defaults to allowlisted aggregates; prompt samples and optional user + context require separate consent. The Optimizer includes **only the text you + paste into it** (never your files or terminal). Both use the exact previewed + bytes, the endpoint in `advice.apiUrl`, and your own `advice.apiKey`. + **Bring your own key**; no key or generative OAuth credential is shipped. + +### Known limits + +- A reset absent from an official response or local structured event cannot be + reconstructed; day-only evidence lowers confidence. +- One Codex home may contain several sign-ins. The current period may therefore + show a low-confidence blended estimate from the latest real observation; + ambiguous completed periods remain used-only rather than inventing an account split. +- API-equivalent values depend on current known API prices and visible pricing + coverage. They are not bills or subscription prices. +- Source-log retention belongs to Claude Code and Codex. Uninstall may leave + host-managed extension storage behind, so the explicit clear controls are the + reliable deletion route. --- @@ -452,6 +616,13 @@ authoritative. - Check the `dataDirectory` setting; auto-detection looks at `~/.claude/projects` and `~/.config/claude/projects`. +**One-shot Claude CLI activity is missing** +- Calls made with `--no-session-persistence` can leave a prompt-history entry + but no project transcript and no token `usage` fields. The extension does not + invent token or cost totals from prompt history. Run future audited calls + without that flag if they should appear; past unpersisted token usage cannot + be reconstructed locally. + **Quota row shows `5h:--% wk:--%`** - Claude Code's OAuth token is missing or expired. Log in to the active Claude profile once. Credentials follow explicit `dataDirectory`, then the first @@ -463,10 +634,10 @@ authoritative. `https://api.deepseek.com/chat/completions`. The extension auto-strips `/v1` if present. -**`Get AI Usage Advice` shows demo instead of real advice** -- AI advice needs a key. With no key under `claudeCodeUsage.advice.apiKey`, the - command opens a hand-written demo (filename-marked `…-DEMO-…`, with a prominent - banner) instead of calling any API. Add a key in Settings to get real advice. +**`Send this exact request` is unavailable** +- Enable the default-off advice-effectiveness setting, allow aggregate data, + and configure your own `claudeCodeUsage.advice.apiKey`. Previewing is always + local; without a key the request remains unsent. **High CPU or sluggish refresh on a large history (Linux included)** - V2.2.1 removes the hidden 8-second active polling override and bounds the diff --git a/docs/releases/2026-09-01-v2.3.1-goal-ledger.en.md b/docs/releases/2026-09-01-v2.3.1-goal-ledger.en.md new file mode 100644 index 00000000..678e2a08 --- /dev/null +++ b/docs/releases/2026-09-01-v2.3.1-goal-ledger.en.md @@ -0,0 +1,341 @@ +# Claude Code Usage v2.3.1 Goal Ledger + +This tracked ledger records G0–G6 stage status, reproducible acceptance evidence, read-only Claude CLI reviews, and residual risk. It never stores accounts, credentials, real logs, prompts, thread titles, or local paths. + +## Execution boundary + +- Branch: `codex/v2.3.1-goal-g0-g6` +- Baseline: `7fd03f3183240940d0a2d1cfe76f60cb80f0a6ae` +- Workspace: isolated worktree; the user's primary checkout and pre-existing edits remain read-only. +- Allowed: local code/document changes, tests, builds, VSIX packaging, stage commits, and the specified read-only Claude CLI checkpoints. +- Forbidden: push, Marketplace publication, remote releases, real GitHub writes, or uploading user logs and identity data. + +## Stage status + +| Stage | Status | Local commit | Verification | Claude review | Residual risk | +|---|---|---|---|---|---| +| G0 baseline and fixtures | Complete | `f0af506` | Node 795 passed / 1 skipped; UI 90 passed; targeted 29 passed | N/A | No blocking risk | +| G1 data contract | Complete | `86d95df` | Focused 17 passed; Node 806 passed / 1 skipped; compile passed | Conditional GO, then revision GO | Blocked legacy workspace plaintext remains until explicit recovery; host SecretStorage backing varies; unified quota store is a G3 deliverable | +| G2 statistics/order/effort | Complete | `49f2041` | Node 815 passed / 1 skipped; UI 90 passed; all focused regressions passed | N/A | Unified observation/account attribution remains a G3 concern | +| G3 quota observations/estimates | Complete | `a04ab04`, `4672079` | Node 841 passed / 1 skipped at exit; installed-candidate regression: quota/weekly 49 passed | GO, then revision GO | Quarantined corrupt/future files remain on disk until the data-clear path or a future cleanup policy removes them | +| G4A visual/interaction/accessibility | Complete | `fca21da` | Node 841 passed / 1 skipped; UI 107 passed; focused G4A 68 passed | N/A | Provider-native metric semantics and card counts intentionally remain different | +| G4B combined heatmap/share | Complete | `1e6bbab`, `5e5bf9f` | Node 861 passed / 1 skipped; UI 112 passed; focused 69 + 5 passed | GO, then revision GO | GitHub `public_repo` remains account-wide for public repositories; local SVG/Markdown requires no scope and is the default safe path | +| G5 README/screenshots | Complete | `e9a149a` | Node 865 passed / 1 skipped; UI 112 passed; three installed-candidate screenshots inspected | GO TO G6 | Final packaging evidence belongs to G6 | +| G6 release candidate | Complete | `b435e06`, `5e6e5cc`, `5af60b4`, `666f04c` | Latest regression candidate: Node 902 passed / 1 skipped; UI 117 passed; VSIX policy, visual QA, and isolated stock-host install passed | Regression first review NO-GO; revision review: **GO** | Hands-on empty-data Settings, legacy plaintext-key upgrade, and Clear All checks remain; broader interaction parity is assigned to the v2.4 roadmap | + +## G0 baseline evidence + +### Environment and tests + +- Node: `v24.19.0` +- npm: `11.17.0` +- `npm ci`: successful. +- `npm run test:node`: 796 tests, 795 passed, 0 failed, 1 skipped. Two loopback `EPERM` failures in the first restricted run were test-sandbox artifacts; both passed when the local test servers were allowed to bind. +- `npm run test:ui`: 90/90 passed. +- Baseline worktree: clean. + +### v2.3.1 minimum regression fixture registry + +| Risk | Fixed input/test | Acceptance fact | +|---|---|---| +| Last 30 days exceeds all time | `codexUsage.test.ts`: `an inflated period sidecar falls back to the verified daily aggregate`; `v2.3.1 acceptance fixture keeps non-negative ranges monotonic and reconciled` | `today ≤ last30Days ≤ allTime`; daily/monthly totals reconcile | +| Reindex double counting | `codexIndex.test.ts`: `fully indexed unchanged corpus returns a warm no-op without body reads`; `cold scan, appended tail, and persisted reload agree` | Repeated refresh is a stable no-op and reload preserves totals | +| Active/archive duplication | `codexIndex.test.ts`: `exact active and archive copies contribute usage only once` | Identical content contributes once and dedup coverage is reported | +| Month ordering | `codexUsage.test.ts`: `all-time, monthly, and behavior views stay provider-native` | Chart/table source rows are chronological | +| Consecutive/irregular quota resets | `codexQuotaHistory.test.ts`: `irregular reset boundaries survive polling compaction`; fresh/irregular reset fixtures in `weeklyValue.test.ts` | Distinct resets remain distinct and windows are not double-counted | +| Unknown reasoning effort | Current, legacy, missing, and unsafe context fixtures in `codexParser.test.ts`; `missing model and effort values are grouped as unknown` in `codexUsage.test.ts` | Parseable values survive; only missing or safely rejected values become unknown | + +### G0 exit gate + +- [x] Isolate the candidate and leave the user checkout untouched. +- [x] Record branch, HEAD, status, and baseline tests. +- [x] Register automated fixtures for every known regression family. +- [x] Add a cross-view non-negative, monotonic, daily/monthly reconciliation assertion. +- [x] Commit the G0 ledger and acceptance assertion (`f0af506`). + +## G1 local-data and privacy evidence + +### Contract and implementation + +- Added the bilingual normative local-data contract covering raw sources, indexes, derived statistics, quota observations, reset events, UI/share preferences, schema migration, retention, clearing, and every remote boundary. +- Defined anonymous account fingerprints, atomic/deduplicated observation writes, per-account isolation, and the prohibition on credentials, complete identifiers, raw CLI output, and private source content. +- Moved the advice BYOK key from contributed configuration/globalState into VS Code SecretStorage. Webview snapshots expose only `configured`, and the password field never rehydrates a stored secret. +- Migration inspects Global, current Workspace, and every open Workspace Folder. It automatically migrates only one unambiguous machine-wide value, writes secure storage first, clears plaintext second, and fails closed with localized recovery copy on workspace-only, conflicting, or provider-failure cases. + +### Verification and review + +- Focused privacy/contract suite: 17 passed. +- Full Node suite on an isolated loopback port: 807 tests, 806 passed, 0 failed, 1 filesystem-capability skip. +- Claude CLI first review: conditional GO, requesting complete scope enumeration, concurrency/idempotency protection, fixed failure UX, and explicit Settings Sync evidence. +- Revision review: GO to G2 with no blocker. Non-blocking caveats about blocked workspace plaintext and host-dependent SecretStorage backing are now explicit in the contract. + +### G1 exit gate + +- [x] Track a bilingual normative data contract in the repository. +- [x] Make every persisted data class, retention rule, clear path, and remote interaction auditable. +- [x] Migrate the only credential to SecretStorage without exposing it to Webview state. +- [x] Fail closed and preserve recoverability for ambiguous or failed legacy migration. +- [x] Pass the G1 test gate and Claude revision review. + +## G2 entry audit + +The following implementation risks are test hypotheses, not accepted behavior. Each must first be reproduced by a minimal fixture before its implementation changes: + +1. Weekly pricing coverage appears to use the whole window rather than the observation-time prefix. +2. Exact-content deduplication does not include day/period distribution and can collapse records with equal totals but different dates. +3. A `codex-spark` limit may be classified account-wide when its scope is model-specific. +4. A delayed post-reset current observation may mask a valid cached pre-reset observation. +5. Cumulative-delta repair may permit `reasoning > output` or `cached input > input`. +6. Residual usage in a partial effort map may disappear instead of being attributed to `unknown`. + +Additional guards cover the complete 30-day definition in the configured timezone, cross-year chronological month order, alias/invalid reasoning-effort variants, and conservation across daily, monthly, model, effort, and total views. + +## G2 correctness evidence + +### Root-cause fixes + +- Exact active/archive deduplication now includes the authoritative all-time `byDay` distribution, so equal totals on different dates cannot silently collapse. Rebuilding `period`/`today` projections intentionally remain outside identity, preserving refresh idempotence while their independent readability checks run. +- Weekly allowance inference gates on priced-token coverage up to the observation timestamp, not later rows in the same week. A later priced row can no longer make a weak prefix look sufficiently priced. +- An explicit model-specific Codex `limitId` takes precedence over a generic `limitName`, preventing Spark and similar allowances from entering the account-wide series. +- A delayed poll written at or after reset no longer shadows a useful cached pre-reset observation. +- Cumulative token deltas clamp cached input to input and reasoning to output, mark the repaired event partial, and continue to count processed tokens exactly once. +- Partial model/effort maps send positive residual components to `unknown`; zero-value buckets are removed from aggregate and thread projections. + +### Actual-schema effort audit + +- A local field-path-only audit emitted counts, never filenames, values, timestamps, or log text. It observed 51,912 `turn_context.payload.effort` fields, 33,403 `thread_settings_applied` variants, and 33 explicit completed-item variants during the bounded scan. +- Every string encountered by the allowlisted paths normalized to `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, or `ultra`; one explicit null remained unattributed. The parser now accepts these explicit current/legacy paths and never infers effort from model names. + +### Verification + +- Focused red/green fixtures cover authoritative day distribution, sidecar migration stability, observation-prefix pricing coverage, explicit limit-ID precedence, delayed rollover polls, cumulative component repair, real effort schema variants, partial/zero unknown buckets, 30-day conservation, and cross-year month order. +- Final full Node suite: 816 tests, 815 passed, 0 failed, 1 filesystem-capability skip. +- Final Playwright suite: 90/90 passed, including accessibility, keyboard, light/dark, 360 px, chronology, and Compare regressions. + +### G2 exit gate + +- [x] “Last 30 days” remains today plus the previous 29 configured-zone civil dates and reconciles with its daily/model/effort rows. +- [x] `today ≤ last 30 days ≤ all time`; daily/monthly totals reconcile with all time. +- [x] Exact duplicates are stable across refresh while differing day distributions are retained as ambiguous. +- [x] Monthly chart and table data are chronological, including a year boundary. +- [x] Explicit reasoning-effort variants normalize; missing/invalid evidence becomes `unknown`; zero unknown is hidden. +- [x] Full Node and browser gates pass. + +## G3 quota-observation and weekly-estimate evidence + +### Persisted observation boundary + +- Added a schema-versioned, provider/account/window-partitioned observation store with machine-local HMAC fingerprints. Raw credentials and identity signals are discarded after fingerprinting; Webview projections receive only per-run ephemeral aliases. +- Observation writes use a same-directory `0600` temporary file, `fsync`, and atomic rename. A cross-process lease, locked re-read, canonical deduplication, 180-day retention, and bounded compaction make repeated refreshes stable without merging account epochs. +- Strict validation quarantines corrupt or future-schema files instead of trusting or deleting them. Legacy P3/P4 global-state observations and P5 Codex index history migrate P2-first; source keys and migration markers advance only after the destination append succeeds, so an interrupted migration retries safely. +- Claude account continuity is derived only after a successful quota response from a one-way refresh-token HMAC. The token itself is never returned, persisted, logged, or exposed to the Webview. Codex observations use the same store and privacy projection. + +### Reset detection and allowance inference + +- Reset events are derived at runtime from provider window identity, changed `resetAt`, or a significant used-percentage rollback. Account changes alone do not invent an official reset; same-day and consecutive-day resets remain distinct. +- Every valid observation with `0 < usedFraction ≤ 1` contributes `priced usage through observedAt ÷ usedFraction` as a candidate total. A weighted robust median combines candidates while pricing coverage, log coverage, boundary precision, and attribution determine confidence. +- Estimated total is never lower than confirmed used value, and unused value is clamped non-negative. A current window with a valid real observation may expose explicitly low-confidence total and unused durability estimates when account or boundary evidence is approximate; completed windows with genuinely competing overlap remain used-only. +- Unused stays hidden when there is no valid observation, competing series cannot be reconciled, or post-observation usage has overrun the candidate total. The last case retains only a low-confidence total lower bound instead of presenting unknown as `$0`. + +### Verification and read-only review + +- Focused fixtures cover current/legacy adapters, atomic/deduplicated persistence, concurrent append, deterministic out-of-order identities, corrupt/future quarantine, retention, interrupted migration, token rotation, stale in-flight responses, same-day and consecutive resets, rollback noise, reset changes, duplicate observations, multi-account ambiguity, low pricing coverage, current windows, and non-negative floors. +- Final full Node suite: 842 tests, 841 passed, 0 failed, 1 filesystem-capability skip. Final Playwright suite: 90/90 passed. TypeScript compilation passed. +- Claude CLI checkpoint review: GO with no blocker. It requested legacy-trend hardening, a real migration-write-failure fixture, and explicit account-transition semantics; all were added. The single permitted revision review returned GO for G4A with no blocker, followed by a tighter exact-error assertion. + +### G3 exit gate + +- [x] Persist immutable, anonymous, per-account quota observations without credentials or stable identifiers in UI state. +- [x] Preserve irregular, consecutive, and same-day reset evidence without treating noise or account switches as official resets. +- [x] Produce a total allowance estimate whenever a valid same-window utilization observation exists, with robust aggregation and explicit confidence. +- [x] Suppress unsafe unused estimates and prevent negative or below-used values. +- [x] Make migration, repeated refresh, and concurrent append idempotent and recoverable. +- [x] Pass full Node/browser/compile gates and both allowed Claude review passes. + +### Installed-candidate regression addendum + +- The G5 installed-VSIX capture exposed a false `account-ambiguous` flag on a new anonymous Codex epoch even though a changed `resetAt` supplied deterministic reset evidence. The epochs were already isolated by fingerprint and window, but the stale flag suppressed the mathematically valid low-confidence total estimate. +- Commit `4672079` now removes only this synthetic ambiguity across a coherent reset boundary, including stores written by the earlier schema-2 behavior. A fingerprint change without reset evidence remains ambiguous, and overlapping anonymous epochs still fail closed. +- The focused quota/weekly suite passed 49/49. After the later preview-regression revision, the synthetic installed candidate's current 74% observation reports `$397.50` used, `$537.16` full allowance estimate, and `$139.66` unused estimate, explicitly at low confidence. No real account, path, project, thread, or log content entered the evidence. + +## G4A visual, interaction, and accessibility evidence + +### One shared visual contract + +- Added shared spacing, radius, surface, border, data-font, and focus tokens to the single production stylesheet used byte-for-byte by Claude and Codex. Summary cards, model disclosures, chart controls, empty states, and compact navigation now use that contract without copying provider branding or asserting that unlike metrics are equivalent. +- Kept provider-native labels, card counts, and accounting definitions. Tests compare component geometry and interaction treatment, not provider values or semantic parity. +- At 360 px, provider and dashboard navigation remain one-line horizontal strips. Every Claude/Codex destination plus Compare is checked in all eight UI locales against absolute page overflow, while tables and dense charts retain their own explicit scrollers. + +### Keyboard and assistive-technology contract + +- Dashboard destinations now implement `tablist` / `tab` / `tabpanel`, roving tabindex, automatic activation, Arrow/Home/End navigation, `aria-selected`, `aria-controls`, and synchronized hidden panels. +- Sortable headers expose keyboard sorting and `aria-sort`. Chart metric controls expose `aria-pressed`; drill-down bars have accessible names, Enter/Space activation, `aria-controls`, and synchronized `aria-expanded`. Claude and Codex model disclosures retain native keyboard behavior. +- Shared `:focus-visible` treatment and reduced-motion handling cover buttons, summaries, inputs, scrollers, sorting controls, and chart drill-downs. Dark-theme Axe coverage found low-contrast description text on the new raised surface; the final design uses the editor canvas plus a border, restoring readable contrast in both Light+ and Dark+. + +### Verification + +- Focused G4A browser gate: 68/68 passed (24 accessibility/keyboard, 15 responsive, 29 visual/component-contract checks). +- Full Node gate: 842 tests, 841 passed, 0 failed, 1 filesystem-capability skip. Full browser gate: 107/107 passed. +- Privacy-safe fixture renders were inspected for Claude light, Codex light, and Codex dark at 360 px. They confirmed aligned density, chronological reading flow, intact provider semantics, readable dark contrast, and one-line narrow navigation. These inspection images are temporary evidence, not release screenshots; G5 will capture the installed VSIX. + +### G4A exit gate + +- [x] Reuse one tokenized stylesheet and shared component treatment without creating a second provider design system. +- [x] Preserve honest provider-specific metrics and destinations. +- [x] Pass keyboard, ARIA, focus, reduced-motion, light/dark, eight-locale, and 360 px gates. +- [x] Pass full Node and browser regression suites and visually inspect representative fixture states. + +## G4B combined heatmap and sharing evidence + +### One aggregate pipeline and deterministic artifact + +- Added a pure, configured-timezone daily merge over the existing Claude `DayUsage` map and Codex daily view. Claude processed activity is input + cache creation + cache read + output; Codex processed activity is input total + output total, with cached input already inside input and reasoning already inside output. +- Identical duplicate provider/day rows are idempotent; conflicting duplicates fail closed. Missing dates and single-provider days remain valid, and the Codex daily projection now retains 370 rows so a complete leap-year share window plus boundary margin never triggers a second log scan or cache. +- The combined share card is deterministic for an explicit end date, uses a neutral non-provider palette, exposes Claude/Codex/combined values in every daily tooltip, and accepts only aggregate date/value DTOs. Privacy-canary tests prove that account, project, thread, path, prompt, and log fields cannot enter the SVG. + +### Compare workflow and publication boundary + +- Compare now leads with the combined heatmap whenever provider activity is available. The user can select 30 days, 90 days, or one year, set an 80-character title, inspect the explicit inclusion/exclusion preview, export SVG, copy a relative Markdown snippet, or reset only the sharing preferences. +- Local export and Markdown copy never request network access. The existing GitHub publisher now requests `public_repo` instead of broad private-repository access, probes repository visibility/default branch and create/update state, fails closed for private or unverifiable targets, and requires a second exact owner/repo/branch/path/action/byte confirmation before the write. +- Destination strings persist only after a successful confirmed write; credentials remain in VS Code authentication. Goal verification uses a mock transport only and performs no real GitHub write. + +### Verification and read-only review + +- Focused pure/host suites: 69/69 passed, including formulas, duplicate and fully missing dates, symmetric Claude-only/Codex-only input, non-Sunday 30/90-day grid starts, deterministic SVG, privacy canaries, public-only GitHub permission and exact confirmation, sharing reset, and the 370-day source cap. +- Focused browser suite: 5/5 passed for default Compare placement, both-provider tooltips, explicit actions, preference reset, Light+/Dark+ Axe, and 360 px containment. +- Final full Node gate: 862 tests, 861 passed, 0 failed, 1 filesystem-capability skip. Full Playwright gate: 112/112 passed. +- Claude CLI checkpoint returned GO to G5 with no blocker. It identified three low-risk test gaps: symmetric Codex-only input, a date missing from both providers, and 30/90-day SVG starts that are not Sunday-aligned. Commit `5e5bf9f` added direct assertions for all three; the single permitted revision review confirmed each gap closed and returned final GO to G5. + +### G4B exit gate + +- [x] Reuse existing provider daily aggregates without another source scan or statistics cache. +- [x] Define and test non-duplicating provider formulas, configured-zone ranges, duplicate semantics, and a complete annual source window. +- [x] Deliver deterministic SVG, combined share card, relative Markdown, custom title/range, and a privacy preview in Compare. +- [x] Keep local export offline and harden optional direct GitHub publication with public-only permission, exact confirmation, and mock-only tests. +- [x] Pass focused and complete Node/browser gates. +- [x] Receive the required Claude CLI checkpoint verdict and close every review finding selected for revision. + +## G5 README, local-data inventory, and installed-VSIX screenshot evidence + +### Release documentation + +- Updated all seven README editions for v2.3.1: Claude/Codex/Compare coverage, corrected time ranges and chronological months, quota observation and reset-aware estimation, combined heatmap sharing, local-only data boundaries, and known uncertainty limits. +- Added concise bilingual user inventories in `LOCAL-DATA.md` and `LOCAL-DATA.zh-CN.md`, backed by the normative contract, covering sources, derived caches, anonymous quota history, preferences, retention, clear controls, remote interactions, and data that is never stored. +- Updated the v2.3.1 changelog, package/lock version, exact-version release announcement, and all eight announcement locales. The release remains explicitly unreleased; no Marketplace, remote release, or repository publication occurred. + +### Real host evidence + +- Built and installed the v2.3.1 candidate VSIX in a separate ad-hoc-signed VS Code copy with isolated extension/user-data directories and synthetic Claude/Codex JSONL only. +- Captured and visually inspected `images/v2.3.1/codex-overview-zh-CN-dark.png`, `images/v2.3.1/codex-weekly-estimate-en-dark.png`, and `images/v2.3.1/compare-heatmap-en-light.png` from that installed candidate. +- The images cover the Codex overview, a reset-aware full allowance estimate, and Compare's combined heatmap/share controls in Chinese/English and dark/light themes. They contain no account identifier, local path, real project/thread title, prompt, credential, or user log content. +- The captured JPEG frames were transcoded to real PNG bytes before commit and stripped of EXIF and textual PNG chunks. Repository-policy tests require every README to reference all three images, every referenced file to exist, the PNG signature/IEND structure to be valid, and `eXIf`/`iTXt`/`tEXt`/`zTXt` chunks to be absent. + +### Verification and read-only review + +- Focused release/document/quota suite: 77/77 passed. +- Full Node gate: 866 tests, 865 passed, 0 failed, 1 filesystem-capability skip. Full Playwright gate: 112/112 passed. +- The G4B host tests explicitly confirm that GitHub destination preferences persist only after a successful exact-target write and that reset clears only the remembered destination. The G5 repository-policy gate separately protects the shipped evidence files. +- Claude CLI returned **GO TO G6** with no blocker or semantic/privacy error. It noted non-native data-inventory language coverage and requested explicit mention of the GitHub test and stronger screenshot scrubbing; the former is now recorded above, while the latter is enforced for file format and metadata plus visual inspection for rendered pixels. Final VSIX packaging, clean fresh-install/migration/clear-path smoke tests, acceptance matrix, and candidate hash belong to G6. + +### G5 exit gate + +- [x] Update all README editions, changelog, version metadata, and migration/uncertainty notes. +- [x] Track concise bilingual local-data inventories consistent with the normative contract. +- [x] Capture three privacy-safe screenshots from an actually installed v2.3.1 candidate. +- [x] Pass focused and complete Node/browser gates. +- [x] Receive the required Claude CLI checkpoint and close the selected evidence-hardening notes. +- [x] Commit the completed G5 implementation and evidence (`e9a149a`). + +## G6 release-candidate evidence + +### Local-data controls and audit hardening + +- Added the Settings/Data inventory and seven separately confirmed controls: rebuild Codex index, clear quota history, clear advice data, reset UI state, reset sharing preferences, clear the BYOK secret, and clear all extension-derived data. +- An independent read-only code audit found five blockers and two high risks around partial configuration deletion, false Webview acknowledgements, quota clear races/quarantine, activation-write resurrection, and overly broad setting/migration deletion. Every finding was closed before the release gate. +- Clear All now preflights every currently visible configuration scope before mutation, drains activation-owned writes, uses exact key/file families, preserves unknown future `ccu.setting.*` keys, verifies postconditions, and fails closed on unregistered legacy configuration. +- Quota all-clear holds one cross-process lease, atomically installs a valid empty P2 document, and purges only exact auxiliary files. Scoped clear refuses quarantined or unresolved migration evidence instead of stranding it. Webview resets use a truthful acknowledgement plus a value-free pending-action tombstone for idempotent retry. +- The bilingual normative contract and user inventory now describe these exact storage, migration, clearing, retention, retry, and host-limit semantics. + +### Final automated and package gates + +- `npm run test:release`: 897 Node tests, 896 passed, 0 failed, 1 filesystem-capability skip; Playwright 116/116 passed. +- `git diff --check` and TypeScript compile passed. +- Pinned `@vscode/vsce@3.9.1` produced the superseding `claude-code-usage-2.3.1-5af60b4.vsix`. The repository verifier accepted version `2.3.1`, runtime main `extension/out/extension.js`, 107 entries, and 1,903,765 bytes. +- Candidate SHA-256: `074d0b774b983cebd654eda59c2f6c22168607768aa99a52fb50c98ec199d7a0`. + +### Stock VS Code isolated smoke + +- Stock VS Code `1.135.0` installed the final VSIX into a new isolated user-data/extensions pair. A second isolated profile installed the earlier screenshot candidate and then force-installed the final candidate over it. +- Both extracted manifests reported `growthjack.claude-code-usage@2.3.1`, `./out/extension.js`, and the new Clear All command. Extracted runtime SHA-256 matched the compiled runtime exactly: `0e86438a32225caffe130ba8326979234b7398e7a07b91cd161d2c0c9e6a2036`. +- With only synthetic Claude/Codex sources, the stock Extension Host activated `GrowthJack.claude-code-usage` without an extension error. The exact isolated process was normally terminated and restarted; the new Extension Host activated the extension again without an extension error. +- Both isolated profiles uninstalled successfully and then listed no installed extension. VS Code retained extension globalStorage after uninstall, confirming the documented need for an explicit clear action. Source fixtures were never rewritten; the before/after Codex index-source hash remained identical. +- The G5 ad-hoc screenshot wrapper was not used in G6. Its macOS crash alert is isolated from the final VSIX and was not reproduced in stock VS Code. + +### Final pre-install Claude CLI review (2026-09-02) + +- Claude Code CLI `2.1.228`, Opus, and `max` effort reviewed the actual 3,488-addition/88-deletion G6 patch from the G5 checkpoint `8eac9a0` through implementation commit `b435e06`, plus final test, package, and stock-host evidence. It ran in safe/print/no-tools/no-session-persistence mode. The complete input-stream SHA-256 was `350582b6b76e58167f1864787c4192f07b6babf7c15911001beca3b56488fb1e`; it contained no real logs, accounts, credentials, project content, or user paths. +- Claude reported **Release blockers: None** and returned **GO FOR USER INSTALL**. This authorizes the maintainer's local install test only, not a push, Marketplace publication, remote release, or real GitHub write. +- The hands-on install pass should prioritize three cases: opening Manage Local Data and Privacy with no Claude/Codex logs; activating an upgrade profile that contains a legacy plaintext `claudeCodeUsage.advice.apiKey`; and testing both blocked-legacy and successful Clear All paths in a scratch workspace. Clear All removes explicitly owned `claudeCodeUsage.*` entries from that scratch workspace's `.vscode/settings.json`, so it must not be tried first in an important workspace. +- Nonblocking follow-ups include a real-temp-globalStorage Clear All postcondition E2E test, an advice-clear versus in-flight-migration race, the Webview two-second ACK timeout, sharing-preference reset scope, and exact blocked-key copy. Any hands-on unhandled activation failure or out-of-scope deletion reopens the candidate before publication. +- A later maintainer preview-feedback revision changed the share studio, heatmap renderer, weekly estimates, localized copy, tests, and release documentation. It therefore supersedes the earlier `b435e06` package; the final review and candidate evidence are recorded below. + +### Post-preview feedback revision and superseding candidate (2026-09-02) + +- The data font was returned to the VS Code UI font while the Markdown field retains the editor monospace font. Compare now uses a preview-first share studio with a privacy badge, grouped card settings, explicit actions, a collapsible Markdown result, desktop-fit preview geometry, and preserved narrow-screen horizontal scrolling. +- Heatmap color is locally selectable. The default Academic Violet ramp is exactly `#ebedf0`, `#eee8f8`, `#d8c9f1`, `#bca5e6`, `#8668c7`, `#4f2f87`; three other curated palettes and one validated custom accent are available. Quantile ties, sparse maxima, near-white custom colors, short-range legend bounds, SVG injection, contrast, deterministic output, and the full desktop `More` legend all have direct tests. +- A coherent Claude or Codex observation now exposes both full and unused API-equivalent subscription-durability estimates for current and completed windows, including unattributed or approximate evidence at low confidence. Dashes remain only when there is no valid observation, genuinely overlapping quota series compete, or later usage has overrun a stale observation-derived candidate; in the latter case the total is a low-confidence lower bound and unused is withheld instead of showing a false zero. +- Claude CLI reviewed the sanitized feedback revision in print/no-tools/no-session-persistence mode and returned **GO FOR USER INSTALL** with no blocker or network, permission, or privacy concern. Its nonblocking findings on sparse/tied quantiles, custom-color contrast, provider-symmetric confidence, stale-observation overrun, surcharge wording, short-range legend bounds, exact palette/source-overlap fixtures, preview semantics, Axe completeness, and UI-font assertions were all closed before the final gate. +- The superseding release gate passed 896/897 Node tests (the one skip is the documented filesystem-capability fixture), 116/116 Playwright tests, TypeScript compile, `git diff --check`, bilingual visual QA, and the repository VSIX policy verifier. Synthetic English-light and Chinese-dark final renders were visually inspected; they contain no real account, project, thread, path, or log data. +- Stock VS Code `1.135.0` force-installed the superseding package over the prior candidate in the same isolated temporary profile and listed `growthjack.claude-code-usage@2.3.1`. Installed `webview.js`, `weeklyValue.js`, and `combinedHeatmapSvg.js` hashes exactly matched the compiled files. No push, Marketplace publication, remote release, or real GitHub write occurred. +- Runtime candidate commit: `5af60b4` (including the main feedback implementation in `5e6e5cc`). Package: `claude-code-usage-2.3.1-5af60b4.vsix`, 1,903,765 bytes, SHA-256 `074d0b774b983cebd654eda59c2f6c22168607768aa99a52fb50c98ec199d7a0`. The following local documentation commit records this evidence and is excluded from the VSIX. + +### Post-install regression correction and final local candidate (2026-09-02) + +- Local implementation commit `666f04c` fixes the maintainer-observed regression: Claude's middle scope is now Today plus the previous 29 civil dates in the configured timezone, and Today / rolling-30 / month daily rows all read `byLocalDay`. An inactive Today renders an explicit zero state rather than looking like a missing page. +- A current Codex period may use the latest real observation for explicitly low-confidence total and unused durability estimates; weekly period tables are collapsed by default. Compare is vertically preview-first, with card settings directly below the share graphic instead of leaving a large empty right column. +- The Codex primary status item now reports configured-timezone Today. Quota compact text uses Claude-compatible used-percent semantics; the tooltip reuses progress bars, thresholds, and reset columns. The item background follows the highest usage among live windows rendered by the active preference, so compact `wk 40%` alongside tooltip `5h 96%` correctly produces an error background. +- A Los Angeles DST/local-boundary fixture directly asserts the Today row equals the Today aggregate, `Today ≤ 30 days ≤ all time`, and snapshot materialization adds no JSONL body read. Additional fixtures cover two-window quota severity, expired windows, provider-label escaping, and the real `renderCodex` wiring. +- Final gates: TypeScript compile; 903 Node tests with 902 passed, 0 failed, and 1 existing filesystem-capability skip; Playwright 117/117; `git diff --check`. Pinned `@vscode/vsce@3.9.1` produced `claude-code-usage-2.3.1-regression-fix-final-20260902.vsix`; the repository verifier accepted 107 files, 1,905,981 bytes, version `2.3.1`, runtime main `extension/out/extension.js`, and SHA-256 `869149b3e6034da4341ba55fa50c2d365accb5280e9ffd16520dfc845340f5b8`. +- The package force-installed into an isolated VS Code/profile using synthetic data only. Installed `extension.js`, `webview.js`, `weeklyValue.js`, and `statusBar.js` hashes exactly match the compiled outputs. The stock-host accessibility tree confirms settings below the preview, both weekly disclosures closed, a current Codex 74% total/unused low-confidence estimate, and compact `CX 5M` / `wk 74%` status items. +- Claude Code CLI `2.1.228`, Opus, and `max` effort ran in safe/print/no-tools/no-session-persistence mode. Its first regression review identified two blockers (Claude day-map consistency and Codex quota severity colour); after revision it marked B1/B2 **CLOSED**, the roadmap **ADEQUATE**, and the local candidate **GO**. The revision-review input SHA-256 was `437fd7a5a593d4b272877f5641e6a8d3545243c9cd575e3684ed50cd29602e1a`; it contained relative-path patches, synthetic evidence, and the roadmap only. +- Broader parity work is deliberately outside v2.3.1 and is tracked in the [v2.4 Claude / Codex interaction-parity roadmap](../roadmap/provider-parity-v2.4.md): month-to-day and day-to-hour drill-down, zero JSONL reads on click, refresh/reload state preservation, non-UTC/DST conservation, sparse-range zero fill, unique accessible names, and top-level chart/status/quota contracts. Maintenance follow-ups include documenting the `byDay`/`byLocalDay` invariant, removing `month` naming drift, structuring tooltip copy, and adding a manager-level five-hour-only fixture. +- No push, Marketplace publication, remote release, real GitHub write, or real user-data scan occurred. This package supersedes every earlier VSIX candidate. + +### Concise-settings and remaining-quota follow-up candidate (2026-09-02) + +- Follow-up implementation commit `ddfe99d` removes the local-data/privacy inventory from the plugin Settings surface while retaining the normative repository documents, exact host-side clear contracts, and their safety tests. Settings now exposes one shared **Enable sharing workspace** switch: it defaults on, controls both Compare and provider share surfaces, and hides them completely when off; every export remains an explicit action. +- Compare remains vertically preview-first, and the SVG now expands to the available desktop width before the card settings below it. Weekly period details remain collapsed by default. Synthetic Chinese-dark visual QA confirmed that enabling the workspace no longer leaves the former right-side void, while disabling it leaves Compare summaries and both weekly charts intact. +- The compact Codex quota item now reports **remaining** capacity (`wk 64%` for 36% used), as requested. Tooltip progress bars, severity colours, and warning thresholds continue to use observed utilisation, and the separate `CX` token item continues to report the configured-timezone Today scope rather than a recent-task subtotal. +- A user-authorized, read-only diagnostic of the selected default Claude profile inspected only file/timestamp metadata and allowlisted numeric usage fields. The production loader found 682 project JSONL files and correctly reconstructed the rolling 30-day scope as 104 messages and 2,487,790 output tokens, but found zero persisted usage for 2026-09-02. Four 2026-09-02 history entries had neither usage fields nor a corresponding project transcript, and there was no measurable 2026-09-01 entry. The existing audit ledger records that those Claude CLI reviews used `--no-session-persistence`; that mode writes no measurable transcript/token record, so the extension cannot truthfully backfill the missing Today/Yesterday values. No prompt, response, command, credential, path, or raw log content was reported or changed. +- Final gates after the desktop-width refinement: TypeScript compile; Node 903 total with 902 passed, 0 failed, and 1 existing filesystem-capability skip; Playwright 118/118; targeted combined-share tests 6/6; `git diff --check`; ZIP integrity; and repository VSIX policy verification. Pinned `@vscode/vsce@3.9.1` produced `claude-code-usage-2.3.1-followup-final-20260902.vsix`, 107 files, 1,906,703 bytes, SHA-256 `33bc404ce0dc693f7d97d40dd485c8d6ea96c8727ea9b178fe978cbb101daa0f`. +- The package installed successfully into a new isolated stock-VS-Code user-data/extensions pair and listed `growthjack.claude-code-usage@2.3.1`. The primary checkout was not modified. No push, Marketplace publication, remote release, or real GitHub write occurred; the read-only Claude diagnostic above is the only real-data access added after the earlier candidate evidence. + +### Acceptance matrix + +| Requirement | Implementation | Automated verification | Screenshot / host evidence | +|---|---|---|---| +| Last-30-day conservation, deduplication, chronological month order | `src/dateKeys.ts`, `src/providers/codex/codexDedup.ts`, `codexIndex.ts`, `codexUsage.ts`, `codexView.ts` | `dateKeys`, `codexDedup`, `codexIndex`, `codexUsage`, Webview visual/interaction suites | Codex overview and weekly screenshots; stock activation/restart | +| Reasoning-effort normalization and meaningful `unknown` | `src/providers/codex/codexSchema.ts`, `codexParser.ts`, `codexUsage.ts`, `src/webview.ts` | current/legacy/missing/invalid/zero/non-zero effort fixtures plus total conservation | Codex overview screenshot | +| Anonymous quota history, multiple resets, robust full/unused estimates | `src/quotaObservationStore.ts`, `codexQuotaHistory.ts`, `src/weeklyValue.ts` | quota-store, quota-history, weekly-value, race, quarantine, migration and ambiguity fixtures | Weekly-estimate screenshot; stock-generated P2 store | +| Claude/Codex visual, keyboard, theme and narrow-width alignment | shared `src/webview.ts` and `src/codexViewComponents.ts` tokens/components | accessibility, responsive, visual and interaction suites | G5 English/Chinese, dark/light screenshots | +| Compare combined heatmap and privacy-bounded sharing | `src/combinedHeatmap.ts`, `combinedHeatmapSvg.ts`, `githubHeatmapPublish.ts`, `webview.ts` | deterministic SVG, duplicate/conflict, timezone, privacy canary, mock GitHub, accessibility tests | Compare heatmap/share screenshot | +| Auditable local inventory, exact clear/migration boundaries | `src/localDataControls.ts`, `extension.ts`, `settings.ts`, `quotaObservationStore.ts` | `localDataControls`, `localDataExtension`, `settingsPrivacy`, quota clear-race/quarantine and UI ACK suites | Stock install/activation/restart/uninstall; host-retained storage observed | +| README, contract, screenshots and migration disclosure | all README editions, CHANGELOG, `LOCAL-DATA*`, normative contract, release ledger | repository/release policy and screenshot metadata/privacy gates | Three installed-candidate screenshots | +| Installable release candidate without remote side effects | package manifest, compiled `out`, `.github/scripts/verify-vsix.mjs` | full release gate and VSIX policy verifier | Two isolated stock profiles; no push, release, Marketplace, or real GitHub write | + +### G6 exit gate + +- [x] Close all read-only audit blockers and high-risk findings. +- [x] Pass final compile, diff, complete Node and complete browser suites. +- [x] Build and policy-verify the v2.3.1 VSIX with a recorded SHA-256. +- [x] Verify isolated fresh install, candidate-over-candidate update, real activation, full process reload, uninstall, migration fixtures, repeated-refresh fixtures, and exact clear paths. +- [x] Record the requirement-to-code-to-test-to-evidence acceptance matrix. +- [x] Receive the final pre-install Claude CLI **GO FOR USER INSTALL** verdict and record the hands-on checkpoints. +- [x] Stop before push, Marketplace publication, remote release, or real GitHub write. +- [x] Commit the G6 implementation and feedback revision (`b435e06`, `5e6e5cc`, `5af60b4`); the following local documentation commit records the superseding package evidence in both ledgers. + +## Update rule + +Each stage must finish its automated verification before this ledger records its commit, evidence, Claude decision, and risk. The G6 acceptance matrix must be derived from these records; screenshots or copy cannot substitute for a failed gate. + +The future ability to select one project, invoke AI on demand to review its inputs/outputs, and return evidence-bound usage-behavior advice now lives in the [v2.5.3 project-scoped AI usage review plan](../superpowers/plans/2026-09-02-v2.5.3-project-ai-usage-review.md). It does not reopen v2.3.1 and requires a new Goal that explicitly ends at R0–R4 or also authorizes the R5 local Claude CLI safety gate. diff --git a/docs/releases/2026-09-01-v2.3.1-goal-ledger.zh-CN.md b/docs/releases/2026-09-01-v2.3.1-goal-ledger.zh-CN.md new file mode 100644 index 00000000..3a4e88b1 --- /dev/null +++ b/docs/releases/2026-09-01-v2.3.1-goal-ledger.zh-CN.md @@ -0,0 +1,341 @@ +# Claude Code Usage v2.3.1 Goal 执行台账 + +本台账记录本地候选从 G0 到 G6 的阶段状态、可复现验收证据、Claude CLI 只读审阅和剩余风险。它不记录账号、凭证、真实日志、提示词、线程标题或本地路径。 + +## 执行边界 + +- 分支:`codex/v2.3.1-goal-g0-g6` +- 基线:`7fd03f3183240940d0a2d1cfe76f60cb80f0a6ae` +- 工作方式:隔离 worktree;用户主 checkout 及其中已有修改保持只读。 +- 允许:本地代码/文档修改、测试、构建、VSIX、阶段性本地 commit、指定检查点的 Claude CLI 只读审阅。 +- 禁止:push、Marketplace 发布、远程 release、真实 GitHub 写入、上传用户日志或身份数据。 + +## 阶段状态 + +| 阶段 | 状态 | 本地 commit | 验证摘要 | Claude 审阅 | 剩余风险 | +|---|---|---|---|---|---| +| G0 基线与夹具 | 已完成 | `f0af506` | Node 795 passed / 1 skipped;UI 90 passed;定向 29 passed | 不适用 | 无阻塞风险 | +| G1 数据契约 | 已完成 | `86d95df` | 定向 17 passed;Node 806 passed / 1 skipped;compile passed | 首轮有条件 GO,修订复核 GO | 受阻 workspace 明文需用户显式恢复;SecretStorage 底层保护依赖宿主;统一额度存储属于 G3 | +| G2 统计/排序/effort | 已完成 | `49f2041` | Node 815 passed / 1 skipped;UI 90 passed;全部定向回归通过 | 不适用 | 统一观测与账号归属仍由 G3 处理 | +| G3 额度观测与估算 | 已完成 | `a04ab04`、`4672079` | 阶段出口 Node 841 passed / 1 skipped;安装候选回归:quota/weekly 49 passed | 首轮 GO,修订复核 GO | 损坏/未来 schema 的隔离文件会保留至“清除数据”或未来清理策略处理 | +| G4A 视觉/交互/可访问性 | 已完成 | `fca21da` | Node 841 passed / 1 skipped;UI 107 passed;G4A 定向 68 passed | 不适用 | 刻意保留 provider 原生指标语义与卡片数量差异 | +| G4B 综合热力图与分享 | 已完成 | `1e6bbab`、`5e5bf9f` | Node 861 passed / 1 skipped;UI 112 passed;定向 69 + 5 passed | 首轮 GO,修订复核 GO | GitHub `public_repo` 对公开仓库仍是账号级权限;本地 SVG/Markdown 无需权限,是默认安全路径 | +| G5 README/截图 | 已完成 | `e9a149a` | Node 865 passed / 1 skipped;UI 112 passed;已目检 3 张安装候选截图 | GO TO G6 | 最终打包证据属于 G6 | +| G6 发布候选 | 已完成 | `b435e06`、`5e6e5cc`、`5af60b4`、`666f04c` | 最新回归候选 Node 902 passed / 1 skipped;UI 117 passed;VSIX policy、视觉 QA 与隔离原生宿主安装通过 | 回归首审 NO-GO;修订复核:**GO** | 需在隔离 profile/临时 workspace 手测空数据设置页、旧明文 key 升级和 Clear All;其余交互一致性进入 v2.4 路线图 | + +## G0 基线证据 + +### 环境与测试 + +- Node:`v24.19.0` +- npm:`11.17.0` +- `npm ci`:成功。 +- `npm run test:node`:796 项,795 通过,0 失败,1 跳过。首次受限运行中的两个 loopback `EPERM` 由测试沙箱引起;允许本地测试服务器绑定后均通过。 +- `npm run test:ui`:90/90 通过。 +- 基线工作树:干净。 + +### v2.3.1 最小回归夹具登记 + +| 风险 | 固定输入/测试 | 验收事实 | +|---|---|---| +| 最近 30 天大于全部时间 | `codexUsage.test.ts`:`an inflated period sidecar falls back to the verified daily aggregate`;`v2.3.1 acceptance fixture keeps non-negative ranges monotonic and reconciled` | `today ≤ last30Days ≤ allTime`,日/月汇总与总计可核对 | +| 重复索引/重复累计 | `codexIndex.test.ts`:`fully indexed unchanged corpus returns a warm no-op without body reads`;`cold scan, appended tail, and persisted reload agree` | 连续刷新为稳定 no-op,重载后总计不变 | +| 活跃/归档重复文件 | `codexIndex.test.ts`:`exact active and archive copies contribute usage only once` | 同一内容只计一次并报告去重覆盖 | +| 月度顺序 | `codexUsage.test.ts`:`all-time, monthly, and behavior views stay provider-native` | 图表/表格源数据按月份正序 | +| 连续/不规则额度重置 | `codexQuotaHistory.test.ts`:`irregular reset boundaries survive polling compaction`;`weeklyValue.test.ts` 的 fresh reset/irregular reset fixtures | 独立 reset 被保留,窗口不重复计量 | +| unknown 推理强度 | `codexParser.test.ts` 的 current/legacy/missing/unsafe context fixtures;`codexUsage.test.ts`:`missing model and effort values are grouped as unknown` | 可解析值保留;确实缺失或被安全拒绝时进入 unknown | + +### G0 通过条件 + +- [x] 隔离候选,不触碰用户 checkout。 +- [x] 记录 branch、HEAD、状态和基线测试。 +- [x] 为五类已知回归建立可重复的自动化夹具索引。 +- [x] 加入跨视图非负、单调、日/月核对断言。 +- [x] 提交 G0 台账与新增验收断言(`f0af506`)。 + +## G1 本地数据与隐私证据 + +### 契约与实现 + +- 新增中英文规范性本地数据契约,覆盖原始来源、索引、派生统计、额度观测、重置事件、UI/分享偏好、schema 迁移、保留期、清除方式和所有远程边界。 +- 定义匿名账号 fingerprint、原子且去重的观测写入、账号隔离,并禁止保存凭证、完整账号标识、原始 CLI 输出及私密源内容。 +- 将 AI 建议 BYOK key 从 contributed configuration/globalState 迁入 VS Code SecretStorage;Webview snapshot 只暴露 `configured`,密码框绝不回填 secret。 +- 迁移检查 Global、当前 Workspace 和所有已打开 Workspace Folder;仅自动迁移唯一且无歧义的机器级值,先写安全存储、后清明文;workspace-only、冲突值或 provider 失败均以本地化固定提示 fail closed,并保留可恢复数据。 + +### 验证与审阅 + +- 隐私/契约定向测试:17 passed。 +- 独立 loopback 端口完整 Node 测试:807 项,806 passed,0 failed,1 项因文件系统能力 skipped。 +- Claude CLI 首轮审阅:有条件 GO,要求补齐 scope 枚举、并发/幂等保护、固定失败 UX 及 Settings Sync 证据。 +- 修订复核:无阻塞,可进入 G2;关于受阻 workspace 明文和 SecretStorage 宿主差异的非阻塞提示已写入契约。 + +### G1 通过条件 + +- [x] 在 repo 内跟踪中英文规范性数据契约。 +- [x] 使所有持久化数据类别、保留期、清除路径和远程交互可审计。 +- [x] 唯一凭证迁入 SecretStorage,且不暴露到 Webview 状态。 +- [x] 对歧义或失败的旧数据迁移 fail closed 并保留可恢复性。 +- [x] 通过 G1 测试门和 Claude 修订复核。 + +## G2 入口审计 + +以下是必须先用最小 fixture 复现、再修改实现的风险假设,不代表已接受的现有行为: + +1. 每周定价覆盖率疑似使用完整窗口,而不是截至观测时刻的前缀。 +2. 精确内容去重签名未纳入日/周期分布,可能把总量相同但日期不同的记录折叠掉。 +3. `codex-spark` 限额可能被误判成账号级,而实际作用域是特定模型。 +4. 重置后延迟到达的当前观测可能掩盖有效的重置前缓存观测。 +5. 累计 delta 修复可能产生 `reasoning > output` 或 `cached input > input`。 +6. 部分 effort map 的剩余用量可能消失,而不是归入 `unknown`。 + +额外 guard 覆盖配置时区下完整的 30 天定义、跨年月份正序、reasoning-effort 别名/非法变体,以及日、月、模型、effort 和总计之间的守恒关系。 + +## G2 正确性证据 + +### 根因修复 + +- active/archive 精确去重签名现包含权威 all-time `byDay` 分布,因此“总量相同、日期不同”不会被静默折叠。可重建的 `period`/`today` 投影不进入身份签名,避免 sidecar 迁移时破坏刷新幂等;它们继续由独立可读性检查保护。 +- 周额度推断改用截至观测时刻的已定价 Token 覆盖率,而不是同周后续记录;后到的已定价行不能再把证据不足的前缀变成可推断样本。 +- 显式模型级 Codex `limitId` 优先于通用 `limitName`,防止 Spark 等独立额度混入账号级序列。 +- reset 时刻或之后才写入的延迟 poll 不再遮蔽有效的重置前缓存观测。 +- 累计 Token delta 强制 cached input ≤ input、reasoning ≤ output;修复事件标为 partial,并保持 processed 只计一次。 +- 部分 model/effort map 的正残差进入 `unknown`;aggregate 与线程投影均删除零值 bucket。 + +### 真实 schema 的 effort 审计 + +- 本地只做字段路径计数,不输出文件名、字段值、时间或日志正文。有限扫描中观察到 51,912 个 `turn_context.payload.effort`、33,403 个 `thread_settings_applied` 变体和 33 个显式 completed-item 变体。 +- 白名单路径中的字符串都可规范为 `none`、`minimal`、`low`、`medium`、`high`、`xhigh`、`max` 或 `ultra`;另有 1 个显式 null 保持未归属。解析器现支持这些显式新旧路径,绝不按模型名称推断 effort。 + +### 验证 + +- 定向 red/green fixture 覆盖权威日期分布、sidecar 迁移稳定性、观测前缀定价覆盖、显式 limit ID 优先、延迟 rollover poll、累计分量修复、真实 effort schema、部分/零值 unknown、30 天守恒和跨年月份正序。 +- 最终完整 Node:816 项,815 passed,0 failed,1 项因文件系统能力 skipped。 +- 最终 Playwright:90/90 passed,覆盖可访问性、键盘、深浅主题、360 px、时间正序和 Compare 回归。 + +### G2 通过条件 + +- [x] “最近 30 天”保持为配置时区下今天及此前 29 个自然日,并与日/model/effort 行守恒。 +- [x] `今日 ≤ 最近 30 天 ≤ 全部时间`;日/月总计与 all-time 核对一致。 +- [x] 精确副本在刷新间稳定;日期分布不同的记录保留为 ambiguous。 +- [x] 月度图表与表格数据按时间正序,包含跨年边界。 +- [x] 显式 reasoning-effort 新旧变体可规范化;缺失/非法证据进入 `unknown`;零 unknown 隐藏。 +- [x] 完整 Node 与浏览器门均通过。 + +## G3 额度观测与周额度估算证据 + +### 持久化观测边界 + +- 新增带 schema 版本、按 provider/账号/窗口分区的观测存储,账号与窗口仅使用机器本地 HMAC fingerprint。原始凭证和身份信号完成摘要后立即丢弃;Webview 只能收到本次运行内的临时别名。 +- 写入采用同目录 `0600` 临时文件、`fsync` 和原子 rename;跨进程 lease、锁内重读、规范化去重、180 天保留期及有界压缩保证重复刷新稳定且不合并账号 epoch。 +- 严格校验会隔离损坏或未来 schema 文件,而不是信任或删除它们。P3/P4 globalState 旧观测及 P5 Codex index history 均先写入 P2,只有目标 append 成功后才清理源键或推进迁移 marker,因此中断后可安全重试。 +- Claude 的账号连续性只在额度请求成功后由 refresh token 的单向 HMAC 得到;token 本身不返回、不持久化、不记录日志、也不进入 Webview。Codex 观测使用同一存储及隐私投影。 + +### 重置检测与额度推断 + +- reset 事件在运行时依据 provider window identity、`resetAt` 变化或 used 百分比显著回落推导。单纯账号切换不会伪造官方重置;同日多次及连续两日重置均保留为独立事件。 +- 每个满足 `0 < usedFraction ≤ 1` 的有效观测都会形成“截至 observedAt 的已定价用量 ÷ usedFraction”候选总额度;多个候选用加权稳健中位数合并,并由定价覆盖、日志覆盖、边界精度和账号归属共同决定可信度。 +- 总额度估算绝不低于窗口已确认使用值;未用值强制非负。当前窗口存在有效真实观测但账号/边界近似时,可以显示明确标为低可信度的总额与未用耐用度估算;已结束窗口若存在竞争性重叠系列则仍只显示已用值。 +- 不存在有效观测、竞争性系列无法归一,或观测后新增用量已超过候选总额时,不显示未用值;最后一种情况只保留低可信度总额下界,不把未知伪装成 `$0`。 + +### 验证与只读审阅 + +- 定向 fixture 覆盖新旧 adapter、原子/去重持久化、并发 append、乱序窗口身份、损坏/未来 schema 隔离、保留期、中断迁移、token 轮换、过期 in-flight 响应、同日/连续 reset、回落噪声、reset 变化、重复观测、多账号歧义、低定价覆盖、当前窗口及非负下限。 +- 最终完整 Node:842 项,841 passed,0 failed,1 项因文件系统能力 skipped;最终 Playwright:90/90 passed;TypeScript compile passed。 +- Claude CLI 检查点首轮无阻塞 GO,并要求加固旧 trend、加入真实迁移写失败 fixture、明确账号切换语义;均已完成。允许的一次修订复核返回“可进入 G4A、无阻塞”,随后又收紧了精确错误断言。 + +### G3 通过条件 + +- [x] 以不可变、匿名、按账号隔离的形式保存额度观测,不保存凭证,不向 UI 暴露稳定标识。 +- [x] 保留不规则、连续及同日多次 reset 证据,且不把噪声或账号切换误判为官方重置。 +- [x] 只要同窗存在有效利用率观测即给出总额度估算,并采用稳健聚合及显式可信度。 +- [x] 抑制不安全的未用额度,且任何估算不得为负或低于已确认使用值。 +- [x] 迁移、重复刷新和并发 append 均幂等且可恢复。 +- [x] 通过完整 Node、浏览器、compile 门及两次允许的 Claude 审阅。 + +### 安装候选回归补记 + +- G5 的已安装 VSIX 截图暴露了一个误判:新的匿名 Codex epoch 明明有 `resetAt` 变化这一确定性重置证据,却仍被自动标成 `account-ambiguous`。不同 epoch 本已由 fingerprint 和窗口隔离,但这枚旧标记会压掉数学上有效的低可信总额度估算。 +- `4672079` 只解除“跨越连贯重置边界”的这类合成歧义,并兼容由早期 schema-2 行为写出的存储;没有 reset 证据的 fingerprint 变化仍是歧义,重叠匿名 epoch 仍然 fail closed。 +- quota/weekly 定向测试 49/49 通过。后续预览回归修订后,合成安装候选中的当前 74% 观测显示已用 `$397.50`、总额度估算 `$537.16`、未用估算 `$139.66`,并明确标为低可信度;证据未使用真实账号、路径、项目、线程或日志内容。 + +## G4A 视觉、交互与可访问性证据 + +### 单一共享视觉契约 + +- 在 Claude 与 Codex 逐字节共用的生产样式表中加入统一的间距、圆角、表面、边框、数据字体和焦点 token;摘要卡、模型折叠、图表控件、空状态及紧凑导航均使用该契约,不复制 provider 品牌色,也不把不同指标宣称为语义等价。 +- 保留 provider 原生标签、卡片数量和核算定义。自动化只比较组件几何及交互处理,不比较 provider 数值或强制语义一致。 +- 360 px 下 provider 与主导航保持单行横向滚动;8 种 UI 语言中 Claude/Codex 的全部目的页和 Compare 均检查绝对页面宽度,表格与密集图表只允许在自身明确的 scroller 内横向滚动。 + +### 键盘与辅助技术契约 + +- 主导航现实现 `tablist` / `tab` / `tabpanel`、roving tabindex、自动激活、方向键/Home/End、`aria-selected`、`aria-controls` 及同步隐藏 panel。 +- 可排序表头支持键盘并公开 `aria-sort`;图表指标公开 `aria-pressed`;可钻取柱具有可访问名称、Enter/Space、`aria-controls` 与同步 `aria-expanded`。Claude/Codex 的模型折叠保留原生键盘行为。 +- 共用 `:focus-visible` 与 reduced-motion 处理覆盖按钮、summary、输入、scroller、排序与图表钻取。新增深色 Axe 门发现抬升表面的辅助文字对比度不足;最终以编辑器底色加边框表达层级,使 Light+ 与 Dark+ 均恢复可读对比度。 + +### 验证 + +- G4A 定向浏览器门:68/68 passed(24 项可访问性/键盘、15 项响应式、29 项视觉/组件契约)。 +- 完整 Node:842 项,841 passed,0 failed,1 项因文件系统能力 skipped;完整浏览器:107/107 passed。 +- 已目检不含敏感信息的 Claude 浅色、Codex 浅色及 360 px Codex 深色 fixture,确认密度对齐、阅读顺序清楚、provider 语义完整、深色对比度可读、窄屏导航保持单行。这些仅为临时检查证据;G5 将从已安装 VSIX 生成正式截图。 + +### G4A 通过条件 + +- [x] 复用一份 token 化样式表与共享组件处理,不建立第二套 provider 设计系统。 +- [x] 保留真实的 provider 专属指标与目的页。 +- [x] 通过键盘、ARIA、焦点、reduced-motion、深浅主题、8 种语言和 360 px 验收。 +- [x] 通过完整 Node/浏览器回归,并目检代表性 fixture。 + +## G4B 综合热力图与分享证据 + +### 单一聚合链与确定性产物 + +- 在既有 Claude `DayUsage` 和 Codex daily view 上新增配置时区下的纯函数按日合并层。Claude processed = input + cache creation + cache read + output;Codex processed = input total + output total,其中 cached input 已包含在 input,reasoning 已包含在 output。 +- 同 provider/日期且数值相同的重复行保持幂等,冲突重复则 fail closed;缺失日期及单 provider 日期仍可用。Codex 日投影保留 370 行,覆盖完整闰年分享窗口及边界余量,不触发第二次日志扫描或第二套缓存。 +- 综合分享卡以显式结束日期确定性生成,使用中性非 provider 配色;每日 tooltip 同时给出 Claude、Codex 和综合值;输入 DTO 只含日期及聚合数值。隐私 canary 测试证明账号、项目、线程、路径、prompt 和日志字段无法进入 SVG。 + +### Compare 工作流与发布边界 + +- Compare 现以综合热力图作为首要内容(存在任一 provider 活动时可用)。用户可选 30 天、90 天或一年,设置 80 字符以内标题,查看明确的包含/排除预览,导出 SVG、复制相对 Markdown,或仅重置分享偏好。 +- 本地导出和 Markdown 复制不请求网络。既有 GitHub 发布器由广泛私有仓库权限改为 `public_repo`,先探测仓库公开性、默认分支及创建/更新状态;私有或无法验证目标均 fail closed;写入前必须二次确认精确 owner/repo/branch/path/action/字节数。 +- 目标字符串只在已确认写入成功后保存,凭证继续由 VS Code authentication 管理。Goal 验证只使用 mock transport,没有向真实 GitHub 写入。 + +### 验证与只读审阅 + +- 定向纯函数/host 测试:69/69 passed,覆盖公式、重复及双方均缺失日期、对称 Claude-only/Codex-only 输入、非周日起始的 30/90 天网格、确定性 SVG、隐私 canary、公开仓库权限与精确确认、分享偏好重置及 370 天源数据上限。 +- 定向浏览器:5/5 passed,覆盖 Compare 默认位置、双 provider tooltip、显式动作、偏好重置、Light+/Dark+ Axe 和 360 px 约束。 +- 最终完整 Node:862 项,861 passed,0 failed,1 项因文件系统能力 skipped;完整 Playwright:112/112 passed。 +- Claude CLI 首轮检查无阻塞并返回 GO to G5,同时指出三个低风险测试空白:Codex-only 对称输入、双方都缺失的日期、以及非周日起始的 30/90 天 SVG。`5e5bf9f` 为三项加入直接断言;允许的一次修订复核确认全部关闭,并给出最终 GO to G5。 + +### G4B 通过条件 + +- [x] 复用既有 provider 日聚合,不新增源扫描或统计缓存。 +- [x] 定义并测试无重复计量的 provider 公式、配置时区范围、重复语义和完整年度源窗口。 +- [x] 在 Compare 交付确定性 SVG、综合分享卡、相对 Markdown、自定义标题/范围和隐私预览。 +- [x] 本地导出保持离线;可选 GitHub 直发采用公开仓库权限、精确确认及纯 mock 测试。 +- [x] 通过定向及完整 Node/浏览器门。 +- [x] 获得规定的 Claude CLI 检查点结论,并关闭本轮选择修订的全部意见。 + +## G5 README、本地数据清单与已安装 VSIX 截图证据 + +### 发版文档 + +- 更新 7 个 README 版本中的 v2.3.1 说明:Claude/Codex/对比覆盖、修正后的时间范围与月份正序、额度观测和重置感知估算、综合热力图分享、本地数据边界及已知不确定性。 +- 新增面向用户的双语简表 `LOCAL-DATA.md`、`LOCAL-DATA.zh-CN.md`,并与规范性数据契约对齐,覆盖来源、派生缓存、匿名额度历史、偏好、保留期、清除入口、远程交互以及绝不保存的数据。 +- 更新 v2.3.1 CHANGELOG、package/lock 版本、精确版本公告及 8 种公告语言。版本仍明确标为未发布;没有执行 Marketplace、远程 release 或仓库发布。 + +### 真实宿主证据 + +- 在独立的临时签名 VS Code 副本中构建并安装 v2.3.1 候选 VSIX,扩展目录与 user-data 均隔离,数据源只有合成 Claude/Codex JSONL。 +- 从该安装候选截图并目检 `images/v2.3.1/codex-overview-zh-CN-dark.png`、`images/v2.3.1/codex-weekly-estimate-en-dark.png`、`images/v2.3.1/compare-heatmap-en-light.png`。 +- 三张图覆盖 Codex 概览、重置感知总额度估算以及 Compare 综合热力图/分享控件,并覆盖中英文、深浅主题;不含账号标识、本地路径、真实项目/线程标题、prompt、凭证或用户日志内容。 +- 提交前已将捕获的 JPEG 帧转码为真实 PNG 字节,并移除 EXIF 与 PNG 文本块。repository-policy 测试要求每个 README 引用三张图、每个引用文件实际存在、PNG signature/IEND 结构有效,并禁止 `eXIf`/`iTXt`/`tEXt`/`zTXt` 块。 + +### 验证与只读审阅 + +- release/document/quota 定向测试:77/77 passed。 +- 完整 Node:866 项,865 passed,0 failed,1 项因文件系统能力 skipped;完整 Playwright:112/112 passed。 +- G4B host 测试明确确认:只有精确目标写入成功后才保存 GitHub 目标偏好;重置只清理已记住的目标。G5 repository-policy 门另行保护交付截图。 +- Claude CLI 返回 **GO TO G6**,未发现阻塞项、语义错误或隐私错误。其非阻塞意见包括非英语数据清单覆盖,以及更强的截图清理证据;前者记录为未来本地化改进,后者已落实为格式/元数据自动门,并继续以目检覆盖实际渲染像素。最终 VSIX 打包、全新安装/迁移/清除路径 smoke、验收矩阵和候选 hash 属于 G6。 + +### G5 通过条件 + +- [x] 更新全部 README、CHANGELOG、版本元数据和迁移/不确定性说明。 +- [x] 跟踪与规范契约一致的双语本地数据清单。 +- [x] 从实际安装的 v2.3.1 候选生成三张隐私安全截图。 +- [x] 通过定向及完整 Node/浏览器门。 +- [x] 获得规定的 Claude CLI 检查点结论,并关闭所选证据加固项。 +- [x] 提交 G5 实现与证据(`e9a149a`)。 + +## G6 发布候选证据 + +### 本地数据控制与审计加固 + +- 在 Settings/Data 中新增本地数据清单和 7 条独立确认路径:重建 Codex 索引、清除额度历史、清除建议数据、重置 UI、重置分享偏好、清除 BYOK secret、清除全部插件派生数据。 +- 独立只读代码审计发现 5 个 blocker 和 2 个高风险点,涉及配置部分删除、Webview 假确认、额度清除竞争/隔离数据、激活写入复活及过宽 setting/迁移删除;全部在 release gate 前关闭。 +- “清除全部”现在会在任何修改前预检所有当前可见配置作用域,排空激活期自有写入,只处理精确 key/文件族,保留未知未来 `ccu.setting.*`,并验证后置条件;遇到 VS Code 无法安全更新的未注册旧配置时零删除失败关闭。 +- 额度全部清除在同一个跨进程 lease 内原子安装合法空 P2 文档,只清理精确辅助文件;范围清除面对隔离或未完成迁移证据时拒绝执行。Webview 重置采用真实 ACK,并以不含数据值的 pending-action tombstone 做幂等重试。 +- 双语规范契约和用户清单已同步上述精确存储、迁移、清除、保留、重试和宿主限制语义。 + +### 最终自动化与打包门 + +- `npm run test:release`:Node 共 897 项,896 passed、0 failed、1 项文件系统能力 skip;Playwright 116/116 passed。 +- `git diff --check` 与 TypeScript compile 通过。 +- 固定版本 `@vscode/vsce@3.9.1` 生成最终替代候选 `claude-code-usage-2.3.1-5af60b4.vsix`;仓库 verifier 确认版本 `2.3.1`、入口 `extension/out/extension.js`、107 个 entry、1,903,765 bytes。 +- 候选 SHA-256:`074d0b774b983cebd654eda59c2f6c22168607768aa99a52fb50c98ec199d7a0`。 + +### 原生 VS Code 隔离 smoke + +- 原生 VS Code `1.135.0` 把最终 VSIX 安装到全新隔离 user-data/extensions;第二个隔离配置先装截图阶段候选,再以 `--force` 覆盖安装最终候选。 +- 两个已解包 manifest 均显示 `growthjack.claude-code-usage@2.3.1`、`./out/extension.js` 和新的 Clear All 命令。已解包 runtime 与编译产物 SHA-256 完全一致:`0e86438a32225caffe130ba8326979234b7398e7a07b91cd161d2c0c9e6a2036`。 +- 仅使用合成 Claude/Codex 源数据时,原生 Extension Host 成功激活 `GrowthJack.claude-code-usage`,无插件异常。随后正常终止并重启精确隔离进程,新 Extension Host 再次无异常激活插件。 +- 两个隔离配置均成功卸载,随后扩展列表为空。VS Code 卸载后仍保留 extension globalStorage,印证“可靠删除需先显式清除”的文档说明。源 fixture 未被改写;Codex index 源文件的前后 hash 一致。 +- G5 临时截图壳未参与 G6;其 macOS crash alert 与最终 VSIX 隔离,原生 VS Code 中未复现。 + +### 安装前 Claude CLI 终审(2026-09-02) + +- 使用 Claude Code CLI `2.1.228`、Opus、`max` effort,以 safe/print/no-tools/no-session-persistence 模式只读审阅 G5 检查点 `8eac9a0` 到 G6 实现 `b435e06` 的实际 3,488 行新增、88 行删除补丁以及最终测试、包和原生宿主证据;输入流 SHA-256 为 `350582b6b76e58167f1864787c4192f07b6babf7c15911001beca3b56488fb1e`。输入不含真实日志、账号、凭证、项目内容或用户路径。 +- Claude 判定 **Release blockers: None**,最终结论为 **GO FOR USER INSTALL**。这只授权维护者进行本地安装测试,不授权 push、Marketplace、远程 release 或真实 GitHub 写入。 +- 安装验收优先覆盖三项:无 Claude/Codex 日志时直接打开“管理本地数据与隐私”;带旧明文 `claudeCodeUsage.advice.apiKey` 的升级激活;在临时 workspace 中分别验证受阻旧配置和成功 Clear All。Clear All 会删除该临时 workspace `.vscode/settings.json` 中明确拥有的 `claudeCodeUsage.*` 设置,不能在重要工作区试验。 +- 非阻塞跟进包括:补齐真实临时 globalStorage 的 Clear All 后置条件端到端测试、建议数据清除与并发迁移的竞争测试、Webview 2 秒 ACK 超时、分享偏好重置范围、以及把受阻 legacy key 精确传达给用户。任一手测若出现未处理激活失败或范围外删除,应在发布前重新开候选修复。 +- 随后的维护者预览反馈修订修改了分享工作台、热力图渲染、周额度估算、本地化文案、测试和发布文档,因此取代此前对应 `b435e06` 的包;最终复核与候选证据记录如下。 + +### 预览反馈修订与最终替代候选(2026-09-02) + +- 数据字体已恢复为 VS Code UI 字体,只有 Markdown 字段继续使用编辑器等宽字体。“对比”页改为预览优先的分享工作台,包含隐私徽标、成组卡片设置、显式操作、可折叠 Markdown 结果、桌面自适应预览,同时保留窄屏横向滚动。 +- 热力图配色可在本地选择。默认“学术紫”严格使用 `#ebedf0`、`#eee8f8`、`#d8c9f1`、`#bca5e6`、`#8668c7`、`#4f2f87`;另有三套预设和一个经校验的自定义主色。分位数并列、稀疏最大值、近白自定义色、短区间图例边界、SVG 注入、对比度、确定性输出,以及桌面完整显示 `More` 图例均有直接测试。 +- 对于内部一致的 Claude/Codex 额度观测,进行中和已结束窗口现在都会展示总额度与未用 API 等效订阅耐用度估算;未归属或边界近似证据仍可低可信度展示。只有无有效观测、确有竞争性重叠额度系列,或最后观测过旧且后续日志已超过其推导候选值时才保留破折号;最后一种情况保留低可信度总额下界,但不伪造 `$0` 未用值。 +- Claude CLI 以 print、禁用工具、禁用会话持久化的只读模式审阅了经清理的反馈修订,并给出 **GO FOR USER INSTALL**,未发现 blocker、网络/权限或隐私风险。其关于稀疏/并列分位数、自定义色对比度、provider 对称可信度、过时观测超额、附加价格文案、短区间图例边界、精确配色/source-overlap 夹具、预览语义、Axe 完整性及 UI 字体断言的非阻塞意见,均在最终门前关闭。 +- 最终替代候选通过 896/897 项 Node 测试(唯一 skip 为已记录的文件系统能力夹具)、116/116 项 Playwright、TypeScript compile、`git diff --check`、双语视觉 QA 和仓库 VSIX policy verifier。最终英文浅色与中文深色渲染使用合成数据并已目检,不含真实账号、项目、线程、路径或日志。 +- 原生 VS Code `1.135.0` 在同一隔离临时 profile 中把最终包强制覆盖安装到上一候选之上,并列出 `growthjack.claude-code-usage@2.3.1`。已安装的 `webview.js`、`weeklyValue.js` 和 `combinedHeatmapSvg.js` 与编译文件哈希完全一致。未发生 push、Marketplace 发布、远程 release 或真实 GitHub 写入。 +- 运行时候选 commit:`5af60b4`(包含 `5e6e5cc` 的主要反馈实现)。包:`claude-code-usage-2.3.1-5af60b4.vsix`,1,903,765 bytes,SHA-256 `074d0b774b983cebd654eda59c2f6c22168607768aa99a52fb50c98ec199d7a0`。其后的本地文档 commit 仅记录本证据,不进入 VSIX。 + +### 安装后回归修正与最终本地候选(2026-09-02) + +- 本地实现 commit `666f04c` 修复维护者安装后发现的回归:Claude 的中间范围改为配置时区下“今天 + 前 29 个自然日”,Today/30 天/月内日表统一读取 `byLocalDay`;Today 无活动时不再把空卡片误当成缺页。 +- Codex 当前周期可由最后一次真实观测给出明确标为低可信度的总额与未用耐用度估算;周额度表默认折叠。Compare 改为纵向预览优先,卡片设置紧接在分享图下方,不再保留右侧大块空白。 +- Codex 状态栏主项改为配置时区下的今日用量,额度短文本使用与 Claude 一致的“已用百分比”。tooltip 复用进度条、阈值和重置列;状态背景由当前偏好实际渲染的有效窗口中最高用量驱动,因此 `wk 40%` 与同表 `5h 96%` 并存时会正确显示红色警告。 +- 新增洛杉矶 DST/本地日边界夹具,直接断言 Today 日行等于 Today 汇总、`Today ≤ 30 天 ≤ 全部` 且物化不增加 JSONL body read;另有双额度窗口、过期窗口、provider 标签转义和真实 `renderCodex` wiring 测试。 +- 最终门:TypeScript compile;Node 903 项中 902 passed、0 failed、1 项既有文件系统能力 skip;Playwright 117/117;`git diff --check` 通过。固定 `@vscode/vsce@3.9.1` 生成 `claude-code-usage-2.3.1-regression-fix-final-20260902.vsix`,仓库 verifier 确认 107 files、1,905,981 bytes、版本 `2.3.1`、入口 `extension/out/extension.js`,SHA-256 `869149b3e6034da4341ba55fa50c2d365accb5280e9ffd16520dfc845340f5b8`。 +- 该包强制覆盖安装至隔离 VS Code/profile,仅使用合成数据。安装后的 `extension.js`、`webview.js`、`weeklyValue.js`、`statusBar.js` 与编译产物哈希完全一致;真实可访问树确认分享设置位于预览下方、两组“周期详情”默认关闭、Codex 当前 74% 可见总额/未用低可信度估算,状态栏为紧凑的 `CX 5M` / `wk 74%`。 +- Claude Code CLI `2.1.228`、Opus、`max` effort 以 safe/print/no-tools/no-session-persistence 模式先指出两个 blocker(Claude 日表口径和 Codex 状态色),修订后复核将 B1/B2 均判定 **CLOSED**、路线图判定 **ADEQUATE**,最终结论为本地候选 **GO**。复核输入流 SHA-256 为 `437fd7a5a593d4b272877f5641e6a8d3545243c9cd575e3684ed50cd29602e1a`,仅含相对路径补丁、合成证据和路线图。 +- 非阻塞一致性工作不再扩入 v2.3.1,已登记到 [`v2.4 Claude / Codex 交互一致性路线图`](../roadmap/provider-parity-v2.4.zh-CN.md):月→日、日→小时、零 JSONL 点击、刷新/重载状态保留、非 UTC/DST 守恒、稀疏范围补零、唯一可访问名称、顶层图表与状态/额度细节契约。维护清理还包括明确 `byDay`/`byLocalDay` 不变量、清除 `month` 命名漂移、结构化 tooltip 文案及 five-hour-only manager 夹具。 +- 未发生 push、Marketplace 发布、远程 release、真实 GitHub 写入或真实用户数据扫描;此前所有 VSIX 均由该包取代。 + +### 简洁设置与额度余量跟进候选(2026-09-02) + +- 跟进实现 commit `ddfe99d` 从插件 Settings 界面移除“本地数据与隐私控制”清单,同时保留仓库中的规范文档、宿主侧精确清除契约及其安全测试。设置页现在只保留一个共享的“启用分享工作台”开关:默认开启,同时控制 Compare 与供应商分享卡;关闭后完整隐藏分享界面,所有导出仍必须显式触发。 +- Compare 继续采用纵向“预览优先”,SVG 现会先铺满桌面可用宽度,再显示其下方的卡片设置;周周期详情仍默认折叠。使用合成数据完成的中文深色目检确认:开启时不再留下原右侧空洞,关闭时 Compare 汇总和两组周额度图仍完整保留。 +- Codex 额度状态栏短文本现按要求显示**剩余**比例(已用 36% 时显示 `wk 64%`)。tooltip 进度条、严重度颜色和警告阈值仍由真实已用比例驱动;独立的 `CX` token 状态项继续显示配置时区下的今日范围,而非最近任务小计。 +- 经用户授权,对当前默认 Claude profile 做了只读排查,仅检查文件/时间戳元数据和允许列出的数值用量字段。生产 loader 找到 682 个项目 JSONL,并正确重建最近 30 天为 104 条消息、2,487,790 个输出 token,但 2026-09-02 的持久化用量为 0。`history.jsonl` 中 2026-09-02 的 4 条记录都没有 usage 字段,也找不到对应项目 transcript;2026-09-01 同样没有可计量记录。既有审计台账明确记录这些 Claude CLI 审阅使用了 `--no-session-persistence`;该模式不会留下可计量 transcript/token,因此插件不能诚实回填缺失的今日/昨日数据。本次未报告或改写 prompt、response、command、凭证、路径或原始日志内容。 +- 桌面宽度修订后的最终门:TypeScript compile;Node 共 903 项,902 passed、0 failed、1 项既有文件系统能力 skip;Playwright 118/118;综合分享定向测试 6/6;`git diff --check`;ZIP 完整性;仓库 VSIX policy verifier。固定 `@vscode/vsce@3.9.1` 生成 `claude-code-usage-2.3.1-followup-final-20260902.vsix`,107 files、1,906,703 bytes,SHA-256 `33bc404ce0dc693f7d97d40dd485c8d6ea96c8727ea9b178fe978cbb101daa0f`。 +- 该包成功安装到全新的原生 VS Code 隔离 user-data/extensions,并列出 `growthjack.claude-code-usage@2.3.1`。主 checkout 未被修改。未发生 push、Marketplace 发布、远程 release 或真实 GitHub 写入;上面的只读 Claude 排查是早期候选证据之后唯一新增的真实数据访问。 + +### 验收矩阵 + +| 需求 | 实现 | 自动验证 | 截图/宿主证据 | +|---|---|---|---| +| 最近 30 天守恒、去重、月份正序 | `src/dateKeys.ts`、`src/providers/codex/codexDedup.ts`、`codexIndex.ts`、`codexUsage.ts`、`codexView.ts` | `dateKeys`、`codexDedup`、`codexIndex`、`codexUsage` 与 Webview visual/interaction suites | Codex 概览/周额度截图;原生激活与重启 | +| reasoning effort 规范化及有意义的 `unknown` | `src/providers/codex/codexSchema.ts`、`codexParser.ts`、`codexUsage.ts`、`src/webview.ts` | 当前/旧版/缺失/非法/零值/非零 effort fixture 与总量守恒 | Codex 概览截图 | +| 匿名额度历史、多次重置、稳健总额/未用估算 | `src/quotaObservationStore.ts`、`codexQuotaHistory.ts`、`src/weeklyValue.ts` | quota store/history、weekly value、竞争、隔离、迁移、歧义 fixture | 周额度截图;原生宿主生成 P2 store | +| Claude/Codex 视觉、键盘、主题和窄屏对齐 | 共享 `src/webview.ts`、`src/codexViewComponents.ts` token/组件 | accessibility、responsive、visual、interaction suites | G5 中英文、深浅主题截图 | +| Compare 综合热力图与隐私有界分享 | `src/combinedHeatmap.ts`、`combinedHeatmapSvg.ts`、`githubHeatmapPublish.ts`、`webview.ts` | 确定性 SVG、重复/冲突、时区、隐私 canary、mock GitHub、可访问性测试 | Compare 热力图/分享截图 | +| 可审计本地清单与精确清除/迁移边界 | `src/localDataControls.ts`、`extension.ts`、`settings.ts`、`quotaObservationStore.ts` | `localDataControls`、`localDataExtension`、`settingsPrivacy`、额度竞争/隔离、UI ACK suites | 原生安装/激活/重启/卸载;观察到宿主保留存储 | +| README、契约、截图和迁移披露 | 全部 README、CHANGELOG、`LOCAL-DATA*`、规范契约、release ledger | repository/release policy 与截图 metadata/privacy gates | 3 张安装候选截图 | +| 无远程副作用的可安装候选 | package manifest、编译 `out`、`.github/scripts/verify-vsix.mjs` | 完整 release gate 与 VSIX policy verifier | 2 个隔离原生配置;无 push/release/Marketplace/真实 GitHub 写入 | + +### G6 通过条件 + +- [x] 关闭只读审计全部 blocker 和高风险意见。 +- [x] 通过最终 compile、diff、完整 Node 与完整浏览器测试。 +- [x] 构建并按 policy 校验 v2.3.1 VSIX,记录 SHA-256。 +- [x] 验证隔离全新安装、候选覆盖更新、真实激活、完整进程 reload、卸载、迁移 fixture、重复刷新 fixture 和精确清除路径。 +- [x] 记录“需求 → 代码 → 测试 → 证据”验收矩阵。 +- [x] 获得安装前 Claude CLI 终审 **GO FOR USER INSTALL**,并登记人工安装检查点。 +- [x] 在 push、Marketplace 发布、远程 release 或真实 GitHub 写入之前停止。 +- [x] 提交 G6 实现与反馈修订(`b435e06`、`5e6e5cc`、`5af60b4`);其后的本地文档 commit 只负责把最终替代包证据回填到双语台账。 + +## 后续更新规则 + +每阶段必须先完成对应自动化验证,再更新本表中的 commit、测试证据、Claude 结论和风险。G6 的最终验收矩阵应由本台账中的证据生成;任何未通过项不得用截图或文案替代。 + +后续“选择单一项目、按需调用 AI 审阅输入/输出并从用量行为给出证据化建议”的能力已放入 [`v2.5.3 项目级 AI 用量审阅计划`](../superpowers/plans/2026-09-02-v2.5.3-project-ai-usage-review.zh-CN.md)。它不回填 v2.3.1,需另建 Goal 并明确授权到 R0–R4 或包含本机 Claude CLI 安全门的 R5。 diff --git a/docs/releases/v2.3.1/AI-ADVICE-EFFECTIVENESS-V2.3.1.md b/docs/releases/v2.3.1/AI-ADVICE-EFFECTIVENESS-V2.3.1.md new file mode 100644 index 00000000..0f8d8ee0 --- /dev/null +++ b/docs/releases/v2.3.1/AI-ADVICE-EFFECTIVENESS-V2.3.1.md @@ -0,0 +1,132 @@ +# v2.3.1 AI 建议有效性:候选实现说明 + +## 状态与边界 + +当前 worktree 是从正式 `v2.3.0` 基线选择性移植并继续收敛的 v2.3.1 本地候选;版本号、 +release workflow 与发布入口保持不变,尚未发布。 + +候选代码已经进入 `extension.ts`、`webview.ts` 与生产 VSIX 路径,但相关功能默认关闭。 +关闭、隐藏或未授权时不创建 AI timer、watcher、worker、network 或额外日志扫描。启用后, +只有用户先检查完整请求预览、再另行点击“发送”,才会调用现有用户配置的 BYOK endpoint。 +旧 `Get AI Advice` 命令仅打开这一统一界面;Prompt Optimizer 也使用同一 prepare → preview → +explicit Send → strict parse → local feedback 边界,不再保留一次性持久授权或宽松 parser fallback。 + +## 新增核心 + +### `src/adviceEffectiveness/contract.ts` + +`AdviceContract` 是 provider-neutral 的 v1 契约,统一保存: + +- host 生成的本地 observation 与 evidence; +- direct / correlational / proxy 证据强度; +- AI 只能引用已有证据的 explanation; +- 带 `when` 与 stop condition 的 conditional action; +- 带最小可比任务数与质量 guardrail 的 success criterion; +- host 盖章的 privacy、source、confidence、quality flags 与 provenance。 + +模型不能提供 observation、evidence、privacy 或 provenance。`createAdviceContract()` +只在整个引用图和隐私声明一致时返回 `{ ok: true }`。空 recommendations 是合法的 +“没有足够证据下结论”,不会自动补通用建议。 + +### `src/adviceEffectiveness/payload.ts` + +`buildAdviceAggregateSnapshot()` 只消费现有 `UsageData` aggregate,并通过 allow-list +重建 DTO。完整/自定义 model ID 被压成 `opus / sonnet / haiku / fable / other`;raw +record、project label/path、cwd、session、prompt、response、credential 没有目标字段。 +可远程发送的 metric 还有单独 allow-list;新增 metric 必须经过显式隐私评审。low/unknown +confidence 或仍带 quality flag 的 source 会在 payload 生成前失败,不会要求模型填补缺口。 + +`prepareAdvicePayload()` 默认生成 `aggregates-only` 的内层 evidence body,且序列化结果中完全没有 +`promptSamples` key。只有调用者额外提供: + +```ts +{ consent: 'explicit', samples: [{ text: '...' }] } +``` + +才会加入受数量、单条长度和总长度限制的 prompt 文本;sample 上的 `cwd` 等多余字段仍会被 +丢弃。`advice.userContext` 与 prompt sample 共用独立于 aggregate 的 personalization consent; +未授权时两者都不进入 body,授权后必须逐字出现在完整预览中。 + +生产路径再由 `preparedRequest.ts` 把内层 evidence body 封装为完整 Anthropic / OpenAI-compatible +provider HTTP JSON body。该 body 只序列化一次,生成 host-retained `PreparedAiInvocation`、 +`canonicalBytes` 与 SHA-256;预览从同一 bytes 解码,实际发送和同一次发送内的 retry / curl +fallback 继续复用该 Prepared bytes。API key 只在发送边界加入 header,不进入预览 body。 + +### `src/adviceEffectiveness/versionedPersistence.ts` + +生产反馈统一写入 `ccu.adviceEffectiveness.localState` v2 envelope,只接受 +`helpful / not-helpful / applied`、格式验证后的 advice/recommendation ID 与本地 epoch 时间。 +它不接受自由文本、prompt、payload、解释、endpoint、path 或 session ID。helpful 与 +not-helpful 互斥,applied 独立;再次点击已选状态会撤回并在全部状态清空时删除该条记录。 +Advice 的每条 recommendation 与 Prompt Optimizer 的每次结果都走同一个写入函数。 +损坏、未知版本或带额外字段的数据 fail closed,写失败后不会用旧快照覆盖新决定。 + +### `src/adviceEffectiveness/comparison.ts` + +`compareAdviceEffectiveness()` 是无时间/IO 依赖的 paired comparison。只有以下条件全部 +满足,才可能返回 `improved`: + +- task kind、complexity、provider、model family、effort、metric definition、单位、方向、 + quality rubric 在 pair 内和 cohort 间一致; +- coverage complete,confidence 不是 low/unknown,无未允许的 quality flag; +- 达到预先声明的最小 pair 数,数值均为有限值且 baseline 非零; +- before/after 质量证据已知,after 全部通过 rubric; +- 主指标达到阈值,同时 minimum quality 与最大允许退化两个 guardrail 都守住。 + +任何可比性、覆盖、置信度、数值或质量证据问题都返回 `insufficient-evidence`。主指标 +改善但质量退化返回 `quality-guardrail-failed`;没有达到预设幅度只返回 +`no-demonstrated-improvement`,不声称建议造成伤害或收益。 + +`comparisonPairing.ts`、`comparisonProduction.ts` 与 `comparisonResult.ts` 把这条纯比较边界接入 +真实、已净化的 provider/task-level 物化 aggregate。只有 scope、task kind、complexity、provider、 +model、effort、metric definition 与 quality rubric 全部相同,且 applied 时间能可靠划分前后时, +才形成 comparable pair。版本化 result envelope 只保存 schema、provider、measurement / recommendation +version、guardrail、replay eligibility、sample 与 result;prompt、response、session、path、正文和未知字段 +没有目标字段。无可靠 pair 时 UI 明确显示“证据不足”。 + +### `src/adviceEffectiveness/structuredOutput.ts` + +`parseStructuredAdviceOutput()` 只接受一个严格 JSON 值,并逐层拒绝未知/缺失字段、错误 +schema version、非法枚举、超长/超量内容、重复 ID、空 action/criterion 和未知证据引用。 +任一 recommendation 非法会拒绝整批。它不会剥 Markdown fence、修 JSON、接受尾随 prose、 +返回 partial batch,或把 raw 输出 fallback 成看似有效的建议;错误结果也不回显 raw 模型 +正文。`recommendations: []` 是明确的 no-conclusion 成功结果。 + +## 当前生产闭环 + +1. **本地证据**:Claude 只消费 `claudeIncrementalIndex` 已物化的同窗口 aggregate / session + summary;Codex 只消费现有结构化数值 insight 与任务级物化 aggregate,不新增日志扫描器。 +2. **独立 consent**:Advice 的 aggregate consent 与 prompt-personalization consent 分开持久化; + 默认是 aggregates-only。Optimizer 只包含用户主动粘贴的 draft,不使用持久网络授权。 +3. **exact preview / explicit Send**:host 保留完整 Prepared provider body;Webview 只持有 opaque + snapshot ID、精确 body、byte count、content type、data mode 与 SHA-256。只有另行 Send 点击会联网。 +4. **唯一生产 sender**:Advice 与 Optimizer 都进入 `sendPreparedModelRequest()` → + `sendPreparedAiInvocation()`,且只能使用配置的 BYOK key / endpoint。 +5. **strict response**:Advice 只接受 exact-shape JSON 与已知 evidence references;Optimizer 只接受 + 完整 marker / 三行 settings contract。任一失败都不显示 raw 或自由文本 fallback。 +6. **可撤销本地 feedback**:每条 Advice recommendation 和 Optimizer result 共用 v2 bounded ledger; + 不接 analytics、telemetry、contribution endpoint 或 advice payload。 +7. **有效性评估**:只有 applied 后出现严格可比的前后任务时才写 pair / result envelope;否则显示 + `insufficient-evidence`。结果是受控描述性证据,不是因果证明。 + +## 排除项与剩余边界 + +- `claudeCodeUsage.getAdvice` 只打开统一 Content 界面,不再构建旧 summary 或直接调用模型。 +- `legacyBridge.ts`、`adviceSummary.ts`、旧 demo / personalization / experiment 准备模块被排除出 VSIX, + 且 `extension.ts` / `webview.ts` 没有生产调用点;它们不能成为默认或第三条 sender。 +- 生产 backend 固定为 BYOK `api`。Claude Code OAuth/subscription 凭据仅服务既有 quota/usage, + 不用于 Advice 或 Optimizer,也不存在后台模型请求。 +- Codex remote advice 仍保持关闭;Codex recommendation 与 comparison 使用本地结构数据。 +- comparison 不做显著性或因果识别;缺少可靠 cohort、质量证据或最小样本时保持证据不足。 +- feedback 不存自由文本、不同步、不发 telemetry;Optimizer feedback 当前不触发 comparable-task comparison。 + +## 验证 + +测试平铺在 `src/test/` 与 `tests/ui/`,覆盖契约引用、完整 Prepared preview/send object identity、 +默认 aggregates-only、prompt 独立 opt-in、Optimizer 关闭态与严格 parser、敌意隐私字段注入、 +可撤销本地 feedback、真实 pairing / 版本化 result envelope、可比性 / quality guardrail 以及 +未知字段 fail-closed。候选验证仍按仓库流程运行: + +```bash +npm test +``` diff --git a/docs/releases/v2.3.1/AI-ADVICE-INTEGRATION-DESIGN-V2.3.1.md b/docs/releases/v2.3.1/AI-ADVICE-INTEGRATION-DESIGN-V2.3.1.md new file mode 100644 index 00000000..53fb5e0b --- /dev/null +++ b/docs/releases/v2.3.1/AI-ADVICE-INTEGRATION-DESIGN-V2.3.1.md @@ -0,0 +1,120 @@ +# v2.3.1 AI Advice Effectiveness: Experimental UI Design Plan + +> Status: v2.3.1 integration candidate only. The feature flag is off by default; +> this document is not a current-release commitment. + +## Goal and boundaries + +The UI answers one question: can a user see which local evidence supports an +advice candidate, exactly what would leave the device, and how effectiveness +would be judged before opting in? It extends the existing AI Advice and Prompt +Optimizer cards on the Content tab instead of adding a third top-level entry. + +Both features are off by default and create no AI network work while disabled. +When enabled, AI Advice and Prompt Optimizer use the same interaction grammar: +prepare a complete provider HTTP JSON body, preview its exact UTF-8 bytes, require +a separate explicit Send click, strictly parse the response, and offer reversible +local helpful / not-helpful / applied feedback. There is no automatic or default +model request. + +## Visual system + +- **Color:** use existing VS Code theme tokens only. Background and copy use + `--vscode-editor-background` / `--vscode-foreground`; borders and secondary + copy use `--vscode-panel-border` / `--vscode-descriptionForeground`; actions + and focus use `--vscode-button-background` / `--vscode-focusBorder`; the + snapshot uses `--vscode-editorWidget-background`. Light+ and Dark+ remain + host-owned, with no new gradient or hard-coded brand accent. +- **Type:** explanatory copy uses `--vscode-font-family` at the existing 13px + density. Metrics, byte counts, and JSON use `--vscode-editor-font-family`. + Small 10–11px status stamps never carry meaning by color alone. +- **Spacing:** reuse `.action-card`, `.model-details-stacked`, and the existing + button/input rhythm. Avoid a new oversized KPI-card language. +- **Signature:** one continuous evidence spine joins five ordered stages. The + sealed snapshot header reads `SEALED · N BYTES · SHA-256`, and its body is + decoded verbatim from the same canonical UTF-8 bytes. + +## Information architecture and wireframe + +Wide layout: + +```text +┌ AI advice effectiveness (experimental) ──────────────────────────┐ +│ [Observed] ─── [Evidence] ─── [Advice] ─── [Action] ─── [Result] │ +│ values strength conditional local feedback │ +│ sample/guardrail│ +│ │ +│ □ Allow aggregates only □ Allow prompt samples (separate, off) │ +│ [Create sealed snapshot] │ +│ ▾ SEALED · 1248 BYTES · SHA-256 · AGGREGATES ONLY │ +│ {"schemaVersion":1,...} │ +│ [Send prepared request] (disabled until a valid preview exists) │ +│ Helpful ○ Not helpful ○ Applied ○ │ +└──────────────────────────────────────────────────────────────────┘ +``` + +At narrow widths the five stages stack vertically and the spine becomes a left +rail. Consent controls and actions wrap naturally. JSON scrolls horizontally; +actual transmitted bytes are never compressed or elided. + +## Interaction and accessibility + +- Aggregate consent and prompt-personalization consent are separate values in + version-migrated VS Code `globalState`. Both start off; prompt consent is + disabled until aggregate consent is selected. Every included prompt is + visible in the sealed snapshot. +- “Create sealed snapshot” asks the extension host to prepare the object. The + host rechecks the flag and consent, serializes the complete provider body once, + and retains its canonical UTF-8 bytes. Preview text, byte count, and SHA-256 all + come from that object. The separately clicked Send action resolves the opaque + snapshot ID and passes the same Prepared object to the sole production BYOK + transport; it cannot rebuild a request from webview text. +- Prompt Optimizer has the same preview and Send stages. Its body contains only + the pasted draft plus the fixed optimizer system instruction and configured + model fields; it has no persistent “first-run authorization.” +- Advice output uses the strict evidence-referencing JSON parser. Optimizer output + uses its strict marker/settings parser. Neither repairs malformed output or + falls back to free-form prose. +- Helpful / not helpful / applied are native buttons with `aria-pressed` for + every advice recommendation and for an Optimizer result. Selecting an active + button again withdraws that value. Helpful and not helpful are mutually + exclusive; applied is independent. All mutations use the same bounded local + `globalState` envelope and never enter a remote payload. +- Every action is keyboard reachable. Headings, lists, `fieldset` / `legend`, + `aria-live`, and VS Code focus tokens give screen-reader and focus semantics. + Consent, disclosure, and provider UI state survive a webview reload. +- The result stage says “insufficient evidence” until comparable sample and + quality guardrails are met; a one-off movement is never called effective. + +## Content and privacy rules + +- The default route carries same-window aggregate numbers, coarse model families, + allow-listed metrics, confidence, and evidence references only. It never accepts + or serializes raw sessions, per-record data, prompts, responses, project paths, + cwd values, or stable session IDs. +- Long sessions use elapsed-duration as a proxy; large context uses numeric token + thresholds. A conditional “start a new session / `/clear` at a stable task + boundary” action appears only when deterministic thresholds and sample rules pass. +- Topic drift is semantic. It may enter the AI Advice model request only after + separate prompt-personalization consent, with every included prompt visible in + the exact preview. The host never infers drift from body-free signals. +- Strict parse failure, unknown persistence versions, damaged state, or incomplete + evidence closes the result and never produces a permissive fallback suggestion. +- `claudeCodeUsage.getAdvice` only reveals the unified Content surface. It does + not call a model, build a legacy summary, or open a separate Markdown result. +- `legacyBridge.ts`, `adviceSummary.ts`, and the demo/preparation modules have no + production import and are excluded from the VSIX. They are neither a default + transport nor a third sender. +- Only the configured Anthropic/OpenAI-compatible BYOK endpoint may receive these + requests. Claude Code OAuth/subscription credentials are not an AI backend, and + no preview, refresh, timer, or background task sends a model request. + +## Design critique and revision + +An early direction risked becoming another generic dashboard and a third isolated +experience. The revision embeds the evidence chain in the existing Advice card and +applies the same preview, Send, strict-result, and feedback grammar to Prompt +Optimizer. The only new visual signature is the sealed byte snapshot because it +directly supports privacy review. Narrow layouts, keyboard use, screen readers, and +theme changes remain candidate checks; with either feature disabled, its host +message seam fails closed and creates no AI network resource. diff --git a/docs/releases/v2.3.1/AI-ADVICE-INTEGRATION-DESIGN-V2.3.1.zh-CN.md b/docs/releases/v2.3.1/AI-ADVICE-INTEGRATION-DESIGN-V2.3.1.zh-CN.md new file mode 100644 index 00000000..2d1ab032 --- /dev/null +++ b/docs/releases/v2.3.1/AI-ADVICE-INTEGRATION-DESIGN-V2.3.1.zh-CN.md @@ -0,0 +1,92 @@ +# v2.3.1 AI 建议有效性:实验界面设计计划 + +> 状态:仅用于 v2.3.1 候选集成。功能开关默认关闭;本文不代表当前发布承诺。 + +## 设计目标与边界 + +界面服务于一个明确问题:用户能否先看清“哪些本地证据支持哪条建议、若继续会发送什么、 +应用后怎样判断是否有效”,再决定是否参与实验。它扩展 Content 页已有的 AI Advice 与 Prompt +Optimizer 卡片,不增加第三个顶层入口。 + +两项功能都默认关闭,关闭时不创建任何 AI 网络工作。启用后,AI Advice 与 Prompt Optimizer +使用同一种交互语法:准备完整 provider HTTP JSON body、精确预览其 UTF-8 bytes、要求用户另行 +明确点击“发送”、严格解析响应,并提供可撤销的本地“有用 / 无用 / 已应用”反馈。不存在自动或 +默认模型请求。 + +## 视觉系统 + +- **颜色**:只使用现有 VS Code 主题令牌。背景与正文使用 + `--vscode-editor-background` / `--vscode-foreground`;边界和次级文本使用 + `--vscode-panel-border` / `--vscode-descriptionForeground`;交互和焦点使用 + `--vscode-button-background` / `--vscode-focusBorder`;快照使用 + `--vscode-editorWidget-background` 与编辑器等宽字体。Light+ 与 Dark+ 均由宿主主题决定, + 不引入品牌外的渐变或硬编码强调色。 +- **字体**:说明文字沿用 `--vscode-font-family` 与现有 13px 密度;指标、字节数和 JSON + 使用 `--vscode-editor-font-family`。小型状态章保持 10–11px,但不承载唯一语义。 +- **空间**:沿用 `.action-card`、`.model-details-stacked`、现有按钮与输入组件的间距, + 保持 Content 页的信息密度,不新增“大号 KPI 卡片”风格。 +- **标志性元素**:一条连续的“证据脊柱”连接五个有序阶段;密封快照标题显示 + `SEALED · N BYTES · SHA-256`,正文逐字呈现同一组 canonical UTF-8 bytes。 + +## 信息架构与草图 + +宽屏: + +```text +┌ AI 建议有效性(实验)──────────────────────────────────────────────┐ +│ [观察] ─── [证据] ─── [建议] ─── [行动] ─── [结果] │ +│ 数值 强度 有条件 本地反馈 样本/质量护栏 │ +│ │ +│ □ 仅允许聚合数据 □ 允许附加用户 prompt(默认关,独立同意) │ +│ [生成密封快照] │ +│ ▾ SEALED · 1248 BYTES · SHA-256 · AGGREGATES ONLY │ +│ {"schemaVersion":1,...} │ +│ [发送已准备请求](只有有效预览后才启用) │ +│ 有用 ○ 无用 ○ 已应用 ○ │ +└──────────────────────────────────────────────────────────────────┘ +``` + +窄屏时五个阶段改为纵向排列,脊柱成为左侧竖线;同意项和按钮自然换行,JSON 区域横向滚动, +不压缩或省略发送字节。 + +## 交互与可访问性 + +- 两项同意分开保存于带版本迁移的 VS Code `globalState`:聚合数据默认未同意;prompt 个性化默认关闭, + 且只有聚合同意后才可选择。prompt 的正文必然出现在密封快照中。 +- “生成密封快照”只向 extension host 请求准备对象。host 再次验证实验开关与同意状态,只序列化 + 一次完整 provider body,并保留 canonical UTF-8 bytes;预览正文、byte count 与 SHA-256 都由 + 该对象派生。用户另行点击“发送”后,host 才通过 opaque snapshot ID 取回同一个 Prepared 对象, + 交给唯一生产 BYOK transport;不能从 webview 文本重建请求。 +- Prompt Optimizer 使用相同的预览与发送阶段。其 body 只包含用户粘贴的 draft、固定 optimizer + system instruction 与已配置模型字段;不存在持久的“首次运行授权”。 +- Advice 输出只进入严格的 evidence-reference JSON parser;Optimizer 输出只进入严格的 marker / settings + parser。两者都不修复畸形输出,也不 fallback 到自由文本。 +- 每条 Advice recommendation 和每次 Optimizer 结果都使用原生 `