Skip to content

YujunZhou/tellonce / codex

tellonce

Verified

Use 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.

FileKindSize
.codex-plugin/plugin.jsonconfig1.3 KB
SKILL.mdskill md12.0 KB
dashboard.shexecutablescript348 B
docs/CC_PARITY_MATRIX.mdmarkdown7.3 KB
docs/README.mdmarkdown3.4 KB
doctor.shexecutablescript345 B
hooks/hooks.jsonconfig714 B
hooks/posttooluse-deterministic-block.shexecutablescript2.0 KB
hooks/sessionstart-init.shexecutablescript1.9 KB
hooks/userpromptsubmit-dispatch.pyscript2.6 KB
hooks/userpromptsubmit-memory-upsert.shscript326 B
hooks/userpromptsubmit-pending-inject.shexecutablescript2.0 KB
hooks/userpromptsubmit-retrieve-inject.shexecutablescript3.1 KB
hooks/userpromptsubmit-shadow-alert-inject.shexecutablescript1.2 KB
install.shexecutablescript13.9 KB
shared_lib/_install_merge_settings.pyscript12.1 KB
shared_lib/_pt_hooks.txtmarkdown407 B
shared_lib/correction_interpretation.pyscript8.5 KB
shared_lib/detect_user_prefer.pyscript7.2 KB
shared_lib/deterministic_block.pyscript9.3 KB
shared_lib/event_obligations.pyscript19.8 KB
shared_lib/execution_support.pyscript75.8 KB
shared_lib/fingerprints.yamlconfig1.1 KB
shared_lib/learning_policy.pyscript4.6 KB
shared_lib/memory_judge.pyscript84.8 KB
shared_lib/memory_publication.pyscript14.9 KB
shared_lib/memory_runtime.pyscript12.2 KB
shared_lib/memory_store.pyscript99.6 KB
shared_lib/memory_upsert.pyscript57.1 KB
shared_lib/memory_upsert_hook.pyscript4.6 KB
shared_lib/model_requests.pyscript5.8 KB
shared_lib/path_config.pyscript13.3 KB
shared_lib/pending_queue_manager.pyscript23.4 KB
shared_lib/pt_platform.pyscript1.5 KB
shared_lib/redaction.pyscript3.4 KB
shared_lib/retrieve_inject.pyexecutablescript57.9 KB
shared_lib/rule_selection.pyscript18.9 KB
shared_lib/shadow_alert_inject.pyscript6.1 KB
shared_lib/training_memory.pyscript17.8 KB
shared_lib/transcript_adapter.pyscript13.7 KB
shared_lib/verify_compliance.pyexecutablescript24.5 KB
shared_lib/verify_retry_shadow.pyscript27.4 KB
tellonce_codex/__init__.pyscript52 B
tellonce_codex/__main__.pyscript49 B
tellonce_codex/cli.pyscript6.8 KB
tellonce_codex/codex_posttooluse_block.pyscript11.2 KB
tellonce_codex/dashboard.pyscript3.4 KB
tellonce_codex/doctor.pyscript10.9 KB
tellonce_codex/index.pyscript1.8 KB
tellonce_codex/install.pyscript3.1 KB
tellonce_codex/install_codex_hooks.pyscript15.1 KB
tellonce_codex/ledger.pyscript17.1 KB
tellonce_codex/memory.pyscript5.3 KB
tellonce_codex/migrate.pyscript1.3 KB
tellonce_codex/mode.pyscript2.3 KB
tellonce_codex/paths.pyscript8.6 KB
tellonce_codex/promote.pyscript4.4 KB
tellonce_codex/scan.pyscript2.6 KB
tellonce_codex/uninstall.pyscript1.7 KB
tellonce_codex/verify.pyscript5.3 KB
tellonce_codex/wrapper.pyscript12.0 KB
uninstall.shexecutablescript4.6 KB

tellonce_codex/install_codex_hooks.py

View on GitHub
#!/usr/bin/env python3
"""Manage tellonce entries in ~/.codex/hooks.json.

Codex hook event names + JSON in/out protocol mirror Claude Code's: stdin
JSON with prompt / tool_name / tool_input / tool_response; stdout JSON with
hookSpecificOutput.additionalContext etc.; exit 2 = block with reason on stderr.

Usage:
  python3 -m tellonce_codex.install_codex_hooks --add
  python3 -m tellonce_codex.install_codex_hooks --remove
  python3 -m tellonce_codex.install_codex_hooks --verify

Sentinel: every PT-managed entry tagged `_pt_managed: true` so cleanup is exact
and we don't trample user's own hook entries.

Hook layout (mirrors CC's UserPromptSubmit chain + adds PostToolUse to fill the
gap that codex doesn't have a Stop hook):

  UserPromptSubmit:
   - userpromptsubmit-dispatch.py           (sequentially enqueue memory,
      retrieve rules, then merge last-turn shadow alerts)

  PostToolUse:
    - posttooluse-deterministic-block.sh     (regex/fingerprint scan tool
      output text; advisory by default, blocking when mode=='blocking')

  SessionStart:
    - sessionstart-init.sh                   (lazy init project state + mode
      file when codex enters a fresh project)
"""
from __future__ import annotations

