codex-agent-hour-tracker 0.2.1__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/CHANGELOG.md +6 -0
  2. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/PKG-INFO +11 -1
  3. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/README.md +10 -0
  4. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/SECURITY.md +3 -1
  5. codex_agent_hour_tracker-0.2.2/docs/account-usage.md +23 -0
  6. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/docs/exports.md +4 -0
  7. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/pyproject.toml +1 -1
  8. codex_agent_hour_tracker-0.2.2/scripts/export_account_usage.py +14 -0
  9. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/skills/codex-agent-hour-tracker/SKILL.md +7 -0
  10. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/__init__.py +1 -1
  11. codex_agent_hour_tracker-0.2.2/src/agent_hour_tracker/account_usage.py +341 -0
  12. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/cli.py +7 -0
  13. codex_agent_hour_tracker-0.2.2/tests/test_account_usage_exporter.py +338 -0
  14. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_public_files.py +1 -1
  15. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/.gitignore +0 -0
  16. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/LICENSE +0 -0
  17. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community/api.js +0 -0
  18. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community/auth.js +0 -0
  19. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community/cookies.js +0 -0
  20. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community/crypto.js +0 -0
  21. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community/db.js +0 -0
  22. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community/score.js +0 -0
  23. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/community-env.d.ts +0 -0
  24. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/docs/community.md +0 -0
  25. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/docs/methodology.md +0 -0
  26. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/functions/api/community/[[path]].js +0 -0
  27. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/functions/community/_middleware.js +0 -0
  28. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/migrations/0001_community.sql +0 -0
  29. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/package-lock.json +0 -0
  30. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/package.json +0 -0
  31. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/scripts/sync_benchmarks.py +0 -0
  32. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/_headers +0 -0
  33. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/app.js +0 -0
  34. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/benchmarks/index.html +0 -0
  35. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/benchmarks-data.js +0 -0
  36. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/benchmarks.js +0 -0
  37. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/community/index.html +0 -0
  38. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/community.js +0 -0
  39. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/favicon.png +0 -0
  40. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/favicon.svg +0 -0
  41. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/index.html +0 -0
  42. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/score.mjs +0 -0
  43. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/social-card.png +0 -0
  44. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/site/styles.css +0 -0
  45. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/skills/codex-agent-hour-tracker/agents/openai.yaml +0 -0
  46. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/__main__.py +0 -0
  47. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/archive.py +0 -0
  48. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/benchmarks.json +0 -0
  49. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/benchmarks.py +0 -0
  50. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/metrics.py +0 -0
  51. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/report.py +0 -0
  52. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/scanner.py +0 -0
  53. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/session_io.py +0 -0
  54. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/share.py +0 -0
  55. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-api.mjs +0 -0
  56. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-auth.mjs +0 -0
  57. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-database.mjs +0 -0
  58. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-headers.mjs +0 -0
  59. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-runtime.mjs +0 -0
  60. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-score.mjs +0 -0
  61. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/community-security-auth.mjs +0 -0
  62. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/site-local.mjs +0 -0
  63. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/site-score.mjs +0 -0
  64. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/site-ui.mjs +0 -0
  65. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_archive.py +0 -0
  66. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_cli.py +0 -0
  67. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_compressed_sessions.py +0 -0
  68. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_metrics.py +0 -0
  69. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_report.py +0 -0
  70. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_scanner.py +0 -0
  71. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/tests/test_v020_reports.py +0 -0
  72. {codex_agent_hour_tracker-0.2.1 → codex_agent_hour_tracker-0.2.2}/wrangler.jsonc +0 -0
@@ -1,5 +1,11 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.2
4
+
5
+ - Add `agent-hours account-usage` for private, service-reported ChatGPT account usage JSON and daily CSV.
6
+ - Fingerprint account identity by default; require explicit flags for plaintext identity or stdout.
7
+ - Keep account usage separate from public share cards and the community scoreboard.
8
+
3
9
  ## 0.2.1
4
10
 
5
11
  - Read `.jsonl.zst` rollouts in local scans and private exports on Python 3.11–3.14.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codex-agent-hour-tracker
3
- Version: 0.2.1
3
+ Version: 0.2.2
4
4
  Summary: Measure cumulative Codex agent runtime without decoding conversation content.
5
5
  Project-URL: Homepage, https://agenthours.dev
6
6
  Project-URL: Repository, https://github.com/tim-osterhus/codex-agent-hour-tracker
@@ -61,6 +61,16 @@ codex-agent-hour-tracker --share
61
61
 
62
62
  Both command names invoke the same tool. Upgrade an existing uv installation with `uv tool upgrade codex-agent-hour-tracker`.
63
63
 
64
+ ## Private ChatGPT account usage
65
+
66
+ ```bash
67
+ agent-hours account-usage --label laptop
68
+ ```
69
+
70
+ Uses your existing ChatGPT-backed Codex login to request service-reported token summaries and daily buckets. API-key-only login is unsupported. It writes private JSON and daily CSV to `reports/account-usage/`, ignored in this repository, with no metrics printed. Choose `--output-dir` for another private location. Identity is fingerprinted by default; `--include-identity` explicitly includes plaintext identity. These exports must never enter share cards or the public scoreboard.
71
+
72
+ This is separate from archive-derived runtime. Daily history can be sparse; timezone, retention, and lifetime completeness are unknown. See [private account exports](docs/account-usage.md) for permissions, Windows, secure capture, and null values.
73
+
64
74
  ## Calculate Agent Leverage
65
75
 
66
76
  Supply your human hours for the entire report period:
@@ -34,6 +34,16 @@ codex-agent-hour-tracker --share
34
34
 
35
35
  Both command names invoke the same tool. Upgrade an existing uv installation with `uv tool upgrade codex-agent-hour-tracker`.
36
36
 
37
+ ## Private ChatGPT account usage
38
+
39
+ ```bash
40
+ agent-hours account-usage --label laptop
41
+ ```
42
+
43
+ Uses your existing ChatGPT-backed Codex login to request service-reported token summaries and daily buckets. API-key-only login is unsupported. It writes private JSON and daily CSV to `reports/account-usage/`, ignored in this repository, with no metrics printed. Choose `--output-dir` for another private location. Identity is fingerprinted by default; `--include-identity` explicitly includes plaintext identity. These exports must never enter share cards or the public scoreboard.
44
+
45
+ This is separate from archive-derived runtime. Daily history can be sparse; timezone, retention, and lifetime completeness are unknown. See [private account exports](docs/account-usage.md) for permissions, Windows, secure capture, and null values.
46
+
37
47
  ## Calculate Agent Leverage
