diff --git a/.agents/mind/gotchas.md b/.agents/mind/gotchas.md new file mode 100644 index 0000000..a36ec0e --- /dev/null +++ b/.agents/mind/gotchas.md @@ -0,0 +1,6 @@ +# Gotchas + +- [2026-10-14] `claude -p "/usage"` writes a transcript into the working directory's project folder unless `--no-session-persistence` is passed; that transcript would show up in Claude token history. +- [2026-10-14] Git Bash rewrites an argument that starts with `/` (`/usage` becomes `C:/Program Files/Git/usage`). Run CLI probes from PowerShell, or set `MSYS_NO_PATHCONV=1`. The app itself starts processes with an argument list, so it is not affected. + +## Archive diff --git a/.agents/mind/index.md b/.agents/mind/index.md new file mode 100644 index 0000000..ddb8072 --- /dev/null +++ b/.agents/mind/index.md @@ -0,0 +1,14 @@ +# Project Mind — Index +> Always-loaded. Everything else is on-demand. Update TOC when files change. + +## Current Focus +- [2026-10-14] v1 on issue #1: Core collectors and store, Avalonia app, Stream Deck plugin. + +## Invariants +- No credential is ever read, stored or sent; providers are reached only through their CLIs (D2). +- Everything shipped stays NativeAOT-safe on win-x64 and linux-x64 (D1). +- A response counts once, across restarts, rescans and resumed sessions (D3, D4, D5). +- `snapshot.json` is the only interface between the app and other processes (D9). + +## Table of Contents +- `gotchas.md` — 2 entries — CLI probing pitfalls on this machine. diff --git a/.gitea/pull_request_template.md b/.gitea/pull_request_template.md new file mode 100644 index 0000000..68d0ef5 --- /dev/null +++ b/.gitea/pull_request_template.md @@ -0,0 +1,11 @@ +Closes # + +## What and why + +## Decisions + + + +## How it was tested + + diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6e80630 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,136 @@ +# FinalToken + +A small tray app that tracks Claude Code and Codex usage and limits on Windows 11 and CachyOS. It +never signs in to a provider and never handles a token: all data comes from the installed CLIs +and the files they write. A stats panel shows history, small popups warn when usage runs ahead +of or behind a limit's pace, and a Stream Deck plugin puts stats on keys. Developer: +schmidt.florian (Gitea user name). + +## Sources of truth + +- `docs/requirements.md` holds the requirements, with stable IDs (`R1`). +- `docs/decisions.md` holds the **recorded decisions** (`D1`), each with why and what it gives + up. Read the ones for your area before working in it. Cite IDs in code comments, commits and + PRs rather than restating the text. +- Each project under `src/` and `tests/` has a short `AGENTS.md`. Read it before changing the + project. + +## Recorded decisions are binding + +Build what the decisions say. When a task conflicts with one, or one looks wrong, stop: comment on +the issue with the conflict and a proposal, add `status/needs-decision`, and leave the call to the +developer. A decision changes only through a PR that edits its text in `docs/decisions.md`, keeps +the decision, why and gives-up format, and carries the `type/decision` label. + +## Layout + +| Path | What it is | +|---|---| +| `src/FinalToken.Core` | No UI. Domain model, pace (D7), collectors (D3, D4), history store (D5), refresh scheduler (D6), snapshot contract (D9), settings, plugin installer (D11) | +| `src/FinalToken.App` | Avalonia desktop app (D8): stats panel, tray, settings, popups | +| `src/FinalToken.Cli` | `finaltoken` console: runs a refresh and prints the snapshot, for scripts and checks | +| `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) | +| `tests/*` | One test project per tested project, named `.Tests` | +| `tools/` | Repository tools, listed under [Tools](#tools) | + +## Rules for code + +- Current C# 14 on .NET 10: file-scoped namespaces, primary constructors, collection expressions, + `required` and `init`, pattern matching, `System.Threading.Lock`. Nullable reference types on. +- NativeAOT-safe everywhere (D1): System.Text.Json source generation, Avalonia compiled bindings, + no reflection-driven serialization, binding or loading, no `dynamic`, no runtime code + generation. Trim and AOT analyzer warnings are errors; never suppress one without a one-line + reason at that spot. +- Never touch credentials (D2): do not open credential files, environment secrets or keychains, + never log message text, and never call a provider's HTTP API. +- Child processes (`claude`, `codex`) run without a shell, with arguments as a list, a timeout and + cancellation, and are killed with their process tree when they overrun (D6). +- Every file the app writes for itself is written atomically (D5). +- Paths come from `Environment.GetFolderPath`, `Path.Combine` and the environment overrides named + in D3 and D4, never from hard-coded drive letters or `/home/`. +- Parsers of CLI output and files are total: unknown or malformed input becomes a diagnostic, + never an exception that stops a refresh, and never a guessed value. +- A new package needs a justification in its PR and must be NativeAOT-compatible. Package + versions live in `Directory.Packages.props`. +- New behaviour has tests. Parser tests use small, hand-written fixtures under the test project; + never copy a real transcript or rollout into the repo. + +## Workflow + +1. **Issue first.** Find or create the Gitea issue at + `https://git.finalfactory.de/FinalFactory/FinalToken` and assign it to schmidt.florian. Put + the plan on the issue as a checklist and keep it current. Give it a `type/` label. Claim agent + work with the [active agent labels](#active-agent-labels). +2. **One branch per issue, in its own worktree:** branch `-` from `origin/master`, + checked out at `../FinalToken-wt/-`. +3. **Commit** with an `area: summary` subject (`docs:`, `tools:`, `core:`, `app:`, + `streamdeck:`, `cli:`), a body that says why, and `Refs #N`. Push after every commit. +4. **Open a PR** into `master` with a body that follows `.gitea/pull_request_template.md` and says + `Closes #N`. The PR title becomes the squash commit subject, so it follows the commit style. +5. **Review.** After the last push, start a fresh reviewer as described in + `docs/agents/review.md`. Fix blocking findings, push, and start a new review. +6. **Merge** with a squash merge once the review passes, then delete the branch and remove the + worktree. + +Codex workers use GPT-6.1 Sol, model ID `gpt-6.1-sol`. Never select GPT-6 Sol or `gpt-6-sol`. + +### Active agent labels + +| Label | Meaning | +|---|---| +| `status/in-progress` | At least one agent works on the issue now | +| `agent/florian` | The active agents work for schmidt.florian | +| `model/` | An active agent uses this exact model ID | + +- Add `status/in-progress`, `agent/florian` and each active model's label when work starts, and + post a claim comment with the models, their roles, the branch and the worktree. +- The coordinating agent keeps labels and comments current; workers report to it and do not edit + the issue. Remove a model label when its last agent stops, and all three kinds when none runs. +- Add and remove single labels. Never replace the issue's label list. + +### Workers + +The coordinating agent briefs workers, answers their questions and keeps the commits, pushes, +issue comments and the PR. Workers leave their changes uncommitted, end with a summary of the +commands they ran and their results, and list open questions under `QUESTIONS:`. Never let two +agents edit the same files at once. + +## When you are stuck + +- **Stop** when the same problem survives two attempts, or as soon as something proves + impossible. Comment on the issue with what you tried, what failed and what you need, and set + `status/blocked` or `status/needs-decision`. +- **The review loop has a limit:** after a PR's second failed review, the developer decides how + it goes on (`docs/agents/review.md`). + +## Building and testing + +Run every command from the repository root. + +| Command | What it does | +|---|---| +| `dotnet build FinalToken.slnx -c Release` | Builds everything; any warning fails | +| `dotnet test --solution FinalToken.slnx -c Release` | Runs every test project | +| `python -B tools/docs/check_docs.py` | Checks that local links and anchors resolve, that each ID is defined once and that every cited ID exists | + +Every change runs the build, the affected tests and the documentation check. UI changes also need +a screenshot of each changed view: compiling is not working. + +## Tools + +- `tools/docs/check_docs.py`: the documentation check; its tests are + `python -B tools/docs/test_check_docs.py`. +- `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`. +- `tools/agent-review.sh`: posts an agent review and sets the `agent-review` status; see + `docs/agents/review.md`. + +## Writing + +Docs, commit messages and PR bodies use plain, short sentences in the style of +`docs/decisions.md`. Link issues as +`[#1](https://git.finalfactory.de/FinalFactory/FinalToken/issues/1)`. + +## Shared memory + +Durable lessons (a gotcha, a convention, a command) go into this file, a project's `AGENTS.md` or +`.agents/mind/`, through a PR. Session state and handoffs go in issue comments. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/docs/agents/review.md b/docs/agents/review.md new file mode 100644 index 0000000..66b3284 --- /dev/null +++ b/docs/agents/review.md @@ -0,0 +1,70 @@ +# Agent review + +Every PR needs a passing review from a fresh agent session before it merges. The review sets the +`agent-review` commit status on the PR's head commit. A push after the review moves the head, so +the PR needs a new review. + +## Starting a review (author) + +After the last push, start a reviewer that has none of the work's context: a new agent session, or +a subagent whose whole prompt is `Review PR # of FinalFactory/FinalToken following +docs/agents/review.md`. Use a capable model at high effort. The PR body, the issue and the earlier +reviews on the PR explain the change; the reviewer gets no other briefing. + +## Reviewing (reviewer) + +1. Record the head commit you review: + `tools/gitea.sh GET /repos/FinalFactory/FinalToken/pulls/ | jq -r .head.sha`. +2. Read the PR, its linked issue, the root `AGENTS.md`, the `AGENTS.md` of every touched project, + the [requirements](../requirements.md) and the [recorded decisions](../decisions.md) the change + touches, and the earlier agent reviews on the PR. +3. Read the whole diff: `git fetch origin && git diff origin/master...`. On a re-review it is + context; step 5 says what can block. +4. Check out the head in a separate worktree and run the checks in + [AGENTS.md](../../AGENTS.md#building-and-testing) that the change affects, always including + `python -B tools/docs/check_docs.py`. +5. If the PR already has a failed agent review, this is a re-review. Check that each blocking + finding of the last failed review is fixed or answered. Then review only the author's commits + since the commit that review covered (named in its first line), leaving out what came in from + `master`: `git log -p --no-merges ^ ^origin/master `. Only these two can block. + Anything else you notice is a note, even a bug; the author decides whether to fix it in this + PR. A full pass in every round finds new problems each time, and the loop never ends. +6. Look for: + - **Spec**: it does what the issue asks and stays inside its scope. + - **Decisions**: it matches the recorded decisions, or the PR changes their text and carries + the `type/decision` label. + - **Correctness**: bugs, edge cases, error handling, concurrency, resource cleanup. + - **Rules**: the rules in `AGENTS.md` and in the touched projects' `AGENTS.md`. + - **Tests**: new behaviour has tests. + - **Docs**: docs and `AGENTS.md` files match the new behaviour, commands and decisions. +7. Decide the verdict. `fail` only for a blocking finding: a bug, missing behaviour the issue asks + for, code that breaks a recorded decision or a rule from step 6, missing tests for new + behaviour, or a failing check. A check or tool that misses some cases does not break the rule + it guards: name the gap as a note. Everything else is a note and the review passes. +8. Write the review to a file in this format, then post it with + `tools/agent-review.sh `: + + ```markdown + ## Blocking + + 1. `path:line`: what is wrong, why it matters, and the fix. + + ## Notes + + - `path:line`: the suggestion. + + ## Checked + + What you read and ran, on which commit. + ``` + +The reviewer reports and leaves the code to the author. + +## After a failed review (author) + +Fix each blocking finding, or answer it in a PR comment when it is wrong. Push, then start a new +fresh review. + +After the second failed review, stop. Comment on the issue with the open findings, add the +`status/needs-decision` label and leave it to a developer: merge anyway, allow more rounds, split +the PR or close it. diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 0000000..7de98fa --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,207 @@ +# Recorded decisions + +These bind. Each says what was decided, why, and what it gives up. A decision changes only through +a PR that edits its text here and carries the `type/decision` label. Code, commits and PRs cite +the IDs instead of restating the text. The requirements (R1 to R7) are in +[requirements.md](requirements.md). + +## D1 — .NET 10, C# 14 and NativeAOT for win-x64 and linux-x64 + +**Decision.** Every shipped executable (the app, the CLI and the Stream Deck plugin) targets +`net10.0` with C# 14 and publishes NativeAOT for `win-x64` and `linux-x64`. `global.json` asks +for SDK 10.0.100 or newer within 10.0 (`rollForward: latestFeature`), so the SDK from CachyOS's +package manager works too. Builds treat warnings as errors and run the trim and AOT analyzers. +JSON goes through System.Text.Json source generation only. Nothing uses reflection-driven +serialization, binding or loading, or runtime code generation. + +**Why.** R1. .NET 10 is the newest stable release on 2026-10-14; .NET 11 is not released yet. + +**Gives up.** .NET 11 preview features, and libraries that need reflection at run time. + +## D2 — The CLIs are the only interface to a provider + +**Decision.** FinalToken never reads, stores, logs or sends a credential (OAuth token, API key, +cookie). It never opens a provider login and never calls a provider's HTTP API itself. It reads +the files the CLIs write and runs the installed `claude` and `codex` executables as child +processes, which use their own login. It never opens credential files such as +`~/.claude/.credentials.json` or `~/.codex/auth.json`, or the OS keychain. Only counts, model +names, timestamps and project paths leave a parser; message text is never kept. A missing or +logged-out CLI makes its provider show "unavailable" with the reason, and the other provider keeps +working. + +**Why.** R2, R3. + +**Gives up.** Whatever the CLIs do not expose, and limit data while a CLI is not installed. + +## D3 — Claude data sources + +**Decision.** + +- **Tokens.** The transcripts `/projects/**/*.jsonl`, where `` is + `CLAUDE_CONFIG_DIR` or `~/.claude`. Each assistant entry gives `message.usage` (input, output, + cache creation and cache read tokens), `message.model`, `timestamp` and `cwd` (the project). + One API response can appear on several lines, and a resumed session copies earlier ones, so a + response counts once, keyed on `message.id` and `requestId`. +- **Limits.** `claude -p "/usage" --output-format json --no-session-persistence`, run with + FinalToken's data directory as the working directory. Claude Code answers it locally + (`num_turns` 0, cost 0) and `--no-session-persistence` keeps it out of the transcripts. The + `result` text holds lines such as + `Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)` and + `Current week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)`. Each becomes a + limit window: the session window is 5 h, a week window 7 d. A line that does not parse is + reported as a diagnostic and skipped; the parser never guesses a value. + +**Why.** Claude Code has no machine-readable limit command, and `/usage` is the CLI's own view. +Claude Code deletes transcripts after `cleanupPeriodDays` (30 days by default), so history +comes from FinalToken's own store ([D5](#d5--own-history-store)), not from re-reading +transcripts. + +**Gives up.** Reset times are known only to the minute, and a Claude Code release can change the +text. Fixtures pin the known formats so a change fails visibly. + +## D4 — Codex data sources + +**Decision.** + +- **Tokens.** The rollouts `/sessions/**/rollout-*.jsonl` and + `/archived_sessions/**/rollout-*.jsonl`, where `` is `CODEX_HOME` or `~/.codex`. + `event_msg` entries of type `token_count` carry `info.total_token_usage` (input, cached input, + output and reasoning output tokens). A session's usage is the increase of that total between + consecutive events, so a repeated event adds nothing. The model comes from the latest + `turn_context` entry before the event. +- **Limits.** `codex app-server` over stdio JSON-RPC: `initialize`, then + `account/rateLimits/read`. The fallback is the latest `rate_limits` object in the newest + rollout: `primary` and `secondary` windows with `used_percent`, `window_minutes` and + `resets_at` in Unix seconds. + +**Why.** R2, R3. The app server is the CLI's machine interface, and the rollouts are written on +every turn. + +**Gives up.** The app server is marked experimental; the rollout fallback keeps limits working +when it changes. + +## D5 — Own history store + +**Decision.** FinalToken keeps its own history in its data directory, which is +`Environment.SpecialFolder.LocalApplicationData/FinalToken` (`%LOCALAPPDATA%\FinalToken` on +Windows, `~/.local/share/FinalToken` on Linux). It holds hourly token buckets per provider, model +and project, and every limit sample (time, provider, window, used percent, reset). The files are +JSON or JSON lines through System.Text.Json source generation, written atomically: a temporary +file in the same directory, then a replace. There is no database dependency. Scanning is +incremental: for each source file the store remembers how far it read and reads only appended +bytes. A file that shrank or was replaced is read again from the start. A response counts once +across restarts, rescans and resumed sessions. + +**Why.** R4 needs history longer than the CLIs keep theirs ([D3](#d3--claude-data-sources)). A +file store has no native dependency to ship with NativeAOT. + +**Gives up.** Ad-hoc queries, and token history finer than an hour. + +## D6 — Refresh + +**Decision.** Token scans run when a watched source directory changes (debounced by 2 s) and at +least every 60 s. Limit probes ([D3](#d3--claude-data-sources), [D4](#d4--codex-data-sources)) +run every 5 min by default (configurable from 1 to 60 min), and also after new tokens arrive, +but at most once a minute per provider. Probes run one at a time per provider with a 60 s +timeout; a probe that times out has its process tree killed and counts as failed. A failed probe +keeps the last good sample and marks it with its age. Shutting down cancels the running work +and waits for it. + +**Why.** Limits change only when tokens are spent, and a probe starts a CLI process, so probing +follows token activity instead of a tight timer. + +**Gives up.** Limit changes caused by other devices or the web show up only at the next timed +probe. + +## D7 — Pace + +**Decision.** For a limit window with used percent `u`, length `W` and reset time `r`, at time `t`: + +- elapsed fraction `e = 1 − (r − t) / W`, clamped to 0..1 +- expected use `100·e`, pace delta `d = u − 100·e` in percentage points +- **ahead** when `d ≥ +threshold`; **behind** when `d ≤ −threshold` and `e ≥ 0.5`; **on track** + otherwise. The threshold defaults to 10 points and is a setting. +- when ahead, the projected time of reaching 100 % at the average rate so far, + `t + (100 − u) · e·W / u`, shown only if it comes before `r`. + +A window without a known length or reset has no pace; FinalToken never guesses one. + +**Why.** R5. A straight line from the window's start to its reset is a pace the user can check +by hand. + +**Gives up.** Weekday and working-hour patterns. + +## D8 — Desktop app + +**Decision.** + +- **Toolkit.** Avalonia, the newest stable release that supports NativeAOT (checked on nuget.org + when the app is built), with the Fluent theme, compiled bindings only and CommunityToolkit.Mvvm + source generators. Charts are small custom controls drawn with Avalonia's `DrawingContext`; + there is no chart library. +- **Lifecycle.** One instance per user; starting it again brings the running one to the front. + The tray icon offers Open, Refresh now, Settings and Quit. Closing the window keeps the app + running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an + opt-in setting. +- **Popups (R5).** A small borderless, topmost window that does not take focus, at the + bottom right of the primary screen's work area. It goes away after 8 s or on a click; a click + opens the stats panel. A popup shows when a window's pace state ([D7](#d7--pace)) changes to + ahead or behind, at most once per window and state until the state changes again, with + hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per + provider and per state. +- **Linux.** The app runs on Avalonia's X11 backend, under XWayland on CachyOS's KDE Plasma + Wayland session, because Wayland clients cannot place their own windows. + +**Why.** R1, R4, R5. Avalonia is the cross-platform .NET UI toolkit with NativeAOT support. A +chart library would add reflection and size for three chart types. + +**Gives up.** Native OS notification styling, and a native Wayland window. + +## D9 — The snapshot file is the app's only output to other processes + +**Decision.** After each refresh the app writes `snapshot.json` atomically to its data directory +([D5](#d5--own-history-store)). It carries a schema version `v` (1 to begin with), the time it +was made, the refresh interval, the path of the app's executable and, per provider, its status +and reason, its limit windows (used percent, reset, length, pace state, delta and projection) +and its token totals for today, the current session window and the current week. The DTOs and +their source-generated JSON context live in `FinalToken.Core`, shared by the app, the CLI and the +Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a +snapshot older than three refresh intervals as stale. + +**Why.** R6 needs the stats outside the app. A file has no network surface, and it survives a +restart of either side. + +**Gives up.** Updates faster than the reader's poll interval. + +## D10 — Stream Deck plugin + +**Decision.** The plugin's UUID is `de.finalfactory.finaltoken`, its folder +`de.finalfactory.finaltoken.sdPlugin`, its manifest SDK version 2. The plugin executable is C# +NativeAOT: `CodePathWin` for Elgato Stream Deck on Windows, and `CodePathLin` for OpenDeck on +Linux, since Elgato's software does not run there. It speaks the Stream Deck WebSocket protocol +itself through `System.Net.WebSockets`, without an SDK package. It reads `snapshot.json` +([D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes)) and draws each key as +an SVG image through `setImage`. One action, "Stat", has a property inspector (HTML in the +plugin folder) that picks the provider and the metric: session percent, week percent, pace +delta, time to reset, tokens today or tokens this week. The key's colour follows the pace state. +A key press opens the app's stats panel. A missing or stale snapshot shows "offline". + +**Why.** R6 and R1 with one language and one snapshot contract. + +**Gives up.** The helpers of Elgato's Node SDK, and marketplace distribution. + +## D11 — Plugin install and update + +**Decision.** A setting has three values: Off, Ask (the default) and Automatic. The app ships the +built plugin folder at `/streamdeck/de.finalfactory.finaltoken.sdPlugin`. On start +it compares the shipped manifest's `Version` with the installed plugin's. The install targets are +`%APPDATA%\Elgato\StreamDeck\Plugins\` on Windows and OpenDeck's plugin directory on Linux, +native or Flatpak. Ask shows a popup with Install (or Update) and Not now; Automatic installs +without asking. An install replaces the plugin folder. When the Stream Deck software is running, +the app stops it first and starts it again afterwards. Nothing is installed while the setting is +Off, or in Ask mode before the user presses Install. When no Stream Deck software is found, the +setting says so and nothing happens. + +**Why.** R7. + +**Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks. diff --git a/docs/requirements.md b/docs/requirements.md new file mode 100644 index 0000000..03ec976 --- /dev/null +++ b/docs/requirements.md @@ -0,0 +1,14 @@ +# Requirements + +Set by schmidt.florian on 2026-10-14 ([#1](https://git.finalfactory.de/FinalFactory/FinalToken/issues/1)). +Each requirement has a stable ID. [Decisions](decisions.md) say how FinalToken meets them. + +- **R1** NativeAOT on the newest .NET. Cross-platform: at least Windows 11 and CachyOS. +- **R2** No sign-in to an AI provider inside the app and no API key or OAuth token. Data comes + through the providers' command-line tools. +- **R3** Supported providers: at least Codex and Claude. +- **R4** Opening the app shows a comprehensive stats panel, history included. +- **R5** Small, non-intrusive popups remind the user when usage runs ahead of or behind the pace + of a limit. +- **R6** A Stream Deck plugin shows selected stats on its buttons. +- **R7** The app installs or updates the Stream Deck plugin automatically, as the user chooses.