import argparse
import json
import os
import shlex
import sys
import time
from pathlib import Path

for stream in (sys.stdout, sys.stderr):
    try:
        stream.reconfigure(encoding="utf-8")
    except (AttributeError, OSError):
        pass


PT_HOOKS_DEFAULT_DIR = Path.home() / ".codex" / "skills" / "tellonce" / "hooks"

# event_name -> ordered list of hook script basenames (run in order).
# Outer timeouts = each script's inner _pt_timeout + ~10s headroom for
# bash+python startup — keep in sync with codex/hooks/hooks.json (the plugin
# registration path); outer <= inner lets the platform kill the hook just
# before the inner subprocess finishes, silently dropping its JSON output.
PT_HOOKS = {
    "UserPromptSubmit": [
        ("userpromptsubmit-dispatch.py", 45),
    ],
    "PostToolUse": [
        ("posttooluse-deterministic-block.sh", 25),
    ],
    "SessionStart": [
        ("sessionstart-init.sh", 20),
    ],
}
LEGACY_HOOK_BASENAMES = {
    "userpromptsubmit-pending-inject.sh",
    "userpromptsubmit-memory-upsert.sh",
    "userpromptsubmit-retrieve-inject.sh",
    "userpromptsubmit-shadow-alert-inject.sh",
}


def _load_hooks_json(path: str) -> dict:
    p = Path(path)
    if not p.is_file():
        return {}
    with p.open(encoding="utf-8") as f:
        value = json.load(f)
    if not isinstance(value, dict):
        raise ValueError(f"hooks config must be a JSON object: {p}")
    return value


def _versioned_backup(path: str) -> str | None:
    p = Path(path)
    if not p.is_file():
        return None
    # Timestamp + pid: install.sh runs --remove then --add back-to-back, and
    # with second-granularity names the --add backup (post-remove, stripped)
    # overwrote the --remove backup — destroying the true pre-install rollback
    # anchor. Matches shared_lib/_install_merge_settings.py's fix.
    ts = time.strftime("%Y%m%d-%H%M%S")
    backup = f"{path}.v3_pre_pt_{ts}-{os.getpid()}.json"
    # Same-process remove+add within one second would still collide — bump
    # a suffix rather than overwrite (mirrors _install_merge_settings.py).
    while Path(backup).exists():
        backup = backup[: -len(".json")] + "b.json"
    p.parent.mkdir(parents=True, exist_ok=True)
    Path(backup).write_text(p.read_text(encoding="utf-8"), encoding="utf-8")
    # GC: every install/uninstall writes one backup; without pruning they
    # accumulate forever. Keep the 5 most recent (matches CC install.sh).
    try:
        siblings = sorted(
            p.parent.glob(p.name + ".v3_pre_pt_*.json"),
            key=lambda b: b.stat().st_mtime,
            reverse=True,
        )
        for old in siblings[5:]:
            old.unlink()
    except Exception:
        pass
    return backup


def _save_hooks_json(path: str, data: dict) -> None:
    import uuid as _uuid
    p = Path(path)
    p.parent.mkdir(parents=True, exist_ok=True)
    # pid + uuid8 suffix avoids tmp-file race when concurrent installers run
    # (mirror codex/tellonce_codex/ledger.py).
    tmp = p.with_suffix(p.suffix + f".tmp.{os.getpid()}.{_uuid.uuid4().hex[:8]}")
    try:
        tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
        try:
            os.chmod(tmp, 0o600)
        except OSError:
            pass
        tmp.replace(p)
    except Exception:
        try:
            tmp.unlink()
        except OSError:
            pass
        raise


def _normalize_command(cmd: str) -> str:
    return str(cmd or "").strip().strip("'\"").replace("\\", "/")


def _command_basename(cmd: str) -> str:
    norm = _normalize_command(cmd)
    known = {
        basename
        for hooks in PT_HOOKS.values()
        for basename, _timeout in hooks
    } | LEGACY_HOOK_BASENAMES
    for basename in known:
        if norm.endswith(basename) or f"/{basename}" in norm:
            return basename
    return norm.rsplit("/", 1)[-1]


def _command_script_path(cmd: str, basename: str) -> Path | None:
    try:
        tokens = shlex.split(str(cmd or ""), posix=True)
    except ValueError:
        return None
    for token in tokens:
        if _normalize_command(token).endswith(basename):
            try:
                return Path(token).expanduser().resolve()
            except OSError:
                return None
    return None


