Initial release: aircontext
This commit is contained in:
93
scripts/core/state.py
Normal file
93
scripts/core/state.py
Normal file
@@ -0,0 +1,93 @@
|
||||
"""state.json read/write — shared between wrapper, hooks, and compactor.
|
||||
|
||||
Schema:
|
||||
{
|
||||
"config_missing": bool, # set by SessionStart hook when AirContext/ template was just created
|
||||
"last_session_id": str | None, # the most recent claude session id we observed
|
||||
"pending_resume_session_id": str | null,# session id to resume after wrapper terminates claude
|
||||
"compaction_ready": bool, # compactor sets to true; wrapper consumes
|
||||
"compaction_in_progress": bool, # compactor sets to true while running, prevents re-entry
|
||||
"last_compaction_unix": int, # cooldown reference
|
||||
"last_tool_count_at_compact": int, # for tool_count strategy (reserved)
|
||||
"paused": bool # /aircontext-pause toggle
|
||||
}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
_DEFAULT: dict[str, Any] = {
|
||||
"config_missing": False,
|
||||
"last_session_id": None,
|
||||
"pending_resume_session_id": None,
|
||||
"compaction_ready": False,
|
||||
"compaction_in_progress": False,
|
||||
"last_compaction_unix": 0,
|
||||
"last_tool_count_at_compact": 0,
|
||||
"paused": False,
|
||||
}
|
||||
|
||||
|
||||
class StateFile:
|
||||
"""Best-effort JSON state store. Writes are atomic via tmp-file rename.
|
||||
|
||||
Concurrency: hook scripts and the wrapper read/write concurrently. We accept
|
||||
last-write-wins semantics for non-critical fields. The compactor uses a
|
||||
separate lock file (see compactor.py) for the critical 'do not start two
|
||||
compactions at once' invariant.
|
||||
"""
|
||||
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not self.path.exists():
|
||||
self._write_atomic(_DEFAULT.copy())
|
||||
|
||||
@property
|
||||
def last_session_id(self) -> str | None:
|
||||
return self.read().get("last_session_id")
|
||||
|
||||
def read(self) -> dict[str, Any]:
|
||||
try:
|
||||
with self.path.open("r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
data = _DEFAULT.copy()
|
||||
# backfill defaults for forward-compat
|
||||
for k, v in _DEFAULT.items():
|
||||
data.setdefault(k, v)
|
||||
return data
|
||||
|
||||
def update(self, **kwargs: Any) -> dict[str, Any]:
|
||||
data = self.read()
|
||||
data.update(kwargs)
|
||||
self._write_atomic(data)
|
||||
return data
|
||||
|
||||
def reset_for_new_session(self) -> None:
|
||||
self.update(
|
||||
compaction_ready=False,
|
||||
compaction_in_progress=False,
|
||||
pending_resume_session_id=None,
|
||||
)
|
||||
|
||||
def clear_ready(self) -> None:
|
||||
self.update(compaction_ready=False, pending_resume_session_id=None)
|
||||
|
||||
def _write_atomic(self, data: dict[str, Any]) -> None:
|
||||
# tempfile in same dir so os.replace is atomic on the same filesystem
|
||||
fd, tmp = tempfile.mkstemp(prefix=".state.", suffix=".tmp", dir=str(self.path.parent))
|
||||
try:
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
os.replace(tmp, self.path)
|
||||
except Exception:
|
||||
try:
|
||||
os.unlink(tmp)
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
Reference in New Issue
Block a user