38
48
 
39
49
  Supply your human hours for the entire report period:
@@ -14,12 +14,14 @@ The `--share` command emits a bounded aggregate designed for sharing. Sharing it
14
14
 
15
15
  ## Data boundaries
16
16
 
17
- The scanner reads local plain or Zstandard-compressed archive bytes and decodes only bounded timing and source metadata. It does not decode conversation, reasoning, or tool payloads. The CLI does not send session data over the network.
17
+ The scanner reads local plain or Zstandard-compressed archive bytes and decodes only bounded timing and source metadata. It does not decode conversation, reasoning, or tool payloads. The archive scanner does not send session data over the network. The separate `account-usage` command queries OpenAI account services through the installed Codex app-server using an existing ChatGPT-backed login; it uploads no exports.
18
18
 
19
19
  Private merge exports retain exact start timestamps, durations, source classes, and persistent hashed turn identifiers. Hashes permit correlation and do not anonymize activity. Keep these exports private. Full text and CSV reports also reveal activity patterns.
20
20
 
21
21
  Public share exports use a separate allowlist of aggregate fields. The website validates that schema, rejects private archives, and renders images locally. Importing a score does not submit it. Downloaded cards still disclose their displayed aggregates and optional human-hours assumptions.
22
22
 
23
+ Account usage exports contain token metrics and daily activity. They use fingerprinted identity by default; fingerprints permit correlation and are not anonymization. Plaintext identity requires `--include-identity`. Default output is under ignored `reports/account-usage/`; other destinations require your own Git exclusions. Files are created exclusively as mode 0600 inside a mode 0700 output directory on POSIX. Direct Windows file output fails closed because private ACLs are not verified. `--stdout` is an explicit private-data disclosure to the caller; capture it securely. Account exports never enter the share schema or scoreboard. See [account export details](docs/account-usage.md).
24
+
23
25
  ## Optional community scoreboard
24
26
 
25
27
  Publishing requires a separate confirmation on the community page. A post links your GitHub login to aggregate runtime, dates, timezone, scope, and software versions. It excludes daily rows, machine labels, turn identifiers, and human-hours assumptions. Public scores are visible to anyone and can be copied.
