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,377 @@
1
+ """The tick: one OS-agnostic, deterministic, model-free routine that decides what is due and starts it (TCK-B16, TCK-B12,
2
+ TCK-B2; ADR `a-model-free-tick-behind-os-agnostic-triggers`).
3
+
4
+ Every edge is injected (clock, run launcher, credential resolver, thread-status reader, repository check), so the tick
5
+ is tested with a fake clock and a scripted launcher and starts no model. The decisions are the pure functions of
6
+ `policies`; this module only reads the fire log, calls them, appends what they return and launches.
7
+
8
+ Exactly once (SCH-B7): a slot is handled by one event (`started`, `skipped`, `missed` or `refused`) appended under the
9
+ schedule's own lock after the log is read again under it, so two ticks, a loop and an external call, or a tick killed
10
+ at any step and run again never handle a slot twice. `started` is appended before the run is launched; a tick killed
11
+ between the two leaves a started fire whose thread never appears, which a later tick settles as lost.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import time
19
+ from collections.abc import Callable, Mapping
20
+ from dataclasses import dataclass, field
21
+ from datetime import UTC, datetime, timedelta
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from tempergraph.constants import ENGINE_VERSION
26
+ from tempergraph.docs import write_json
27
+ from tempergraph.durability.lock import LockHeld, RunLock
28
+ from tempergraph.schedule import credentials, ledger, policies, store
29
+ from tempergraph.schedule.model import floor_minute
30
+ from tempergraph.store.layout import ensure_home
31
+
32
+ MAX_RUNS = 4 # TCK-B16: runs started in one tick
33
+ BUDGET_S = 20.0 # TCK-B16: seconds one tick spends
34
+ LOST_AFTER_S = 600 # a started fire whose thread never appeared this long after is settled as lost
35
+ HEARTBEAT = "tick.json"
36
+ LOCK = "tick.lock"
37
+ FINISHED_STATES = ("finished", "stopped", "unfinished")
38
+ KILLED = {"stopped": 4, "unfinished": 5, "lost": 5}
39
+
40
+ Launcher = Callable[[dict[str, Any], dict[str, Any]], bool] # (entry, start) -> the run was started
41
+ Resolver = Callable[[dict[str, Any]], credentials.Check]
42
+ StatusOf = Callable[[dict[str, Any], str], dict[str, Any] | None] # (entry, thread id) -> state, exit_code, cost, alive
43
+
44
+
45
+ def _noop(*_a: Any) -> None:
46
+ return None
47
+
48
+
49
+ @dataclass
50
+ class Edges:
51
+ clock: Callable[[], datetime]
52
+ launcher: Launcher
53
+ resolver: Resolver
54
+ status_of: StatusOf = lambda entry, thread: None
55
+ state_root_of: Callable[[dict[str, Any]], Path | None] = lambda entry: None
56
+ repo_ok: Callable[[str], bool] = lambda repo: Path(repo).is_dir()
57
+ preflight: Callable[[dict[str, Any]], tuple[str, str] | None] = lambda entry: None # `run --check`: (reason, message)
58
+ monotonic: Callable[[], float] = time.monotonic
59
+ on_hook: Callable[[str, dict[str, Any], dict[str, Any]], None] = lambda event, entry, facts: None
60
+ log_error: Callable[[BaseException], None] = lambda exc: logging.getLogger("tempergraph").error(
61
+ "schedule_tick_error", exc_info=exc)
62
+ checkpoint: Callable[[str], None] = _noop # tests kill the tick at a named step: lock, settle, decide, started, launch, ended
63
+
64
+
65
+ @dataclass
66
+ class Result:
67
+ exit_code: int = 0
68
+ locked: bool = False
69
+ started: list[str] = field(default_factory=list)
70
+ refused: list[str] = field(default_factory=list)
71
+ settled: list[str] = field(default_factory=list)
72
+ skipped: int = 0
73
+ missed: int = 0
74
+ deferred: list[dict[str, str]] = field(default_factory=list)
75
+ error: str | None = None
76
+
77
+ def summary(self) -> str:
78
+ if self.locked:
79
+ return "tick: another tick holds the lock"
80
+ if self.exit_code:
81
+ return f"tick: the home store is not writable ({self.error})"
82
+ text = (f"tick: started {len(self.started)}, refused {len(self.refused)}, skipped {self.skipped}, missed "
83
+ f"{self.missed}, settled {len(self.settled)}, deferred {len(self.deferred)}")
84
+ return text + (f"; error {self.error}" if self.error else "")
85
+
86
+ def to_doc(self) -> dict[str, Any]:
87
+ return {"schema_version": 1, "locked": self.locked, "exit_code": self.exit_code, "started": self.started,
88
+ "refused": self.refused, "settled": self.settled, "skipped": self.skipped, "missed": self.missed,
89
+ "deferred": self.deferred, "error": self.error, "summary": self.summary()}
90
+
91
+
92
+ def _iso(at: datetime) -> str:
93
+ return at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
94
+
95
+
96
+ def entry_resolver(environment: Mapping[str, str], profile: Mapping[str, str], user_home: Path | None = None) -> Resolver:
97
+ """TCK-B19 at a fire: the executors recorded at `add` and `edit`, resolved in the tick's own environment."""
98
+
99
+ def resolve(entry: dict[str, Any]) -> credentials.Check:
100
+ return credentials.check_fire(entry, environment, profile, user_home)
101
+
102
+ return resolve
103
+
104
+
105
+ def schedule_lock_path(schedule_id: str, home: Path | None = None) -> Path:
106
+ return store.entry_path(schedule_id, home).parent / "fire.lock"
107
+
108
+
109
+ # --- the fire log under the schedule's lock ----------------------------------------------------------------------------
110
+
111
+
112
+ class _Fires:
113
+ """One schedule's fire log written through `commit_events` and mirrored into the ledger."""
114
+
115
+ def __init__(self, entry: dict[str, Any], home: Path, edges: Edges, now: datetime, trigger: str, result: Result) -> None:
116
+ self.entry, self.home, self.edges, self.now, self.trigger, self.result = entry, home, edges, now, trigger, result
117
+ self.sid = str(entry["schedule_id"])
118
+ self.log = store.read_log(self.sid, home)
119
+
120
+ def append(self, event: dict[str, Any]) -> bool:
121
+ """Append one event unless its slot is already handled (SCH-B7); mirror a handled one into the ledger."""
122
+ if not policies.commit_events(list(self.log), [event]):
123
+ return False
124
+ meta = {k: v for k, v in event.items() if k not in ("kind", "slot", "fire_id", "at")}
125
+ rec = store.append_event(self.sid, str(event["kind"]), now=self.now, slot=event.get("slot"),
126
+ fire_id=event.get("fire_id"), home=self.home, **meta)
127
+ if rec is None:
128
+ return False
129
+ self.log.append(rec)
130
+ if event["kind"] in policies.HANDLED:
131
+ root = self.edges.state_root_of(self.entry) if event["kind"] == "started" else None
132
+ ledger.append(ledger.fire_row(self.entry, fire_id=str(event.get("fire_id")), slot=event.get("slot"),
133
+ outcome=str(event["kind"]), at=self.now, reason=event.get("reason"),
134
+ thread_id=event.get("thread"), state_root=root, trigger=self.trigger), self.home)
135
+ if event["kind"] == "skipped":
136
+ self.result.skipped += 1
137
+ elif event["kind"] == "missed":
138
+ self.result.missed += 1
139
+ return True
140
+
141
+ def after(self) -> None:
142
+ """SCH-B23: the failure count reaches the limit: pause the schedule and fire `schedule_paused`."""
143
+ d = policies.decide_after(self.entry, self.log, self.now)
144
+ if d.state != "paused":
145
+ return
146
+ for e in d.events:
147
+ self.append(e)
148
+ self.entry = dict(self.entry, state="paused")
149
+ store.write_entry(self.entry, self.home)
150
+ for a in d.attention:
151
+ self.edges.on_hook("schedule_paused", self.entry, a)
152
+
153
+
154
+ def _live(log: list[dict[str, Any]], entry: dict[str, Any], edges: Edges) -> list[policies.LiveRun]:
155
+ ended = {e.get("fire_id") for e in log if e.get("kind") == "ended"}
156
+ out: list[policies.LiveRun] = []
157
+ for e in log:
158
+ if e.get("kind") == "started" and e.get("fire_id") not in ended:
159
+ st = edges.status_of(entry, str(e.get("thread"))) if e.get("thread") else None
160
+ state = "paused" if st and st.get("state") == "paused" else "running"
161
+ out.append(policies.LiveRun(str(e["fire_id"]), str(e["slot"]), str(e.get("thread")), state, e.get("at")))
162
+ return out
163
+
164
+
165
+ def _cost(raw: Any) -> dict[str, Any]:
166
+ c = raw if isinstance(raw, dict) else {}
167
+ reported = float(c.get("reported") or 0.0)
168
+ estimated = reported + float(c.get("estimated_only") or 0.0)
169
+ return {"reported": reported, "estimated": estimated if (c or reported) else None,
170
+ "incomplete": bool(c.get("incomplete") or c.get("unmeasured") or not c)}
171
+
172
+
173
+ def _settle(f: _Fires) -> None:
174
+ """Every `started` fire with no `ended`: from its thread's status, append `ended` and update the failure count."""
175
+ ended = {e.get("fire_id") for e in f.log if e.get("kind") == "ended"}
176
+ for e in [x for x in f.log if x.get("kind") == "started" and x.get("fire_id") not in ended]:
177
+ st = f.edges.status_of(f.entry, str(e.get("thread"))) if e.get("thread") else None
178
+ age = (f.now - datetime.fromisoformat(str(e.get("at") or e["slot"]).replace("Z", "+00:00"))).total_seconds()
179
+ state = str((st or {}).get("state") or "none")
180
+ if state in ("running", "paused") or (state == "none" and age < LOST_AFTER_S):
181
+ continue
182
+ outcome = "lost" if state == "none" else state
183
+ code = (st or {}).get("exit_code")
184
+ if code is None:
185
+ code = 0 if outcome == "finished" else KILLED.get(outcome, 5)
186
+ meta: dict[str, Any] = {"exit": int(code), "outcome": outcome, "cost": _cost((st or {}).get("cost")),
187
+ "thread": e.get("thread")}
188
+ if f.append({"kind": "ended", "slot": None, "fire_id": e["fire_id"], **meta}):
189
+ ledger.settle(str(e["fire_id"]), {k: meta[k] for k in ("exit", "outcome", "cost")}, at=f.now, home=f.home)
190
+ f.result.settled.append(str(e["fire_id"]))
191
+ f.edges.checkpoint("ended")
192
+ f.after()
193
+
194
+
195
+ # --- one start -----------------------------------------------------------------------------------------------------------
196
+
197
+
198
+ def _refuse(f: _Fires, start: dict[str, Any], reason: str, message: str, executor: str | None = None) -> None:
199
+ extra: dict[str, Any] = {"message": message[:200]}
200
+ if executor:
201
+ extra["executor"] = executor
202
+ if f.append({"kind": "refused", "slot": start["slot"], "fire_id": start["fire_id"], "reason": reason, **extra}):
203
+ f.result.refused.append(str(start["fire_id"]))
204
+ f.after()
205
+
206
+
207
+ def start_one(f: _Fires, start: dict[str, Any]) -> bool:
208
+ """The refusals of TCK-B16 (a moved repository, the preflight, the credential check), then `started` and the launch."""
209
+ repo = str((f.entry.get("target") or {}).get("repo") or "")
210
+ if not repo or not f.edges.repo_ok(repo):
211
+ _refuse(f, start, "repo_missing", f"the repository {repo!r} was moved or deleted")
212
+ return False
213
+ problem = f.edges.preflight(f.entry)
214
+ if problem is not None:
215
+ _refuse(f, start, problem[0], problem[1])
216
+ return False
217
+ verdict = f.edges.resolver(f.entry)
218
+ if verdict.refusal is not None:
219
+ code, message = verdict.refusal
220
+ _refuse(f, start, code, message, next((r["executor"] for r in verdict.checked if r.get("result") in ("refused", "none")),
221
+ None))
222
+ return False
223
+ if not f.append(policies.started_event(start)): # the slot was handled under the lock: nothing to launch
224
+ return False
225
+ f.result.started.append(str(start["fire_id"]))
226
+ f.edges.checkpoint("started")
227
+ ok = f.edges.launcher(f.entry, start)
228
+ f.edges.checkpoint("launch")
229
+ if not ok: # the run could not be started: an `ended` that counts as a failure (SCH-B23)
230
+ meta = {"exit": 5, "outcome": "launch_failed", "cost": {"reported": 0.0, "estimated": 0.0, "incomplete": False},
231
+ "thread": start.get("thread")}
232
+ if f.append({"kind": "ended", "slot": None, "fire_id": start["fire_id"], **meta}):
233
+ ledger.settle(str(start["fire_id"]), {k: meta[k] for k in ("exit", "outcome", "cost")}, at=f.now, home=f.home)
234
+ f.after()
235
+ return ok
236
+
237
+
238
+ # --- the tick ----------------------------------------------------------------------------------------------------------------
239
+
240
+
241
+ def heartbeat_path(home: Path) -> Path:
242
+ return store.schedules_root(home) / HEARTBEAT
243
+
244
+
245
+ def read_heartbeat(home: Path | None = None) -> dict[str, Any] | None:
246
+ """The heartbeat `tick.json`, or None; read-only."""
247
+ try:
248
+ doc = json.loads((store.schedules_root(home) / HEARTBEAT).read_text(encoding="utf-8"))
249
+ except (OSError, ValueError):
250
+ return None
251
+ return doc if isinstance(doc, dict) else None
252
+
253
+
254
+ def _due_key(entry: dict[str, Any], log: list[dict[str, Any]], now: datetime) -> str:
255
+ passed = policies.passed_slots(entry, log, now) if entry.get("state") == "active" else []
256
+ return _iso(min(passed)) if passed else "9999"
257
+
258
+
259
+ def run_tick(home: Path, edges: Edges, *, trigger: str = "external", interval_s: int = policies.DEFAULT_TICK_S) -> Result:
260
+ """TCK-B16. Never raises for a schedule's own trouble: an unhandled error goes to the code log and the heartbeat."""
261
+ result = Result()
262
+ try:
263
+ ensure_home(home)
264
+ store.schedules_root(home).mkdir(parents=True, exist_ok=True, mode=0o700)
265
+ lock = RunLock(store.schedules_root(home) / LOCK).acquire()
266
+ except LockHeld:
267
+ result.locked = True # TCK-B2: exit 0 at once, nothing read
268
+ return result
269
+ except OSError as exc:
270
+ result.exit_code, result.error = 1, type(exc).__name__ # an unwritable home store: nothing started
271
+ return result
272
+ now = edges.clock()
273
+ kinds: dict[str, list[str]] = {}
274
+ try:
275
+ edges.checkpoint("lock")
276
+ entries = store.list_entries(home)
277
+ for entry in entries:
278
+ if entry.get("state") != "removed":
279
+ _locked(entry, home, edges, now, trigger, result, lambda f: _settle(f))
280
+ edges.checkpoint("settle")
281
+ order = sorted((e for e in store.list_entries(home) if e.get("state") == "active"),
282
+ key=lambda e: _due_key(e, store.read_log(str(e["schedule_id"]), home), now))
283
+ started = [0]
284
+ t0 = edges.monotonic()
285
+ for entry in order:
286
+ _locked(entry, home, edges, now, trigger, result,
287
+ lambda f: _decide(f, interval_s, started, t0, kinds))
288
+ except Exception as exc: # noqa: BLE001 - the tick ends with exit 0 and says what failed (TCK-B16)
289
+ result.error = f"{type(exc).__name__}: {exc}"[:200]
290
+ edges.log_error(exc)
291
+ finally:
292
+ try:
293
+ _heartbeat(home, edges, now, trigger, interval_s, result, kinds)
294
+ finally:
295
+ lock.release()
296
+ return result
297
+
298
+
299
+ def _locked(entry: dict[str, Any], home: Path, edges: Edges, now: datetime, trigger: str, result: Result,
300
+ body: Callable[[_Fires], None]) -> None:
301
+ """Run `body` under the schedule's own lock; a schedule another process is handling is left for the next tick."""
302
+ sid = str(entry["schedule_id"])
303
+ lock = RunLock(schedule_lock_path(sid, home))
304
+ try:
305
+ lock.acquire()
306
+ except LockHeld:
307
+ return
308
+ try:
309
+ fresh = store.read_entry(sid, home) # read again under the lock: a `fire` or an edit may have just changed it
310
+ body(_Fires(fresh, home, edges, now, trigger, result))
311
+ finally:
312
+ lock.release()
313
+
314
+
315
+ def _decide(f: _Fires, interval_s: int, started: list[int], t0: float, kinds: dict[str, list[str]]) -> None:
316
+ if f.entry.get("state") != "active":
317
+ return
318
+ live = _live(f.log, f.entry, f.edges)
319
+ d = policies.decide_tick(f.entry, f.log, live, f.now, tick_s=interval_s)
320
+ f.edges.checkpoint("decide")
321
+ for e in d.events:
322
+ f.append(e)
323
+ for row in f.edges.resolver(f.entry).checked:
324
+ kinds[str(row["executor"])] = list(row["kinds"])
325
+ waiting = False
326
+ for start in sorted(d.start, key=lambda s: s["slot"]):
327
+ if started[0] >= MAX_RUNS or f.edges.monotonic() - t0 >= BUDGET_S:
328
+ f.result.deferred.append({"schedule_id": f.sid, "slot": str(start["slot"])})
329
+ waiting = True
330
+ continue
331
+ started[0] += 1
332
+ start_one(f, start)
333
+ if d.state == "done" and not waiting and f.entry.get("state") == "active":
334
+ f.entry = dict(f.entry, state=d.state)
335
+ store.write_entry(f.entry, f.home)
336
+
337
+
338
+ def _heartbeat(home: Path, edges: Edges, now: datetime, trigger: str, interval_s: int, result: Result,
339
+ kinds: dict[str, list[str]]) -> None:
340
+ doc = {"schema_version": 1, "last_tick_at": _iso(now), "engine_version": ENGINE_VERSION, "trigger": trigger,
341
+ "interval_s": interval_s, "credentials": kinds, "deferred": result.deferred,
342
+ "started": len(result.started), "last_error": result.error}
343
+ try:
344
+ write_json(heartbeat_path(home), doc)
345
+ except OSError as exc:
346
+ edges.log_error(exc)
347
+
348
+
349
+ # --- `schedule fire` (SCH-B26): one manual slot through the same path, no catch-up -------------------------------------------
350
+
351
+
352
+ def manual_start(entry: dict[str, Any], now: datetime, log: list[dict[str, Any]]) -> dict[str, Any]:
353
+ """The start of a manual fire: id `<schedule_id>@manual-<yyyymmddThhmmssZ>`, its slot the second it was asked."""
354
+ sid, workflow = str(entry["schedule_id"]), str((entry.get("target") or {}).get("workflow"))
355
+ at = now.astimezone(UTC).replace(microsecond=0)
356
+ start = policies.plan_start(entry, floor_minute(at), log)
357
+ start.update(slot=_iso(at), fire_id=policies.fire_id(sid, at, manual_at=at),
358
+ thread=f"{workflow}/s-{sid}-manual-{at:%Y%m%dT%H%M%S}")
359
+ return start
360
+
361
+
362
+ def fire_now(entry: dict[str, Any], edges: Edges, home: Path, *, trigger: str = "manual") -> tuple[Result, dict[str, Any]]:
363
+ now = edges.clock()
364
+ result = Result()
365
+ holder: dict[str, Any] = {}
366
+
367
+ def body(f: _Fires) -> None:
368
+ start = manual_start(f.entry, now, f.log)
369
+ holder.update(start)
370
+ start_one(f, start)
371
+
372
+ _locked(entry, home, edges, now, trigger, result, body)
373
+ return result, holder
374
+
375
+
376
+ def stale_after(interval_s: int) -> timedelta:
377
+ return timedelta(seconds=3 * interval_s)
@@ -0,0 +1,81 @@
1
+ """The fire token (TCK-B17; ADR `a-model-free-tick-behind-os-agnostic-triggers`).
2
+
3
+ A random token is made at `schedule add`; its SHA-256 is the entry's `token_digest` and the token itself lives only in
4
+ a private file beside the entry (`schedules/<schedule_id>/token`, owner-only). The tick puts it in the child's
5
+ `TEMPERGRAPH_SCHEDULE_TOKEN` and nowhere else; the run's caller classification checks it against the digest of the entry
6
+ the fire id names. The token is on no argv, in no record and in no step session's environment.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import hmac
13
+ import os
14
+ import re
15
+ import secrets
16
+ from datetime import UTC, datetime
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from tempergraph.schedule import store
21
+ from tempergraph.store.layout import ensure_home
22
+
23
+ ENV_VAR = "TEMPERGRAPH_SCHEDULE_TOKEN"
24
+ FIRE_ID = re.compile(r"^(?P<sid>[a-z0-9][a-z0-9-]{0,63})@(?P<when>manual-\d{8}T\d{6}Z|\d{8}T\d{4}Z)$")
25
+
26
+
27
+ def make_token() -> str:
28
+ return secrets.token_urlsafe(32)
29
+
30
+
31
+ def digest(token: str) -> str:
32
+ return hashlib.sha256(token.encode("utf-8")).hexdigest()
33
+
34
+
35
+ def matches(token: str, wanted: str | None) -> bool:
36
+ """A constant-time compare of the token's digest with the stored one."""
37
+ return bool(wanted) and hmac.compare_digest(digest(token), str(wanted))
38
+
39
+
40
+ def write_token(schedule_id: str, token: str, home: Path | None = None) -> Path:
41
+ """Owner-only (0600) beside the entry; on Windows the user's profile is the only guard the platform gives."""
42
+ ensure_home(home)
43
+ path = store.token_path(schedule_id, home)
44
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
45
+ tmp = path.with_name(path.name + ".tmp")
46
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
47
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
48
+ fh.write(token)
49
+ os.replace(tmp, path)
50
+ return path
51
+
52
+
53
+ def read_token(schedule_id: str, home: Path | None = None) -> str | None:
54
+ try:
55
+ return store.token_path(schedule_id, home).read_text(encoding="utf-8").strip() or None
56
+ except OSError:
57
+ return None
58
+
59
+
60
+ def parse_fire_id(fire_id: str) -> tuple[str, str] | None:
61
+ """`(schedule_id, slot as an ISO UTC instant)` of a fire id, or None when it is not one (SCH-B26)."""
62
+ m = FIRE_ID.match(fire_id or "")
63
+ if not m:
64
+ return None
65
+ when = m.group("when")
66
+ if when.startswith("manual-"):
67
+ at = datetime.strptime(when[len("manual-"):], "%Y%m%dT%H%M%SZ")
68
+ else:
69
+ at = datetime.strptime(when, "%Y%m%dT%H%MZ")
70
+ return m.group("sid"), at.replace(tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
71
+
72
+
73
+ def entry_for_fire(fire_id: str, home: Path | None = None) -> dict[str, Any] | None:
74
+ """The entry a fire id names, or None; read-only."""
75
+ parsed = parse_fire_id(fire_id)
76
+ if parsed is None:
77
+ return None
78
+ try:
79
+ return store.read_entry(parsed[0], home)
80
+ except (OSError, ValueError):
81
+ return None
@@ -0,0 +1,210 @@
1
+ """The `os` trigger adapter: one per-user autostart entry that runs the shim's absolute path (TCK-B14, TCK-B15; SEC-B7).
2
+
3
+ The entry holds the shim's path and the verb `schedule loop` (`schedule tick` every 5 minutes for the crontab fallback),
4
+ nothing else: no shell, no person-typed value, no environment value. It is written as a file (a LaunchAgent, a systemd user
5
+ unit with its `default.target.wants` link, a Task Scheduler definition, a crontab line); this module starts no process, so
6
+ the OS picks the entry up at the next login (macOS, Linux) or when the person imports it (Windows, crontab), as `install`
7
+ says. `install` is idempotent and rewrites an entry whose shim path changed; `status` calls an entry whose shim is missing
8
+ `broken`; `remove` deletes what `install` wrote.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import os
14
+ import shutil
15
+ import sys
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import Any
20
+ from xml.sax.saxutils import escape
21
+
22
+ from tempergraph.install import shim as shimmod
23
+
24
+ LABEL = "dev.tempergraph.schedule"
25
+ UNIT = "tempergraph-schedule.service"
26
+ MARKER = "tempergraph-schedule"
27
+ CRON_EVERY = "*/5 * * * *"
28
+ PLATFORM = sys.platform # tests replace it: the one place the platform is read
29
+ KINDS = ("launchagent", "systemd", "taskscheduler", "crontab")
30
+ SAFE = frozenset("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_./:-+@\\")
31
+
32
+
33
+ class NoOsScheduler(Exception):
34
+ """No per-user scheduler is usable (TCK-B14): `no_os_scheduler`; `loop` and `external` still work."""
35
+
36
+
37
+ class UnsafePath(Exception):
38
+ """The shim's path holds a character a crontab line cannot carry without a shell."""
39
+
40
+
41
+ @dataclass
42
+ class Entry:
43
+ kind: str
44
+ path: Path
45
+ text: str
46
+
47
+
48
+ def shim_for(home: Path, platform: str) -> Path:
49
+ path = shimmod.shim_path(home)
50
+ return path.with_name(path.name + ".cmd") if platform.startswith("win") else path
51
+
52
+
53
+ def detect(platform: str, user_home: Path, which: Callable[[str], str | None] | None = None) -> str | None:
54
+ """The entry kind this machine takes, or None (`no_os_scheduler`)."""
55
+ which = which or shutil.which
56
+ if platform == "darwin":
57
+ return "launchagent"
58
+ if platform.startswith("win"):
59
+ return "taskscheduler"
60
+ if platform.startswith("linux") and which("systemctl"):
61
+ return "systemd"
62
+ return "crontab" if which("crontab") else None
63
+
64
+
65
+ def render(kind: str, shim: Path) -> str:
66
+ """The entry text of one kind: the shim's absolute path and the verb only."""
67
+ p = str(shim)
68
+ if kind == "launchagent":
69
+ return ('<?xml version="1.0" encoding="UTF-8"?>\n'
70
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n'
71
+ '<plist version="1.0">\n<dict>\n'
72
+ f" <key>Label</key>\n <string>{LABEL}</string>\n"
73
+ " <key>ProgramArguments</key>\n <array>\n"
74
+ f" <string>{escape(p)}</string>\n <string>schedule</string>\n <string>loop</string>\n </array>\n"
75
+ " <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n</dict>\n</plist>\n")
76
+ if kind == "systemd":
77
+ quoted = '"' + p.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + '"'
78
+ return ("[Unit]\nDescription=tempergraph schedule loop\n\n[Service]\n"
79
+ f"ExecStart={quoted} schedule loop\nRestart=on-failure\n\n[Install]\nWantedBy=default.target\n")
80
+ if kind == "taskscheduler":
81
+ return ('<?xml version="1.0" encoding="UTF-8"?>\n'
82
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">\n'
83
+ " <Triggers>\n <LogonTrigger>\n <Enabled>true</Enabled>\n </LogonTrigger>\n </Triggers>\n"
84
+ " <Settings>\n <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>\n"
85
+ " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>\n <RestartOnFailure>\n"
86
+ " <Interval>PT1M</Interval>\n <Count>999</Count>\n </RestartOnFailure>\n </Settings>\n"
87
+ f" <Actions>\n <Exec>\n <Command>{escape(p)}</Command>\n"
88
+ " <Arguments>schedule loop</Arguments>\n </Exec>\n </Actions>\n</Task>\n")
89
+ if kind == "crontab":
90
+ if not set(p) <= SAFE:
91
+ raise UnsafePath(p)
92
+ return f"{CRON_EVERY} {p} schedule tick # {MARKER}\n"
93
+ raise ValueError(kind)
94
+
95
+
96
+ def entry_path(kind: str, home: Path, user_home: Path) -> Path:
97
+ if kind == "launchagent":
98
+ return user_home / "Library" / "LaunchAgents" / f"{LABEL}.plist"
99
+ if kind == "systemd":
100
+ return user_home / ".config" / "systemd" / "user" / UNIT
101
+ return home / "triggers" / ("tempergraph-schedule.task.xml" if kind == "taskscheduler" else "tempergraph-schedule.crontab")
102
+
103
+
104
+ def _wants(user_home: Path) -> Path:
105
+ return user_home / ".config" / "systemd" / "user" / "default.target.wants" / UNIT
106
+
107
+
108
+ def _kinds_present(home: Path, user_home: Path) -> list[Entry]:
109
+ out = []
110
+ for kind in KINDS:
111
+ p = entry_path(kind, home, user_home)
112
+ if p.is_file():
113
+ out.append(Entry(kind, p, p.read_text(encoding="utf-8", errors="replace")))
114
+ return out
115
+
116
+
117
+ def entries_present(home: Path, user_home: Path | None = None) -> bool:
118
+ """An `os` entry exists (read-only): a live trigger for `schedule add` (TCK-B15)."""
119
+ return bool(_kinds_present(home, user_home or Path.home()))
120
+
121
+
122
+ def install(home: Path, *, platform: str | None = None, user_home: Path | None = None,
123
+ which: Callable[[str], str | None] | None = None) -> dict[str, Any]:
124
+ """Write the entry (idempotent: the same text is left alone, a changed shim path is rewritten) and the shim it names.
125
+ Raises `NoOsScheduler`."""
126
+ platform, user_home = platform or PLATFORM, user_home or Path.home()
127
+ kind = detect(platform, user_home, which or shutil.which)
128
+ if kind is None:
129
+ raise NoOsScheduler("no per-user scheduler is usable here; `schedule loop --detach` and an external `schedule tick` still work")
130
+ text = render(kind, shim_for(home, platform))
131
+ if not platform.startswith("win"):
132
+ shimmod.write_shim(home) # an entry that points at a missing shim is mended with it
133
+ path = entry_path(kind, home, user_home)
134
+ same = path.is_file() and path.read_text(encoding="utf-8") == text
135
+ if not same:
136
+ path.parent.mkdir(parents=True, exist_ok=True)
137
+ tmp = path.with_name(path.name + ".tmp")
138
+ tmp.write_text(text, encoding="utf-8")
139
+ os.replace(tmp, path)
140
+ if kind == "systemd":
141
+ link = _wants(user_home)
142
+ link.parent.mkdir(parents=True, exist_ok=True)
143
+ if not link.is_symlink() or Path(os.readlink(link)) != path:
144
+ link.unlink(missing_ok=True)
145
+ link.symlink_to(path) # what `systemctl --user enable` does: nothing to launch
146
+ return {"kind": kind, "path": str(path), "written": not same,
147
+ "activate": {"launchagent": "it starts at your next login", "systemd": "it starts at your next login "
148
+ "(`systemctl --user enable --now tempergraph-schedule` starts it now)",
149
+ "taskscheduler": f"import it with: schtasks /create /tn tempergraph-schedule /xml \"{path}\"",
150
+ "crontab": f"add its line to your crontab with `crontab -e`: {path}"}[kind]}
151
+
152
+
153
+ def _shim_of(entry: Entry) -> str | None:
154
+ for line in entry.text.splitlines():
155
+ s = line.strip()
156
+ if s.startswith("<string>/") or s.startswith("<string>"):
157
+ inner = s.removeprefix("<string>").removesuffix("</string>")
158
+ if inner not in ("schedule", "loop", LABEL):
159
+ return inner.replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")
160
+ if s.startswith("ExecStart="):
161
+ return s.removeprefix("ExecStart=").rsplit(" schedule loop", 1)[0].strip('"').replace("%%", "%")
162
+ if s.startswith("<Command>"):
163
+ return s.removeprefix("<Command>").removesuffix("</Command>")
164
+ if s.startswith(CRON_EVERY):
165
+ return s.removeprefix(CRON_EVERY).split(" schedule tick", 1)[0].strip()
166
+ return None
167
+
168
+
169
+ def status(home: Path, *, platform: str | None = None, user_home: Path | None = None) -> list[dict[str, Any]]:
170
+ """Every `os` entry seen, with its state: `installed`, `outdated` (a shim path that moved) or `broken` (a missing shim)."""
171
+ platform, user_home = platform or PLATFORM, user_home or Path.home()
172
+ out = []
173
+ for e in _kinds_present(home, user_home):
174
+ wanted = shim_for(home, platform)
175
+ named = _shim_of(e)
176
+ state = "broken" if not named or not Path(named).is_file() else "installed" if named == str(wanted) else "outdated"
177
+ out.append({"trigger": f"os:{e.kind}", "state": state, "path": str(e.path), "shim": named})
178
+ return out
179
+
180
+
181
+ def refresh(home: Path, *, platform: str | None = None, user_home: Path | None = None) -> list[str]:
182
+ """After an `update` moved the shim: rewrite an entry whose shim path changed (TCK-B8); nothing when none exists."""
183
+ platform, user_home = platform or PLATFORM, user_home or Path.home()
184
+ done = []
185
+ for e in _kinds_present(home, user_home):
186
+ try:
187
+ if e.text != render(e.kind, shim_for(home, platform)):
188
+ e.path.write_text(render(e.kind, shim_for(home, platform)), encoding="utf-8")
189
+ done.append(e.kind)
190
+ except (OSError, UnsafePath):
191
+ continue
192
+ return done
193
+
194
+
195
+ def remove(home: Path, *, user_home: Path | None = None) -> list[str]:
196
+ """Delete what `install` wrote and leave no trace (the empty folders it made go too)."""
197
+ user_home = user_home or Path.home()
198
+ gone = []
199
+ for e in _kinds_present(home, user_home):
200
+ e.path.unlink(missing_ok=True)
201
+ gone.append(str(e.path))
202
+ starts = [e.path.parent]
203
+ if e.kind == "systemd":
204
+ _wants(user_home).unlink(missing_ok=True)
205
+ starts.append(_wants(user_home).parent)
206
+ for parent in starts: # the folders `install` made, while they are empty
207
+ while parent not in (user_home, home) and parent.is_dir() and not any(parent.iterdir()):
208
+ parent.rmdir()
209
+ parent = parent.parent
210
+ return gone