|
4 | 4 | from __future__ import annotations |
5 | 5 |
|
6 | 6 | import argparse |
7 | | -from contextlib import contextmanager |
8 | | -import json |
9 | | -import os |
10 | 7 | import sys |
11 | | -import tempfile |
12 | | -import time |
13 | | -from datetime import datetime, timezone |
14 | 8 | from pathlib import Path |
15 | | -from typing import Any, Iterator |
16 | | - |
17 | | -try: |
18 | | - import fcntl |
19 | | -except ImportError: # pragma: no cover - Windows fallback only. |
20 | | - fcntl = None |
21 | | - |
22 | | -STATE_DIR = Path(".codex-fable5") |
23 | | -GOALS_FILE = STATE_DIR / "goals.json" |
24 | | -FINDINGS_FILE = STATE_DIR / "findings.json" |
25 | | -LEDGER_FILE = STATE_DIR / "ledger.jsonl" |
26 | | -LOCK_FILE = STATE_DIR / "state.lock" |
| 9 | +from typing import Any |
| 10 | + |
| 11 | +from codex_fable_state import ( |
| 12 | + FINDINGS_FILE, |
| 13 | + GOALS_FILE, |
| 14 | + LEDGER_FILE, |
| 15 | + LOCK_FILE, |
| 16 | + STATE_DIR, |
| 17 | + append_event, |
| 18 | + locked_state, |
| 19 | + now, |
| 20 | + read_json, |
| 21 | + require_object, |
| 22 | + write_json, |
| 23 | +) |
| 24 | + |
27 | 25 | OPEN_STATUSES = {"pending", "in_progress"} |
28 | 26 | INCOMPLETE_TERMINAL_STATUSES = {"failed", "blocked"} |
29 | 27 | BLOCKING_FINDING_STATUSES = {"open", "blocked"} |
30 | 28 | GOAL_STATUSES = {"pending", "in_progress", "complete", "failed", "blocked"} |
31 | 29 | GOAL_REQUIRED_FIELDS = {"id", "title", "objective", "status", "evidence", "verify_cmd", "verify_evidence"} |
32 | 30 | FINDING_STATUSES = {"open", "blocked", "resolved", "rejected"} |
33 | 31 | FINDING_REQUIRED_FIELDS = {"id", "goal", "title", "severity", "source", "status", "evidence"} |
34 | | -LOCK_TIMEOUT_SECONDS = 30.0 |
35 | | - |
36 | | - |
37 | | -def now() -> str: |
38 | | - return datetime.now(timezone.utc).isoformat() |
39 | 32 |
|
40 | 33 |
|
41 | 34 | def safe_stamp() -> str: |
42 | 35 | return now().replace(":", "").replace("+", "Z") |
43 | 36 |
|
44 | 37 |
|
45 | | -@contextmanager |
46 | | -def locked_state() -> Iterator[None]: |
47 | | - STATE_DIR.mkdir(exist_ok=True) |
48 | | - if fcntl is None: |
49 | | - fallback = STATE_DIR / "state.lockdir" |
50 | | - deadline = time.monotonic() + LOCK_TIMEOUT_SECONDS |
51 | | - while True: |
52 | | - try: |
53 | | - fallback.mkdir() |
54 | | - break |
55 | | - except FileExistsError: |
56 | | - if time.monotonic() >= deadline: |
57 | | - sys.exit(f"codex-fable5: timed out waiting for state lock ({fallback}).") |
58 | | - time.sleep(0.05) |
59 | | - try: |
60 | | - yield |
61 | | - finally: |
62 | | - fallback.rmdir() |
63 | | - return |
64 | | - |
65 | | - with LOCK_FILE.open("a", encoding="utf-8") as handle: |
66 | | - fcntl.flock(handle, fcntl.LOCK_EX) |
67 | | - try: |
68 | | - yield |
69 | | - finally: |
70 | | - fcntl.flock(handle, fcntl.LOCK_UN) |
71 | | - |
72 | | - |
73 | | -def read_json(path: Path, label: str) -> Any: |
74 | | - try: |
75 | | - return json.loads(path.read_text(encoding="utf-8")) |
76 | | - except json.JSONDecodeError as exc: |
77 | | - sys.exit( |
78 | | - f"codex-fable5: {label} is not valid JSON " |
79 | | - f"({path}:{exc.lineno}:{exc.colno}: {exc.msg})." |
80 | | - ) |
81 | | - |
82 | | - |
83 | | -def write_json(path: Path, data: dict[str, Any]) -> None: |
84 | | - STATE_DIR.mkdir(exist_ok=True) |
85 | | - tmp_name = "" |
86 | | - with tempfile.NamedTemporaryFile( |
87 | | - "w", |
88 | | - encoding="utf-8", |
89 | | - dir=STATE_DIR, |
90 | | - prefix=f".{path.name}.", |
91 | | - delete=False, |
92 | | - ) as handle: |
93 | | - tmp_name = handle.name |
94 | | - handle.write(json.dumps(data, ensure_ascii=False, indent=2) + "\n") |
95 | | - handle.flush() |
96 | | - os.fsync(handle.fileno()) |
97 | | - Path(tmp_name).replace(path) |
98 | | - |
99 | | - |
100 | | -def append_event(event: str, **fields: Any) -> None: |
101 | | - STATE_DIR.mkdir(exist_ok=True) |
102 | | - record = {"ts": now(), "event": event, **fields} |
103 | | - with LEDGER_FILE.open("a", encoding="utf-8") as handle: |
104 | | - handle.write(json.dumps(record, ensure_ascii=False) + "\n") |
105 | | - |
106 | | - |
107 | | -def require_object(value: Any, path: Path, label: str) -> dict[str, Any]: |
108 | | - if not isinstance(value, dict): |
109 | | - sys.exit(f"codex-fable5: {label} must be a JSON object ({path}).") |
110 | | - return value |
111 | | - |
112 | | - |
113 | 38 | def validate_plan(data: dict[str, Any], path: Path, label: str) -> dict[str, Any]: |
114 | 39 | if not isinstance(data.get("brief"), str): |
115 | 40 | sys.exit(f"codex-fable5: {label} field 'brief' must be a string ({path}).") |
|
0 commit comments