sim-cli-core 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
sim/history.py ADDED
@@ -0,0 +1,170 @@
1
+ """Global run history — append-only JSON Lines at ~/.sim/history.jsonl.
2
+
3
+ Replaces the per-project `.sim/runs/NNN.json` layout used by `RunStore`.
4
+ Every `sim run` (one-shot) and every `/exec` call through a live session
5
+ appends one record here. The record shape is pinned by
6
+ `docs/architecture/multi-session-and-config.md` §2 — all fields are
7
+ always present (nulls / empty strings for unused dimensions).
8
+
9
+ Filtering is the reader's job — callers pass `cwd`, `solver`, or
10
+ `session_id` to narrow the view. The file itself is a pure append log.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import datetime as _dt
15
+ import json
16
+ from pathlib import Path
17
+ from typing import Any, Iterable
18
+
19
+ from sim import config as _cfg
20
+
21
+
22
+ SCHEMA_FIELDS = (
23
+ "ts",
24
+ "cwd",
25
+ "session_id",
26
+ "solver",
27
+ "run_id",
28
+ "kind",
29
+ "label",
30
+ "ok",
31
+ "duration_ms",
32
+ "error",
33
+ "parsed_output",
34
+ )
35
+
36
+
37
+ def _now_utc_iso() -> str:
38
+ return _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
39
+
40
+
41
+ def _ensure_file() -> Path:
42
+ path = _cfg.history_path()
43
+ path.parent.mkdir(parents=True, exist_ok=True)
44
+ if not path.exists():
45
+ path.touch()
46
+ return path
47
+
48
+
49
+ def _normalize(record: dict[str, Any]) -> dict[str, Any]:
50
+ """Fill in missing schema fields so every line has the same columns."""
51
+ out = {
52
+ "ts": record.get("ts") or _now_utc_iso(),
53
+ "cwd": record.get("cwd") or str(Path.cwd()),
54
+ "session_id": record.get("session_id") or "",
55
+ "solver": record.get("solver") or "",
56
+ "run_id": record.get("run_id") or "",
57
+ "kind": record.get("kind") or "run",
58
+ "label": record.get("label") or "",
59
+ "ok": bool(record.get("ok", False)),
60
+ "duration_ms": int(record.get("duration_ms", 0) or 0),
61
+ "error": record.get("error"),
62
+ }
63
+ # Parsed output is optional but commonly present for one-shot runs.
64
+ if "parsed_output" in record:
65
+ out["parsed_output"] = record["parsed_output"]
66
+ # Preserve script path for one-shot runs so `sim logs` can show it.
67
+ if "script" in record:
68
+ out["script"] = record["script"]
69
+ return out
70
+
71
+
72
+ def append(record: dict[str, Any]) -> str:
73
+ """Append one record and return its `run_id` (allocates if missing)."""
74
+ rec = _normalize(record)
75
+ if not rec["run_id"]:
76
+ rec["run_id"] = _next_run_id()
77
+ path = _ensure_file()
78
+ with path.open("a", encoding="utf-8") as f:
79
+ f.write(json.dumps(rec, default=str) + "\n")
80
+ return rec["run_id"]
81
+
82
+
83
+ def _next_run_id() -> str:
84
+ """Scan existing records for max numeric id and return id+1.
85
+
86
+ Kept simple — for throughput-bound workflows we'd move to UUIDs, but
87
+ at human-CLI pace monotonic ints are more readable in `sim logs`.
88
+ """
89
+ records = _read_raw()
90
+ max_n = 0
91
+ for r in records:
92
+ rid = r.get("run_id", "")
93
+ try:
94
+ n = int(rid)
95
+ except (TypeError, ValueError):
96
+ continue
97
+ if n > max_n:
98
+ max_n = n
99
+ return f"{max_n + 1:03d}"
100
+
101
+
102
+ def _read_raw() -> list[dict]:
103
+ path = _cfg.history_path()
104
+ if not path.is_file():
105
+ return []
106
+ out: list[dict] = []
107
+ for line in path.read_text(encoding="utf-8").splitlines():
108
+ line = line.strip()
109
+ if not line:
110
+ continue
111
+ try:
112
+ out.append(json.loads(line))
113
+ except json.JSONDecodeError:
114
+ continue # skip corrupt lines rather than fail
115
+ return out
116
+
117
+
118
+ def read(
119
+ *,
120
+ cwd: str | Path | None = None,
121
+ solver: str | None = None,
122
+ session_id: str | None = None,
123
+ limit: int | None = None,
124
+ ) -> list[dict]:
125
+ """Read records with optional filters. Most recent first."""
126
+ records = _read_raw()
127
+ if cwd is not None:
128
+ cwd_s = str(Path(cwd).resolve())
129
+ records = [r for r in records if _resolve_cwd(r.get("cwd", "")) == cwd_s]
130
+ if solver is not None:
131
+ records = [r for r in records if r.get("solver") == solver]
132
+ if session_id is not None:
133
+ records = [r for r in records if r.get("session_id") == session_id]
134
+ # Newest first: reverse write order.
135
+ records = list(reversed(records))
136
+ if limit is not None:
137
+ records = records[:limit]
138
+ return records
139
+
140
+
141
+ def _resolve_cwd(raw: str) -> str:
142
+ """Best-effort resolve of a stored cwd for comparison. Missing path stays as-is."""
143
+ if not raw:
144
+ return ""
145
+ try:
146
+ return str(Path(raw).resolve())
147
+ except OSError:
148
+ return raw
149
+
150
+
151
+ def get_by_id(run_id: str, *, cwd: str | Path | None = None) -> dict | None:
152
+ """Look up a single record by id. `last` returns the most recent record.
153
+
154
+ When `cwd` is given, filters to that project scope (both for `last`
155
+ and for numeric ids). Returns None if nothing matches.
156
+ """
157
+ records = read(cwd=cwd)
158
+ if not records:
159
+ return None
160
+ if run_id == "last":
161
+ return records[0]
162
+ for r in records:
163
+ if r.get("run_id") == run_id:
164
+ return r
165
+ return None
166
+
167
+
168
+ def iter_all() -> Iterable[dict]:
169
+ """Iterate every record, in write order. Useful for tools that stream."""
170
+ yield from _read_raw()