Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions demon_mode/sources.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ class InputUnavailable(ValueError):
"""A source did not contain one unambiguous, supported numeric observation."""


def _unique_json_object(pairs):
value = {}
for key, item in pairs:
if key in value:
raise ValueError("duplicate JSON object key")
value[key] = item
return value


def _read_json(stream, maximum: int) -> object:
source = getattr(stream, "buffer", stream)
raw = source.read(maximum + 1)
Expand All @@ -24,7 +33,10 @@ def _read_json(stream, maximum: int) -> object:
if len(raw) > maximum:
raise ValueError("input exceeds the configured size limit")
try:
return json.loads(raw.decode("utf-8-sig"))
return json.loads(
raw.decode("utf-8-sig"),
object_pairs_hook=_unique_json_object,
)
except (UnicodeDecodeError, ValueError, RecursionError) as exc:
raise ValueError("input must be valid UTF-8 JSON") from exc

Expand Down Expand Up @@ -161,8 +173,8 @@ def app_server_observation(value: object, observed_at: object, now: datetime):
value = value.get("params")
if not isinstance(value, dict):
raise ValueError("Codex app-server rate-limit export is unavailable")
if value.get("ordinaryUsageAllowed") is False:
raise ValueError("Codex reports ordinary included usage is blocked; refresh provider status")
if "ordinaryUsageAllowed" in value and value["ordinaryUsageAllowed"] is not True:
raise ValueError("Codex ordinary included usage is not confirmed available; refresh provider status")
if "rateLimitsByLimitId" in value and value["rateLimitsByLimitId"] is not None:
buckets = value["rateLimitsByLimitId"]
if not isinstance(buckets, dict) or "codex" not in buckets:
Expand Down
13 changes: 9 additions & 4 deletions docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,15 @@ demon ingest codex-app-server --file './rate-limits.json' --at '<original-observ
```

`--stdin` is also available; both forms accept up to 64 KiB of UTF-8, with or
without a BOM. Multi-bucket exports select `codex` only. Explicit
`ordinaryUsageAllowed: false`, `spendControlReached: true`, or non-null
`rateLimitReachedType` fails even with low percentages. Account identifiers,
credit details, and unrelated export fields are not retained.
without a BOM. Multi-bucket exports select `codex` only. When
`ordinaryUsageAllowed` is present, only `true` is accepted; `false`, `null`, or
another value fails closed even with low percentages. A missing field remains
tolerated for backwards compatibility, including sparse notifications.
Duplicate JSON object keys are rejected so conflicting permission values cannot
be resolved by parser-specific last-value behavior.
`spendControlReached: true` or a
non-null `rateLimitReachedType` also fails. Account identifiers, credit details,
and unrelated export fields are not retained.

The GUI imports Claude status-line JSON or Codex app-server JSON. Claude readings
use the import time; Codex requires the original capture time. Its hook template
Expand Down
7 changes: 4 additions & 3 deletions docs/research-and-next-steps.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
# Research and next improvements

Reviewed for 0.1.1 on October 23, 2026. Public primary sources only; no private
accounts, provider credentials, or hosted model calls were used.
Reviewed for 0.1.1 on October 23, 2026; refreshed October 31, 2026. Public
primary sources only; no private accounts, provider credentials, or hosted
model calls were used.

| Evidence | Consequence implemented |
| --- | --- |
| [OpenAI hooks](https://learn.chatgpt.com/docs/hooks): wrapper, trust, working directory, local/cloud boundary | Additive native config, absolute paths, pasteable fallback, honest host limits |
| [OpenAI app-server](https://learn.chatgpt.com/docs/app-server): camelCase, durations, multiple buckets, sparse updates | Export reader, original timestamp, shared `codex` selection, unsupported-window rejection |
| [Account protocol](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/account.rs): usage/spend restrictions | Reject blocked exports rather than infer permission from low percentages |
| [Account protocol](https://github.com/openai/codex/blob/main/codex-rs/app-server-protocol/src/protocol/v2/account.rs): permission is nullable; null means unavailable | Reject present null or malformed permission values as well as explicit denial; tolerate omitted permission fields for backwards compatibility, including sparse notifications |
| [Codex hook runner](https://github.com/openai/codex/blob/main/codex-rs/hooks/src/engine/command_runner.rs) and [shell detection](https://github.com/openai/codex/blob/main/codex-rs/shell-command/src/shell_detect.rs) | Literal PowerShell wrapper on Windows; no assumed Codex exec form |
| [Claude command fields](https://code.claude.com/docs/en/hooks#command-hook-fields) | Shell-free native Claude executable/args configuration |
| [Claude statusline](https://code.claude.com/docs/en/statusline): UI/timer updates, optional fields | Original capture timestamp option; freshness caveat |
Expand Down
13 changes: 12 additions & 1 deletion tests/test_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,18 @@ def start(self, **kwargs):
server = GuiServer(str(Path(temp.name) / "s.sqlite3"), 0, **kwargs)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
self.addCleanup(server.server_close)

def stop_server():
try:
if thread.is_alive():
server.shutdown()
thread.join(2)
if thread.is_alive():
raise AssertionError("GUI server thread did not stop before socket cleanup")
finally:
server.server_close()

self.addCleanup(stop_server)
return server, thread

def request(self, server, method, path, headers=None):
Expand Down
29 changes: 28 additions & 1 deletion tests/test_reliability.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,17 @@ def test_app_server_file_accepts_utf8_bom_and_json_output(self):
self.assertEqual(code, 0, err)
self.assertEqual(json.loads(out)["weekly_used_percent"], 18)

def test_app_server_duplicate_permission_key_is_rejected_without_state_mutation(self):
with tempfile.TemporaryDirectory() as temp:
db = Path(temp).resolve() / "state.sqlite3"
rate_limits = json.dumps({"rateLimits": snapshot()})[1:]
payload = '{"ordinaryUsageAllowed":false,"ordinaryUsageAllowed":true,' + rate_limits
code, out, err = invoke(["--db", str(db), "ingest", "codex-app-server", "--stdin",
"--at", NOW.isoformat()], stdin=io.StringIO(payload))
self.assertEqual(code, 2)
self.assertEqual(out, "")
self.assertFalse(db.exists())

def test_claude_native_hook_uses_shell_free_argument_vector(self):
with tempfile.TemporaryDirectory() as temp:
db = Path(temp).resolve() / "ledger's $literal.sqlite3"
Expand All @@ -300,7 +311,10 @@ def test_claude_native_hook_uses_shell_free_argument_vector(self):
self.assertIn(str(db), handler["args"])

def test_app_server_does_not_infer_permission_from_low_percentages(self):
for field, value in (("ordinaryUsageAllowed", False), ("spendControlReached", True),
for field, value in (("ordinaryUsageAllowed", False), ("ordinaryUsageAllowed", None),
("ordinaryUsageAllowed", "true"), ("ordinaryUsageAllowed", 1),
("ordinaryUsageAllowed", 1.0), ("ordinaryUsageAllowed", 0.0),
("spendControlReached", True),
("rateLimitReachedType", "workspace_owner_usage_limit_reached")):
with self.subTest(field=field):
data = {"rateLimits": snapshot()}
Expand All @@ -310,6 +324,19 @@ def test_app_server_does_not_infer_permission_from_low_percentages(self):
with self.assertRaises(ValueError):
app_server_observation(data, NOW, NOW)

def test_app_server_rejects_minimal_explicit_null_permission(self):
from demon_mode.sources import app_server_observation
with self.assertRaises(ValueError):
app_server_observation({"ordinaryUsageAllowed": None}, NOW, NOW)

def test_app_server_allows_missing_or_explicitly_true_usage_permission(self):
from demon_mode.sources import app_server_observation
for data in ({"rateLimits": snapshot()},
{"ordinaryUsageAllowed": True, "rateLimits": snapshot()}):
with self.subTest(data=data):
result = app_server_observation(data, NOW, NOW)
self.assertEqual(result.weekly_used, 18)

def test_hook_refresh_lock_wait_is_bounded(self):
with tempfile.TemporaryDirectory() as temp:
db = Path(temp).resolve() / "state.sqlite3"
Expand Down
Loading