feat: add FinalToken v1 for Claude and Codex usage (#2)

FinalToken v1: a NativeAOT tray app for Windows 11 and CachyOS that tracks
Claude Code and Codex usage and limits through their CLIs only, with no
provider sign-in and no tokens (R1-R7, D1-D11).

- Core: incremental collectors for Claude transcripts and Codex
  rollouts, limit probes through `claude -p /usage` and
  `codex app-server`, a journaled history store, the refresh engine,
  pace and popup decisions, and the snapshot.json contract.
- App (Avalonia): stats panel with limit bars, pace, projections, token
  totals, charts, limit history and breakdowns; tray, settings,
  non-activating pace popups, single-instance activation, start with
  the OS, and the Off/Ask/Automatic Stream Deck plugin install.
- Stream Deck plugin (SDK v2, NativeAOT) for Elgato and OpenDeck.
- finaltoken-cli, tools/publish.py, the documentation check and the
  agent review workflow.

Closes #1
This commit was merged in pull request #2.
This commit is contained in:
2026-10-14 22:11:19 +02:00
parent 6d67f157a5
commit f8afd11679
106 changed files with 6583 additions and 0 deletions
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Usage: tools/agent-review.sh <pr> <full 40-char sha> <pass|fail> <review.md>
set -euo pipefail
usage() { echo 'Usage: tools/agent-review.sh <pr> <full 40-char sha> <pass|fail> <review.md>' >&2; exit 2; }
[[ $# == 4 ]] || usage
pr=$1 sha=$2 verdict=$3 file=$4
[[ $pr =~ ^[1-9][0-9]*$ && $sha =~ ^[0-9a-f]{40}$ ]] || usage
case $verdict in
pass) state=success ;;
fail) state=failure ;;
*) usage ;;
esac
[[ -s $file && -r $file ]] || { echo "Review file '$file' is missing, empty or unreadable" >&2; exit 2; }
command -v jq >/dev/null 2>&1 || { echo 'agent-review requires jq' >&2; exit 1; }
gitea=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/gitea.sh
repo=/repos/FinalFactory/FinalToken
info=$(bash "$gitea" GET "$repo/pulls/$pr") || { echo "PR $pr not found or could not be read" >&2; exit 1; }
prstate=$(jq -er '.state' <<< "$info") || { echo "PR $pr response has no state" >&2; exit 1; }
head=$(jq -er '.head.sha' <<< "$info") || { echo "PR $pr response has no head" >&2; exit 1; }
[[ $prstate == open ]] || { echo "PR $pr is $prstate" >&2; exit 1; }
[[ $head == "$sha" ]] || { echo "PR $pr head is $head, not the reviewed $sha: review the new head" >&2; exit 1; }
url=$(jq -n --arg b "**Agent review: $verdict** on $sha" --rawfile r "$file" '{body: ($b + "\n\n" + $r)}' \
| bash "$gitea" POST "$repo/issues/$pr/comments" - | jq -er '.html_url // empty') || {
echo 'Posting the review comment failed' >&2; exit 1;
}
id=$(jq -n --arg s "$state" --arg d "agent review: $verdict" --arg u "$url" \
'{state: $s, context: "agent-review", description: $d, target_url: $u}' \
| bash "$gitea" POST "$repo/statuses/$sha" - | jq -er '.id // empty') || {
echo "The comment is posted ($url) but setting the status failed" >&2; exit 1;
}
echo "agent-review $verdict on $sha: $url (status $id)"
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Check local Markdown links, anchors and canonical R/D identifiers (Python 3.9+)."""
from collections import defaultdict
import html
import os
from pathlib import Path
import re
import sys
from urllib.parse import unquote, urlsplit
SKIP = {".git", "bin", "obj", ".artifacts", "node_modules"}
IDENTIFIER = re.compile(r"\b[RD][0-9]+\b")
LINK = re.compile(r"!?\[[^\]\n]*\]\((<[^>\n]+>|[^()\s]*(?:\([^()\s]*\)[^()\s]*)*)(?:\s+[\"'][^\n]*?[\"'])?\)")
REFERENCE = re.compile(r"^\s{0,3}\[[^\]]+\]:\s*(<[^>]+>|\S+)")
def markdown_files(root):
"""Skip build output, symlinks and nested repositories (including worktrees)."""
for directory, directories, files in os.walk(root):
directories[:] = sorted(name for name in directories if name not in SKIP
and not os.path.islink(os.path.join(directory, name))
and not os.path.lexists(os.path.join(directory, name, ".git")))
for name in sorted(files):
if name.lower().endswith(".md"):
yield Path(directory) / name
def prose_lines(text):
"""Ignore fenced code while preserving original line numbers."""
fence = None
for number, line in enumerate(text.splitlines(), 1):
marker = re.match(r"^\s*(`{3,}|~{3,})(.*)$", line)
if fence is None and marker:
fence = marker.group(1)
yield number, ""
elif fence is not None:
if marker and marker.group(1)[0] == fence[0] and len(marker.group(1)) >= len(fence) and not marker.group(2).strip():
fence = None
yield number, ""
else:
yield number, line
def anchors(text):
found, used = set(), set()
previous = ""
for _, line in prose_lines(text):
for tag in re.findall(r"<a\b[^>]*>", line, re.IGNORECASE):
found.update(html.unescape(match[1]) for match in re.findall(
r"\b(?:id|name)\s*=\s*([\"'])(.*?)\1", tag, re.IGNORECASE))
match = re.match(r"^\s{0,3}#{1,6}\s+(.+?)(?:\s+#+)?\s*$", line)
heading = match.group(1) if match else None
if heading is None and previous.strip() and re.fullmatch(r"\s{0,3}(?:=+|-+)\s*", line):
heading = previous.strip()
if heading is not None:
value = re.sub(r"!?\[([^\]]+)\]\([^)]*\)", r"\1", heading)
value = html.unescape(re.sub(r"<[^>]*>", "", value)).lower()
value = "".join(c for c in value if c.isalnum() or c in "- ").replace(" ", "-")
candidate, suffix = value, 0
while candidate in used:
suffix += 1
candidate = f"{value}-{suffix}"
used.add(candidate)
found.add(candidate)
previous = line
return found
def check(root):
root = Path(root).resolve()
errors, definitions, references, anchor_cache = [], defaultdict(list), [], {}
for path in markdown_files(root):
relative = path.relative_to(root).as_posix()
for number, line in prose_lines(path.read_text(encoding="utf-8-sig")):
where = f"{relative}:{number}"
definition = None
if relative == "docs/requirements.md":
definition = re.match(r"^- \*\*(R[0-9]+)\*\*", line)
elif relative == "docs/decisions.md":
definition = re.match(r"^## (D[0-9]+) —\s+", line)
if definition:
definitions[definition.group(1)].append(where)
references.extend((identifier, where) for identifier in IDENTIFIER.findall(line))
targets = [match.group(1) for match in LINK.finditer(line)]
reference = REFERENCE.match(line)
if reference:
targets.append(reference.group(1))
for raw in targets:
target = raw.strip("<>")
try:
parts = urlsplit(target)
except ValueError:
errors.append(f"{where}: malformed link: {target}")
continue
if parts.scheme or parts.netloc:
continue
destination = (path.parent / unquote(parts.path)).resolve() if parts.path else path
if not destination.exists():
errors.append(f"{where}: broken link: {target}")
elif parts.fragment:
if destination not in anchor_cache:
anchor_cache[destination] = (anchors(destination.read_text(encoding="utf-8-sig"))
if destination.is_file() and destination.suffix.lower() == ".md" else set())
if unquote(parts.fragment) not in anchor_cache[destination]:
errors.append(f"{where}: missing anchor: {target}")
for identifier, places in sorted(definitions.items()):
if len(places) > 1:
errors.extend(f"{where}: identifier {identifier} is defined more than once ({', '.join(places)})"
for where in places)
for identifier, where in references:
if identifier not in definitions:
errors.append(f"{where}: undefined identifier {identifier}")
return errors
def main():
errors = check(Path(__file__).resolve().parents[2])
for error in errors:
print(error)
print(f"documentation check: {len(errors)} error(s)")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
+93
View File
@@ -0,0 +1,93 @@
"""Run with python -B tools/docs/test_check_docs.py."""
from pathlib import Path
import tempfile
import unittest
from check_docs import check
class DocumentationCheck(unittest.TestCase):
def setUp(self):
self.scratch = tempfile.TemporaryDirectory(prefix="finaltoken-doc-check-")
self.root = Path(self.scratch.name)
self.write("docs/requirements.md", "# Requirements\n- **R1** A goal.\n")
self.write("docs/decisions.md", "# Decisions\n## D1 — A choice\nServes R1.\n")
self.write("README.md", "[Choice](docs/decisions.md#d1--a-choice), R1 and D1.\n")
def tearDown(self):
self.scratch.cleanup()
def write(self, relative, text):
path = self.root / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def test_clean_tree(self):
self.assertEqual([], check(self.root))
def test_broken_file_link(self):
self.write("notes.md", "[Gone](gone.md)\n")
self.assertEqual(["notes.md:1: broken link: gone.md"], check(self.root))
def test_broken_anchor(self):
self.write("notes.md", "[Gone](docs/decisions.md#gone)\n")
self.assertEqual(["notes.md:1: missing anchor: docs/decisions.md#gone"], check(self.root))
def test_repeated_heading_anchors(self):
self.write("notes.md", "# Step!\n## Step!\n## Step!\n[First](#step) [Second](#step-1) [Third](#step-2)\n")
self.assertEqual([], check(self.root))
def test_duplicate_requirement(self):
self.write("docs/requirements.md", "- **R1** First.\n- **R1** Again.\n")
errors = check(self.root)
self.assertEqual(2, len(errors))
self.assertTrue(all("identifier R1 is defined more than once" in error for error in errors))
def test_duplicate_decision(self):
self.write("docs/decisions.md", "## D1 — A choice\n## D1 — Again\n")
self.assertEqual(2, len(check(self.root)))
def test_undefined_citation(self):
self.write("notes.md", "See R99 and D99. D3D12, x64 and RD8 are unrelated.\n")
self.assertEqual(["notes.md:1: undefined identifier R99", "notes.md:1: undefined identifier D99"], check(self.root))
def test_only_canonical_files_define_ids(self):
self.write("notes.md", "- **R99** A citation here.\n## D99 — A citation here\n")
self.assertEqual(2, len(check(self.root)))
def test_fenced_code_ignored(self):
self.write("notes.md", "````python\n[Gone](gone.md) R99\n```\nD99\n````\n~~~\nR98\n~~~\n")
self.assertEqual([], check(self.root))
def test_explicit_anchors(self):
self.write("notes.md", '<a class="target" id="one"></a>\n<a name=\'two\'></a>\n[One](#one) [Two](#two)\n')
self.assertEqual([], check(self.root))
def test_code_does_not_define_anchor(self):
self.write("notes.md", '```html\n<a id="hidden">\n```\n[Hidden](#hidden)\n')
self.assertEqual(["notes.md:4: missing anchor: #hidden"], check(self.root))
def test_excluded_trees(self):
for directory in (".git", "bin", "obj", ".artifacts", "node_modules"):
self.write(f"{directory}/notes.md", "R99 [Gone](gone.md)\n")
self.write("nested/.git", "gitdir: elsewhere\n")
self.write("nested/notes.md", "R99\n")
self.assertEqual([], check(self.root))
def test_directory_encoded_path_and_external_links(self):
self.write("docs/with space.md", "# Title\n")
self.write("notes.md", "[Dir](docs) [Title](docs/with%20space.md#title) [Web](https://example.org) [Mail](mailto:[email protected])\n")
self.assertEqual([], check(self.root))
def test_reference_link(self):
self.write("notes.md", "[Gone][target]\n[target]: gone.md\n")
self.assertEqual(["notes.md:2: broken link: gone.md"], check(self.root))
def test_link_followed_by_parenthesis(self):
self.write("notes.md", "([Choice](docs/decisions.md#d1--a-choice)).\n")
self.assertEqual([], check(self.root))
if __name__ == "__main__":
unittest.main()
Executable
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env bash
# Usage: tools/gitea.sh <METHOD> <path under /api/v1> [body file | -]
set -euo pipefail
# Credentials must never appear in shell traces, even when called with bash -x.
set +x
usage() { echo 'Usage: tools/gitea.sh <METHOD> <path under /api/v1> [body file | -]' >&2; exit 2; }
[[ $# -ge 2 && $# -le 3 ]] || usage
method=$1 path=$2
[[ $method =~ ^[A-Z]+$ && $path == /* && $path != //* && $path != *$'\n'* && $path != *$'\r'* ]] || usage
scratch=$(mktemp -d)
trap 'rm -rf -- "$scratch"' EXIT
body=''
if [[ $# == 3 ]]; then
if [[ $3 == - ]]; then
cat > "$scratch/body"
body=$scratch/body
else
[[ -f $3 && -r $3 ]] || { echo "Body file '$3' is not readable" >&2; exit 2; }
body=$3
fi
fi
# Quote curl config values, including credentials containing quotes or backslashes.
config_quote() {
local value=$1
value=${value//\\/\\\\}
value=${value//\"/\\\"}
value=${value//$'\n'/\\n}
value=${value//$'\r'/\\r}
value=${value//$'\t'/\\t}
printf '"%s"' "$value"
}
if [[ -n ${GITEA_TOKEN:-} ]]; then
auth_key=header
auth_value="Authorization: token $GITEA_TOKEN"
else
credential=$(printf 'protocol=https\nhost=git.finalfactory.de\n\n' | GIT_TERMINAL_PROMPT=0 git credential fill) || {
echo 'No stored Gitea credential; set GITEA_TOKEN or configure a git credential helper' >&2
exit 1
}
username='' password=''
while IFS= read -r entry; do
case $entry in
username=*) username=${entry#username=} ;;
password=*) password=${entry#password=} ;;
esac
done <<< "$credential"
[[ -n $username && -n $password ]] || { echo 'Stored Gitea credential has no username or password' >&2; exit 1; }
auth_key=user
auth_value="$username:$password"
unset credential username password
fi
# Native Windows curl needs native paths when paths are supplied inside its config.
response=$scratch/response
if command -v cygpath >/dev/null 2>&1; then
response=$(cygpath -m "$response")
if [[ -n $body ]]; then body=$(cygpath -m "$body"); fi
fi
curl_config() {
printf '%s = ' "$auth_key"; config_quote "$auth_value"; printf '\n'
printf 'request = '; config_quote "$method"; printf '\n'
printf 'url = '; config_quote "https://git.finalfactory.de/api/v1$path"; printf '\n'
printf 'output = '; config_quote "$response"; printf '\n'
printf 'header = "Accept: application/json"\n'
if [[ -n $body ]]; then
printf 'header = "Content-Type: application/json"\n'
printf 'data-binary = '; config_quote "@$body"; printf '\n'
fi
}
status=$(curl_config | curl -q --silent --show-error --connect-timeout 15 --max-time 120 --write-out '%{http_code}' -K -) || {
echo 'Gitea request failed before receiving a successful response' >&2
exit 1
}
if [[ $status != 2?? ]]; then
echo "Gitea HTTP $status for $method $path" >&2
exit 1
fi
cat "$scratch/response"
+75
View File
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""D1/D11: publish the three NativeAOT programs and bundle the plugin assets."""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import zipfile
import xml.etree.ElementTree as ET
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('rid', choices=['win-x64', 'linux-x64'])
parser.add_argument('--out', type=Path)
parser.add_argument('--skip-app', action='store_true')
args = parser.parse_args()
root = Path(__file__).resolve().parent.parent
version = ET.parse(root / 'Directory.Build.props').findtext('.//Version')
parts = (version or '').split('.')
if len(parts) != 3 or not all(part.isascii() and part.isdigit() for part in parts):
parser.error('Directory.Build.props must define a three-part numeric Version.')
plugin_version = version + '.0'
output = (args.out or root / 'artifacts' / 'publish' / args.rid).resolve()
output.mkdir(parents=True, exist_ok=True)
if any(output.iterdir()):
parser.error('Output directory must be empty; existing files are never deleted.')
plugin = output / 'streamdeck' / 'de.finalfactory.finaltoken.sdPlugin'
with tempfile.TemporaryDirectory(prefix='finaltoken-publish-') as temporary:
for name in ['App', 'Cli', 'StreamDeck']:
if name == 'App' and args.skip_app:
continue
stage = Path(temporary) / name
subprocess.run(['dotnet', 'publish', str(root / 'src' / ('FinalToken.' + name)),
'-c', 'Release', '-r', args.rid, '-p:PublishAot=true',
'-o', str(stage)], cwd=root, check=True)
destination = plugin if name == 'StreamDeck' else output
destination.mkdir(parents=True, exist_ok=True)
for file in stage.iterdir():
if file.suffix in ['.pdb', '.dbg']:
continue
target = destination / file.name
if target.exists():
if file.is_file() and target.is_file() and file.read_bytes() == target.read_bytes():
continue
raise RuntimeError('Publish outputs collide: ' + str(target))
if file.is_dir():
shutil.copytree(file, target)
else:
shutil.copy2(file, target)
shutil.copytree(root / 'src' / 'FinalToken.StreamDeck' / 'plugin', plugin, dirs_exist_ok=True)
manifest_path = plugin / 'manifest.json'
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
manifest['Version'] = plugin_version
manifest_path.write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8')
archive = output.parent / (output.name + '.zip')
if archive.exists():
raise RuntimeError('Archive already exists: ' + str(archive))
temporary_zip = archive.with_suffix('.zip.tmp')
with zipfile.ZipFile(temporary_zip, 'w', zipfile.ZIP_DEFLATED) as bundle:
for file in sorted(output.rglob('*')):
if file.is_file():
bundle.write(file, file.relative_to(output))
os.replace(temporary_zip, archive)
for file in sorted(output.rglob('*')):
if file.is_file():
print(str(file.relative_to(output)) + ' (' + str(file.stat().st_size) + ' bytes)')
print('Archive: ' + str(archive))
print('Plugin Version: ' + plugin_version)
if __name__ == '__main__':
main()
+34
View File
@@ -0,0 +1,34 @@
"""Check release assembly and manifest versions without invoking NativeAOT."""
import contextlib
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import xml.etree.ElementTree as ET
import publish
class PublishTests(unittest.TestCase):
def test_published_manifest_uses_shared_version(self):
def fake_publish(command, **kwargs):
stage = Path(command[command.index('-o') + 1])
stage.mkdir(parents=True)
(stage / (stage.name + '.exe')).write_bytes(b'synthetic executable')
with tempfile.TemporaryDirectory(prefix='finaltoken-publish-test-') as temporary:
output = Path(temporary) / 'package'
with patch('sys.argv', ['publish.py', 'win-x64', '--out', str(output)]), \
patch.object(publish.subprocess, 'run', side_effect=fake_publish), \
contextlib.redirect_stdout(io.StringIO()):
publish.main()
version = ET.parse(Path(publish.__file__).resolve().parent.parent / 'Directory.Build.props').findtext('.//Version')
self.assertIsNotNone(version)
manifest = json.loads((output / 'streamdeck/de.finalfactory.finaltoken.sdPlugin/manifest.json').read_text(encoding='utf-8'))
self.assertEqual(version + '.0', manifest['Version'])
if __name__ == '__main__':
unittest.main()