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
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ jobs:
- name: Compile scripts
run: |
python3 -m py_compile \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_fable_state.py \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_findings.py \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_goals.py \
plugins/codex-fable5/skills/codex-fable5/scripts/fable_coverage.py \
Expand Down
1 change: 1 addition & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ Before opening a pull request, also run:

```bash
python3 -m py_compile \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_fable_state.py \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_findings.py \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_goals.py \
plugins/codex-fable5/skills/codex-fable5/scripts/fable_coverage.py \
Expand Down
1 change: 1 addition & 0 deletions docs/RELEASING.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ This project uses a lightweight release process because it is a small Codex plug
```bash
python3 -m unittest discover -s tests -v
python3 -m py_compile \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_fable_state.py \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_findings.py \
plugins/codex-fable5/skills/codex-fable5/scripts/codex_goals.py \
plugins/codex-fable5/skills/codex-fable5/scripts/fable_coverage.py \
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Shared Codex Fable5 local state helpers."""

from __future__ import annotations

from contextlib import contextmanager
import json
import os
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator

try:
import fcntl
except ImportError: # pragma: no cover - Windows fallback only.
fcntl = None

STATE_DIR = Path(".codex-fable5")
GOALS_FILE = STATE_DIR / "goals.json"
FINDINGS_FILE = STATE_DIR / "findings.json"
LEDGER_FILE = STATE_DIR / "ledger.jsonl"
LOCK_FILE = STATE_DIR / "state.lock"
LOCK_TIMEOUT_SECONDS = 30.0


def now() -> str:
return datetime.now(timezone.utc).isoformat()


@contextmanager
def locked_state() -> Iterator[None]:
STATE_DIR.mkdir(exist_ok=True)
if fcntl is None:
fallback = STATE_DIR / "state.lockdir"
deadline = time.monotonic() + LOCK_TIMEOUT_SECONDS
while True:
try:
fallback.mkdir()
break
except FileExistsError:
if time.monotonic() >= deadline:
sys.exit(f"codex-fable5: timed out waiting for state lock ({fallback}).")
time.sleep(0.05)
try:
yield
finally:
fallback.rmdir()
return

with LOCK_FILE.open("a", encoding="utf-8") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)


def read_json(path: Path, label: str) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
sys.exit(
f"codex-fable5: {label} is not valid JSON "
f"({path}:{exc.lineno}:{exc.colno}: {exc.msg})."
)


def write_json(path: Path, data: dict[str, Any]) -> None:
STATE_DIR.mkdir(exist_ok=True)
tmp_name = ""
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=STATE_DIR,
prefix=f".{path.name}.",
delete=False,
) as handle:
tmp_name = handle.name
handle.write(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
handle.flush()
os.fsync(handle.fileno())
Path(tmp_name).replace(path)


def append_event(event: str, **fields: Any) -> None:
STATE_DIR.mkdir(exist_ok=True)
record = {"ts": now(), "event": event, **fields}
with LEDGER_FILE.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=False) + "\n")


def require_object(value: Any, path: Path, label: str) -> dict[str, Any]:
if not isinstance(value, dict):
sys.exit(f"codex-fable5: {label} must be a JSON object ({path}).")
return value
105 changes: 15 additions & 90 deletions plugins/codex-fable5/skills/codex-fable5/scripts/codex_findings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,107 +4,32 @@
from __future__ import annotations

import argparse
from contextlib import contextmanager
import json
import os
import re
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator
from typing import Any

from codex_fable_state import (
FINDINGS_FILE,
GOALS_FILE,
LEDGER_FILE,
LOCK_FILE,
STATE_DIR,
append_event,
locked_state,
now,
read_json,
require_object,
write_json,
)

try:
import fcntl
except ImportError: # pragma: no cover - Windows fallback only.
fcntl = None

STATE_DIR = Path(".codex-fable5")
GOALS_FILE = STATE_DIR / "goals.json"
FINDINGS_FILE = STATE_DIR / "findings.json"
LEDGER_FILE = STATE_DIR / "ledger.jsonl"
LOCK_FILE = STATE_DIR / "state.lock"

OPEN_STATUSES = {"open"}
BLOCKING_STATUSES = {"open", "blocked"}
TERMINAL_STATUSES = {"resolved", "rejected"}
SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3}
FINDING_STATUSES = {"open", "blocked", "resolved", "rejected"}
FINDING_REQUIRED_FIELDS = {"id", "goal", "title", "severity", "source", "status", "evidence"}
LOCK_TIMEOUT_SECONDS = 30.0


def now() -> str:
return datetime.now(timezone.utc).isoformat()


@contextmanager
def locked_state() -> Iterator[None]:
STATE_DIR.mkdir(exist_ok=True)
if fcntl is None:
fallback = STATE_DIR / "state.lockdir"
deadline = time.monotonic() + LOCK_TIMEOUT_SECONDS
while True:
try:
fallback.mkdir()
break
except FileExistsError:
if time.monotonic() >= deadline:
sys.exit(f"codex-fable5: timed out waiting for state lock ({fallback}).")
time.sleep(0.05)
try:
yield
finally:
fallback.rmdir()
return

with LOCK_FILE.open("a", encoding="utf-8") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)


def read_json(path: Path, label: str) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
sys.exit(
f"codex-fable5: {label} is not valid JSON "
f"({path}:{exc.lineno}:{exc.colno}: {exc.msg})."
)


def write_json(path: Path, data: dict[str, Any]) -> None:
STATE_DIR.mkdir(exist_ok=True)
tmp_name = ""
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=STATE_DIR,
prefix=f".{path.name}.",
delete=False,
) as handle:
tmp_name = handle.name
handle.write(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
handle.flush()
os.fsync(handle.fileno())
Path(tmp_name).replace(path)


def append_event(event: str, **fields: Any) -> None:
STATE_DIR.mkdir(exist_ok=True)
record = {"ts": now(), "event": event, **fields}
with LEDGER_FILE.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=False) + "\n")


def require_object(value: Any, path: Path, label: str) -> dict[str, Any]:
if not isinstance(value, dict):
sys.exit(f"codex-fable5: {label} must be a JSON object ({path}).")
return value


def validate_findings(data: dict[str, Any], path: Path, label: str) -> dict[str, Any]:
Expand Down
107 changes: 16 additions & 91 deletions plugins/codex-fable5/skills/codex-fable5/scripts/codex_goals.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,112 +4,37 @@
from __future__ import annotations

import argparse
from contextlib import contextmanager
import json
import os
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator

try:
import fcntl
except ImportError: # pragma: no cover - Windows fallback only.
fcntl = None

STATE_DIR = Path(".codex-fable5")
GOALS_FILE = STATE_DIR / "goals.json"
FINDINGS_FILE = STATE_DIR / "findings.json"
LEDGER_FILE = STATE_DIR / "ledger.jsonl"
LOCK_FILE = STATE_DIR / "state.lock"
from typing import Any

from codex_fable_state import (
FINDINGS_FILE,
GOALS_FILE,
LEDGER_FILE,
LOCK_FILE,
STATE_DIR,
append_event,
locked_state,
now,
read_json,
require_object,
write_json,
)

OPEN_STATUSES = {"pending", "in_progress"}
INCOMPLETE_TERMINAL_STATUSES = {"failed", "blocked"}
BLOCKING_FINDING_STATUSES = {"open", "blocked"}
GOAL_STATUSES = {"pending", "in_progress", "complete", "failed", "blocked"}
GOAL_REQUIRED_FIELDS = {"id", "title", "objective", "status", "evidence", "verify_cmd", "verify_evidence"}
FINDING_STATUSES = {"open", "blocked", "resolved", "rejected"}
FINDING_REQUIRED_FIELDS = {"id", "goal", "title", "severity", "source", "status", "evidence"}
LOCK_TIMEOUT_SECONDS = 30.0


def now() -> str:
return datetime.now(timezone.utc).isoformat()


def safe_stamp() -> str:
return now().replace(":", "").replace("+", "Z")


@contextmanager
def locked_state() -> Iterator[None]:
STATE_DIR.mkdir(exist_ok=True)
if fcntl is None:
fallback = STATE_DIR / "state.lockdir"
deadline = time.monotonic() + LOCK_TIMEOUT_SECONDS
while True:
try:
fallback.mkdir()
break
except FileExistsError:
if time.monotonic() >= deadline:
sys.exit(f"codex-fable5: timed out waiting for state lock ({fallback}).")
time.sleep(0.05)
try:
yield
finally:
fallback.rmdir()
return

with LOCK_FILE.open("a", encoding="utf-8") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)


def read_json(path: Path, label: str) -> Any:
try:
return json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
sys.exit(
f"codex-fable5: {label} is not valid JSON "
f"({path}:{exc.lineno}:{exc.colno}: {exc.msg})."
)


def write_json(path: Path, data: dict[str, Any]) -> None:
STATE_DIR.mkdir(exist_ok=True)
tmp_name = ""
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=STATE_DIR,
prefix=f".{path.name}.",
delete=False,
) as handle:
tmp_name = handle.name
handle.write(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
handle.flush()
os.fsync(handle.fileno())
Path(tmp_name).replace(path)


def append_event(event: str, **fields: Any) -> None:
STATE_DIR.mkdir(exist_ok=True)
record = {"ts": now(), "event": event, **fields}
with LEDGER_FILE.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, ensure_ascii=False) + "\n")


def require_object(value: Any, path: Path, label: str) -> dict[str, Any]:
if not isinstance(value, dict):
sys.exit(f"codex-fable5: {label} must be a JSON object ({path}).")
return value


def validate_plan(data: dict[str, Any], path: Path, label: str) -> dict[str, Any]:
if not isinstance(data.get("brief"), str):
sys.exit(f"codex-fable5: {label} field 'brief' must be a string ({path}).")
Expand Down
Loading