tempergraph 0.7.1__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.
Files changed (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. tempergraph_pytest_plugin.py +64 -0
@@ -0,0 +1,138 @@
1
+ """The per-thread run lock (WSP-B8, WSP-B9, WSP-B11, DUR-B9 `running`, DUR-B4).
2
+
3
+ An OS file lock held for the life of the run process. Observers probe it without creating the file and
4
+ for an instant only: a shared, non-blocking lock on an existing file that is released at once.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import contextlib
10
+ import json
11
+ import os
12
+ import sys
13
+ import time
14
+ from collections.abc import Iterator
15
+ from pathlib import Path
16
+ from typing import IO, Any
17
+
18
+ from tempergraph.constants import ENGINE_VERSION
19
+ from tempergraph.docs import write_json
20
+
21
+ if sys.platform != "win32":
22
+ import fcntl
23
+
24
+ def _try(fh: IO[Any], exclusive: bool) -> bool:
25
+ try:
26
+ fcntl.flock(fh.fileno(), (fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH) | fcntl.LOCK_NB)
27
+ return True
28
+ except OSError:
29
+ return False
30
+
31
+ def _release(fh: IO[Any]) -> None:
32
+ fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
33
+ else: # pragma: no cover - Windows
34
+ import msvcrt
35
+
36
+ def _try(fh: IO[Any], exclusive: bool) -> bool:
37
+ try:
38
+ fh.seek(0)
39
+ msvcrt.locking(fh.fileno(), msvcrt.LK_NBLCK, 1)
40
+ return True
41
+ except OSError:
42
+ return False
43
+
44
+ def _release(fh: IO[Any]) -> None:
45
+ fh.seek(0)
46
+ msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)
47
+
48
+
49
+ class LockHeld(Exception):
50
+ def __init__(self, path: Path, holder: dict[str, Any]) -> None:
51
+ super().__init__(f"run lock held: {path}")
52
+ self.path, self.holder = path, holder
53
+
54
+
55
+ def holder() -> dict[str, Any]:
56
+ """MIG-B8: the process and the engine it runs on, read by `update` and `--prune-engines`."""
57
+ env = Path(sys.prefix)
58
+ managed = env.parent.name == "engines"
59
+ return {"pid": os.getpid(), "engine_version": ENGINE_VERSION, "engine": env.name if managed else None,
60
+ "engine_digest": env.name.rsplit("-", 1)[-1] if managed else None}
61
+
62
+
63
+ class RunLock:
64
+ """Exclusive lock for one thread; use as a context manager."""
65
+
66
+ def __init__(self, path: Path) -> None:
67
+ self.path = path
68
+ self._fh: IO[Any] | None = None
69
+
70
+ def acquire(self) -> RunLock:
71
+ self.path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
72
+ fh = open(self.path, "a+") # noqa: SIM115 - held for the run's life
73
+ os.chmod(self.path, 0o600)
74
+ if not _try(fh, exclusive=True):
75
+ fh.close()
76
+ raise LockHeld(self.path, read_holder(self.path))
77
+ self._fh = fh
78
+ write_json(self.path.with_suffix(".holder.json"), holder())
79
+ return self
80
+
81
+ def release(self) -> None:
82
+ if self._fh is not None:
83
+ with contextlib.suppress(OSError):
84
+ self.path.with_suffix(".holder.json").unlink()
85
+ _release(self._fh)
86
+ self._fh.close()
87
+ self._fh = None
88
+
89
+ def __enter__(self) -> RunLock:
90
+ return self.acquire()
91
+
92
+ def __exit__(self, *exc: object) -> None:
93
+ self.release()
94
+
95
+
96
+ @contextlib.contextmanager
97
+ def exclusive(path: Path, timeout_s: float = 60.0) -> Iterator[None]:
98
+ """An exclusive OS lock held for the body (OUT-B30): waits up to `timeout_s`, then raises `LockHeld`. It writes
99
+ no holder file, so `is_held` sees it and the run lock is unchanged."""
100
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
101
+ fh = open(path, "a+") # noqa: SIM115 - closed below
102
+ try:
103
+ deadline = time.monotonic() + timeout_s
104
+ while not _try(fh, exclusive=True):
105
+ if time.monotonic() >= deadline:
106
+ raise LockHeld(path, {})
107
+ time.sleep(0.05)
108
+ try:
109
+ yield
110
+ finally:
111
+ _release(fh)
112
+ finally:
113
+ fh.close()
114
+
115
+
116
+ def read_holder(path: Path) -> dict[str, Any]:
117
+ try:
118
+ data = json.loads(path.with_suffix(".holder.json").read_text(encoding="utf-8"))
119
+ return data if isinstance(data, dict) else {}
120
+ except (OSError, ValueError):
121
+ return {}
122
+
123
+
124
+ def is_held(path: Path) -> bool:
125
+ """Probe the lock without creating it (DUR-B4)."""
126
+ if not path.exists():
127
+ return False
128
+ try:
129
+ fh = open(path) # noqa: SIM115
130
+ except OSError:
131
+ return False
132
+ try:
133
+ if _try(fh, exclusive=False):
134
+ _release(fh)
135
+ return False
136
+ return True
137
+ finally:
138
+ fh.close()
@@ -0,0 +1,390 @@
1
+ """Classification, the status document and wait (DUR-B9, DUR-B11, DUR-B4, DUR-B5).
2
+
3
+ All three are read-only and model-free: the checkpoint opens read-only, the lock is probed without
4
+ being created, and nothing is written. A wait rebuilds a row only when a file or the lock changed.
5
+
6
+ Fields the run has not recorded yet are left out, never zeroed (CON-B14, CON-B1, CON-B15).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import contextlib
12
+ import json
13
+ import time
14
+ from collections.abc import Callable, Mapping
15
+ from dataclasses import dataclass, field
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from tempergraph.constants import SCHEMA, ExitCode
21
+ from tempergraph.contracts import ThreadState, WorkflowSpec, thread_id
22
+ from tempergraph.durability import alias as aliases
23
+ from tempergraph.durability import engine_file
24
+ from tempergraph.durability.checkpoint import (
25
+ Snapshot,
26
+ classify_snapshot,
27
+ observer_graph,
28
+ open_readonly,
29
+ snapshot,
30
+ thread_ids,
31
+ )
32
+ from tempergraph.durability.lock import is_held
33
+ from tempergraph.model import flow
34
+ from tempergraph.store.layout import checkpoint_path, lock_path, now_iso, run_dir
35
+
36
+ RUN_FIELDS = ("attempt_in_flight", "last_verdict", "cost", "executors", "label", "origin", "rerun_of", "reruns",
37
+ "settings_digest", "overridden_keys", "parent", "schedule", "resume_count", "engine", "engine_pin", "exit_code")
38
+
39
+
40
+ def split_thread(tid: str) -> tuple[str, str]:
41
+ workflow, _, task = tid.partition("/")
42
+ return workflow, task
43
+
44
+
45
+ def _read(state_root: Path, spec: WorkflowSpec, tid: str) -> tuple[Snapshot, bool]:
46
+ _, task = split_thread(tid)
47
+ held = is_held(lock_path(state_root, spec.name, task))
48
+ with open_readonly(engine_file.checkpoint_of(state_root, spec.name, task)) as saver:
49
+ if saver is None:
50
+ return Snapshot(exists=False), held
51
+ return snapshot(observer_graph(spec, saver), tid), held
52
+
53
+
54
+ def breakpoint_at(state_root: Path, workflow: str, task_id: str) -> dict[str, Any] | None:
55
+ """The operator breakpoint a thread is paused at, if any (FLX-B10): a marker beside the run log."""
56
+ try:
57
+ doc = json.loads((run_dir(state_root, workflow, task_id) / "breakpoint.json").read_text(encoding="utf-8"))
58
+ except (OSError, ValueError):
59
+ return None
60
+ return doc if isinstance(doc, dict) else None
61
+
62
+
63
+ def _state(state_root: Path, spec: WorkflowSpec, tid: str, snap: Snapshot, held: bool) -> ThreadState:
64
+ state = classify_snapshot(snap, held)
65
+ if state is ThreadState.UNFINISHED and breakpoint_at(state_root, spec.name, split_thread(tid)[1]):
66
+ return ThreadState.PAUSED # nothing of the next unit ran; a person's `proceed` runs it
67
+ return state
68
+
69
+
70
+ def classify(state_root: Path, spec: WorkflowSpec, task_id: str) -> ThreadState:
71
+ """DUR-B9, DUR-B11 `classify`: read-only; creates nothing."""
72
+ tid = thread_id(spec.name, task_id)
73
+ snap, held = _read(state_root, spec, tid)
74
+ return _state(state_root, spec, tid, snap, held)
75
+
76
+
77
+ def resume_command(workflow: str, tid: str, decisions: list[str] | None = None) -> str:
78
+ from tempergraph.improve.pause_facts import OPERATOR_REASONS
79
+
80
+ cmd = f"tempergraph resume {workflow} {split_thread(tid)[1]}"
81
+ return cmd + (f" --decision <{'|'.join(decisions)}> --reason <{'|'.join(OPERATOR_REASONS)}>"
82
+ if decisions else "")
83
+
84
+
85
+ def _pending(workflow: str, tid: str, snap: Snapshot) -> list[dict[str, Any]]:
86
+ out = []
87
+ for node, payload in snap.interrupts:
88
+ p = payload if isinstance(payload, dict) else {}
89
+ unit = node.rsplit(".", 1)[0] if node.endswith(".human") else node
90
+ g = {"unit": unit, "item": p.get("item"), "kind": p.get("kind", "escalation"),
91
+ "resume": p.get("resume") or resume_command(workflow, tid, p.get("decisions"))}
92
+ if p.get("reason") == "usage_limit": # DUR-B13: the instant the account's limit lifts, value or None
93
+ g["usage_limit_resets_at"] = p.get("usage_limit_resets_at")
94
+ if p.get("deadline_at"): # FLX-B8: overdue until someone applies the deadline
95
+ g["deadline_at"] = p["deadline_at"]
96
+ g["on_deadline"] = p.get("on_deadline")
97
+ with contextlib.suppress(ValueError, TypeError):
98
+ due = datetime.fromisoformat(str(p["deadline_at"]))
99
+ g["overdue"] = datetime.now(due.tzinfo) >= due
100
+ out.append(g)
101
+ return out
102
+
103
+
104
+ def _input_counts(state_root: Path, workflow: str, tid: str, gates: list[dict[str, Any]], snap: Snapshot) -> None:
105
+ """ASK-B4: an `input` gate's count of required questions still unanswered, from the answers file."""
106
+ for g in gates:
107
+ if g["kind"] != "input":
108
+ continue
109
+ qs = ((snap.values.get("attempts") or {}).get(g["unit"]) or {}).get("questions") or []
110
+ try:
111
+ doc = json.loads((run_dir(state_root, workflow, split_thread(tid)[1]) / "answers"
112
+ / f"{g['unit']}.json").read_text(encoding="utf-8"))
113
+ have = set(doc.get("answers") or {})
114
+ except (OSError, ValueError, AttributeError):
115
+ have = set()
116
+ g["questions"] = len(qs)
117
+ g["unanswered"] = sum(1 for q in qs if q.get("required", True) and q.get("name") not in have)
118
+
119
+
120
+ def _settings(state_root: Path, spec: WorkflowSpec, options: Any) -> dict[str, Any]:
121
+ """RST-B27: the thread's digest and overridden keys from its snapshot, and `settings_stale` when the
122
+ settings files now resolve differently. Read-only; a snapshot it cannot read adds nothing."""
123
+ if not isinstance(options, dict) or not options.get("settings"):
124
+ return {}
125
+ from tempergraph import settings as rst
126
+ from tempergraph.contracts import RunOptions
127
+ from tempergraph.store.layout import home_path
128
+
129
+ try:
130
+ opts = RunOptions(settings={k: dict(v) for k, v in options["settings"].items()},
131
+ profiles=tuple(options.get("profiles") or ()))
132
+ then = rst.resolve(spec, opts)
133
+ out: dict[str, Any] = {"settings_digest": then.digest, "overridden_keys": rst.overridden_keys(then)}
134
+ files = rst.load_files(state_root, home_path())
135
+ out["settings_stale"] = None if files.errors else rst.resolve(spec, opts, files).digest != then.digest
136
+ return out
137
+ except Exception: # noqa: BLE001 - a status row never fails on its settings (DUR-B10, DUR-B3, DUR-B11)
138
+ return {}
139
+
140
+
141
+ def _lineage(state_root: Path, workflow: str, tid: str, run: Mapping[str, Any]) -> dict[str, Any]:
142
+ """RRN-B17, RRN-B18: the source of a rerun (from the thread's state) and the reruns made from it (`lineage.json`)."""
143
+ out: dict[str, Any] = {}
144
+ src = run.get("rerun_of") or (run.get("meta") or {}).get("rerun_of")
145
+ if isinstance(src, dict):
146
+ out["rerun_of"] = {k: src.get(k) for k in ("thread", "unit", "checkpoint_id", "workflow_version")}
147
+ try:
148
+ doc = json.loads((run_dir(state_root, workflow, split_thread(tid)[1]) / "lineage.json").read_text("utf-8"))
149
+ made = [{"thread": x.get("thread"), "from": x.get("from"), "at": x.get("at"),
150
+ **({"same_branch": True} if x.get("same_branch") else {})}
151
+ for x in doc.get("reruns") or [] if isinstance(x, dict)]
152
+ superseded = doc.get("superseded_by") if isinstance(doc, dict) else None
153
+ except (OSError, ValueError, AttributeError):
154
+ made, superseded = [], None
155
+ if made:
156
+ out["reruns"] = made
157
+ if isinstance(superseded, str):
158
+ out["superseded_by"] = superseded # RRN-B17, RRN-B18: a `--same-branch` rerun took this finished thread's branch
159
+ return out
160
+
161
+
162
+ def row(state_root: Path, spec: WorkflowSpec, tid: str) -> dict[str, Any]:
163
+ snap, held = _read(state_root, spec, tid)
164
+ state = _state(state_root, spec, tid, snap, held)
165
+ gates = _pending(spec.name, tid, snap)
166
+ _input_counts(state_root, spec.name, tid, gates, snap)
167
+ bp = breakpoint_at(state_root, spec.name, split_thread(tid)[1]) if state is ThreadState.PAUSED and not gates \
168
+ else None
169
+ if bp:
170
+ gates.append({"unit": bp.get("unit"), "item": None, "kind": "breakpoint", "resume": bp.get("resume")})
171
+ r: dict[str, Any] = {"thread_id": tid, "workflow": spec.name, "state": str(state), "alive": held,
172
+ "pending_gates": gates,
173
+ "log_path": str(run_dir(state_root, spec.name, split_thread(tid)[1]) / "run.jsonl")}
174
+ if state is ThreadState.UNFINISHED: # DUR-B15: an unfinished thread continues with the plain command
175
+ r["resume"] = resume_command(spec.name, tid)
176
+ limited = [g["usage_limit_resets_at"] for g in gates if "usage_limit_resets_at" in g]
177
+ if limited: # DUR-B13: the latest reset of the pending usage-limit pauses
178
+ known = [x for x in limited if x is not None]
179
+ r["usage_limit_resets_at"] = max(known) if known else None
180
+ run = snap.values.get("run") or {}
181
+ for key in RUN_FIELDS:
182
+ if key in run:
183
+ r[key] = run[key]
184
+ sched = (run.get("meta") or {}).get("schedule") # TCK-B24: a scheduled run's fire, beside `parent`
185
+ if sched and "schedule" not in r:
186
+ r["origin"], r["schedule"] = "schedule", dict(sched)
187
+ if run.get("degraded"): # FLX-AC4: a run that took a fallback is never shown without it
188
+ r["degraded"] = True
189
+ r["degraded_unit"] = (run["degraded"] or {}).get("unit")
190
+ fin = snap.values.get("finalized") or {}
191
+ if fin.get("manual_steps") or fin.get("outcome") == "error": # FIN-B8: the steps a person still has to take
192
+ r["finalizer"] = {"outcome": fin.get("outcome"), "reason": fin.get("reason") or "",
193
+ "manual_steps": list(fin.get("manual_steps") or [])}
194
+ r.update(_settings(state_root, spec, run.get("options")))
195
+ r.update(_lineage(state_root, spec.name, tid, run))
196
+ try: # DUR-B17: the two filing words of the newest loop summary; none before a child has ended
197
+ from tempergraph.improve import loop_summary
198
+
199
+ newest = loop_summary.thread_newest(state_root, spec.name, split_thread(tid)[1]) or {}
200
+ r.update({k: newest[k] for k in ("filing", "filing_source") if newest.get(k)})
201
+ r.update({k: newest[k] for k in ("capped", "issue_cap") if newest.get(k) is not None}) # a 0 is shown
202
+ except Exception: # noqa: BLE001 - a status row never fails on the loop's files (DUR-B10)
203
+ pass
204
+ ws = (snap.values.get("workspace") or {})
205
+ if ws:
206
+ r["workspace"] = {k: ws.get(k) for k in ("mode", "path", "branch", "state") if k in ws}
207
+ exit_path = run_dir(state_root, spec.name, split_thread(tid)[1]) / "exit.json"
208
+ if exit_path.exists() and state is not ThreadState.RUNNING:
209
+ try:
210
+ ex = json.loads(exit_path.read_text(encoding="utf-8"))
211
+ r.setdefault("exit_code", ex.get("exit_code"))
212
+ r["exit_reason"] = ex.get("reason")
213
+ except (OSError, ValueError):
214
+ pass
215
+ name = aliases.alias_of(state_root, tid)
216
+ if name:
217
+ r["alias"] = name
218
+ from tempergraph.durability import carry
219
+
220
+ carried = carry.marker(state_root, spec.name, split_thread(tid)[1])
221
+ if carried.get("on") or carried.get("state") in ("unpushed", "delete_failed"): # CAR-B5, CAR-B8, CAR-B11, CAR-B6
222
+ r["carry"] = carried.get("state") or "on"
223
+ eng = engine_file.read(state_root, spec.name, split_thread(tid)[1]) # MIG-B8
224
+ if (eng.get("last_on") or {}).get("engine_version"):
225
+ r["engine"] = eng["last_on"]["engine_version"]
226
+ r["engine_digest"] = eng["last_on"].get("engine_digest") # the build and program of the last process
227
+ r["program"] = eng["last_on"].get("program")
228
+ if eng.get("pinned"):
229
+ r["engine_pin"] = dict(eng["pinned"])
230
+ if snap.next and state is ThreadState.UNFINISHED:
231
+ r["next"] = [n for n in snap.next if n != flow.FINALIZER] or list(snap.next)
232
+ return r
233
+
234
+
235
+ @dataclass(frozen=True, kw_only=True)
236
+ class Selector:
237
+ """A thread id, an alias, a workflow name, or everything (None)."""
238
+
239
+ value: str | None = None
240
+
241
+
242
+ def _threads(state_root: Path, spec: WorkflowSpec) -> list[str]:
243
+ """Every thread in the databases of the checkpoint formats this engine resumes (MIG-B12, MIG-B13, MIG-B14)."""
244
+ out: list[str] = []
245
+ for fmt in sorted({*engine_file.resumes(), engine_file.checkpoint_format()}):
246
+ with open_readonly(checkpoint_path(state_root, spec.name, fmt)) as saver:
247
+ out += [t for t in (thread_ids(saver) if saver is not None else []) if t not in out]
248
+ return out
249
+
250
+
251
+ def select(state_root: Path, specs: Mapping[str, WorkflowSpec], sel: Selector) -> list[tuple[WorkflowSpec, str]]:
252
+ v = sel.value
253
+ if v is None or v in specs:
254
+ names = [v] if v else sorted(specs)
255
+ return [(specs[n], t) for n in names for t in _threads(state_root, specs[n])]
256
+ if "/" in v and split_thread(v)[0] in specs:
257
+ return [(specs[split_thread(v)[0]], v)]
258
+
259
+ def live(t: str) -> bool:
260
+ w = split_thread(t)[0]
261
+ return w in specs and classify_snapshot(*_read(state_root, specs[w], t)) not in (
262
+ ThreadState.FINISHED, ThreadState.NONE)
263
+
264
+ tid = aliases.resolve(state_root, v, live)
265
+ if tid and split_thread(tid)[0] in specs:
266
+ return [(specs[split_thread(tid)[0]], tid)]
267
+ return []
268
+
269
+
270
+ def status(state_root: Path, specs: Mapping[str, WorkflowSpec], sel: Selector | None = None) -> dict[str, Any]:
271
+ rows = []
272
+ for spec, tid in select(state_root, specs, sel or Selector()):
273
+ try:
274
+ rows.append(row(state_root, spec, tid))
275
+ except Exception as exc: # noqa: BLE001 - one unreadable thread marks only its row (DUR-B10, DUR-B3, DUR-B11)
276
+ rows.append({"thread_id": tid, "workflow": spec.name, "state": "unreadable", "error": type(exc).__name__})
277
+ return {"schema_version": SCHEMA["status"], "generated_at": now_iso(), "threads": rows}
278
+
279
+
280
+ # ---------------------------------------------------------------------------------------------
281
+ # wait (DUR-B5)
282
+
283
+
284
+ @dataclass(kw_only=True)
285
+ class WaitOutcome:
286
+ state: str
287
+ exit_code: ExitCode
288
+ row: dict[str, Any] = field(default_factory=dict)
289
+ reason: str = ""
290
+
291
+
292
+ EXIT_FOR = {"finished": ExitCode.FINISHED, "paused": ExitCode.PAUSED, "stopped": ExitCode.STOPPED,
293
+ "unfinished": ExitCode.STOPPED, "none": ExitCode.USAGE}
294
+
295
+
296
+ def _signature(paths: list[Path]) -> tuple[tuple[int, int], ...]:
297
+ sig = []
298
+ for p in paths:
299
+ try:
300
+ st = p.stat()
301
+ sig.append((st.st_size, st.st_mtime_ns))
302
+ except OSError:
303
+ sig.append((-1, -1))
304
+ return tuple(sig)
305
+
306
+
307
+ def _observed(paths: list[Path], lock: Path) -> tuple[Any, ...]:
308
+ """What a waiter compares between polls: the files' sizes and times and whether the run lock is held.
309
+
310
+ The release of the lock moves no watched file, so the held flag is part of the value (DUR-B18)."""
311
+ return (_signature(paths), is_held(lock))
312
+
313
+
314
+ def wait(state_root: Path, spec: WorkflowSpec, tid: str, timeout_s: float, *, poll_s: float = 0.5,
315
+ clock: Callable[[], float] = time.monotonic, sleep: Callable[[float], None] = time.sleep) -> WaitOutcome:
316
+ """Block until the thread pauses, ends or records a new verdict, or the timeout passes.
317
+
318
+ Polls file sizes and times and the run lock, and rebuilds the row only when a file or the lock changed."""
319
+ _, task = split_thread(tid)
320
+ db = engine_file.checkpoint_of(state_root, spec.name, task)
321
+ lock = lock_path(state_root, spec.name, task)
322
+ watched = [db, db.with_name(db.name + "-wal"), lock, run_dir(state_root, spec.name, task) / "run.jsonl"]
323
+ start = clock()
324
+ sig: tuple[Any, ...] | None = None
325
+ first_verdict: Any = None
326
+ while True:
327
+ now_sig = _observed(watched, lock)
328
+ if now_sig != sig:
329
+ sig = now_sig
330
+ r = row(state_root, spec, tid)
331
+ verdict = r.get("last_verdict")
332
+ if first_verdict is None:
333
+ first_verdict = verdict if verdict is not None else ""
334
+ elif verdict is not None and verdict != first_verdict:
335
+ return WaitOutcome(state=r["state"], exit_code=ExitCode.FINISHED, row=r, reason="verdict")
336
+ if r["state"] != "running":
337
+ code = r.get("exit_code")
338
+ exit_code = ExitCode(code) if isinstance(code, int) and code in set(ExitCode) else EXIT_FOR.get(
339
+ r["state"], ExitCode.INTERNAL)
340
+ return WaitOutcome(state=r["state"], exit_code=exit_code, row=r, reason="state")
341
+ if clock() - start >= timeout_s:
342
+ return WaitOutcome(state="running", exit_code=ExitCode.BUDGET_OR_INFRA, reason="timeout")
343
+ sleep(poll_s)
344
+
345
+
346
+ @dataclass(kw_only=True)
347
+ class WaitAnyOutcome:
348
+ state: str
349
+ exit_code: ExitCode
350
+ row: dict[str, Any] = field(default_factory=dict)
351
+ reason: str = ""
352
+ threads: list[dict[str, Any]] = field(default_factory=list)
353
+
354
+
355
+ def wait_any(state_root: Path, threads: list[tuple[WorkflowSpec, str]], timeout_s: float, *, poll_s: float = 0.5,
356
+ clock: Callable[[], float] = time.monotonic,
357
+ sleep: Callable[[float], None] = time.sleep) -> WaitAnyOutcome:
358
+ """DUR-B16: block until the first of several threads is not running (a pause or any end), or the timeout passes.
359
+
360
+ A new gate verdict on a running thread does not end the wait. Each thread's row is rebuilt only when one of its
361
+ files or its run lock changed."""
362
+ watched: list[list[Path]] = []
363
+ locks: list[Path] = []
364
+ for spec, tid in threads:
365
+ _, task = split_thread(tid)
366
+ db = engine_file.checkpoint_of(state_root, spec.name, task)
367
+ locks.append(lock_path(state_root, spec.name, task))
368
+ watched.append([db, db.with_name(db.name + "-wal"), locks[-1],
369
+ run_dir(state_root, spec.name, task) / "run.jsonl"])
370
+ sigs: list[tuple[Any, ...] | None] = [None] * len(threads)
371
+ states: dict[str, str] = {}
372
+ start = clock()
373
+ while True:
374
+ for i, (spec, tid) in enumerate(threads):
375
+ now_sig = _observed(watched[i], locks[i])
376
+ if now_sig == sigs[i]:
377
+ continue
378
+ sigs[i] = now_sig
379
+ r = row(state_root, spec, tid)
380
+ states[tid] = r["state"]
381
+ if r["state"] != "running":
382
+ code = r.get("exit_code")
383
+ exit_code = ExitCode(code) if isinstance(code, int) and code in set(ExitCode) else EXIT_FOR.get(
384
+ r["state"], ExitCode.INTERNAL)
385
+ return WaitAnyOutcome(state=r["state"], exit_code=exit_code, row=r, reason="state",
386
+ threads=[{"thread_id": t, "state": states.get(t)} for _, t in threads])
387
+ if clock() - start >= timeout_s:
388
+ return WaitAnyOutcome(state="running", exit_code=ExitCode.BUDGET_OR_INFRA, reason="timeout",
389
+ threads=[{"thread_id": t, "state": states.get(t)} for _, t in threads])
390
+ sleep(poll_s)
@@ -0,0 +1,42 @@
1
+ """Which engine made a report: its build label and the folder it was imported from (EID-B1, EID-B2)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import tempergraph
8
+ from tempergraph.constants import ENGINE_VERSION
9
+
10
+ INSTALLED = "installed"
11
+
12
+
13
+ def _package_dir() -> Path:
14
+ """The folder that holds the `tempergraph` package the running engine was imported from."""
15
+ return Path(tempergraph.__file__).resolve().parents[1]
16
+
17
+
18
+ def build_label(engine_root: Path | None = None) -> str:
19
+ """EID-B1: the version, a hyphen and the first 12 characters of the source digest, or the version alone."""
20
+ from tempergraph.install.environment import source_digest
21
+
22
+ root = Path(engine_root) if engine_root is not None else _package_dir().parent
23
+ if not (root / "pyproject.toml").is_file():
24
+ return ENGINE_VERSION
25
+ try:
26
+ return f"{ENGINE_VERSION}-{source_digest(root)[:12]}"
27
+ except OSError:
28
+ return ENGINE_VERSION
29
+
30
+
31
+ def source_label(cwd: Path, package_dir: Path | str | None = None) -> str:
32
+ """EID-B2: the folder that holds the package, relative to `cwd` with `/`, or `installed` outside it."""
33
+ folder = Path(package_dir).resolve() if package_dir is not None else _package_dir()
34
+ try:
35
+ rel = folder.relative_to(Path(cwd).resolve())
36
+ except ValueError:
37
+ return INSTALLED
38
+ return rel.as_posix().strip("/") or "."
39
+
40
+
41
+ def identity(cwd: Path) -> dict[str, str]:
42
+ return {"engine": build_label(), "source": source_label(cwd)}
@@ -0,0 +1,56 @@
1
+ """The executor compatibility table (LIF-B7 to LIF-B16, LIF-AC4): per executor, the versions its probe facts or contract
2
+ tests were recorded for. Outside the range: a warning, and capabilities are projected (EAG-B7)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import re
8
+ from functools import cache
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from tempergraph.model.validate import Finding
13
+
14
+ TABLE = Path(__file__).parent / "data" / "executor_compat.json"
15
+
16
+
17
+ @cache
18
+ def table() -> dict[str, Any]:
19
+ doc = json.loads(TABLE.read_text(encoding="utf-8"))
20
+ return dict(doc.get("executors") or {})
21
+
22
+
23
+ def _v(text: str) -> tuple[int, ...]:
24
+ m = re.search(r"(\d+(?:\.\d+)*)", text)
25
+ return tuple(int(x) for x in m.group(1).split(".")) if m else ()
26
+
27
+
28
+ def in_range(version: str, spec_range: str) -> bool:
29
+ v = _v(version)
30
+ for part in (p.strip() for p in spec_range.split(",") if p.strip()):
31
+ m = re.match(r"^(>=|<=|==|<|>)\s*(\S+)$", part)
32
+ if m is None or not v:
33
+ return False
34
+ b = _v(m.group(2))
35
+ if not {">=": v >= b, "<=": v <= b, "==": v == b, "<": v < b, ">": v > b}[m.group(1)]:
36
+ return False
37
+ return True
38
+
39
+
40
+ def row(executor: str, version: str | None) -> dict[str, Any]:
41
+ """What `executors` shows: the recorded versions, the range, and whether this version is inside it."""
42
+ t = table().get(executor)
43
+ if t is None:
44
+ return {"executor": executor, "state": "no_table"}
45
+ state = "unknown_version" if not version or not _v(version) else ("recorded" if in_range(version, t["range"]) else "outside")
46
+ return {"executor": executor, "version": version, "range": t["range"], "recorded": t.get("recorded", []),
47
+ "state": state}
48
+
49
+
50
+ def finding(executor: str, version: str | None) -> Finding | None:
51
+ """For preflight: a warning when the probed version lies outside the recorded range."""
52
+ r = row(executor, version)
53
+ if r["state"] == "outside":
54
+ return Finding("executor-version-untested", None, f"{executor} {version} is outside the versions its facts "
55
+ f"were recorded for ({r['range']}); capabilities are projected", "warning")
56
+ return None
@@ -0,0 +1,4 @@
1
+ """The executor layer (EXI): the only part of the engine that knows how a model session is started.
2
+
3
+ Only modules of this package import a concrete executor (EXI-AC1).
4
+ """