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/paths.py

View on GitHub
from __future__ import annotations

from dataclasses import dataclass
import hashlib
import os
import tempfile
from pathlib import Path

from .ledger import secure_mkdir, secure_write_text
from .mode import load_mode, write_mode


class ProjectRootError(ValueError):
    pass


@dataclass(frozen=True)
class Registration:
    project_root: Path
    state_root: Path
    state_location: str


def project_id_for(path: Path) -> str:
    resolved = str(path.resolve())
    name = path.resolve().name or "project"
    digest = hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:12]
    return f"{name}-{digest}"


_UNSAFE_TMP_PREFIXES = ("/tmp", "/private/tmp", "/var/tmp")


def _norm_for_compare(p: str) -> str:
    """Normalize a path string for prefix comparison across platforms.

    Lowercases on case-insensitive filesystems (Windows), collapses `.`/`..`,
    and unifies separators so both `/` and `\\` forms compare equal.
    """
    return os.path.normcase(os.path.normpath(p))


def _unsafe_tmp_prefixes() -> tuple[str, ...]:
    """All temp-dir prefixes to reject, normalized for the current platform.

    Includes the fixed POSIX list (so behavior on Linux/macOS is unchanged)
    plus the platform temp dir reported by `tempfile.gettempdir()`, which on
    Windows resolves to `%TEMP%` (e.g. C:\\Users\\<name>\\AppData\\Local\\Temp).

    The platform temp dir is run through `Path.resolve()` so a Windows 8.3
    short name (e.g. `C:\\Users\\T-YUJU~1\\...`) is canonicalized to the same
    long form a resolved project root produces; otherwise the prefix compare
    would miss.
    """
    prefixes = list(_UNSAFE_TMP_PREFIXES)
    try:
        prefixes.append(str(Path(tempfile.gettempdir()).resolve()))
    except Exception:
        pass
    return tuple(_norm_for_compare(p) for p in prefixes)


def resolve_project_root(path: Path, allow_unsafe: bool = False) -> Path:
    """Reject unsafe project roots (root, HOME, /tmp variants).

    HX-11 fix: macOS `/tmp` is a symlink → `/private/tmp`. The original
    `startswith("/tmp")` check passed `/private/tmp/...` through. Now we
    check the resolved path against an explicit list of tmp prefixes plus
    `/var/tmp` (some distros).

    CX-B3 fix: the prefix list was POSIX-only and compared with a forward-
    slash separator, so on Windows `%TEMP%` was never blacklisted and
    backslash paths never matched. We now include `tempfile.gettempdir()`
    and normalize separators/case (via os.path.normcase/normpath) so both
    `/` and `\\` forms are caught on every platform.
    """
    root = Path(path).resolve()
    home = Path(os.path.expanduser("~")).resolve()
    allow_unsafe = allow_unsafe or os.environ.get("TELLONCE_CODEX_ALLOW_TEMP") == "1"
    root_norm = _norm_for_compare(str(root))
    is_tmp = any(
        root_norm == p or root_norm.startswith(p + os.sep)
        for p in _unsafe_tmp_prefixes()
    )
    if not allow_unsafe and (root == Path("/") or root == home or is_tmp):
        raise ProjectRootError(f"unsafe project root: {root}")
    return root


def default_state_root(project_root: Path) -> Path:
    return project_root / ".codex" / "tellonce"


def fallback_state_root(project_root: Path) -> Path:
    return Path(os.path.expanduser("~")) / ".codex" / "projects" / project_id_for(project_root) / "tellonce"