def _is_pt_command(cmd: str) -> bool:
    """Identify any registration string we previously wrote so cleanup is safe.

    PT hook commands always live under */tellonce/hooks/ AND have one
    of our known basenames. We use path-based identification (rather than a
    sentinel field on the entry) so hooks.json stays strictly schema-compliant.

    CX-B5 fix: normalize separators before matching. Hook commands written on
    Windows use backslashes (`...\\tellonce\\hooks\\foo.sh`), so the
    old forward-slash-only `/hooks/` substring and `rsplit("/")` basename
    extraction never matched and cleanup/verify silently missed PT entries.
    """
    norm = _normalize_command(cmd)
    if "tellonce" not in norm:
        return False
    if "/hooks/" not in norm:
        return False
    known = {
        basename
        for lst in PT_HOOKS.values()
        for basename, _ in lst
    } | LEGACY_HOOK_BASENAMES
    return any(norm.endswith(name) or f"/{name}" in norm for name in known)


def cmd_add(hooks_path: str, hooks_dir: str) -> int:
    hooks_dir_p = Path(hooks_dir).expanduser().resolve()
    if not hooks_dir_p.is_dir():
        print(f"⚠ hooks_dir does not exist: {hooks_dir_p}", file=sys.stderr)
        # don't fail — install.sh may run --add before --copy in some flows
    backup = _versioned_backup(hooks_path)
    if backup:
        print(f"  versioned backup: {backup}")

    data = _load_hooks_json(hooks_path)
    data.setdefault("hooks", {})
    for event, chain in data["hooks"].items():
        cleaned_chain = []
        for entry in chain:
            hooks = []
            for hook in entry.get("hooks", []) or []:
                command = hook.get("command", "")
                basename = _command_basename(_normalize_command(command))
                if basename in LEGACY_HOOK_BASENAMES and _is_pt_command(command):
                    continue
                hooks.append(hook)
            if hooks:
                entry["hooks"] = hooks
                cleaned_chain.append(entry)
            elif not entry.get("hooks"):
                cleaned_chain.append(entry)
        data["hooks"][event] = cleaned_chain

    added = 0
    skipped = 0
    for event, hook_list in PT_HOOKS.items():
        chain = data["hooks"].setdefault(event, [])
        existing_basenames = set()
        cleaned_chain = []
        for entry in chain:
            user_hooks = []
            for hook in entry.get("hooks", []) or []:
                command = hook.get("command", "")
                if _is_pt_command(command):
                    existing_basenames.add(_command_basename(command))
                else:
                    user_hooks.append(hook)
            if user_hooks:
                preserved = dict(entry)
                preserved.pop("_pt_managed", None)
                preserved["hooks"] = user_hooks
                cleaned_chain.append(preserved)
            elif not entry.get("hooks"):
                cleaned_chain.append(entry)

        managed_hooks = []
        for basename, timeout in hook_list:
            # shlex.quote: codex shlex-splits the command string and execs it
            # directly — a HOME containing a space would split a bare path
            # into two tokens and every hook would exit 127 silently. For
            # space-free paths quote() is a no-op, so existing installs see
            # byte-identical commands (no re-trust churn).
            import shlex
            script = str(hooks_dir_p / basename)
            cmd = (
                f"{shlex.quote(sys.executable)} {shlex.quote(script)}"
                if basename.endswith(".py")
                else shlex.quote(script)
            )
            if basename in existing_basenames:
                skipped += 1
            else:
                added += 1
            managed_hooks.append({
                "type": "command",
                "command": cmd,
                "timeout": timeout,
            })
        # Keep all Tellonce hooks in one schema-clean entry and rebuild it in
        # PT_HOOKS order on every upgrade. The memory-upsert hook must run
        # before retrieval rotates the clarification presentation sidecar.
        cleaned_chain.insert(0, {"matcher": "", "hooks": managed_hooks})
        data["hooks"][event] = cleaned_chain
    _save_hooks_json(hooks_path, data)
    print(f"  added {added}, skipped {skipped} (already registered)")
    return 0