@@ -0,0 +1,23 @@
1
+ # Private account usage exports
2
+
3
+ `agent-hours account-usage --label laptop` writes `laptop.json` and `laptop.daily.csv` under `reports/account-usage/`. The long command alias supports the same arguments. Existing files are never overwritten. Success prints a generic message, without identity, token metrics, or dates. Use a new label for each snapshot.
4
+
5
+ The command uses an existing ChatGPT-backed Codex login. API-key-only login is unsupported. `--codex PATH` selects a native executable; Windows requires `codex.exe`, not an npm shell shim. Only `initialize`, `initialized`, `account/read` with `refreshToken: false`, and `account/usage/read` are sent. No turns, login/logout operations, credential file reads, thread filters, or export uploads occur. Errors omit protocol content, notifications, and app-server stderr.
6
+
7
+ [Official token-usage documentation](https://learn.chatgpt.com/docs/app-server#7-token-usage-chatgpt) defines nullable summary metrics and optional daily buckets. These service-reported metrics are separate from local runtime and Agent-Hour Score. The service does not document bucket timezone, retention, date filters, pagination, or lifetime completeness. Sparse history is not proof of zero use on missing dates. Null metrics and null buckets remain null in JSON; a null bucket list produces a header-only CSV, so consult JSON to distinguish null from empty history. Dates are preserved verbatim. Duplicate dates remain separate rows; diagnostics flag duplicates and leave the daily total null to avoid implying a reliable total.
8
+
9
+ JSON uses the private `agent-hours-account-usage` schema, version 1. The account contains a stable SHA-256 fingerprint of the returned email and workspace account ID, or null if neither is available. It enables correlation, not anonymity; it may change when those identity fields change. By default plaintext email, workspace name, account ID, and plan are omitted. `--include-identity` explicitly includes the allowlisted identity fields. Credentials and unknown fields are never exported. Labels are user-supplied private provenance, so avoid sensitive labels when possible.
10
+
11
+ `--output-dir DIRECTORY` selects another private location. The default `reports/` path is ignored by this repository; it is not automatically ignored in other repositories. Check your own Git exclusions. On POSIX the destination directory is mode 0700 and files are mode 0600; files are created exclusively, without replacement. Parent-directory access, storage encryption, backups, and secure transfer remain your responsibility. A write failure never falls back to stdout.
12
+
13
+ Direct Windows file output fails closed until private ACLs can be verified. Use explicit `--stdout` only to capture PRIVATE JSON on a secured POSIX host over an authorized SSH connection. For example, after configuring a private capture directory:
14
+
15
+ ```bash
16
+ mkdir -p private-capture
17
+ chmod 700 private-capture
18
+ (umask 077; set -C; ssh WINDOWS_HOST 'agent-hours account-usage --label remote --stdout' > private-capture/remote.json)
19
+ ```
20
+
21
+ Check the SSH exit status before using the result; a failed command may leave an empty or incomplete capture. Stdout remains fingerprinted unless `--include-identity` is also supplied. This mode emits JSON only and no success status text. Never paste either JSON or CSV into share cards, public issues, the website, or the community scoreboard. Neither command accepts `--share`. The existing runtime share schema and website payloads are unchanged.
22
+
23
+ The historical `python scripts/export_account_usage.py` entry point remains a wrapper with the same options, plus the private defaults above.
@@ -38,3 +38,7 @@ Precise timestamps and persistent hashes reveal activity patterns and permit cor
38
38
  ## Reproduction
39
39
 
40
40
  Use the same methodology, scope, date bounds, timezone, and input archives to reproduce a report. Individual input subtotals may overlap. Use the globally deduplicated combined total. Session histories that have been removed or rewritten can change later measurements.
41
+
42
+ ## Account usage
43
+
44
+ `agent-hours account-usage --label NAME` writes a separate private account schema and daily CSV. It cannot be merged into runtime archives or used as a public score. See [account usage](account-usage.md).
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "codex-agent-hour-tracker"
7
- version = "0.2.1"
7
+ version = "0.2.2"
8
8
  description = "Measure cumulative Codex agent runtime without decoding conversation content."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.11"
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env python3
2
+ """Compatibility entry point for the installed private account-usage exporter.
3
+
4
+ Prefer: agent-hours account-usage --label NAME
5
+ """
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ # Keep the original checkout invocation working before installation.
10
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
11
+ from agent_hour_tracker.account_usage import main
12
+
13
+ if __name__ == '__main__':
14
+ raise SystemExit(main())
@@ -33,6 +33,13 @@ Use the installed `agent-hours` CLI, or `uvx codex-agent-hour-tracker`. The pack
33
33
  - `--human-hours TOTAL` uses reported period hours; `--human-hours-per-week WEEKLY` uses an explicitly labeled prorated estimate.
34
34
  - Never invent human hours from prompt timestamps or drop low-use calendar days to improve a score.
35
35
 
36
+ ## Private account usage
37
+
38
+ - Use `agent-hours account-usage --label NAME` only when account token summaries or daily history are requested. This queries the existing ChatGPT-backed Codex login; API-key-only auth is unsupported. Never read credentials.
39
+ - Keep outputs private under ignored `reports/account-usage/` by default. Identity is fingerprinted. Use `--include-identity` only for explicitly requested plaintext identity and `--stdout` only for explicitly authorized secure capture. Never print daily history into a public result.
40
+ - Preserve nulls and sparse history. Bucket timezone, retention, and lifetime completeness are unknown. Do not infer lifetime coverage or treat missing days as zero.
41
+ - Account usage must never enter `--share`, website payloads, share cards, or the public scoreboard.
42
+
36
43
  ## Sharing
37
44
 
38
45
  - `--share` produces the canonical aggregate text card. `--share --format json` produces sanitized public score JSON for the website.
@@ -2,5 +2,5 @@
2
2
 
3
3
  __all__ = ["METHODOLOGY_VERSION", "__version__"]
4
4
 
5
- __version__ = "0.2.1"
5
+ __version__ = "0.2.2"
6
6
  METHODOLOGY_VERSION = "1"
@@ -0,0 +1,341 @@
1
+ #!/usr/bin/env python3
2
+ """Export service-reported ChatGPT account usage without reading credentials.
3
+
4
+ Run with an existing Codex ChatGPT login. Only initialize, initialized,
5
+ account/read (refreshToken=false), and account/usage/read are sent. No turns run.
6
+ The service does not document date filters, pagination, timezone, or retention;
7
+ all returned daily buckets are preserved, without implying lifetime coverage.
8
+ Source: https://learn.chatgpt.com/docs/app-server#7-token-usage-chatgpt
9
+
10
+ Example: agent-hours account-usage --label laptop
11
+ Windows: use a native codex.exe with --codex if PATH resolves to an npm .cmd shim.
12
+ Output contains private account usage; keep it outside public repositories.
13
+ Identity is fingerprinted unless --include-identity is explicitly supplied.
14
+ For remote Windows, use --stdout over SSH and capture on a
15
+ secured POSIX host; direct Windows file output fails closed (ACLs unverified).
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import csv
21
+ import datetime as dt
22
+ from collections import Counter
23
+ import json
24
+ import hashlib
25
+ import os
26
+ from pathlib import Path
27
+ import queue
28
+ import re
29
+ import shutil
30
+ import signal
31
+ import subprocess
32
+ import sys
33
+ import threading
34
+ import time
35
+
36
+ from . import __version__
37
+
38
+ DOC_URL = 'https://learn.chatgpt.com/docs/app-server#7-token-usage-chatgpt'
39
+ SUMMARY_FIELDS = ('lifetimeTokens', 'peakDailyTokens', 'longestRunningTurnSec',
40
+ 'currentStreakDays', 'longestStreakDays')
41
+ MAX_LINE = 8 * 1024 * 1024
42
+ MAX_BYTES = 32 * 1024 * 1024
43
+
44
+
45
+ class ExportError(Exception):
46
+ """A sanitized failure safe to show without protocol or credential contents."""
47
+
48
+
49
+ def resolve_codex(explicit: str | None) -> str:
50
+ candidates = [explicit] if explicit else [
51
+ str(Path('/Applications/ChatGPT.app/Contents/Resources/codex')),
52
+ str(Path.home() / 'Applications/ChatGPT.app/Contents/Resources/codex'),
53
+ shutil.which('codex'),
54
+ ]
55
+ for candidate in candidates:
56
+ if candidate and Path(candidate).is_file():
57
+ if (Path(candidate).suffix.lower() in ('.cmd', '.bat')
58
+ or (os.name == 'nt' and Path(candidate).suffix.lower() != '.exe')):
59
+ raise ExportError('PATH resolves to a Windows shell shim; pass a native codex.exe using --codex.')
60
+ return str(Path(candidate).resolve())
61
+ raise ExportError('Codex executable unavailable; pass its path using --codex.')
62
+
63
+
64
+ def close_process(process: subprocess.Popen) -> None:
65
+ # The process has its own group/session: never signal the caller's group.
66
+ if os.name == 'nt':
67
+ subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],
68
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
69
+ else:
70
+ # Signal once while the leader is still unreaped, retaining ownership of
71
+ # this group ID until all group signals are finished.
72
+ try:
73
+ os.killpg(process.pid, signal.SIGKILL)
74
+ except ProcessLookupError:
75
+ pass
76
+ try:
77
+ process.wait(timeout=5)
78
+ except subprocess.TimeoutExpired:
79
+ process.kill()
80
+ process.wait(timeout=5)
81
+ for stream in (process.stdin, process.stdout):
82
+ if stream:
83
+ stream.close()
84
+
85
+
86
+ def unique_json_object(pairs):
87
+ result = {}
88
+ for key, value in pairs:
89
+ if key in result:
90
+ raise ValueError('Duplicate JSON object key')
91
+ result[key] = value
92
+ return result
93
+
94
+
95
+ class RpcClient:
96
+ def __init__(self, command: list[str], timeout: float):
97
+ self.timeout = timeout
98
+ self.messages: queue.Queue = queue.Queue(maxsize=32)
99
+ self.stop = threading.Event()
100
+ try:
101
+ self.process = subprocess.Popen(
102
+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
103
+ stderr=subprocess.DEVNULL, start_new_session=os.name != 'nt',
104
+ creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0,
105
+ )
106
+ except OSError:
107
+ raise ExportError('Unable to launch Codex app-server.') from None
108
+ self.reader = threading.Thread(target=self._read, daemon=True)
109
+ self.reader.start()
110
+ self.next_id = 0
111
+
112
+ def _read(self):
113
+ total = 0
114
+ while not self.stop.is_set():
115
+ line = self.process.stdout.readline(MAX_LINE + 1)
116
+ total += len(line)
117
+ if len(line) > MAX_LINE or total > MAX_BYTES:
118
+ item = ExportError('App-server response exceeds the export size limit.')
119
+ elif not line:
120
+ item = ExportError('App-server closed before completing the request.')
121
+ else:
122
+ try:
123
+ item = json.loads(line, object_pairs_hook=unique_json_object)
124
+ if not isinstance(item, dict):
125
+ raise ValueError
126
+ except (ValueError, UnicodeError):
127
+ item = ExportError('App-server returned malformed JSON.')
128
+ while not self.stop.is_set():
129
+ try:
130
+ self.messages.put(item, timeout=0.1)
131
+ break
132
+ except queue.Full:
133
+ pass
134
+ if isinstance(item, ExportError):
135
+ return
136
+
137
+ def send(self, message):
138
+ try:
139
+ self.process.stdin.write((json.dumps(message) + '\n').encode())
140
+ self.process.stdin.flush()
141
+ except (OSError, ValueError):
142
+ raise ExportError('App-server connection closed.') from None
143
+
144
+ def request(self, method, params=None):
145
+ self.next_id += 1
146
+ message = {'id': self.next_id, 'method': method}
147
+ if params is not None:
148
+ message['params'] = params
149
+ self.send(message)
150
+ deadline = time.monotonic() + self.timeout
151
+ while True:
152
+ remaining = deadline - time.monotonic()
153
+ if remaining <= 0:
154
+ raise ExportError(f'App-server timed out during {method}.')
155
+ try:
156
+ item = self.messages.get(timeout=remaining)
157
+ except queue.Empty:
158
+ raise ExportError(f'App-server timed out during {method}.') from None
159
+ if isinstance(item, ExportError):
160
+ raise item
161
+ if item.get('id') != self.next_id or 'method' in item:
162
+ continue # Ignore notifications and unrelated server requests, without logging.
163
+ if 'error' in item:
164
+ code = item['error'].get('code') if isinstance(item['error'], dict) else None
165
+ if code == -32601:
166
+ raise ExportError(f'Installed Codex does not support {method}; use a compatible CLI.')
167
+ suffix = f' (RPC code {code})' if type(code) is int else ''
168
+ raise ExportError(f'App-server rejected {method}{suffix}; check existing login and CLI compatibility.')
169
+ if 'result' not in item:
170
+ raise ExportError('App-server response has no result.')
171
+ return item['result']
172
+
173
+ def close(self):
174
+ self.stop.set()
175
+ close_process(self.process)
176
+ self.reader.join(timeout=1)
177
+
178
+
179
+ def sanitize_usage(value):
180
+ if not isinstance(value, dict) or not isinstance(value.get('summary'), dict):
181
+ raise ExportError('Usage response is missing its summary.')
182
+ summary = {}
183
+ for name in SUMMARY_FIELDS:
184
+ number = value['summary'].get(name)
185
+ if number is not None and (type(number) is not int or number < 0):
186
+ raise ExportError('Usage summary contains an invalid metric.')
187
+ summary[name] = number
188
+ buckets = value.get('dailyUsageBuckets')
189
+ if buckets is not None:
190
+ if not isinstance(buckets, list):
191
+ raise ExportError('Usage daily buckets have an invalid shape.')
192
+ clean = []
193
+ for row in buckets:
194
+ if (not isinstance(row, dict) or not isinstance(row.get('startDate'), str)
195
+ or not row['startDate'] or type(row.get('tokens')) is not int or row['tokens'] < 0):
196
+ raise ExportError('Usage daily bucket contains an invalid date or token count.')
197
+ clean.append({'startDate': row['startDate'], 'tokens': row['tokens']})
198
+ buckets = clean
199
+ counts = Counter(row['startDate'] for row in buckets) if buckets is not None else None
200
+ return {
201
+ 'summary': summary, 'dailyUsageBuckets': buckets,
202
+ 'diagnostics': {
203
+ 'dailyBucketCount': len(buckets) if buckets is not None else None,
204
+ 'dailyDistinctStartDateCount': len(counts) if counts is not None else None,
205
+ 'duplicateStartDateCount': sum(count > 1 for count in counts.values()) if counts is not None else None,
206
+ 'dailyTokenTotal': (sum(row['tokens'] for row in buckets)
207
+ if counts is not None and all(count == 1 for count in counts.values()) else None),
208
+ },
209
+ }
210
+
211
+
212
+ def sanitize_account(value):
213
+ account = value.get('account') if isinstance(value, dict) else None
214
+ if not isinstance(account, dict) or account.get('type') != 'chatgpt':
215
+ raise ExportError('An existing ChatGPT-backed Codex login is required; account/read did not return one.')
216
+ clean = {'type': 'chatgpt'}
217
+ for name in ('email', 'planType', 'workspaceName'):
218
+ entry = account.get(name)
219
+ if entry is not None and not isinstance(entry, str):
220
+ raise ExportError('Account identity has an invalid shape.')
221
+ clean[name] = entry
222
+ routing = value.get('workspaceRouting')
223
+ account_id = routing.get('chatgptAccountId') if isinstance(routing, dict) else None
224
+ if account_id is not None and not isinstance(account_id, str):
225
+ raise ExportError('Account identity has an invalid shape.')
226
+ clean['chatgptAccountId'] = account_id
227
+ return clean
228
+
229
+
230
+ def read_usage(command: list[str], timeout=30):
231
+ client = RpcClient(command, timeout)
232
+ try:
233
+ client.request('initialize', {'clientInfo': {
234
+ 'name': 'agent_hour_tracker_usage_export', 'version': __version__}})
235
+ client.send({'method': 'initialized', 'params': {}})
236
+ account = sanitize_account(client.request('account/read', {'refreshToken': False}))
237
+ usage = sanitize_usage(client.request('account/usage/read'))
238
+ return {'account': account, **usage}
239
+ finally:
240
+ client.close()
241
+
242
+
243
+ def private_export(data, *, include_identity=False):
244
+ """Build the private schema, omitting plaintext account identity by default."""
245
+ account = data['account']
246
+ identity = [account.get('email'), account.get('chatgptAccountId')]
247
+ fingerprint = (hashlib.sha256(json.dumps(identity, separators=(',', ':')).encode()).hexdigest()
248
+ if any(identity) else None)
249
+ exported_account = {'type': account['type'], 'fingerprint': fingerprint}
250
+ if include_identity:
251
+ exported_account.update(account)
252
+ return {'schema': 'agent-hours-account-usage', 'schemaVersion': 1,
253
+ **data, 'account': exported_account}
254
+
255
+
256
+ def write_export(data, output_dir: Path, label: str):
257
+ if os.name == 'nt':
258
+ raise ExportError('Private Windows file ACLs are not verified; use --stdout and capture on a secured host.')
259
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,79}', label):
260
+ raise ExportError('Label must use 1–80 letters, digits, dots, underscores, or hyphens.')
261
+ output_dir.mkdir(mode=0o700, parents=True, exist_ok=True)
262
+ if os.name != 'nt':
263
+ os.chmod(output_dir, 0o700)
264
+ paths = [output_dir / f'{label}.json', output_dir / f'{label}.daily.csv']
265
+ created = []
266
+ handles = []
267
+ try:
268
+ for path in paths:
269
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
270
+ created.append(path)
271
+ handles.append(os.fdopen(fd, 'w', encoding='utf-8', newline=''))
272
+ json.dump(data, handles[0], indent=2, ensure_ascii=False)
273
+ handles[0].write('\n')
274
+ writer = csv.DictWriter(handles[1], fieldnames=['startDate', 'tokens'])
275
+ writer.writeheader()
276
+ writer.writerows(data['dailyUsageBuckets'] or [])
277
+ for handle in handles:
278
+ handle.close()
279
+ return paths
280
+ except BaseException:
281
+ for handle in handles:
282
+ handle.close()
283
+ for path in created:
284
+ path.unlink(missing_ok=True)
285
+ raise
286
+
287
+
288
+ def main(argv=None):
289
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
290
+ parser.add_argument('--codex', help='Native Codex executable (existing login is used)')
291
+ parser.add_argument('--label', required=True)
292
+ destination = parser.add_mutually_exclusive_group()
293
+ destination.add_argument('--output-dir', type=Path, help='Private directory (default: reports/account-usage; ignored in this repository)')
294
+ destination.add_argument('--stdout', action='store_true', help='Emit PRIVATE usage JSON and daily patterns to stdout; capture securely')
295
+ parser.add_argument('--include-identity', action='store_true', help='Include PRIVATE plaintext email and workspace identity in the selected output')
296
+ parser.add_argument('--timeout', type=float, default=30, help='Seconds per RPC (default: 30)')
297
+ try:
298
+ args = parser.parse_args(argv)
299
+ except SystemExit as error:
300
+ return int(error.code)
301
+ if not args.stdout and args.output_dir is None:
302
+ args.output_dir = Path('reports/account-usage')
303
+ try:
304
+ if not 0 < args.timeout <= 300:
305
+ raise ExportError('Timeout must be greater than zero and at most 300 seconds.')
306
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,79}', args.label):
307
+ raise ExportError('Invalid export label.')
308
+ if args.output_dir is not None and os.name == 'nt':
309
+ raise ExportError('Private Windows file ACLs are not verified; use --stdout and capture on a secured host.')
310
+ if args.output_dir is not None and any((args.output_dir / f'{args.label}{suffix}').exists() for suffix in ('.json', '.daily.csv')):
311
+ raise ExportError('Export already exists; choose another label or output directory.')
312
+ codex = resolve_codex(args.codex)
313
+ try:
314
+ version = subprocess.run([codex, '--version'], capture_output=True, timeout=10, check=True)
315
+ version_text = version.stdout.decode().strip()
316
+ if not re.fullmatch(r'codex-cli [A-Za-z0-9.+_-]+', version_text):
317
+ raise ValueError
318
+ except (OSError, subprocess.SubprocessError, ValueError, UnicodeError):
319
+ raise ExportError('Unable to verify Codex CLI version.') from None
320
+ data = private_export(read_usage([codex, 'app-server'], args.timeout),
321
+ include_identity=args.include_identity)
322
+ data['provenance'] = {
323
+ 'source': DOC_URL, 'method': 'account/usage/read', 'cliVersion': version_text,
324
+ 'collectedAt': dt.datetime.now(dt.timezone.utc).isoformat(), 'label': args.label,
325
+ 'dailyTimezone': None, 'dailyCoverage': 'all buckets returned; retention and lifetime completeness unknown',
326
+ }
327
+ if args.stdout:
328
+ json.dump(data, sys.stdout, ensure_ascii=False)
329
+ sys.stdout.write('\n')
330
+ else:
331
+ write_export(data, args.output_dir, args.label)
332
+ print('Exported private account usage JSON and daily CSV.')
333
+ return 0
334
+ except (ExportError, OSError, subprocess.SubprocessError):
335
+ error = sys.exc_info()[1]
336
+ print(f'Error: {error}' if isinstance(error, ExportError) else 'Error: local export operation failed.', file=sys.stderr)
337
+ return 1
338
+
339
+
340
+ if __name__ == '__main__':
341
+ raise SystemExit(main())
@@ -40,6 +40,12 @@ class _ReportInput:
40
40
  def main(argv: list[str] | None = None) -> int:
41
41
  """Run the agent-hour tracker CLI and return a process exit code."""
42
42
 
43
+ argv = list(sys.argv[1:] if argv is None else argv)
44
+ if argv and argv[0] == "account-usage":
45
+ from .account_usage import main as account_usage_main
46
+
47
+ return account_usage_main(argv[1:])
48
+
43
49
  parser = _build_parser()
44
50
  try:
45
51
  arguments = parser.parse_args(argv)
@@ -137,6 +143,7 @@ def _build_parser() -> argparse.ArgumentParser:
137
143
  parser = argparse.ArgumentParser(
138
144
  prog="agent-hours",
139
145
  description="Report cumulative Codex agent-hours from local session metadata.",
146
+ epilog="Private account tokens: agent-hours account-usage --help",
140
147
  )
141
148
  parser.add_argument(
142
149
  "--sessions-dir",
@@ -0,0 +1,338 @@
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import io
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import stat
9
+ import shutil
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ from types import SimpleNamespace
14
+ import unittest
15
+ from unittest import mock
16
+
17
+ from agent_hour_tracker import account_usage as exporter
18
+
19
+ # The fake rejects any unexpected request or ordering; no real service is used.
20
+ FAKE = r'''
21
+ import json,sys,time
22
+ scenario=sys.argv[1]
23
+ def receive(method):
24
+ value=json.loads(sys.stdin.readline())
25
+ assert value['method']==method
26
+ return value
27
+ def reply(request,result):
28
+ print(json.dumps({'id':request['id'],'result':result}),flush=True)
29
+ a=receive('initialize')
30
+ assert a['params']['clientInfo']['name']=='agent_hour_tracker_usage_export'
31
+ reply(a,{'userAgent':'fake'})
32
+ receive('initialized')
33
+ a=receive('account/read')
34
+ assert a['params']=={'refreshToken':False}
35
+ if scenario=='auth':
36
+ reply(a,{'account':None,'secret':'FAKE_SECRET'})
37
+ else:
38
+ reply(a,{'account':{'type':'chatgpt','email':'user@example.invalid','planType':'pro',
39
+ 'accessToken':'FAKE_SECRET'},
40
+ 'workspaceRouting':{'chatgptAccountId':'workspace-1','backendOrigin':'FAKE_SECRET'}})
41
+ a=receive('account/usage/read')
42
+ assert 'params' not in a
43
+ print(json.dumps({'method':'unrelated','params':{'secret':'FAKE_SECRET'}}),flush=True)
44
+ if scenario=='timeout': time.sleep(30)
45
+ elif scenario=='missing':
46
+ print(json.dumps({'id':a['id'],'error':{'code':-32601,'message':'FAKE_SECRET'}}),flush=True)
47
+ elif scenario=='error':
48
+ print(json.dumps({'id':a['id'],'error':{'code':401,'message':'FAKE_SECRET'}}),flush=True)
49
+ elif scenario=='invalidjson': print('FAKE_SECRET',flush=True)
50
+ elif scenario=='duplicatekeys': print('{"id":3,"result":{},"result":{"secret":"FAKE_SECRET"}}',flush=True)
51
+ elif scenario=='badbucket': reply(a,{'summary':{},'dailyUsageBuckets':[{'tokens':True}]})
52
+ else:
53
+ reply(a,{'summary':{'lifetimeTokens':123,'peakDailyTokens':None,'secret':'FAKE_SECRET'},
54
+ 'dailyUsageBuckets':None if scenario=='null' else [
55
+ {'startDate':'service-verbatim-date','tokens':17,'secret':'FAKE_SECRET'},
56
+ {'startDate':'2026-01-01','tokens':0}]})
57
+ time.sleep(30)
58
+ '''
59
+
60
+
61
+ class AccountUsageExporterTests(unittest.TestCase):
62
+ def setUp(self):
63
+ self.temp = tempfile.TemporaryDirectory()
64
+ self.addCleanup(self.temp.cleanup)
65
+ self.root = Path(self.temp.name)
66
+ self.fake = self.root / 'fake_server.py'
67
+ self.fake.write_text(FAKE)
68
+
69
+ def read(self, scenario='good', timeout=2):
70
+ return exporter.read_usage([sys.executable, str(self.fake), scenario], timeout)
71
+
72
+ def test_handshake_allowlist_and_verbatim_dates(self):
73
+ value = self.read()
74
+ self.assertEqual(value['summary']['lifetimeTokens'], 123)
75
+ self.assertIsNone(value['summary']['currentStreakDays'])
76
+ self.assertEqual(value['dailyUsageBuckets'][0], {'startDate': 'service-verbatim-date', 'tokens': 17})
77
+ self.assertEqual(value['account']['chatgptAccountId'], 'workspace-1')
78
+ self.assertNotIn('FAKE_SECRET', json.dumps(value))
79
+
80
+ def test_null_is_not_zero_or_empty_list(self):
81
+ value = self.read('null')
82
+ self.assertIsNone(value['dailyUsageBuckets'])
83
+ self.assertIsNone(value['summary']['peakDailyTokens'])
84
+
85
+ def test_sanitized_protocol_errors(self):
86
+ for scenario in ('missing', 'error', 'invalidjson', 'duplicatekeys', 'badbucket', 'auth'):
87
+ with self.subTest(scenario=scenario), self.assertRaises(exporter.ExportError) as raised:
88
+ self.read(scenario)
89
+ self.assertNotIn('FAKE_SECRET', str(raised.exception))
90
+ with self.assertRaisesRegex(exporter.ExportError, 'does not support'):
91
+ self.read('missing')
92
+
93
+ def test_timeout_cleans_up_owned_process(self):
94
+ client = exporter.RpcClient([sys.executable, str(self.fake), 'timeout'], .1)
95
+ try:
96
+ client.request('initialize', {'clientInfo': {'name': 'agent_hour_tracker_usage_export'}})
97
+ client.send({'method': 'initialized', 'params': {}})
98
+ client.request('account/read', {'refreshToken': False})
99
+ with self.assertRaisesRegex(exporter.ExportError, 'timed out'):
100
+ client.request('account/usage/read')
101
+ finally:
102
+ client.close()
103
+ self.assertIsNotNone(client.process.poll())
104
+ self.assertFalse(client.reader.is_alive())
105
+
106
+ @unittest.skipIf(os.name == 'nt', 'POSIX process-group assertion')
107
+ def test_timeout_cleans_child_group(self):
108
+ fake = self.root / 'child.py'
109
+ fake.write_text("import subprocess,sys,time\nsubprocess.Popen([sys.executable,'-c','import time; time.sleep(30)'])\ntime.sleep(30)\n")
110
+ client = exporter.RpcClient([sys.executable, str(fake)], .1)
111
+ group = client.process.pid
112
+ try:
113
+ with self.assertRaises(exporter.ExportError):
114
+ client.request('initialize')
115
+ finally:
116
+ client.close()
117
+ # No running process should remain in the separately owned group.
118
+ import subprocess
119
+ result = subprocess.run(['ps', '-axo', 'pgid=,stat='], capture_output=True, text=True, check=True)
120
+ running = [row for row in result.stdout.splitlines()
121
+ if row.split() and row.split()[0] == str(group) and not row.split()[1].startswith('Z')]
122
+ self.assertEqual(running, [])
123
+
124
+ def test_notifications_cannot_extend_deadline(self):
125
+ fake = self.root / 'noisy.py'
126
+ fake.write_text("import json\nwhile True: print(json.dumps({'method':'noise'}),flush=True)\n")
127
+ client = exporter.RpcClient([sys.executable, str(fake)], .1)
128
+ try:
129
+ with self.assertRaisesRegex(exporter.ExportError, 'timed out'):
130
+ client.request('initialize')
131
+ finally:
132
+ client.close()
133
+
134
+ def test_oversized_response_is_rejected_without_content(self):
135
+ fake = self.root / 'oversized.py'
136
+ fake.write_text("import time\nprint('FAKE_SECRET'*200,flush=True)\ntime.sleep(30)\n")
137
+ with mock.patch.object(exporter, 'MAX_LINE', 1024):
138
+ client = exporter.RpcClient([sys.executable, str(fake)], 2)
139
+ try:
140
+ with self.assertRaisesRegex(exporter.ExportError, 'size limit') as raised:
141
+ client.request('initialize')
142
+ self.assertNotIn('FAKE_SECRET', str(raised.exception))
143
+ finally:
144
+ client.close()
145
+
146
+ @unittest.skipIf(os.name == 'nt', 'Private file output requires POSIX permissions')
147
+ def test_write_private_outputs_and_no_overwrite(self):
148
+ data = self.read()
149
+ output = self.root / 'private'
150
+ paths = exporter.write_export(data, output, 'account-1')
151
+ self.assertEqual(json.loads(paths[0].read_text()), data)
152
+ self.assertIn('service-verbatim-date,17', paths[1].read_text())
153
+ if os.name != 'nt':
154
+ self.assertEqual(stat.S_IMODE(output.stat().st_mode), 0o700)
155
+ self.assertTrue(all(stat.S_IMODE(path.stat().st_mode) == 0o600 for path in paths))
156
+ original = paths[0].read_bytes()
157
+ with self.assertRaises(FileExistsError):
158
+ exporter.write_export(data, output, 'account-1')
159
+ self.assertEqual(paths[0].read_bytes(), original)
160
+
161
+ @unittest.skipIf(os.name == 'nt', 'Private file output requires POSIX permissions')
162
+ def test_second_collision_rolls_back_only_new_file(self):
163
+ output = self.root / 'out'
164
+ output.mkdir()
165
+ (output / 'collision.daily.csv').write_text('existing')
166
+ with self.assertRaises(FileExistsError):
167
+ exporter.write_export({'dailyUsageBuckets': None}, output, 'collision')
168
+ self.assertFalse((output / 'collision.json').exists())
169
+ self.assertEqual((output / 'collision.daily.csv').read_text(), 'existing')
170
+
171
+ @unittest.skipIf(os.name == 'nt', 'Private file output requires POSIX permissions')
172
+ def test_main_existing_output_does_not_launch(self):
173
+ output = self.root / 'out'
174
+ output.mkdir()
175
+ (output / 'a.json').write_text('existing')
176
+ stderr = io.StringIO()
177
+ with contextlib.redirect_stderr(stderr):
178
+ code = exporter.main(['--label', 'a', '--output-dir', str(output), '--codex', 'missing-secret'])
179
+ self.assertEqual(code, 1)
180
+ self.assertIn('already exists', stderr.getvalue())
181
+ self.assertNotIn('missing-secret', stderr.getvalue())
182
+
183
+ def test_duplicate_daily_dates_are_preserved_and_flagged(self):
184
+ rows = [{'startDate': 'verbatim', 'tokens': 2}, {'startDate': 'verbatim', 'tokens': 3}]
185
+ value = exporter.sanitize_usage({'summary': {}, 'dailyUsageBuckets': rows})
186
+ self.assertEqual(value['dailyUsageBuckets'], rows)
187
+ self.assertEqual(value['diagnostics'], {
188
+ 'dailyBucketCount': 2, 'dailyDistinctStartDateCount': 1,
189
+ 'duplicateStartDateCount': 1, 'dailyTokenTotal': None})
190
+
191
+ @unittest.skipIf(os.name == 'nt', 'POSIX signal ownership')
192
+ def test_group_signal_precedes_leader_reaping(self):
193
+ process = mock.Mock()
194
+ process.pid = 12345
195
+ def signal_group(pid, sig):
196
+ self.assertEqual(pid, process.pid)
197
+ self.assertEqual(sig, exporter.signal.SIGKILL)
198
+ process.poll.assert_not_called()
199
+ process.wait.assert_not_called()
200
+ with mock.patch.object(exporter.os, 'killpg', side_effect=signal_group) as kill:
201
+ exporter.close_process(process)
202
+ kill.assert_called_once()
203
+ process.wait.assert_called_once()
204
+
205
+ def test_windows_file_output_fails_closed(self):
206
+ destination = self.root / 'windows-output'
207
+ with mock.patch.object(exporter.os, 'name', 'nt'):
208
+ with self.assertRaisesRegex(exporter.ExportError, 'ACLs are not verified'):
209
+ exporter.write_export({}, destination, 'account')
210
+ self.assertFalse(destination.exists())
211
+
212
+ def test_windows_cli_file_output_fails_closed_before_launch(self):
213
+ destination = self.root / 'private-output'
214
+ destination.mkdir()
215
+ existing = destination / 'account.json'
216
+ existing.write_text('existing')
217
+ for options in ([], ['--output-dir', str(destination)]):
218
+ with self.subTest(options=options):
219
+ output, error = io.StringIO(), io.StringIO()
220
+ # Replace this module's OS reference without changing pathlib's
221
+ # host-platform behavior while parsing the output directory.
222
+ with mock.patch.object(exporter, 'os', SimpleNamespace(name='nt')), \
223
+ mock.patch.object(exporter, 'resolve_codex') as resolve, \
224
+ mock.patch.object(exporter, 'write_export') as write, \
225
+ contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
226
+ code = exporter.main(['--label', 'account', *options])
227
+ self.assertEqual(code, 1)
228
+ self.assertEqual(output.getvalue(), '')
229
+ self.assertIn('Private Windows file ACLs are not verified', error.getvalue())
230
+ resolve.assert_not_called()
231
+ write.assert_not_called()
232
+ self.assertEqual(existing.read_text(), 'existing')
233
+ self.assertFalse((destination / 'account.daily.csv').exists())
234
+
235
+ def test_stdout_is_allowlisted_json_without_status_text(self):
236
+ output = io.StringIO()
237
+ version = mock.Mock(stdout=b'codex-cli 0.1.0')
238
+ value = self.read()
239
+ with mock.patch.object(exporter, 'resolve_codex', return_value='native-codex'), \
240
+ mock.patch.object(exporter.subprocess, 'run', return_value=version), \
241
+ mock.patch.object(exporter, 'read_usage', return_value=value), \
242
+ contextlib.redirect_stdout(output):
243
+ code = exporter.main(['--label', 'remote', '--stdout'])
244
+ self.assertEqual(code, 0)
245
+ self.assertEqual(json.loads(output.getvalue())['summary']['lifetimeTokens'], 123)
246
+ self.assertNotIn('FAKE_SECRET', output.getvalue())
247
+ self.assertEqual(json.loads(output.getvalue())['provenance']['label'], 'remote')
248
+
249
+ @unittest.skipIf(os.name == 'nt', 'POSIX executable fixture')
250
+ def test_installed_aliases_private_defaults_and_no_overwrite(self):
251
+ fake_cli = self.root / 'codex'
252
+ fake_cli.write_text('#!' + sys.executable + '\n' +
253
+ "import sys\nif sys.argv[1]=='--version':\n print('codex-cli 0.1.0');sys.exit()\n" +
254
+ "sys.argv[1]='good'\n" + FAKE)
255
+ fake_cli.chmod(0o700)
256
+ for alias in ('agent-hours', 'codex-agent-hour-tracker'):
257
+ executable = shutil.which(alias)
258
+ self.assertIsNotNone(executable, 'Run tests in an installed package environment')
259
+ command = [executable, 'account-usage', '--label', alias, '--codex', str(fake_cli)]
260
+ result = subprocess.run(command, cwd=self.root, capture_output=True, text=True)
261
+ self.assertEqual(result.returncode, 0, result.stderr)
262
+ self.assertEqual(result.stdout, 'Exported private account usage JSON and daily CSV.\n')
263
+ destination = self.root / 'reports/account-usage'
264
+ output = destination / (alias + '.json')
265
+ data = json.loads(output.read_text())
266
+ self.assertEqual(data['schema'], 'agent-hours-account-usage')
267
+ self.assertEqual(data['schemaVersion'], 1)
268
+ self.assertEqual(set(data['account']), {'type', 'fingerprint'})
269
+ self.assertEqual(len(data['account']['fingerprint']), 64)
270
+ self.assertNotIn('user@example.invalid', output.read_text())
271
+ self.assertNotIn('workspace-1', output.read_text())
272
+ self.assertEqual(stat.S_IMODE(destination.stat().st_mode), 0o700)
273
+ for suffix in ('.json', '.daily.csv'):
274
+ self.assertEqual(stat.S_IMODE((destination / (alias + suffix)).stat().st_mode), 0o600)
275
+ original = output.read_bytes()
276
+ again = subprocess.run(command, cwd=self.root, capture_output=True, text=True)
277
+ self.assertEqual(again.returncode, 1)
278
+ self.assertEqual(again.stdout, '')
279
+ self.assertEqual(output.read_bytes(), original)
280
+ private_stdout = subprocess.run(command + ['--stdout'], cwd=self.root, capture_output=True, text=True)
281
+ self.assertEqual(private_stdout.returncode, 0, private_stdout.stderr)
282
+ redacted = json.loads(private_stdout.stdout)
283
+ self.assertEqual(data['account'], redacted['account'])
284
+ self.assertNotIn('user@example.invalid', private_stdout.stdout)
285
+ identified = subprocess.run(command + ['--stdout', '--include-identity'], cwd=self.root,
286
+ capture_output=True, text=True)
287
+ self.assertEqual(identified.returncode, 0, identified.stderr)
288
+ self.assertEqual(json.loads(identified.stdout)['account']['email'], 'user@example.invalid')
289
+ self.assertNotIn('FAKE_SECRET', identified.stdout + identified.stderr)
290
+ unsafe = subprocess.run(command + ['--share'], cwd=self.root, capture_output=True, text=True)
291
+ self.assertEqual(unsafe.returncode, 2)
292
+ self.assertEqual(unsafe.stdout, '')
293
+
294
+ @unittest.skipIf(os.name == 'nt', 'Private file output requires POSIX permissions')
295
+ def test_file_failure_never_falls_back_to_stdout(self):
296
+ output = io.StringIO()
297
+ stderr = io.StringIO()
298
+ version = mock.Mock(stdout=b'codex-cli 0.1.0')
299
+ with mock.patch.object(exporter, 'resolve_codex', return_value='native-codex'), \
300
+ mock.patch.object(exporter.subprocess, 'run', return_value=version), \
301
+ mock.patch.object(exporter, 'read_usage', return_value=self.read()), \
302
+ mock.patch.object(exporter, 'write_export', side_effect=OSError('private path')), \
303
+ contextlib.redirect_stdout(output), contextlib.redirect_stderr(stderr):
304
+ code = exporter.main(['--label', 'failure', '--output-dir', str(self.root / 'out')])
305
+ self.assertEqual(code, 1)
306
+ self.assertEqual(output.getvalue(), '')
307
+ self.assertEqual(stderr.getvalue(), 'Error: local export operation failed.\n')
308
+
309
+ def test_fingerprint_stability_and_identity_opt_in(self):
310
+ data = self.read()
311
+ first = exporter.private_export(data)
312
+ second = exporter.private_export(data)
313
+ self.assertEqual(first['account'], second['account'])
314
+ self.assertNotIn('email', first['account'])
315
+ self.assertEqual(exporter.private_export(data, include_identity=True)['account']['email'],
316
+ 'user@example.invalid')
317
+ self.assertIsNone(exporter.private_export({**data, 'account': {'type': 'chatgpt'}})['account']['fingerprint'])
318
+
319
+ def test_missing_client_is_sanitized_and_quiet(self):
320
+ output, error = io.StringIO(), io.StringIO()
321
+ with contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
322
+ code = exporter.main(['--label', 'missing', '--stdout', '--codex',
323
+ str(self.root / 'private-missing-client')])
324
+ self.assertEqual(code, 1)
325
+ self.assertEqual(output.getvalue(), '')
326
+ self.assertIn('Codex executable unavailable', error.getvalue())
327
+ self.assertNotIn('private-missing-client', error.getvalue())
328
+
329
+ def test_bad_metric_and_bad_label(self):
330
+ for value in (True, -1, '17', 1.5):
331
+ with self.assertRaises(exporter.ExportError):
332
+ exporter.sanitize_usage({'summary': {'lifetimeTokens': value}})
333
+ with self.assertRaises(exporter.ExportError):
334
+ exporter.write_export({}, self.root / 'out', '../escape')
335
+
336
+
337
+ if __name__ == '__main__':
338
+ unittest.main()
@@ -208,7 +208,7 @@ class PublicFilesTests(unittest.TestCase):
208
208
  with (PROJECT_ROOT / "pyproject.toml").open("rb") as handle:
209
209
  metadata = tomllib.load(handle)
210
210
  self.assertEqual(metadata["project"]["version"], __version__)
211
- self.assertEqual(__version__, "0.2.1")
211
+ self.assertEqual(__version__, "0.2.2")
212
212
  for alias in ("agent-hours", "codex-agent-hour-tracker"):
213
213
  self.assertEqual(metadata["project"]["scripts"][alias], "agent_hour_tracker.cli:main")
214
214
  self.assertIn("/CHANGELOG.md", metadata["tool"]["hatch"]["build"]["targets"]["sdist"]["include"])