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,275 @@
1
+ """The exact formats: `--at`, `--rrule`, `--every`, `--cron`, with `--tz`, `--starts`, `--until` and `--count`
2
+ (SCH-B15, SCH-B29 to SCH-B32, SCH-B34 to SCH-B36; ADR `exact-formats-first-and-an-optional-word-grammar-echoed-back`).
3
+
4
+ No model and no guess: a value is the canonical form or a refusal, and so never a `needs`. The word grammar
5
+ (`words.py`) ends in the same builders, so a phrase and its exact twin store one form.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import re
12
+ from dataclasses import dataclass, field
13
+ from datetime import UTC, datetime, time, timedelta, timezone
14
+
15
+ from tempergraph.schedule.model import (
16
+ HORIZON_DAYS,
17
+ MIN_INTERVAL_MIN,
18
+ Rule,
19
+ ScheduleError,
20
+ When,
21
+ floor_minute,
22
+ machine_zone,
23
+ next_slots,
24
+ parse_rule,
25
+ shortest_gap_minutes,
26
+ wall_to_utc,
27
+ zone_of,
28
+ )
29
+
30
+ ISO_MINUTE = "%Y-%m-%dT%H:%M"
31
+ _ISO = re.compile(r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?)?\s*(Z|[+-]\d{2}:?\d{2})?$")
32
+ _MONTHS = {n: i + 1 for i, n in enumerate(("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov",
33
+ "dec"))}
34
+ _DOWS = {n: i for i, n in enumerate(("sun", "mon", "tue", "wed", "thu", "fri", "sat"))}
35
+ ABBREVIATIONS = {"EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", "PDT", "CET", "CEST", "EET", "EEST", "WET", "WEST",
36
+ "BST", "GMT", "IST", "JST", "KST", "HST", "AKST", "AKDT", "NZST", "NZDT", "AEST", "AEDT", "MSK"}
37
+
38
+
39
+ @dataclass
40
+ class Parsed:
41
+ """A parsed When: the canonical form, what was assumed on the way, and what the person gave."""
42
+
43
+ when: When
44
+ assumptions: list[str] = field(default_factory=list)
45
+ phrase: str | None = None
46
+ given: dict[str, str] = field(default_factory=dict)
47
+
48
+
49
+ def check_zone(name: str) -> str:
50
+ """An IANA name; `UTC` is accepted and an abbreviation such as `EST` or `CET` is refused: it names no rules."""
51
+ if "/" not in name and name != "UTC":
52
+ hint = " (an abbreviation names no rules)" if name.upper() in ABBREVIATIONS else ""
53
+ raise ScheduleError("zone_unknown", f"{name!r} is not an IANA time zone name{hint}; use one like Europe/Warsaw")
54
+ zone_of(name)
55
+ return name
56
+
57
+
58
+ def resolve_zone(tz: str | None, machine: tuple[str, str] | None, assumptions: list[str]) -> str:
59
+ if tz is not None:
60
+ return check_zone(tz)
61
+ name, source = machine or machine_zone()
62
+ assumptions.append(f"zone from this machine ({source})")
63
+ return name
64
+
65
+
66
+ def local_now(now: datetime, zone_name: str) -> datetime:
67
+ return floor_minute(now).astimezone(zone_of(zone_name)).replace(tzinfo=None)
68
+
69
+
70
+ def parse_wall(text: str, zone_name: str, flag: str, assumptions: list[str], *, need_time: bool = True
71
+ ) -> tuple[datetime, bool]:
72
+ """ISO 8601 as a local date-time to the minute: local, or with an offset or `Z` (the same instant, in the zone).
73
+ Returns the wall time and whether the text had a time; a date alone is midnight."""
74
+ m = _ISO.match(text.strip())
75
+ if not m:
76
+ raise ScheduleError("when_malformed", f"{flag} {text!r}: ISO 8601 is needed, such as 2026-12-01T08:00")
77
+ y, mo, d, hh, mi, ss, off = m.groups()
78
+ if hh is None and (need_time or off):
79
+ raise ScheduleError("when_malformed", f"{flag} {text!r}: a date and a time are needed, such as 2026-12-01T08:00")
80
+ try:
81
+ wall = datetime(int(y), int(mo), int(d), int(hh or 0), int(mi or 0))
82
+ except ValueError:
83
+ raise ScheduleError("when_malformed", f"{flag} {text!r}: not a date and time that exist") from None
84
+ if ss and int(ss) != 0:
85
+ assumptions.append(f"seconds dropped from {flag}")
86
+ if off:
87
+ if off == "Z":
88
+ tzinfo = UTC
89
+ else:
90
+ sign = 1 if off[0] == "+" else -1
91
+ digits = off[1:].replace(":", "")
92
+ tzinfo = timezone(sign * timedelta(hours=int(digits[:2]), minutes=int(digits[2:])))
93
+ zone = zone_of(zone_name)
94
+ wall = wall.replace(tzinfo=tzinfo).astimezone(zone).replace(tzinfo=None)
95
+ assumptions.append(f"{flag} {text} read as {wall.strftime(ISO_MINUTE)} in {zone_name}")
96
+ return wall, hh is not None
97
+
98
+
99
+ def build_once(wall: datetime, zone_name: str, now: datetime, assumptions: list[str]) -> Parsed:
100
+ zone = zone_of(zone_name)
101
+ u = wall_to_utc(wall, zone)
102
+ if u < floor_minute(now):
103
+ raise ScheduleError("when_in_past", f"{wall.strftime(ISO_MINUTE)} in {zone_name} has passed")
104
+ if u > now + timedelta(days=HORIZON_DAYS):
105
+ raise ScheduleError("when_too_far", f"{wall.strftime(ISO_MINUTE)} is more than {HORIZON_DAYS} days ahead")
106
+ return Parsed(When(kind="once", zone=zone_name, at=wall.strftime(ISO_MINUTE)), assumptions)
107
+
108
+
109
+ def build_recur(rule: Rule, zone_name: str, starts: datetime | None, now: datetime, assumptions: list[str]) -> Parsed:
110
+ """The canonical recurrence, or the refusal: slots under 15 minutes apart, ended, or no slot within 400 days."""
111
+ if starts is None:
112
+ starts = local_now(now, zone_name)
113
+ if rule.is_interval or rule.interval > 1:
114
+ assumptions.append("starts now: the first slot, and the count of intervals, run from this minute")
115
+ when = When(kind="recur", zone=zone_name, rule=rule.render(), starts=starts.strftime(ISO_MINUTE))
116
+ start = floor_minute(now)
117
+ if not rule.is_interval:
118
+ gap = shortest_gap_minutes(when, start)
119
+ if gap is not None and gap < MIN_INTERVAL_MIN:
120
+ raise ScheduleError("interval_too_short", f"slots {gap} minutes apart; the least is {MIN_INTERVAL_MIN} minutes")
121
+ if not next_slots(when, start, 1, HORIZON_DAYS):
122
+ if next_slots(when, start, 1, 4000):
123
+ raise ScheduleError("when_too_far", f"the first slot is more than {HORIZON_DAYS} days ahead")
124
+ if rule.until is not None or rule.count is not None:
125
+ raise ScheduleError("when_in_past", "the recurrence has ended: no slot at or after now")
126
+ raise ScheduleError("when_too_far", f"no slot within {HORIZON_DAYS} days")
127
+ return Parsed(when, assumptions)
128
+
129
+
130
+ # --- --every ----------------------------------------------------------------------------------------------------
131
+
132
+ _DURATION = re.compile(r"^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(\d+S)?)?$")
133
+
134
+
135
+ def parse_every(text: str) -> Rule:
136
+ """An ISO 8601 duration of weeks, days, hours and minutes (a day is 24 elapsed hours) as an interval rule."""
137
+ m = _DURATION.match(text.strip().upper())
138
+ if not m or not any(m.groups()[:4]) or m.group(5) or text.strip().upper() in ("P", "PT"):
139
+ raise ScheduleError("when_malformed", f"--every {text!r}: an ISO 8601 duration of weeks, days, hours and minutes "
140
+ "is needed, such as PT2H (years, months and seconds are not accepted)")
141
+ w, d, h, mi = (int(x or 0) for x in m.groups()[:4])
142
+ total = w * 10080 + d * 1440 + h * 60 + mi
143
+ if total == 0:
144
+ raise ScheduleError("when_malformed", f"--every {text!r}: a duration longer than zero is needed")
145
+ return interval_rule(total)
146
+
147
+
148
+ def interval_rule(total_minutes: int) -> Rule:
149
+ """The one interval rule for a period: whole hours are `HOURLY`, any other period `MINUTELY`; 15 minutes at least."""
150
+ if total_minutes < MIN_INTERVAL_MIN:
151
+ raise ScheduleError("interval_too_short", f"the shortest gap is {total_minutes} minutes; the least is "
152
+ f"{MIN_INTERVAL_MIN} minutes")
153
+ if total_minutes % 60 == 0:
154
+ return Rule(freq="HOURLY", interval=total_minutes // 60)
155
+ return Rule(freq="MINUTELY", interval=total_minutes)
156
+
157
+
158
+ # --- --cron -----------------------------------------------------------------------------------------------------
159
+
160
+
161
+ def _cron_field(text: str, name: str, lo: int, hi: int, names: dict[str, int] | None) -> set[int]:
162
+ def bad(why: str) -> ScheduleError:
163
+ return ScheduleError("when_malformed", f"cron {name} field {text!r}: {why}")
164
+
165
+ def number(tok: str) -> int:
166
+ if tok.isdigit():
167
+ return int(tok)
168
+ if names and tok.lower() in names:
169
+ return names[tok.lower()]
170
+ raise bad(f"{tok!r} is not a number" + (" or a name" if names else ""))
171
+
172
+ out: set[int] = set()
173
+ for item in text.split(","):
174
+ m = re.fullmatch(r"([^/]+)(?:/(\d+))?", item)
175
+ if not m:
176
+ raise bad("lists, ranges and steps are written like 1,5 and 9-17 and */15")
177
+ body, step_text = m.groups()
178
+ step = int(step_text) if step_text is not None else 1
179
+ if step < 1:
180
+ raise bad("a step is 1 or more")
181
+ if body == "*":
182
+ a, b = lo, (6 if name == "day of week" else hi)
183
+ elif "-" in body:
184
+ parts = body.split("-")
185
+ if len(parts) != 2:
186
+ raise bad("a range is a-b")
187
+ a, b = number(parts[0]), number(parts[1])
188
+ else:
189
+ if step_text is not None:
190
+ raise bad("a step goes on * or on a range")
191
+ a = b = number(body)
192
+ if a < lo or b > hi or a > b:
193
+ raise bad(f"values are {lo} to {hi}, a range does not run backwards")
194
+ out |= set(range(a, b + 1, step))
195
+ return out
196
+
197
+
198
+ def parse_cron(text: str) -> Rule:
199
+ """Five fields to the one stored rule that fires at the local times they name (SCH-B29, SCH-B30)."""
200
+ fields = text.split()
201
+ if len(fields) != 5:
202
+ raise ScheduleError("when_malformed", f"cron {text!r}: five fields are needed (minute, hour, day of month, month, "
203
+ "day of week); macros, seconds and a year are not accepted")
204
+ mi = _cron_field(fields[0], "minute", 0, 59, None)
205
+ ho = _cron_field(fields[1], "hour", 0, 23, None)
206
+ dom = _cron_field(fields[2], "day of month", 1, 31, None)
207
+ mon = _cron_field(fields[3], "month", 1, 12, _MONTHS)
208
+ dow = {d % 7 for d in _cron_field(fields[4], "day of week", 0, 7, _DOWS)}
209
+ hour_star, dom_star, mon_star, dow_star = len(ho) == 24, len(dom) == 31, len(mon) == 12, len(dow) == 7
210
+ if not mon_star:
211
+ raise ScheduleError("rule_unsupported", "cron month field: a restricted month has no stored form")
212
+ if not dom_star and not dow_star:
213
+ raise ScheduleError("rule_unsupported", "cron day of month and the day of week both restricted: no one rule holds "
214
+ "cron's either-day reading")
215
+ if hour_star:
216
+ freq = "HOURLY"
217
+ elif not dow_star:
218
+ freq = "WEEKLY"
219
+ elif not dom_star:
220
+ freq = "MONTHLY"
221
+ else:
222
+ freq = "DAILY"
223
+ return Rule(freq=freq, byday=tuple((0, (d - 1) % 7) for d in sorted(dow)) if not dow_star else (),
224
+ bymonthday=tuple(sorted(dom)) if not dom_star else (), byhour=() if hour_star else tuple(sorted(ho)),
225
+ byminute=tuple(sorted(mi)))
226
+
227
+
228
+ # --- the entry point --------------------------------------------------------------------------------------------
229
+
230
+
231
+ def with_bounds(rule: Rule, until: str | None, count: int | None, zone_name: str, assumptions: list[str]) -> Rule:
232
+ if count is not None:
233
+ if count < 1:
234
+ raise ScheduleError("when_malformed", f"--count {count}: a whole number of 1 or more is needed")
235
+ if rule.count is not None or rule.until is not None:
236
+ raise ScheduleError("when_malformed", "--count with COUNT or UNTIL already in the rule")
237
+ rule = dataclasses.replace(rule, count=count)
238
+ if until is not None:
239
+ if rule.count is not None or rule.until is not None:
240
+ raise ScheduleError("when_malformed", "--until with COUNT or UNTIL already in the rule (RFC 5545 allows one)")
241
+ wall, has_time = parse_wall(until, zone_name, "--until", assumptions, need_time=False)
242
+ if not has_time:
243
+ wall = datetime.combine(wall.date(), time(23, 59))
244
+ rule = dataclasses.replace(rule, until=wall_to_utc(wall, zone_of(zone_name)))
245
+ return rule
246
+
247
+
248
+ def parse_exact(*, at: str | None = None, rrule: str | None = None, every: str | None = None, cron: str | None = None,
249
+ tz: str | None = None, starts: str | None = None, until: str | None = None, count: int | None = None,
250
+ now: datetime, machine: tuple[str, str] | None = None) -> Parsed:
251
+ """One exact format to the canonical form, with no model (SCH-B15); a refusal is a ScheduleError."""
252
+ given = {flag: value for flag, value in (("--at", at), ("--rrule", rrule), ("--every", every), ("--cron", cron))
253
+ if value is not None}
254
+ if len(given) != 1:
255
+ raise ScheduleError("when_malformed", "give exactly one of --at, --rrule, --every, --cron (or a phrase)")
256
+ assumptions: list[str] = []
257
+ zone_name = resolve_zone(tz, machine, assumptions)
258
+ flag, value = next(iter(given.items()))
259
+ if at is not None:
260
+ if starts is not None or until is not None or count is not None:
261
+ raise ScheduleError("when_malformed", "--starts, --until and --count belong to a recurrence, not to --at")
262
+ wall, _ = parse_wall(at, zone_name, "--at", assumptions)
263
+ parsed = build_once(wall, zone_name, now, assumptions)
264
+ else:
265
+ if rrule is not None:
266
+ rule = parse_rule(rrule)
267
+ elif every is not None:
268
+ rule = parse_every(every)
269
+ else:
270
+ rule = parse_cron(str(cron))
271
+ rule = with_bounds(rule, until, count, zone_name, assumptions)
272
+ start = parse_wall(starts, zone_name, "--starts", assumptions, need_time=False)[0] if starts is not None else None
273
+ parsed = build_recur(rule, zone_name, start, now, assumptions)
274
+ parsed.given = {"format": flag, "value": value}
275
+ return parsed
@@ -0,0 +1,164 @@
1
+ """`schedule export`: a snippet for a pipeline system, printed and kept nowhere (TCK-B20, TCK-B11).
2
+
3
+ The rule becomes five-field cron in UTC; a calendar rule in a zone with daylight saving is refused (`export_needs_utc`) unless
4
+ `--pin-offset` pins today's offset and says what the other season does. The command is `tempergraph run <workflow> …` with
5
+ the schedule's options, its run cost cap, a label and `--caller pipeline`; the request is read from a file in the repository,
6
+ never inlined; the secrets are of kind `api_key` or `cloud` only, named and never valued; the pipeline's own concurrency
7
+ group stands for `overlap`. No credential value and no person's text goes into a snippet.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import shlex
13
+ from datetime import UTC, datetime, timedelta
14
+ from typing import Any
15
+
16
+ from tempergraph.schedule.model import ScheduleError, When, parse_rule, utc_offset, wall_to_utc, zone_of
17
+
18
+ TARGETS = ("github-actions", "gitlab-ci", "crontab")
19
+ SECRETS = {"claude": "ANTHROPIC_API_KEY", "agent-sdk": "ANTHROPIC_API_KEY", "messages-api": "ANTHROPIC_API_KEY",
20
+ "antigravity": "GEMINI_API_KEY"} # kind `api_key`; `cloud` is the pipeline's own workload identity
21
+ CRON_DAYS = "0123456"
22
+
23
+
24
+ def _minutes(zone: Any, at: datetime) -> int:
25
+ off = at.astimezone(zone).utcoffset() or timedelta(0)
26
+ return int(off.total_seconds() // 60)
27
+
28
+
29
+ def moves(zone: Any, now: datetime) -> bool:
30
+ """The zone's offset differs between two seasons of this year (daylight saving)."""
31
+ return _minutes(zone, datetime(now.year, 1, 15, tzinfo=UTC)) != _minutes(zone, datetime(now.year, 7, 15, tzinfo=UTC))
32
+
33
+
34
+ def _ranges(values: list[int]) -> str:
35
+ out: list[str] = []
36
+ run = sorted(set(values))
37
+ i = 0
38
+ while i < len(run):
39
+ j = i
40
+ while j + 1 < len(run) and run[j + 1] == run[j] + 1:
41
+ j += 1
42
+ out.append(str(run[i]) if j == i else (f"{run[i]},{run[j]}" if j == i + 1 else f"{run[i]}-{run[j]}"))
43
+ i = j + 1
44
+ return ",".join(out)
45
+
46
+
47
+ def to_cron(entry: dict[str, Any], pin_offset: bool, now: datetime) -> tuple[str, list[str]]:
48
+ """The five-field UTC cron line of the schedule's rule and the comments that go with it."""
49
+ when = When.from_doc(entry["when"])
50
+ zone = zone_of(when.zone)
51
+ notes: list[str] = []
52
+ if when.kind == "once":
53
+ utc = wall_to_utc(datetime.fromisoformat(str(when.at)), zone)
54
+ notes.append("a one-time schedule: cron repeats this date every year, so remove the job after it has run")
55
+ return f"{utc.minute} {utc.hour} {utc.day} {utc.month} *", notes
56
+ rule = parse_rule(str(when.rule))
57
+ needs_zone = rule.freq != "HOURLY" or rule.interval > 1 or bool(rule.byday)
58
+ if needs_zone and moves(zone, now):
59
+ if not pin_offset:
60
+ raise ScheduleError("export_needs_utc", f"{when.zone} changes its UTC offset with daylight saving, which cron cannot follow: "
61
+ "give the rule in UTC (`--tz UTC`) or pass --pin-offset to pin today's offset")
62
+ other = datetime(now.year, 7, 15, tzinfo=UTC) if _minutes(zone, now) == _minutes(zone, datetime(now.year, 1, 15, tzinfo=UTC)) \
63
+ else datetime(now.year, 1, 15, tzinfo=UTC)
64
+ pinned = _minutes(zone, now)
65
+ else:
66
+ other, pinned = None, _minutes(zone, now)
67
+ if rule.byday and any(o for o, _ in rule.byday):
68
+ raise ScheduleError("export_not_expressible", "an nth weekday of the month cannot be written as a cron line")
69
+ if rule.freq == "HOURLY":
70
+ if rule.interval > 1 and 24 % rule.interval:
71
+ raise ScheduleError("export_not_expressible", f"every {rule.interval} hours does not divide the day, so cron cannot keep it")
72
+ if pinned % 60 and rule.interval > 1:
73
+ raise ScheduleError("export_needs_utc", f"{when.zone} is not a whole-hour offset: give the rule in UTC")
74
+ minutes = sorted({(m - pinned) % 60 for m in (rule.byminute or (0,))})
75
+ hour_field = "*" if rule.interval == 1 else f"*/{rule.interval}"
76
+ return f"{','.join(map(str, minutes))} {hour_field} * * *", notes
77
+ if not rule.byhour:
78
+ raise ScheduleError("export_not_expressible", "this rule names no hour of the day")
79
+ times = [(h * 60 + m - pinned) for h in rule.byhour for m in (rule.byminute or (0,))]
80
+ shifts = {t // 1440 for t in times}
81
+ if len(shifts) != 1:
82
+ raise ScheduleError("export_not_expressible", "the times of this rule fall on different UTC days; give the rule in UTC")
83
+ shift = shifts.pop()
84
+ hours = sorted({(t % 1440) // 60 for t in times})
85
+ minutes = sorted({t % 60 for t in times})
86
+ dom, dow = "*", "*"
87
+ if rule.freq == "WEEKLY":
88
+ days = [((wd + 1) % 7 + shift) % 7 for _, wd in rule.byday] # rule weekday 0 is Monday, cron 0 is Sunday
89
+ dow = _ranges(days) if days else "*"
90
+ elif rule.freq == "MONTHLY":
91
+ if rule.bymonthday and shift == 0 and all(1 <= d <= 31 for d in rule.bymonthday):
92
+ dom = _ranges(list(rule.bymonthday))
93
+ else:
94
+ raise ScheduleError("export_not_expressible", "this monthly rule cannot be written as a cron line in UTC")
95
+ elif rule.freq != "DAILY":
96
+ raise ScheduleError("export_not_expressible", f"{rule.freq} cannot be written as a cron line")
97
+ if other is not None:
98
+ was = datetime(2000, 1, 1, hours[0], minutes[0], tzinfo=UTC) + timedelta(minutes=_minutes(zone, other))
99
+ mine = datetime(2000, 1, 1, hours[0], minutes[0], tzinfo=UTC) + timedelta(minutes=pinned)
100
+ season = "summer" if other.month == 7 else "winter"
101
+ notes.append(f"pinned to today's offset ({utc_offset(zone, now)}): in {season} ({utc_offset(zone, other)}) this job "
102
+ f"runs at {was:%H:%M} local instead of {mine:%H:%M}")
103
+ return f"{','.join(map(str, minutes))} {','.join(map(str, hours))} {dom} * {dow}", notes
104
+
105
+
106
+ def _command(entry: dict[str, Any], system: str) -> list[str]:
107
+ """`tempergraph run <workflow> …`: the schedule's options, its cap, a label and `--caller pipeline`; the request from a file."""
108
+ t = entry["target"]
109
+ sid = str(entry["schedule_id"])
110
+ words = ["tempergraph", "run", shlex.quote(str(t["workflow"]))]
111
+ flags = {k: c["value"] for k, c in ((entry.get("options") or {}).get("flag") or {}).items()}
112
+ cap = flags.pop("run.run_cost_cap_usd", entry.get("run_cost_cap_usd"))
113
+ words += ["--run-cost-cap", shlex.quote(f"{float(cap):g}")]
114
+ for k, v in sorted(flags.items()):
115
+ words += ["--set", shlex.quote(f"{k}={v}")]
116
+ for p in (entry.get("options") or {}).get("profiles") or []:
117
+ words += ["--profile", shlex.quote(str(p))]
118
+ for k, v in sorted((t.get("inputs") or {}).items()):
119
+ words += ["--input", shlex.quote(f"{k}={v}")]
120
+ words += ["--label", shlex.quote(f"schedule-{sid}"), "--caller", "pipeline", f'"$(cat {request_file(sid)})"']
121
+ return words
122
+
123
+
124
+ def request_file(schedule_id: str) -> str:
125
+ return f".tempergraph/schedules/{schedule_id}.request.md"
126
+
127
+
128
+ def _secrets(entry: dict[str, Any]) -> list[str]:
129
+ """Secret names for kind `api_key` only; never `oauth_token`, never a cached sign-in."""
130
+ names: list[str] = []
131
+ for c in entry.get("executors_checked") or []:
132
+ if "api_key" in (c.get("kinds") or []) or not c.get("kinds"):
133
+ n = SECRETS.get(str(c.get("executor")))
134
+ if n and n not in names:
135
+ names.append(n)
136
+ return names
137
+
138
+
139
+ def render(entry: dict[str, Any], target: str, pin_offset: bool, now: datetime) -> str:
140
+ if target not in TARGETS:
141
+ raise ScheduleError("export_target", f"--for takes {', '.join(TARGETS)}")
142
+ sid, cron_line, notes = str(entry["schedule_id"]), *to_cron(entry, pin_offset, now)
143
+ fields = cron_line
144
+ overlap = str(entry.get("overlap") or "skip")
145
+ command = " ".join(_command(entry, target))
146
+ secrets = _secrets(entry)
147
+ records = f"records: origin ci, schedule {{schedule_id: {sid}, declared: true}}; host ci:{target}; the tie is the pipeline's word, not attested"
148
+ head = [f"# tempergraph schedule {sid}, exported for {target}: nothing is kept; commit this to the pipeline's configuration",
149
+ f"# the request is read from {request_file(sid)} in the repository: commit it there (never inline)",
150
+ f"# {records}", "# a run that pauses exits 3 as any pipeline run does; resume it where the engine runs"]
151
+ head += [f"# {n}" for n in notes]
152
+ if target == "github-actions":
153
+ env = " env:\n" + "".join(f" {n}: ${{{{ secrets.{n} }}}}\n" for n in secrets) if secrets else ""
154
+ return ("\n".join(head) + f"\nname: tempergraph-{sid}\non:\n schedule:\n - cron: \"{fields}\" # UTC\n"
155
+ f"concurrency:\n group: tempergraph-{sid}\n cancel-in-progress: false # overlap {overlap}: a new job waits\n"
156
+ "jobs:\n run:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n"
157
+ f" - name: run\n{env} run: {command}\n")
158
+ if target == "gitlab-ci":
159
+ var = "".join(f"# CI/CD variable (masked): {n}\n" for n in secrets)
160
+ return ("\n".join(head) + f"\n# create a pipeline schedule with the cron `{fields}` (UTC) under CI/CD > Schedules\n{var}"
161
+ f"tempergraph-{sid}:\n rules:\n - if: $CI_PIPELINE_SOURCE == \"schedule\"\n resource_group: tempergraph-{sid}\n"
162
+ f" script:\n - {command}\n")
163
+ lock = f"flock -n /tmp/tempergraph-{sid}.lock" if overlap == "skip" else f"flock /tmp/tempergraph-{sid}.lock"
164
+ return ("\n".join(head) + f"\n{fields} cd {shlex.quote(str(entry['target']['repo']))} && {lock} {command}\n")
@@ -0,0 +1,89 @@
1
+ """Starting a scheduled run: the hand-off ticket and the detached `run` (TCK-B16, TCK-B17; SEC-B5, SEC-B6).
2
+
3
+ The child's argv holds only `run <workflow> --schedule <fire id> --task-id <id>`: constants and checked values. The
4
+ rendered request, the inputs, the options and the label wait in a hand-off ticket (owner-only, in the schedule's folder)
5
+ that the run reads once and removes; the fire token goes in the child's environment and nowhere else.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ from collections.abc import Callable
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from tempergraph import detach
17
+ from tempergraph.schedule import credentials, policies, store, token
18
+ from tempergraph.store.layout import ensure_home, home_path
19
+
20
+ Starter = Callable[..., bool]
21
+
22
+
23
+ def ticket_path(schedule_id: str, fire_id: str, home: Path | None = None) -> Path:
24
+ return store.schedules_root(home) / schedule_id / "tickets" / f"{fire_id}.json"
25
+
26
+
27
+ def build_ticket(entry: dict[str, Any], start: dict[str, Any]) -> dict[str, Any]:
28
+ """The request and the inputs with the fire keys rendered (SCH-B11), the options, the profiles and the label."""
29
+ target = entry.get("target") or {}
30
+ keys = start.get("keys") or {}
31
+ options = entry.get("options") or {}
32
+ return {"fire_id": start["fire_id"], "slot": start["slot"], "label": start["label"],
33
+ "request": policies.render_fire_text(str(target.get("request") or ""), keys),
34
+ "inputs": {k: policies.render_fire_text(str(v), keys) for k, v in (target.get("inputs") or {}).items()},
35
+ "flags": {k: c["value"] for k, c in (options.get("flag") or {}).items()},
36
+ "profiles": list(options.get("profiles") or [])}
37
+
38
+
39
+ def write_ticket(entry: dict[str, Any], start: dict[str, Any], home: Path | None = None) -> Path:
40
+ path = ticket_path(str(entry["schedule_id"]), str(start["fire_id"]), home)
41
+ ensure_home(home)
42
+ path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
43
+ tmp = path.with_name(path.name + ".tmp")
44
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
45
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
46
+ json.dump(build_ticket(entry, start), fh)
47
+ os.replace(tmp, path)
48
+ return path
49
+
50
+
51
+ def read_ticket(fire_id: str, home: Path | None = None, *, remove: bool = True) -> dict[str, Any] | None:
52
+ """The ticket of a fire, validated (SEC-B6): the run removes it once read, so nothing is left behind."""
53
+ parsed = token.parse_fire_id(fire_id)
54
+ if parsed is None:
55
+ return None
56
+ path = ticket_path(parsed[0], fire_id, home)
57
+ try:
58
+ doc = json.loads(path.read_text(encoding="utf-8"))
59
+ except (OSError, ValueError):
60
+ return None
61
+ if remove:
62
+ path.unlink(missing_ok=True)
63
+ if not (isinstance(doc, dict) and doc.get("fire_id") == fire_id and isinstance(doc.get("request"), str)
64
+ and isinstance(doc.get("inputs"), dict) and isinstance(doc.get("flags"), dict)
65
+ and isinstance(doc.get("profiles"), list) and isinstance(doc.get("label"), str)):
66
+ return None
67
+ return doc
68
+
69
+
70
+ def launch_run(entry: dict[str, Any], start: dict[str, Any], *, home: Path | None = None,
71
+ starter: Starter = detach.start_run) -> bool:
72
+ """Write the ticket, then start `run` detached in its own process group and never wait for it. False when the token
73
+ or the ticket is missing or the start failed (the tick records the failure)."""
74
+ home = home or home_path()
75
+ sid, workflow, thread = str(entry["schedule_id"]), (entry.get("target") or {}).get("workflow"), start.get("thread")
76
+ secret = token.read_token(sid, home)
77
+ if not secret or not workflow or not thread or "/" not in str(thread):
78
+ return False
79
+ try:
80
+ path = write_ticket(entry, start, home)
81
+ except OSError:
82
+ return False
83
+ profile = credentials.read_profile(home) # a fire runs in the trigger's environment: the operator's profile supplies it
84
+ child_env = {**{k: v for k, v in profile.items() if k in credentials.CREDENTIAL_NAMES}, token.ENV_VAR: secret}
85
+ words = ("run", str(workflow), "--schedule", str(start["fire_id"]), "--task-id", str(thread).split("/", 1)[1])
86
+ ok = starter(words, home, env=child_env, cwd=Path(str((entry.get("target") or {}).get("repo"))))
87
+ if not ok:
88
+ path.unlink(missing_ok=True)
89
+ return ok
@@ -0,0 +1,133 @@
1
+ """The machine-wide scheduled-run ledger `schedules/runs.jsonl` of the home store (TCK-B13, TCK-B23; LOS-B10).
2
+
3
+ One `fire` row for each fire the tick or `schedule fire` handles (started, skipped, missed or refused), and one `ended`
4
+ row for a started fire, which `read` lays over its fire row. Metadata only (never request, input or feedback text),
5
+ scrubbed, kept when the schedule, the state root or the repository is gone, and shortened only by `prune`
6
+ (`store prune --schedules --older-than <days>`). Reading creates nothing.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ import sys
14
+ import tempfile
15
+ from datetime import UTC, date, datetime, time, timedelta
16
+ from pathlib import Path
17
+ from typing import IO, Any
18
+
19
+ from tempergraph.docs import append_jsonl, iter_jsonl
20
+ from tempergraph.schedule.store import TEXT_KEYS, schedules_root
21
+ from tempergraph.security.scrub import scrub
22
+
23
+ OUTCOMES = ("started", "skipped", "missed", "refused")
24
+
25
+
26
+ def ledger_path(home: Path | None = None) -> Path:
27
+ return schedules_root(home) / "runs.jsonl"
28
+
29
+
30
+ def _iso(at: datetime) -> str:
31
+ return at.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
32
+
33
+
34
+ def fire_row(entry: dict[str, Any], *, fire_id: str, slot: str | None, outcome: str, at: datetime, reason: str | None = None,
35
+ thread_id: str | None = None, state_root: Path | None = None, trigger: str = "tick",
36
+ orchestration_id: str | None = None) -> dict[str, Any]:
37
+ """The row of one handled fire, from the schedule's entry (SCH-B14) and what the tick decided."""
38
+ target = entry.get("target") or {}
39
+ repo = str(target.get("repo") or "")
40
+ return {"kind": "fire", "fire_id": fire_id, "schedule_id": entry["schedule_id"], "name": entry.get("name"), "slot": slot,
41
+ "fired_at": _iso(at),
42
+ "target": {"kind": target.get("kind"), "workflow": target.get("workflow") or target.get("orchestration_file"),
43
+ "repo": repo, "repo_name": Path(repo).name if repo else None},
44
+ "created_from": (entry.get("created") or {}).get("from"), "outcome": outcome, "reason": reason,
45
+ "thread_id": thread_id, "orchestration_id": orchestration_id,
46
+ "state_root": str(state_root) if state_root is not None else None, "trigger": trigger}
47
+
48
+
49
+ def _clean(value: Any) -> Any:
50
+ if isinstance(value, str):
51
+ return scrub(value)
52
+ if isinstance(value, dict):
53
+ return {k: _clean(v) for k, v in value.items()}
54
+ if isinstance(value, list):
55
+ return [_clean(v) for v in value]
56
+ return value
57
+
58
+
59
+ def _write(row: dict[str, Any], home: Path | None, err: IO[str] | None) -> bool:
60
+ bad = TEXT_KEYS & set(row)
61
+ if bad:
62
+ raise ValueError(f"the ledger holds metadata only, never {sorted(bad)[0]} text (TCK-B23)")
63
+ try:
64
+ append_jsonl(ledger_path(home), _clean(row))
65
+ return True
66
+ except OSError as exc:
67
+ (err or sys.stderr).write(f"tempergraph: the schedule ledger could not be written ({type(exc).__name__}); going on\n")
68
+ return False
69
+
70
+
71
+ def append(row: dict[str, Any], home: Path | None = None, err: IO[str] | None = None) -> bool:
72
+ """One fire row. A failed write is reported on standard error and returns False; the fire goes on."""
73
+ return _write(dict(row, kind="fire"), home, err)
74
+
75
+
76
+ def settle(fire_id: str, ended: dict[str, Any], *, at: datetime, home: Path | None = None, err: IO[str] | None = None) -> bool:
77
+ """The `ended` row of a started fire: exit, run outcome and cost (`reported`, `estimated`, `incomplete`)."""
78
+ return _write({"kind": "ended", "fire_id": fire_id, "at": _iso(at), **{k: v for k, v in ended.items() if k != "at"}},
79
+ home, err)
80
+
81
+
82
+ def _rows(home: Path | None) -> list[dict[str, Any]]:
83
+ return list(iter_jsonl(ledger_path(home)))
84
+
85
+
86
+ def read(home: Path | None = None, *, schedule: str | None = None, repo: str | None = None, workflow: str | None = None,
87
+ since: date | None = None, outcome: str | None = None) -> list[dict[str, Any]]:
88
+ """Every fire in file order with its `ended` block laid over it (or None); read-only."""
89
+ ended: dict[str, dict[str, Any]] = {}
90
+ fires: list[dict[str, Any]] = []
91
+ for r in _rows(home):
92
+ if r.get("kind") == "ended" and r.get("fire_id"):
93
+ ended[str(r["fire_id"])] = {k: v for k, v in r.items() if k not in ("kind", "fire_id")}
94
+ elif r.get("kind") == "fire":
95
+ fires.append(r)
96
+ out: list[dict[str, Any]] = []
97
+ cut = datetime.combine(since, time(0), tzinfo=UTC) if since else None
98
+ for r in fires:
99
+ t = r.get("target") or {}
100
+ if schedule and r.get("schedule_id") != schedule:
101
+ continue
102
+ if repo and t.get("repo") != repo:
103
+ continue
104
+ if workflow and t.get("workflow") != workflow:
105
+ continue
106
+ if outcome and r.get("outcome") != outcome:
107
+ continue
108
+ if cut and datetime.fromisoformat(str(r["fired_at"]).replace("Z", "+00:00")) < cut:
109
+ continue
110
+ out.append({**r, "ended": ended.get(str(r.get("fire_id")))})
111
+ return out
112
+
113
+
114
+ def prune(older_than_days: float, now: datetime, home: Path | None = None, *, dry_run: bool = False) -> int:
115
+ """Drop the fire rows fired before `now - older_than_days`, with their `ended` rows; atomic. Returns how many fires."""
116
+ cut = now - timedelta(days=older_than_days)
117
+ rows = _rows(home)
118
+ old = {str(r["fire_id"]) for r in rows if r.get("kind") == "fire" and r.get("fired_at")
119
+ and datetime.fromisoformat(str(r["fired_at"]).replace("Z", "+00:00")) < cut}
120
+ if dry_run or not old:
121
+ return len(old)
122
+ keep = [r for r in rows if str(r.get("fire_id")) not in old]
123
+ path = ledger_path(home)
124
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".runs.")
125
+ try:
126
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
127
+ fh.write("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in keep))
128
+ os.chmod(tmp, 0o600)
129
+ os.replace(tmp, path)
130
+ except BaseException:
131
+ Path(tmp).unlink(missing_ok=True)
132
+ raise
133
+ return len(old)