YujunZhou/tellonce / codex
tellonce
VerifiedUse to view, explain, correct, delete or reorganize the user's saved preferences, or to record one by hand when automatic recording is off; learning and rule injection otherwise run automatically through Codex hooks.
tellonce_codex/doctor.py
View on GitHubfrom __future__ import annotations
import os
import re
from dataclasses import dataclass
from pathlib import Path
from .ledger import SECRET_PATTERNS
from .mode import load_mode
from .paths import find_registration
# CX-3 fix: previously default empty + module-load-time env read. Now:
# - default has a small generic-leak heuristic (kicks in even without env)
# - reads env on every run_doctor() call
# - SECRET_PATTERNS is an additional always-on safety net
#
# The generic-leak default looks for things that almost certainly mean a
# fork picked up an upstream author's hardcoded path (rather than a runtime-
# detected one): non-user `/scratch*` paths, non-user `/users/<other>/`,
# `/private/var/folders` references that are platform-specific build leaks.
_GENERIC_LEAK_HEURISTIC: tuple[re.Pattern, ...] = (
# `/Users/<name>/...` (macOS) and `/users/<name>/...` (some Linux installs).
# Case-insensitive so macOS `/Users/alice/` matches.
re.compile(r"/[Uu]sers/[A-Za-z][A-Za-z0-9_\-]{1,32}/[A-Za-z]"),
# Windows user-home path: `C:\Users\<name>\...` (any drive letter).
# CX-B4 fix: POSIX-only patterns let Windows private-path leaks
# (`C:\Users\alice\...`) pass undetected. Match a drive letter + the
# backslash `Users` segment + a username component.
re.compile(r"[A-Za-z]:\\[Uu]sers\\[A-Za-z][A-Za-z0-9_\-. ]{1,32}\\"),
# Hardcoded skill-dir paths under someone else's home — almost always a
# leak from a fork-author's install script that shouldn't be in user state.
re.compile(r"/home/[A-Za-z][A-Za-z0-9_\-]{1,32}/\.claude/skills"),
# Note: removed the `/scratch\d*/[a-z]` rule because legitimate HPC users
# work out of /scratch/<user>/ and would hit the heuristic on every event.
# If a fork wants to detect a specific cluster path leak, set
# CODEX_PT_PRIVATE_PATTERNS=/scratch/<your-id> explicitly.
)
_REGISTRATION_FILES = {"registration.json", "install_record.json"}
# Skip very large files (likely captured stdout) — they're already sanitized
# at write time via secure_write_text + sanitize, and reading them all into
# memory would make doctor extremely slow on long-running projects.
_PRIVATE_PATH_MAX_FILE_BYTES = 256 * 1024 # 256KB per file
def _runtime_env_patterns() -> tuple[str, ...]:
"""Read CODEX_PT_PRIVATE_PATTERNS at call time so dynamic env settings work."""
return tuple(
p.strip()
for p in os.environ.get("CODEX_PT_PRIVATE_PATTERNS", "").split(",")
if p.strip()
)
# Backwards-compatible module attribute (tests poke at it via importlib.reload).
PRIVATE_PATTERNS: tuple[str, ...] = _runtime_env_patterns()
@dataclass(frozen=True)
class DoctorReport:
sections: dict
status_line: str
def _own_home_prefixes() -> tuple:
"""Path prefixes that belong to the CURRENT user's own home directory.
The generic leak heuristic exists to catch a FORK AUTHOR's hardcoded
paths surviving into someone else's install. The current user's own home
path is not a leak — it lands in events.jsonl legitimately via wrapper
argv / scan excerpts (e.g. every macOS user's project lives under
/Users/<them>/...). Without this exemption doctor FAILs for every macOS
user on their first wrapped command.
"""
prefixes = []
home = os.path.expanduser("~")
if home and home != "~":
prefixes.append(home.rstrip("/\\"))
# macOS/Linux case variants of the same home (APFS is case-insensitive).
if home.lower() != home:
prefixes.append(home.lower().rstrip("/\\"))
return tuple(prefixes)
def _file_has_leak(text: str, env_patterns: tuple[str, ...]) -> bool:
"""A file leaks if it matches any:
- configured env-driven literal pattern (substring match)
- generic leak heuristic (regex) — except matches inside the current
user's own home path (their own project paths are not a leak)
- a SECRET_PATTERNS hit (catches API keys / DB URIs that slipped past
the sanitize step at write time)
"""
for pat in env_patterns:
if pat and pat in text:
return True
own_homes = _own_home_prefixes()
for pat in _GENERIC_LEAK_HEURISTIC:
for m in pat.finditer(text):
# Each heuristic regex matches starting at the path root
# (`/Users/...`, `C:\Users\...`, `/home/...`), so the match start
# aligns with where $HOME would appear. Compare prefix there.
def _is_own_home(h: str) -> bool:
if text[m.start():m.start() + len(h)].lower() != h.lower():
return False
# Path boundary: /home/sam must not exempt /home/samantha.
nxt = text[m.start() + len(h):m.start() + len(h) + 1]
return nxt in ('', '/', '\\', '"', "'", ' ', '\t', '\n', ':', ',')
if own_homes and any(_is_own_home(h) for h in own_homes):
continue # current user's own home — not a fork leak
return True
for pat, _replacement in SECRET_PATTERNS:
if pat.search(text):
return True
return False
def _private_path_status(state_root: Path) -> str:
"""Walk state_root files; return PASS if no leak signature found.
HX-3/HX-10 fix: skip files larger than 256KB (subprocess stdout dumps),
skip registration files (they legitimately contain absolute paths),
skip events.lock and *.tmp.
"""
env_patterns = _runtime_env_patterns()
for path in state_root.rglob("*"):
if not path.is_file():
continue
if path.name in _REGISTRATION_FILES:
continue
if path.suffix == ".tmp" or path.name.endswith(".lock"):
continue
try:
size = path.stat().st_size
except OSError:
continue
if size > _PRIVATE_PATH_MAX_FILE_BYTES:
continue
try:
text = path.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
if _file_has_leak(text, env_patterns):
return "FAIL"
return "PASS"
def _hooks_status() -> str:
"""Report whether codex global hook registration is in place.
Compare (event,
basename) pairs, not basenames alone. Otherwise a hook registered to
the WRONG event (e.g. posttooluse-deterministic-block.sh under
UserPromptSubmit) would still report PASS, masking a broken install.
Returns:
PASS — every (event, basename) pair from PT_HOOKS is present
and registered to the correct event
PARTIAL — some pairs missing OR a basename registered to wrong event
NOT_INSTALLED — no PT hooks at all
FAIL — hooks.json corrupt
"""
import json
hooks_json = Path.home() / ".codex" / "hooks.json"
if not hooks_json.is_file():
return "NOT_INSTALLED"
try:
data = json.loads(hooks_json.read_text(encoding="utf-8"))
except Exception:
return "FAIL"
try:
from .install_codex_hooks import (
PT_HOOKS,
_command_basename,
_command_script_path,
_is_pt_command,
)
except Exception:
return "FAIL"
expected_pairs = {
(event, basename)
for event, lst in PT_HOOKS.items()
for basename, _ in lst
}
found_pairs: set[tuple[str, str]] = set()
found_order: dict[str, list[str]] = {}
paths_ready = True
valid_hook_dirs = {
(Path.home() / ".codex" / "skills" / "tellonce" / "hooks").resolve(),
(Path.home() / ".codex" / "skills" / "tellonce-runtime" / "hooks").resolve(),
}
found_any = False
for event, chain in (data.get("hooks") or {}).items():
for entry in chain or []:
for h in entry.get("hooks") or []:
cmd = h.get("command", "")
if not _is_pt_command(cmd):
continue
found_any = True
basename = _command_basename(cmd)
script_path = _command_script_path(cmd, basename)
if (
script_path is None
or script_path.parent not in valid_hook_dirs
or not script_path.is_file()
or (
basename.endswith(".sh")
and os.name != "nt"
and not os.access(script_path, os.X_OK)
)
):
paths_ready = False
found_pairs.add((event, basename))
found_order.setdefault(event, []).append(basename)
if not found_any:
return "NOT_INSTALLED"
expected_order = {
event: [basename for basename, _timeout in hooks]
for event, hooks in PT_HOOKS.items()
}
if paths_ready and found_pairs == expected_pairs and found_order == expected_order:
return "PASS"
return "PARTIAL"
def run_doctor(project_root: Path) -> DoctorReport:
"""Build a DoctorReport. CX-3/HX-4 fix: doctor no longer appends a
`doctor_run` event to the ledger — that turned doctor into a self-amplifying
write source on every health check, defeating its read-only intent and
making append_event slower on each run.
"""
registration = find_registration(project_root)
if registration is None:
sections = {
"state": "NOT_INSTALLED",
"private_paths": "NOT_INSTALLED",
"wrapper": "NOT_USED",
"hooks": _hooks_status(),
"shadow": "DISABLED",
}
return DoctorReport(
sections=sections,
status_line=(
"Tellonce status: state=NOT_INSTALLED, private_paths=NOT_INSTALLED, "
f"wrapper=NOT_USED, hooks={sections['hooks']}, shadow=DISABLED, "
"install=NOT_INSTALLED"
),
)
state = registration.state_root
mode = load_mode(state)
wrapper_events = False
try:
from .ledger import read_events
wrapper_events = any(e.get("event_type") == "wrapper_run_completed" for e in read_events(state))
except Exception:
wrapper_events = False
sections = {
"state": "PASS" if state.is_dir() else "FAIL",
"private_paths": _private_path_status(state) if state.is_dir() else "FAIL",
"wrapper": "PASS" if (mode.wrapper_seen or wrapper_events) else "NOT_USED",
"hooks": _hooks_status(),
"shadow": "DISABLED",
}
install_status = "OBSERVE_ONLY" if all(v != "FAIL" for v in sections.values()) else "FAILED"
# HX-10 UX fix: stop emitting "DEGRADED" / "NOT_USED" by default — they
# made every fresh install look broken. Use neutral words.
status_line = (
"Tellonce status: "
f"state={sections['state']}, "
f"private_paths={sections['private_paths']}, "
f"wrapper={sections['wrapper']}, "
f"hooks={sections['hooks']}, "
f"shadow={sections['shadow']}, "
f"install={install_status}"
)
return DoctorReport(sections=sections, status_line=status_line)
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 323k | Updated | Claude CodeCodex | Verified | Install |