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,125 @@
1
+ """The supervision record of a run, built at every `run_exit` for the thread so far (SUP-B10, SUP-B11).
2
+
3
+ Read from the thread's intervention rows in the ledger and its `run_started` records. Cost fields and
4
+ `observations` come from the supervision journal (SCO-B15, T7.6) and stay null until then: unmeasured is
5
+ never zero.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import statistics
12
+ from collections.abc import Mapping, Sequence
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ DECIDERS = ("person", "agent", "unknown", "pipeline", "orchestrator", "scheduler", "engine")
17
+ CLASSES = ("designed", "rescue", "steer", "engine")
18
+
19
+
20
+ def _rows(path: Path, kind: str, **match: Any) -> list[dict[str, Any]]:
21
+ out: list[dict[str, Any]] = []
22
+ try:
23
+ lines = path.read_text(encoding="utf-8").splitlines()
24
+ except OSError:
25
+ return out
26
+ for ln in lines:
27
+ try:
28
+ r = json.loads(ln)
29
+ except ValueError:
30
+ continue
31
+ if isinstance(r, dict) and r.get("kind") == kind and all(r.get(k) == v for k, v in match.items()):
32
+ out.append(r)
33
+ return out
34
+
35
+
36
+ def build(ledger: Path, run_log: Path, thread: str, units_reached: Sequence[str]) -> dict[str, Any]:
37
+ rows = _rows(ledger, "intervention", thread_id=thread)
38
+ starts = _rows(run_log, "run_started")
39
+ touches = {c: {d: 0 for d in DECIDERS} for c in CLASSES}
40
+ rescue_by_pause: dict[str, int] = {}
41
+ relayed = {"turn_named": 0, "turn_only": 0, "claimed": 0}
42
+ waits: dict[str, float] = {}
43
+ per_pause: list[float] = []
44
+ undesigned_units: set[str] = set()
45
+ undesigned_by: set[str] = set()
46
+ designed_by: set[str] = set()
47
+ unknown = sum(1 for s in starts if (s.get("caller") or {}).get("kind") == "unknown")
48
+ sessions: set[tuple[str, str]] = set()
49
+ for s in starts:
50
+ c = s.get("caller") or {}
51
+ if c.get("host_session"):
52
+ sessions.add((str(c.get("host")), str(c["host_session"])))
53
+ for r in rows:
54
+ c = r.get("caller") or {}
55
+ by = str(c.get("decided_by") or c.get("kind") or "unknown")
56
+ by = by if by in DECIDERS else "unknown"
57
+ if c.get("kind") == "unknown":
58
+ unknown += 1
59
+ if c.get("relay") in relayed:
60
+ relayed[str(c["relay"])] += 1
61
+ if c.get("host_session"):
62
+ sessions.add((str(c.get("host")), str(c["host_session"])))
63
+ if r.get("wait_s") is not None:
64
+ waits[by] = round(waits.get(by, 0.0) + float(r["wait_s"]), 1)
65
+ per_pause.append(float(r["wait_s"]))
66
+ for t in r.get("touches") or []:
67
+ cls = str(t.get("class"))
68
+ if cls not in touches:
69
+ continue
70
+ touches[cls][by] += 1
71
+ if cls == "rescue":
72
+ kind = str(r.get("pause_kind") or "escalation")
73
+ rescue_by_pause[kind] = rescue_by_pause.get(kind, 0) + 1
74
+ if cls in ("rescue", "steer"):
75
+ undesigned_units.add(str(r.get("unit") or ""))
76
+ undesigned_by.add(by)
77
+ if cls == "designed":
78
+ designed_by.add(by)
79
+ total = {c: sum(v.values()) for c, v in touches.items()}
80
+ undesigned = total["rescue"] + total["steer"]
81
+ reached = [u for u in dict.fromkeys(units_reached) if u]
82
+ if reached and undesigned and len(undesigned_units & set(reached)) * 2 >= len(reached):
83
+ level = "operator"
84
+ elif total["steer"]:
85
+ level = "collaborator"
86
+ elif total["rescue"]:
87
+ level = "consultant"
88
+ elif total["designed"]:
89
+ level = "approver"
90
+ else:
91
+ level = "observer"
92
+ if level in ("observer", "approver"):
93
+ level_by = "none"
94
+ else:
95
+ level_by = next(iter(undesigned_by)) if len(undesigned_by) == 1 else "mixed"
96
+ rec: dict[str, Any] = {
97
+ "touches": {**touches, "rescue_by_pause": rescue_by_pause}, "undesigned": undesigned, "relayed": relayed,
98
+ "agent_own_rescues": touches["rescue"]["agent"], "wait_s": waits, "person_wait_s": waits.get("person", 0.0),
99
+ "latency_s": {"median": statistics.median(per_pause), "max": max(per_pause)} if per_pause else None,
100
+ "observations": None, "supervisors": {"sessions": len(sessions), "hosts": sorted({h for h, _ in sessions})},
101
+ "callers_unknown": unknown, "supervision_cost": None, "supervision_share": None,
102
+ "level": level, "level_by": level_by}
103
+ if level == "approver" and designed_by == {"agent"}:
104
+ rec["designed_by"] = "agent"
105
+ if starts and (starts[0].get("caller") or {}).get("kind") == "scheduler":
106
+ rec["start_cost"] = "measured_zero" # TCK-B24: a fire's start asks no one for anything; its supervision cost is zero
107
+ return rec
108
+
109
+
110
+ def schedule_setup(log: Sequence[Mapping[str, Any]]) -> dict[str, Any]:
111
+ """TCK-B24 (SUP): the person's `add` and `edit` of one schedule are one `designed` setup touch, counted once and by
112
+ the decider of the `add`; a fire counts no touch (`started` events add nothing) and its start costs `measured_zero`."""
113
+ made = next((e for e in log if e.get("kind") == "created"), None)
114
+ c = (made or {}).get("caller") or {}
115
+ by = str(c.get("decided_by") or c.get("kind") or "unknown")
116
+ by = by if by in DECIDERS else "unknown"
117
+ designed = {d: 0 for d in DECIDERS}
118
+ if made is not None:
119
+ designed[by] = 1
120
+ return {"touches": {"designed": designed, "rescue": {d: 0 for d in DECIDERS}, "steer": {d: 0 for d in DECIDERS}},
121
+ "fire_touches": 0, "fires": sum(1 for e in log if e.get("kind") == "started"), "start_cost": "measured_zero"}
122
+
123
+
124
+ def path_units(values: Mapping[str, Any]) -> list[str]:
125
+ return list(((values.get("run") or {}).get("path") or {}).get("units") or [])
@@ -0,0 +1,101 @@
1
+ """Which tools an attempt could not reach, their refusal class and the grant that fixes each (RST-B28, RST-B29, RST-B30, TSA-B7).
2
+
3
+ A name the step did not declare is `undeclared_tool` and a declared name the session never started is
4
+ `missing_at_start`. Any other refused name is classed from the session's own call record (the first call of
5
+ that name that did not succeed): `outside_workspace` or `inside_workspace` for a path target, `command` for a
6
+ shell call with the longest declared prefix or `undeclared`, `unclassified` where the record cannot tell. An entry
7
+ holds `path_class` or `prefix`, never the path or the command line.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from collections.abc import Sequence
14
+ from typing import Any
15
+
16
+ from tempergraph.contracts import Capabilities, StepSpec
17
+ from tempergraph.executors.capabilities import tool_names
18
+ from tempergraph.executors.summary import OUTSIDE
19
+
20
+
21
+ def capability_of(caps: Capabilities, name: str) -> str | None:
22
+ """The engine capability an executor tool name stands for, `mcp:<server>/<tool>` included."""
23
+ for cap, names in caps.tool_map.items():
24
+ if "*" not in cap and name in names:
25
+ return cap
26
+ for tmpl in caps.tool_map.get("mcp:*", ()):
27
+ pattern = re.escape(tmpl).replace(r"\{server\}", r"(?P<server>[^_/()]+)").replace(r"\{tool\}", r"(?P<tool>.+)")
28
+ m = re.fullmatch(pattern, name)
29
+ if m:
30
+ return f"mcp:{m.group('server')}/{m.group('tool')}"
31
+ if name in caps.tool_map.get("skill:*", ()):
32
+ return "skill:*"
33
+ return None
34
+
35
+
36
+ _PATH_CAPABILITIES = ("read", "edit", "write", "list") # a call of any other capability names no path
37
+
38
+
39
+ def _prefix_of(line: str, prefixes: Sequence[str]) -> str:
40
+ """The longest declared prefix the command line starts with at whole words, else `undeclared`."""
41
+ words = line.split()
42
+ best = ""
43
+ for p in prefixes:
44
+ pw = p.split()
45
+ if pw and words[:len(pw)] == pw and len(p) > len(best):
46
+ best = p
47
+ return best or "undeclared"
48
+
49
+
50
+ def _classed(name: str, cap: str | None, calls: Sequence[dict[str, Any]] | None,
51
+ prefixes: Sequence[str]) -> dict[str, Any]:
52
+ """The class facts of a refused name from the first call of that name that did not succeed (HUM-B24, HUM-B25).
53
+
54
+ The entry holds a class, `path_class` or `prefix`, and never the path or the command line itself.
55
+ """
56
+ call = next((c for c in calls or () if c.get("name") == name and c.get("ok") is not True), None)
57
+ unclassified: dict[str, Any] = {"class": "unclassified",
58
+ "fix": "retry with --feedback naming the permitted way, or stop"}
59
+ if call is None:
60
+ return unclassified
61
+ target, capability = call.get("target"), call.get("capability")
62
+ if capability == "shell" or cap == "shell":
63
+ prefix = _prefix_of(target, prefixes) if isinstance(target, str) and target.strip() else "undeclared"
64
+ fix = ("retry with --feedback to use a declared command, or stop" if prefix != "undeclared"
65
+ else "--decision retry --allow-command <unit>=<command prefix> (or retry with --feedback)")
66
+ return {"class": "command", "prefix": prefix, "fix": fix}
67
+ if capability not in _PATH_CAPABILITIES or not isinstance(target, str) or not target:
68
+ return unclassified
69
+ if capability == "list" and any(ch in target for ch in "*?["):
70
+ return unclassified
71
+ if target == OUTSIDE:
72
+ return {"class": "outside_workspace", "path_class": "outside",
73
+ "fix": "retry with --feedback naming a path inside the workspace, or stop"}
74
+ return {"class": "inside_workspace", "path_class": "inside",
75
+ "fix": "retry with --feedback naming the permitted way, or stop"}
76
+
77
+
78
+ def refused(unit: str, step: StepSpec, caps: Capabilities, denied: Sequence[str],
79
+ tools_at_start: Sequence[str], calls: Sequence[dict[str, Any]] | None = None,
80
+ prefixes: Sequence[str] = ()) -> list[dict[str, Any]]:
81
+ """One entry per refused or missing name: `{name, capability, class, fix}` and `path_class` or `prefix`."""
82
+ out: list[dict[str, Any]] = []
83
+ declared = set(step.tools)
84
+ for name in dict.fromkeys(denied):
85
+ cap = capability_of(caps, name)
86
+ if cap is None or cap == "skill:*" or cap == "shell" or cap in declared:
87
+ out.append({"name": name, "capability": cap, **_classed(name, cap, calls, prefixes)})
88
+ else:
89
+ out.append({"name": name, "capability": cap, "class": "undeclared_tool",
90
+ "fix": f"--decision retry --grant {unit}={cap}"})
91
+ if tools_at_start:
92
+ start = set(tools_at_start)
93
+ for cap in step.tools:
94
+ names = tool_names(caps, cap)
95
+ if not names or cap.startswith("skill:") and "Skill" in start or set(names) & start:
96
+ continue
97
+ host = (f"configure the MCP server {cap[4:].split('/', 1)[0]!r} on this machine, then "
98
+ if cap.startswith("mcp:") else "")
99
+ out.append({"name": names[0], "capability": cap, "class": "missing_at_start",
100
+ "fix": f"{host}--decision retry"})
101
+ return out
@@ -0,0 +1,25 @@
1
+ """Schedules (SCH, release 3 phase R3-T5.1): rule model and slots, exact formats and the word grammar, the canonical
2
+ form and its echo, the schedule entry and fire log, and the fire-decision policies as pure functions.
3
+
4
+ Nothing in this package reads the clock on its own, starts a process or spends: a caller passes the clock, and the
5
+ tick of the next phase only calls the policies (TCK, R3-T5.2). The engine names no workflow here (ADR `the-engine-names-no-workflow`).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from tempergraph.schedule.model import (
11
+ Clock,
12
+ Needs,
13
+ Reading,
14
+ Rule,
15
+ ScheduleError,
16
+ Slot,
17
+ When,
18
+ next_slots,
19
+ parse_rule,
20
+ slots_between,
21
+ system_clock,
22
+ )
23
+
24
+ __all__ = ["Clock", "Needs", "Reading", "Rule", "ScheduleError", "Slot", "When", "next_slots", "parse_rule",
25
+ "slots_between", "system_clock"]
@@ -0,0 +1,167 @@
1
+ """Unattended credential kinds and the per-executor check (TCK-B18, TCK-B19, TCK-B5, TCK-B6).
2
+
3
+ A fire runs with nobody present, so each executor declares the kinds it can use unattended (`Capabilities.
4
+ unattended_credentials`) and the check resolves what the operator's credentials profile (`config/credentials/default`
5
+ under the home store) and the environment hold. Presence only: no value is kept, no network call and no model call is
6
+ made (C13). Four kinds: `api_key`, `cloud`, `oauth_token`, `interactive_login`.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from collections.abc import Mapping, Sequence
13
+ from dataclasses import dataclass, field
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from tempergraph.executors.capabilities import DECLARED
18
+
19
+ PROFILE = "default" # the credentials profile a fire reads (assumption recorded in research `rationale-carried-from-the-engine-specs` F50)
20
+ CLOUD_FLAGS = ("CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY")
21
+ ENV_NAMES: dict[str, dict[str, tuple[str, ...]]] = {
22
+ "claude": {"api_key": ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"), "cloud": CLOUD_FLAGS,
23
+ "oauth_token": ("CLAUDE_CODE_OAUTH_TOKEN",)},
24
+ "agent-sdk": {"api_key": ("ANTHROPIC_API_KEY",), "cloud": CLOUD_FLAGS},
25
+ "messages-api": {"api_key": ("ANTHROPIC_API_KEY",), "cloud": CLOUD_FLAGS},
26
+ "antigravity": {"api_key": ("GEMINI_API_KEY",)},
27
+ }
28
+ HELPER = "apiKeyHelper" # a command in the profile that prints an API key
29
+ LOGIN_FILES: dict[str, tuple[str, ...]] = {"claude": (".claude/.credentials.json",), "antigravity": (".gemini/oauth_creds.json",)}
30
+ CREDENTIAL_NAMES = frozenset(n for kinds in ENV_NAMES.values() for names in kinds.values() for n in names) | {
31
+ "CLAUDE_CODE_OAUTH_TOKEN"}
32
+ FIX = "an API key, an apiKeyHelper or cloud credentials (Bedrock, Vertex or Foundry) in the credentials profile"
33
+
34
+
35
+ @dataclass
36
+ class Check:
37
+ checked: list[dict[str, Any]] = field(default_factory=list) # one row per executor and role: what `executors_checked` keeps
38
+ warnings: list[str] = field(default_factory=list)
39
+ refusal: tuple[str, str] | None = None # (code, message), the first refusal
40
+
41
+
42
+ WARNING_TEXT = {
43
+ "credential_may_expire": "a signed-in session can end; fires then refuse",
44
+ "credential_none": "no credential this check can see; every fire is refused `credential` until the profile or the "
45
+ "environment holds one",
46
+ }
47
+
48
+
49
+ def read_profile(home: Path | None = None, name: str = PROFILE) -> dict[str, str]:
50
+ """`name=value` lines of the credentials profile (as the claude executor reads a judge's), or nothing."""
51
+ from tempergraph.store.layout import home_path
52
+
53
+ path = (home or home_path()) / "config" / "credentials" / name
54
+ out: dict[str, str] = {}
55
+ try:
56
+ lines = path.read_text(encoding="utf-8").splitlines()
57
+ except OSError:
58
+ return out
59
+ for line in lines:
60
+ if "=" in line and not line.lstrip().startswith("#"):
61
+ k, v = line.split("=", 1)
62
+ if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", k.strip()):
63
+ out[k.strip()] = v.strip()
64
+ return out
65
+
66
+
67
+ def profile_values(profile: Mapping[str, str]) -> dict[str, str]:
68
+ """The names of the profile that carry credentials: what a fire's child receives, never kept in any entry."""
69
+ return {k: v for k, v in profile.items() if k in CREDENTIAL_NAMES or k == HELPER}
70
+
71
+
72
+ def resolve_kinds(executor: str, environment: Mapping[str, str], profile: Mapping[str, str], *,
73
+ login_present: bool = False) -> frozenset[str]:
74
+ """Which kinds the environment and the profile hold for one executor (presence only)."""
75
+ names = ENV_NAMES.get(executor, {})
76
+ merged = {**profile, **environment}
77
+ kinds = {kind for kind, vars_ in names.items() if any(merged.get(v) for v in vars_)}
78
+ if executor == "claude" and profile.get(HELPER):
79
+ kinds.add("api_key")
80
+ if login_present and executor in LOGIN_FILES:
81
+ kinds.add("interactive_login")
82
+ return frozenset(kinds)
83
+
84
+
85
+ def login_cached(executor: str, user_home: Path | None = None, environment: Mapping[str, str] | None = None) -> bool:
86
+ """A person's cached sign-in file of the product; the Keychain cannot be read model-free (P-SCH-2)."""
87
+ base = user_home or Path.home()
88
+ paths = [base / rel for rel in LOGIN_FILES.get(executor, ())]
89
+ if executor == "claude" and (environment or {}).get("CLAUDE_CONFIG_DIR"):
90
+ paths.append(Path(str((environment or {})["CLAUDE_CONFIG_DIR"])) / ".credentials.json")
91
+ return any(p.is_file() for p in paths)
92
+
93
+
94
+ def held_kinds(executors: Sequence[str], environment: Mapping[str, str], profile: Mapping[str, str],
95
+ user_home: Path | None = None) -> dict[str, frozenset[str]]:
96
+ return {ex: resolve_kinds(ex, environment, profile, login_present=login_cached(ex, user_home, environment))
97
+ for ex in dict.fromkeys(executors)}
98
+
99
+
100
+ def bare_judge(executor: str) -> bool:
101
+ """A judge launched with `--bare` reads no sign-in, so it needs `api_key` or `cloud` (TCK-B6)."""
102
+ caps = DECLARED.get(executor)
103
+ return bool(executor == "claude" and caps is not None and caps.isolates_user_config)
104
+
105
+
106
+ def bindings_of(step_executors: Mapping[str, str], judges: Mapping[str, str]) -> list[dict[str, Any]]:
107
+ """One binding per executor and role, from the preflight report's step and judge executors."""
108
+ out: list[dict[str, Any]] = []
109
+ for role, names in (("step", step_executors.values()), ("judge", judges.values())):
110
+ for name in dict.fromkeys(names):
111
+ out.append({"executor": name, "role": role, "bare": role == "judge" and bare_judge(name)})
112
+ return out
113
+
114
+
115
+ def check_fire(entry: Mapping[str, Any], environment: Mapping[str, str], profile: Mapping[str, str],
116
+ user_home: Path | None = None) -> Check:
117
+ """The check at a fire (TCK-B19, TCK-B5): the executors and judges recorded in the entry at `add` and `edit`,
118
+ resolved in the tick's own environment; a binding with no credential is the `credential` refusal."""
119
+ bindings = [{"executor": c["executor"], "role": c.get("role") or "step",
120
+ "bare": c.get("role") == "judge" and bare_judge(str(c["executor"]))}
121
+ for c in entry.get("executors_checked") or []]
122
+ held = held_kinds([str(b["executor"]) for b in bindings], environment, profile, user_home)
123
+ return check(bindings, held, at_fire=True)
124
+
125
+
126
+ def check(bindings: Sequence[Mapping[str, Any]], held: Mapping[str, frozenset[str]], *, at_fire: bool = False) -> Check:
127
+ """TCK-B19: accept the kinds each executor declares; `credential_unattended` for any other kind held,
128
+ `judge_credential` for a `--bare` judge with neither `api_key` nor `cloud`, and at a fire `credential` when nothing
129
+ is held (TCK-B5). A weaker `interactive_login` is a `credential_may_expire` warning. Never a model call."""
130
+ out = Check()
131
+ seen: set[tuple[str, str]] = set()
132
+ for b in bindings:
133
+ executor, role = str(b["executor"]), str(b.get("role") or "step")
134
+ if (executor, role) in seen:
135
+ continue
136
+ seen.add((executor, role))
137
+ kinds = held.get(executor, frozenset())
138
+ caps = DECLARED.get(executor)
139
+ row: dict[str, Any] = {"executor": executor, "role": role, "kinds": sorted(kinds), "result": "ok",
140
+ "may_expire": False}
141
+ out.checked.append(row)
142
+ if caps is None or not caps.unattended_credentials:
143
+ row["result"] = "not_checked"
144
+ continue
145
+ usable = kinds & caps.unattended_credentials
146
+ problem: tuple[str, str] | None = None
147
+ if not kinds:
148
+ row["result"] = "none"
149
+ if at_fire:
150
+ problem = ("credential", f"{executor}: no credential in the profile or the environment; add {FIX}")
151
+ elif "credential_none" not in out.warnings: # saved all the same; every fire refuses until one is added
152
+ out.warnings.append("credential_none")
153
+ elif not usable:
154
+ problem = ("credential_unattended", f"{executor}: {', '.join(sorted(kinds))} cannot be used unattended; "
155
+ f"it takes {', '.join(sorted(caps.unattended_credentials))}")
156
+ elif role == "judge" and b.get("bare") and not usable & {"api_key", "cloud"}:
157
+ problem = ("judge_credential", f"{executor}: a judge launched with --bare needs {FIX}; "
158
+ f"{', '.join(sorted(kinds))} alone does not reach it")
159
+ elif usable == {"interactive_login"}:
160
+ row["may_expire"] = True
161
+ if "credential_may_expire" not in out.warnings:
162
+ out.warnings.append("credential_may_expire")
163
+ if problem is not None:
164
+ row["result"] = "refused"
165
+ row["reason"] = problem[0]
166
+ out.refusal = out.refusal or problem
167
+ return out
@@ -0,0 +1,169 @@
1
+ """The echo: a sentence rendered from the canonical form only (SCH-B18, SCH-B20, SCH-B2; ADR `exact-formats-first-and-an-optional-word-grammar-echoed-back`).
2
+
3
+ Never rendered from the phrase the person typed: the same stored rule gives the same sentence, and the `rule:`,
4
+ `starts:`, `zone:` and `at:` lines of the text re-parse (through the exact formats) to the stored form.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Sequence
10
+ from dataclasses import dataclass
11
+ from datetime import datetime
12
+ from typing import Any
13
+
14
+ from tempergraph.schedule.model import (
15
+ Rule,
16
+ Slot,
17
+ When,
18
+ floor_minute,
19
+ next_slots,
20
+ parse_rule,
21
+ utc_offset,
22
+ zone_of,
23
+ )
24
+
25
+ NAMES = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
26
+ ORDINALS = {1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", -1: "last"}
27
+
28
+
29
+ def _join(items: Sequence[str]) -> str:
30
+ return items[0] if len(items) == 1 else ", ".join(items[:-1]) + " and " + items[-1]
31
+
32
+
33
+ def _nums(values: Sequence[int]) -> str:
34
+ return ", ".join(str(v) for v in sorted(values))
35
+
36
+
37
+ def _ordinal(n: int) -> str:
38
+ return ORDINALS.get(n, f"{-n}th from last" if n < 0 else f"{n}th")
39
+
40
+
41
+ def _weekdays(days: Sequence[int]) -> str:
42
+ days = sorted(set(days))
43
+ if days == [0, 1, 2, 3, 4]:
44
+ return "Monday to Friday"
45
+ if len(days) == 7:
46
+ return "every day"
47
+ return _join([NAMES[d] for d in days])
48
+
49
+
50
+ def _monthdays(rule: Rule, default: int | None = None) -> str:
51
+ vals = sorted(rule.bymonthday) if rule.bymonthday else [default or 1]
52
+ return "on " + _join([f"day {v}" if v > 0 else "the last day" for v in vals]) + " of the month"
53
+
54
+
55
+ def _times(rule: Rule, dt0: datetime) -> str:
56
+ minutes = rule.byminute or (dt0.minute,)
57
+ if rule.freq == "HOURLY":
58
+ text = f"At minute {_nums(minutes)}"
59
+ if rule.byhour:
60
+ text += f" past hour {_nums(rule.byhour)}"
61
+ return text + (f", every {rule.interval} hours" if rule.interval > 1 else "")
62
+ return text + (" of every hour" if rule.interval == 1 else f" of every {rule.interval} hours")
63
+ hours = rule.byhour or (dt0.hour,)
64
+ times = [f"{h:02d}:{m:02d}" for h in sorted(hours) for m in sorted(minutes)]
65
+ return "At " + _join(times) if len(times) <= 6 else f"At minute {_nums(minutes)} past hour {_nums(hours)}"
66
+
67
+
68
+ def _days(rule: Rule, dt0: datetime) -> str:
69
+ plain = [w for n, w in rule.byday if n == 0]
70
+ nth = [(n, w) for n, w in rule.byday if n != 0]
71
+ k = rule.interval
72
+ if rule.freq == "MONTHLY":
73
+ if nth:
74
+ day = "on the " + _join([f"{_ordinal(n)} {NAMES[w]}" for n, w in nth]) + " of the month"
75
+ elif plain:
76
+ day = "on every " + _join([NAMES[w] for w in sorted(set(plain))]) + " of the month"
77
+ if rule.bymonthday:
78
+ day += " " + _monthdays(rule)
79
+ else:
80
+ day = _monthdays(rule, dt0.day)
81
+ return day + (f", every {k} months" if k > 1 else "")
82
+ names = plain or ([] if rule.bymonthday else [dt0.weekday()])
83
+ parts = ([_weekdays(names)] if names and (rule.freq == "WEEKLY" or plain) else []) + (
84
+ [_monthdays(rule)] if rule.bymonthday else [])
85
+ if rule.freq == "WEEKLY":
86
+ return " ".join(parts) + (f", every {k} weeks" if k > 1 else "")
87
+ day = " ".join(parts) or "every day" # DAILY and HOURLY
88
+ if rule.freq == "DAILY" and k > 1:
89
+ return f"every {k} days" if not parts else f"{day}, every {k} days"
90
+ return day
91
+
92
+
93
+ def sentence(when: When) -> str:
94
+ """The echo's sentence, a fixed template over the canonical form (SCH-B18's "At 08:00, Monday to Friday.")."""
95
+ zone = zone_of(when.zone)
96
+ if when.kind == "once":
97
+ at = datetime.fromisoformat(str(when.at))
98
+ return f"Once, on {at:%Y-%m-%d} at {at:%H:%M}."
99
+ rule = parse_rule(str(when.rule))
100
+ dt0 = datetime.fromisoformat(str(when.starts))
101
+ if rule.is_interval:
102
+ if rule.freq == "HOURLY":
103
+ base = "Every hour" if rule.interval == 1 else f"Every {rule.interval} hours"
104
+ else:
105
+ base = f"Every {rule.interval} minutes"
106
+ base += f", from {dt0:%Y-%m-%d %H:%M}"
107
+ else:
108
+ base = f"{_times(rule, dt0)}, {_days(rule, dt0)}"
109
+ if rule.until is not None:
110
+ base += f", until {rule.until.astimezone(zone):%Y-%m-%d %H:%M}"
111
+ if rule.count is not None:
112
+ base += f", for {rule.count} times"
113
+ return base + "."
114
+
115
+
116
+ def _note(s: Slot, zone_name: str) -> str:
117
+ if s.note == "gap":
118
+ return (f"{s.wall:%Y-%m-%d %H:%M} does not exist in {zone_name}; the offset from before the gap makes it "
119
+ f"{s.local:%H:%M}")
120
+ if s.note == "overlap":
121
+ return f"{s.wall:%Y-%m-%d %H:%M} happens twice in {zone_name}; the first occurrence is used"
122
+ return ""
123
+
124
+
125
+ @dataclass
126
+ class Echo:
127
+ sentence: str
128
+ doc: dict[str, Any]
129
+
130
+ def to_doc(self) -> dict[str, Any]:
131
+ return self.doc
132
+
133
+ def text(self) -> str:
134
+ d = self.doc
135
+ lines = [d["sentence"]]
136
+ if d["kind"] == "once":
137
+ lines.append(f"at: {d['at']}")
138
+ else:
139
+ lines += [f"rule: {d['rule']}", f"starts: {d['starts']}"]
140
+ lines.append(f"zone: {d['zone']} (UTC{d['utc_offset']})")
141
+ if not d["slots"]:
142
+ lines.append("next slots: none")
143
+ else:
144
+ lines.append("next slot:" if d["kind"] == "once" else f"next {len(d['slots'])} slots:")
145
+ for s in d["slots"]:
146
+ lines.append(f" {s['local']} local = {s['utc'].replace('T', ' ').replace('Z', '')} UTC")
147
+ lines += [f" note: {n}" for n in d["notes"]]
148
+ lines += [f"assumed: {a}" for a in d["assumptions"]]
149
+ return "\n".join(lines) + "\n"
150
+
151
+
152
+ def build_echo(when: When, assumptions: Sequence[str], now: datetime, n: int = 3) -> Echo:
153
+ """The echo of a canonical When: the sentence, the zone with its current UTC offset, the next `n` slots (one for
154
+ a `once`) in local and UTC time, any gap or overlap on a listed slot, and each assumption."""
155
+ zone = zone_of(when.zone)
156
+ start = floor_minute(now)
157
+ slots = next_slots(when, start, 1 if when.kind == "once" else n)
158
+ doc: dict[str, Any] = {
159
+ "sentence": sentence(when), "kind": when.kind, "zone": when.zone, "utc_offset": utc_offset(zone, start),
160
+ "slots": [{"local": s.local.strftime("%Y-%m-%d %H:%M"), "utc": s.utc.strftime("%Y-%m-%dT%H:%MZ"), "note": s.note}
161
+ for s in slots],
162
+ "notes": [t for t in (_note(s, when.zone) for s in slots) if t], "assumptions": list(assumptions),
163
+ "canonical": when.to_doc(),
164
+ }
165
+ if when.kind == "once":
166
+ doc["at"] = when.at
167
+ else:
168
+ doc.update(rule=when.rule, starts=when.starts)
169
+ return Echo(sentence=str(doc["sentence"]), doc=doc)