def register_project(project_root: Path, allow_unsafe: bool = False) -> Registration:
    """Idempotent registration.

    CX-5 fix: do NOT call write_mode unconditionally — that resets
    mode.json back to `audit_only`/`wrapper_seen=False` on every CLI
    invocation, breaking the wrapper-mode state machine's monotonicity.
    Now we only write the default mode if mode.json doesn't already exist.
    """
    root = resolve_project_root(project_root, allow_unsafe=allow_unsafe)
    state_root = default_state_root(root)
    location = "project"
    try:
        secure_mkdir(state_root)
        probe = state_root / ".write_test"
        probe.write_text("ok", encoding="utf-8")
        probe.unlink()
    except OSError:
        state_root = fallback_state_root(root)
        secure_mkdir(state_root)
        location = "global_project_fallback"

    import json as _json

    # Version from the package constant — a hardcoded literal here went stale
    # (0.1.0 recorded for 1.3.x installs) and misled version-based triage.
    try:
        from . import __version__ as _pkg_version
    except Exception:
        _pkg_version = "unknown"
    registration = {
        "project_root": str(root),
        "install_cwd": str(Path.cwd().resolve()),
        "state_root": str(state_root),
        "state_location": location,
        "package_version": _pkg_version,
        "mode": "audit_only",
    }
    secure_write_text(
        state_root / "registration.json",
        _json.dumps(registration, indent=2) + "\n",
        atomic=True,
    )
    # Only initialize mode.json on first install — preserve later mode/wrapper_seen.
    if not (state_root / "mode.json").is_file():
        write_mode(state_root)
    return Registration(project_root=root, state_root=state_root, state_location=location)


def load_registration(project_root: Path) -> Registration:
    """Locate or create the project's registration.

    CX-10 + post-review fix: the fallback "create on miss" path used to be
    `allow_unsafe=True` (silently bypassed safety) — that was wrong. We then
    flipped it to `allow_unsafe=False`, which broke legacy installs whose
    project_root happens to be HOME or under /tmp (e.g. someone who already
    ran the package against `~`). Now we forward the same `allow_unsafe`
    policy that the caller asked for: load is permissive (so we can find
    legacy installs), but create-on-miss inherits the original caller's
    safety preference. The test fixture path that uses
    `TELLONCE_CODEX_ALLOW_TEMP=1` continues to work; cli.py paths that
    don't set that env still get strict semantics on first install.
    """
    import json as _json

    # If the user explicitly opted into unsafe roots (via env), let load and
    # create both honor that. Otherwise: load is lax (find legacy state),
    # create is strict (don't silently provision under HOME/`/`/`/tmp`).
    env_allow = os.environ.get("TELLONCE_CODEX_ALLOW_TEMP") == "1"
    root = resolve_project_root(project_root, allow_unsafe=True)
    state = default_state_root(root)
    path = state / "registration.json"
    if not path.is_file():
        fallback = fallback_state_root(root)
        path = fallback / "registration.json"
        state = fallback
    if not path.is_file():
        # No prior install — create. Use env_allow so test mode and
        # explicit-opt-in users can register against /tmp / HOME.
        return register_project(root, allow_unsafe=env_allow)
    try:
        data = _json.loads(path.read_text(encoding="utf-8"))
    except (OSError, UnicodeError, _json.JSONDecodeError, TypeError) as exc:
        raise ProjectRootError(f"invalid registration file {path}: {exc}") from exc
    if not isinstance(data, dict):
        raise ProjectRootError(f"invalid registration file {path}: expected JSON object")
    return Registration(
        project_root=Path(data.get("project_root", str(root))),
        state_root=path.parent,
        state_location=data.get("state_location", "project"),
    )


def find_registration(project_root: Path) -> Registration | None:
    """Read an existing registration without creating project state."""
    import json as _json

    root = resolve_project_root(project_root, allow_unsafe=True)
    for state in (default_state_root(root), fallback_state_root(root)):
        path = state / "registration.json"
        if not path.is_file():
            continue
        try:
            data = _json.loads(path.read_text(encoding="utf-8"))
        except (OSError, UnicodeError, _json.JSONDecodeError, TypeError) as exc:
            raise ProjectRootError(f"invalid registration file {path}: {exc}") from exc
        if not isinstance(data, dict):
            raise ProjectRootError(f"invalid registration file {path}: expected JSON object")
        return Registration(
            project_root=Path(data.get("project_root", str(root))),
            state_root=state,
            state_location=data.get("state_location", "project"),
        )
    return None


def ensure_registered(project_root: Path) -> Registration:
    """Get the Registration without re-running write_mode side effects.

    CX-5 helper used by cli.py for scan/dashboard/exec/promote/migrate so
    those commands don't reset mode.json. Falls back to register_project
    on first run, which is fine because that goes through the same
    monotone path now.
    """
    return load_registration(project_root)
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