def cmd_remove(hooks_path: str, hooks_dir: str | None = None) -> int:
    """Remove all PT hooks. Identifies them by path (any command under
    */tellonce/hooks/<known-basename>). Drops emptied entries
    cleanly."""
    backup = _versioned_backup(hooks_path)
    if backup:
        print(f"  versioned backup: {backup}")
    data = _load_hooks_json(hooks_path)
    hooks_block = data.get("hooks") or {}
    removed = 0
    for event, chain in list(hooks_block.items()):
        new_chain = []
        for entry in chain:
            sub = []
            for h in entry.get("hooks", []) or []:
                cmd = h.get("command", "")
                if _is_pt_command(cmd):
                    removed += 1
                    continue
                sub.append(h)
            # Skip backwards-compat: legacy entries had a `_pt_managed: true`
            # field. Strip them whole if all hooks were PT.
            if entry.get("_pt_managed") and not sub:
                continue
            if sub:
                new_entry = {k: v for k, v in entry.items() if k != "_pt_managed"}
                new_entry["hooks"] = sub
                new_chain.append(new_entry)
            elif not entry.get("hooks"):
                # entry started empty — preserve it (user's empty placeholder)
                new_chain.append(entry)
        if new_chain:
            hooks_block[event] = new_chain
        else:
            hooks_block.pop(event, None)
    if hooks_block:
        data["hooks"] = hooks_block
    else:
        data.pop("hooks", None)
    _save_hooks_json(hooks_path, data)
    print(f"  removed {removed} hooks")
    return 0


def cmd_verify(hooks_path: str, hooks_dir: str) -> int:
    """Verify (event,
    command) pair, not just command-path presence. Otherwise a hook
    misregistered to the wrong event (e.g. PostToolUse hook under
    UserPromptSubmit) would print a green check and rc=0, masking a
    broken install. Now we distinguish:
      ✓                — registered to the correct event
      ✗ (missing)      — not registered at all
      ⚠ (wrong event)  — registered, but to a different event than expected
    Returns 1 if any hook is missing OR registered to the wrong event.
    """
    hooks_dir_p = Path(hooks_dir).expanduser().resolve()
    expected_pairs = {
        (event, basename)
        for event, lst in PT_HOOKS.items()
        for basename, _ in lst
    }
    basename_to_entries: dict[str, list[tuple[str, Path | None]]] = {}
    for event, chain in (data := _load_hooks_json(hooks_path)).get("hooks", {}).items():
        for entry in chain:
            for h in entry.get("hooks", []) or []:
                cmd = h.get("command", "")
                if not cmd or not _is_pt_command(cmd):
                    continue
                basename = _command_basename(cmd)
                basename_to_entries.setdefault(basename, []).append(
                    (event, _command_script_path(cmd, basename))
                )
    print(f"  Codex tellonce hook registration status:")
    print(f"    hooks.json: {hooks_path}")
    print(f"    hooks dir:  {hooks_dir_p}")
    bad = 0
    for expected_event, basename in expected_pairs:
        expected_path = (hooks_dir_p / basename).resolve()
        entries = basename_to_entries.get(basename, [])
        path_ready = expected_path.is_file() and (
            basename.endswith(".py") or os.name == "nt" or os.access(expected_path, os.X_OK)
        )
        if (
            path_ready
            and any(event == expected_event and path == expected_path for event, path in entries)
        ):
            print(f"    ✓ {basename} → {expected_event}")
        elif any(event == expected_event and path == expected_path for event, path in entries):
            print(f"    ⚠ {basename} path is missing or not executable: {expected_path}")
            bad += 1
        elif any(event == expected_event for event, _path in entries):
            paths = ", ".join(
                str(path) if path is not None else "<unparseable>"
                for event, path in entries
                if event == expected_event
            )
            print(f"    ⚠ {basename} uses stale path(s): {paths}; expected {expected_path}")
            bad += 1
        elif entries:
            events_seen = {event for event, _path in entries}
            wrong = ", ".join(sorted(events_seen))
            print(f"    ⚠ {basename} registered to {wrong}, expected {expected_event}")
            bad += 1
        else:
            print(f"    ✗ {basename} → {expected_event} (missing)")
            bad += 1
    return 0 if bad == 0 else 1


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Merge tellonce hooks into ~/.codex/hooks.json")
    ap.add_argument("--hooks-json", default=str(Path.home() / ".codex" / "hooks.json"))
    ap.add_argument("--hooks-dir", default=str(PT_HOOKS_DEFAULT_DIR))
    grp = ap.add_mutually_exclusive_group(required=True)
    grp.add_argument("--add", action="store_true")
    grp.add_argument("--remove", action="store_true")
    grp.add_argument("--verify", action="store_true")
    args = ap.parse_args(argv)
    if args.add:
        return cmd_add(args.hooks_json, args.hooks_dir)
    if args.remove:
        return cmd_remove(args.hooks_json, args.hooks_dir)
    return cmd_verify(args.hooks_json, args.hooks_dir)


if __name__ == "__main__":
    sys.exit(main())
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: 472kUpdated Claude CodeCodexVerifiedInstall
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: 323kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 323kUpdated Claude CodeCodexVerifiedInstall
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 availableStars: 323kUpdated Claude CodeCodexVerifiedInstall