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
tempergraph/catalog.py ADDED
@@ -0,0 +1,134 @@
1
+ """The workflow catalog and request resolution (CLI-B7, CLI-B8, CLI-B14, CON-B9, UPD-B20 to UPD-B24).
2
+
3
+ The catalog reads the home registry (`registry.json`, UPD-B20 to UPD-B24) and loads each entry's package by PKG-B15, PKG-B16, PKG-B17
4
+ (`tempergraph.package.loader`): both manifests, the interface level, the dependency gate and the source
5
+ scan, the import under the package's private name, the build and the outcome.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import hashlib
12
+ import json
13
+ import re
14
+ from collections.abc import Mapping
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from tempergraph.constants import SCHEMA
20
+ from tempergraph.contracts import Question, ResolveResult, WorkflowSpec
21
+ from tempergraph.package.loader import LoadedPackage, PackageNotLoaded
22
+ from tempergraph.package.loader import load_package as _load
23
+ from tempergraph.store.layout import home_path
24
+
25
+ TASK_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
26
+ TRACKER_KEY = re.compile(r"^[A-Z][A-Z0-9]{0,9}-[0-9]{1,9}$")
27
+
28
+
29
+ @dataclass(kw_only=True)
30
+ class Catalog:
31
+ specs: dict[str, WorkflowSpec] = field(default_factory=dict)
32
+ broken: dict[str, str] = field(default_factory=dict) # name -> not_loaded reason
33
+ packages: dict[str, LoadedPackage] = field(default_factory=dict) # name -> digests and load findings
34
+ compat: dict[str, str] = field(default_factory=dict) # name -> VER-B2, VER-B5 state
35
+
36
+ def to_json(self) -> dict[str, Any]:
37
+ rows = [{"name": n, "version": s.version, "state": "ok", "description": s.routing.description,
38
+ "when_to_use": s.routing.when_to_use, "task_kind": s.routing.task_kind, "input": s.input.kind,
39
+ "units": list(s.order),
40
+ "workflow_version": self.packages[n].workflow_version if n in self.packages else None,
41
+ "compatibility": self.compat.get(n)}
42
+ for n, s in sorted(self.specs.items()) if not s.builtin] # a built-in is no routing target
43
+ rows += [{"name": n, "state": "not_loaded", "reason": r} for n, r in sorted(self.broken.items())]
44
+ return {"schema_version": SCHEMA.get("catalog", 1), "workflows": rows}
45
+
46
+
47
+ def load_package(path: Path) -> WorkflowSpec:
48
+ """PKG-B15, PKG-B16, PKG-B17; read-only, calls no model."""
49
+ return _load(path).spec
50
+
51
+
52
+ def _compat(loaded: LoadedPackage) -> str:
53
+ """VER-B2, VER-B5, read-only and model-free; the state is a catalog column and never refuses on its own."""
54
+ from tempergraph.package.changelog import compatibility
55
+ from tempergraph.package.stamp import read_stamp
56
+
57
+ try:
58
+ return str(compatibility(loaded.spec, loaded.root, read_stamp(loaded.root))["state"])
59
+ except (OSError, ValueError):
60
+ return "unknown"
61
+
62
+
63
+ def builtins(cat: Catalog) -> Catalog:
64
+ """The engine's own workflows, added after every package so none can shadow them (UWF-B6, UWF-B5, UWF-B7)."""
65
+ from tempergraph.builtin import upgrade
66
+
67
+ cat.broken.pop(upgrade.NAME, None)
68
+ cat.packages.pop(upgrade.NAME, None)
69
+ cat.specs[upgrade.NAME] = upgrade.workflow()
70
+ return cat
71
+
72
+
73
+ def from_registry(home: Path | None = None) -> Catalog:
74
+ cat = Catalog()
75
+ reg = (home or home_path()) / "registry.json"
76
+ if not reg.exists():
77
+ return builtins(cat)
78
+ try:
79
+ entries = json.loads(reg.read_text(encoding="utf-8")).get("workflows") or []
80
+ except (OSError, ValueError, AttributeError):
81
+ return builtins(cat)
82
+ for e in entries:
83
+ name = str(e.get("name") or "")
84
+ if not name:
85
+ continue
86
+ try:
87
+ loaded = _load(Path(str(e.get("path") or "")))
88
+ cat.specs[name], cat.packages[name] = loaded.spec, loaded
89
+ cat.compat[name] = _compat(loaded)
90
+ except PackageNotLoaded as exc:
91
+ cat.broken[name] = exc.reason
92
+ return builtins(cat)
93
+
94
+
95
+ def _digest(text: str, n: int = 10) -> str:
96
+ return hashlib.sha256(" ".join(text.split()).encode()).hexdigest()[:n]
97
+
98
+
99
+ def resolve_request(spec: WorkflowSpec, words: list[str], inputs: Mapping[str, str], cwd: Path,
100
+ task_id: str | None = None) -> ResolveResult:
101
+ """Turn a start request into a task source with a stable id; read-only, model-free.
102
+
103
+ Without a resolver the id is the request's own: a tracker key as given, else `t-<hash>` of the
104
+ whitespace-normalised text, so the same request finds the same thread (ROP-B1 to ROP-B13)."""
105
+ text = " ".join(words).strip()
106
+ if task_id is not None and not TASK_ID.match(task_id):
107
+ return ResolveResult(status="error", message=f"task id {task_id!r}: 1 to 64 letters, digits, '.', '_' or '-'")
108
+ decl = spec.input
109
+ if decl.kind == "resolver" and decl.resolver is not None:
110
+ try:
111
+ res = decl.resolver.resolve()(text)
112
+ except Exception as exc: # noqa: BLE001 - a resolver's failure is the workflow's, shown as broken
113
+ raise PackageNotLoaded("resolver", type(exc).__name__) from exc
114
+ if not isinstance(res, ResolveResult):
115
+ raise PackageNotLoaded("resolver", "the resolver did not return a ResolveResult")
116
+ if res.status == "ok":
117
+ res = dataclasses.replace(res, task_id=task_id or res.task_id,
118
+ inputs={"request": text, **dict(res.inputs), **dict(inputs)})
119
+ return res
120
+ if not text:
121
+ return ResolveResult(status="needs", questions=(Question(name="request", question="What should the run do?"),))
122
+ merged = {"request": text, **dict(inputs)}
123
+ if decl.kind == "tracker_key":
124
+ if not TRACKER_KEY.match(text):
125
+ return ResolveResult(status="error", message=f"{text!r} is not a tracker key such as ABC-123")
126
+ return ResolveResult(status="ok", task_id=task_id or text, inputs=merged)
127
+ if decl.kind == "file":
128
+ p = (cwd / text).resolve()
129
+ if not p.is_file():
130
+ return ResolveResult(status="error", message=f"{text}: no such file")
131
+ stem = re.sub(r"[^A-Za-z0-9._-]+", "-", p.stem)[:40].strip("-") or "file"
132
+ return ResolveResult(status="ok", task_id=task_id or f"f-{stem}-{_digest(str(p), 6)}",
133
+ inputs={**merged, "file": str(p)})
134
+ return ResolveResult(status="ok", task_id=task_id or f"t-{_digest(text)}", inputs=merged)
@@ -0,0 +1,99 @@
1
+ """The engine's check helpers, `tempergraph.api.checks` (SCF-B14, SCF-B15, SCF-B16, SCF-B17): the primitives a scaffolded check uses for
2
+ a `check` criterion. Each returns one `CheckFinding` naming the criterion id; `result` combines them. Pure
3
+ over the workspace (CHK: no write, no model)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections.abc import Iterable
9
+ from typing import Any
10
+
11
+ from tempergraph.contracts import CheckFinding, CheckResult
12
+
13
+ PRIMITIVES = ("file_present", "headings_in_order", "pattern_present", "pattern_absent", "value_in_choices",
14
+ "git_clean", "git_pushed")
15
+
16
+
17
+ def artifact_path(ctx: Any, key: str) -> str | None:
18
+ """The path a step recorded for artifact `key`, from any unit (latest unit in the mapping wins)."""
19
+ found = None
20
+ for arts in (ctx.artifacts or {}).values():
21
+ if isinstance(arts, dict) and arts.get(key):
22
+ found = str(arts[key])
23
+ return found
24
+
25
+
26
+ def _text(ctx: Any, key: str) -> str | None:
27
+ path = artifact_path(ctx, key)
28
+ if path is None:
29
+ return None
30
+ try:
31
+ return str(ctx.read_text(path))
32
+ except (OSError, PermissionError):
33
+ return None
34
+
35
+
36
+ def _f(ok: bool, criterion: str, place: str, message: str, fix: str = "") -> CheckFinding:
37
+ # every stock helper checks the shape of the output, never its substance (LAD-B10)
38
+ return CheckFinding(status="pass" if ok else "fail", criterion=criterion, place=place,
39
+ message=message if not ok else "", fix=fix if not ok else "", kind="output_contract")
40
+
41
+
42
+ def file_present(ctx: Any, key: str, criterion: str) -> CheckFinding:
43
+ path = artifact_path(ctx, key)
44
+ ok = path is not None and (ctx.workdir / path).is_file()
45
+ return _f(ok, criterion, path or key, f"artifact {key!r} is not a file in the workspace", f"write {key}")
46
+
47
+
48
+ def headings_in_order(ctx: Any, key: str, headings: Iterable[str], criterion: str) -> CheckFinding:
49
+ """Every heading present, in this order (`#` level ignored, case and spacing normalised)."""
50
+ want = [" ".join(h.lower().split()) for h in headings]
51
+ text = _text(ctx, key)
52
+ if text is None:
53
+ return _f(False, criterion, key, f"artifact {key!r} cannot be read")
54
+ found = [" ".join(m.group(1).lower().split()) for m in re.finditer(r"^\s*#{1,6}\s+(.+?)\s*#*\s*$", text, re.M)]
55
+ pos = 0
56
+ for h in want:
57
+ try:
58
+ pos = found.index(h, pos) + 1
59
+ except ValueError:
60
+ return _f(False, criterion, key, f"heading {h!r} is missing or out of order", f"add the {h!r} heading")
61
+ return _f(True, criterion, key, "")
62
+
63
+
64
+ def pattern_present(ctx: Any, key: str, pattern: str, criterion: str) -> CheckFinding:
65
+ text = _text(ctx, key)
66
+ ok = text is not None and re.search(pattern, text, re.M) is not None
67
+ return _f(ok, criterion, key, f"{key} does not match {pattern!r}")
68
+
69
+
70
+ def pattern_absent(ctx: Any, key: str, pattern: str, criterion: str) -> CheckFinding:
71
+ text = _text(ctx, key)
72
+ m = re.search(pattern, text, re.M) if text is not None else None
73
+ ok = text is not None and m is None
74
+ line = text.count("\n", 0, m.start()) + 1 if (text is not None and m is not None) else 0
75
+ return _f(ok, criterion, f"{key}:{line}" if line else key, f"{key} matches {pattern!r}")
76
+
77
+
78
+ def value_in_choices(ctx: Any, key: str, choices: Iterable[str], criterion: str) -> CheckFinding:
79
+ value = None
80
+ for vals in (ctx.values or {}).values():
81
+ if isinstance(vals, dict) and key in vals:
82
+ value = vals[key]
83
+ ok = value is not None and str(value) in set(choices)
84
+ return _f(ok, criterion, key, f"value {key}={value!r} is not one of {sorted(choices)}")
85
+
86
+
87
+ def git_clean(ctx: Any, criterion: str) -> CheckFinding:
88
+ return _f(bool(ctx.git.clean), criterion, "git", "the workspace has uncommitted changes", "commit or remove them")
89
+
90
+
91
+ def git_pushed(ctx: Any, criterion: str) -> CheckFinding:
92
+ return _f(bool(ctx.git.pushed), criterion, "git", "the branch is not pushed", "push the branch")
93
+
94
+
95
+ def result(findings: Iterable[CheckFinding], evidence: str = "") -> CheckResult:
96
+ fs = list(findings)
97
+ bad = [f for f in fs if f.status == "fail"]
98
+ return CheckResult(result="FAIL" if bad else "PASS", evidence=evidence or (
99
+ "; ".join(f"{f.criterion}: {f.message}" for f in bad) or f"{len(fs)} checked"), findings=fs)
@@ -0,0 +1 @@
1
+ """The engine CLI (CLI)."""
@@ -0,0 +1,190 @@
1
+ """`tempergraph audit <workflow>` and `audit prompts <workflow>` (AUD-B11, AUD-B6, AUD-B9, PRA-B11).
2
+
3
+ Advisory: exit 0 whatever is found, 6 with `--fail-on` when a finding not ignored is at or above the level,
4
+ 2 for an unknown workflow or option. Output goes to stdout only; nothing is written (AUD-B6).
5
+ `--layer history` reads the workflow's local run records in `--window` days and `--version` (read-only); a bare
6
+ `audit` reads them when the history layer is asked for by default and runs it when runs exist (AUD-B1, AUD-B11).
7
+ `audit tools <workflow> [--executor <name>] [--step <unit>]` prints the tool surface matrix of TSA instead of
8
+ findings, from the surface the audit builds once; `--fail-on` counts the tool findings (TSA-B8, TSA-B5).
9
+ `audit prompts` reads `changed` from the same history facts (PRA-B11).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import datetime as dt
16
+ import json
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from tempergraph.audit import AuditContext, audit, audit_layers
21
+ from tempergraph.audit.catalog import BY_ID
22
+ from tempergraph.audit.history import HistoryFacts, read_history
23
+ from tempergraph.audit.prompts import prompt_rows
24
+ from tempergraph.audit.report import AuditFinding, AuditReport, render
25
+ from tempergraph.audit.tools import matrix, render_matrix
26
+ from tempergraph.constants import ENGINE_VERSION, ExitCode
27
+ from tempergraph.executors.capabilities import DECLARED
28
+
29
+
30
+ def add_parsers(sub: Any) -> None:
31
+ p = sub.add_parser("audit", help="advisory, read-only audit of a workflow (no model call)")
32
+ p.add_argument("first", metavar="workflow",
33
+ help="a workflow, or `prompts` / `tools` / `decisions` then a workflow")
34
+ p.add_argument("second", nargs="?", default=None, help=argparse.SUPPRESS)
35
+ p.add_argument("--layer", action="append", choices=("definition", "host", "history"), default=None)
36
+ p.add_argument("--target", default=None)
37
+ p.add_argument("--executor", default=None)
38
+ p.add_argument("--step", action="append", default=[])
39
+ p.add_argument("--window", type=int, default=30)
40
+ p.add_argument("--version", default="current")
41
+ p.add_argument("--all", action="store_true", dest="show_all")
42
+ p.add_argument("--format", choices=("text", "json", "sarif"), default="text")
43
+ p.add_argument("--fail-on", choices=("error", "warning", "never"), default="never")
44
+
45
+
46
+ def _probe(env: Any) -> Any:
47
+ def probe(name: str) -> str | None:
48
+ try:
49
+ got = env.registry.get(name).probe()
50
+ except Exception: # noqa: BLE001 - an unknown or failing executor skips the rule (AUD-B15, AUD-B9, AUD-B2)
51
+ return None
52
+ return got.version if got.ok and got.version else None
53
+
54
+ return probe
55
+
56
+
57
+ def _issue_state(spec: Any) -> Any:
58
+ """DRV-B2: an issue of the workflow's issue repository, read through `gh` once per number."""
59
+ repo = getattr(spec, "issue_repository", None)
60
+ if not repo:
61
+ return None
62
+ seen: dict[int, str | None] = {}
63
+
64
+ def read(n: int) -> str | None:
65
+ if n not in seen:
66
+ from tempergraph.improve.codehost import GhCodeHost
67
+
68
+ seen[n] = GhCodeHost(timeout_s=20).issue_state(str(repo), n)
69
+ return seen[n]
70
+
71
+ return read
72
+
73
+
74
+ def cmd_audit(env: Any, a: argparse.Namespace) -> int:
75
+ view, name = ("findings", a.first) if a.second is None else (a.first, a.second)
76
+ if view not in ("findings", "prompts", "tools", "decisions"):
77
+ env.err.write(f"tempergraph: audit takes a workflow, or prompts, tools or decisions then a workflow; got "
78
+ f"{view!r}\n")
79
+ return int(ExitCode.USAGE)
80
+ if view == "tools" and a.executor and a.executor not in DECLARED and a.executor not in env.registry.available():
81
+ env.err.write(f"tempergraph: unknown executor {a.executor!r} for audit tools\n")
82
+ return int(ExitCode.USAGE)
83
+ target = Path(a.target) if a.target else env.cwd
84
+ target = target if target.is_absolute() else env.cwd / target
85
+ if not target.is_dir():
86
+ env.err.write(f"tempergraph: --target {a.target!r} is not a directory\n")
87
+ return int(ExitCode.USAGE)
88
+ got = _workflow(env, name)
89
+ if got is None:
90
+ env.err.write(f"tempergraph: unknown workflow {name!r}; `tempergraph workflows list` shows them\n")
91
+ return int(ExitCode.USAGE)
92
+ if isinstance(got, AuditReport): # not loaded: one finding, the manifest row only (AUD-B15, AUD-B9, AUD-B2)
93
+ env.out.write(render(got, a.format))
94
+ return got.exit_code(a.fail_on)
95
+ spec, manifest, stamp = got
96
+ caps = {n: env.registry.get(n).capabilities() for n in env.registry.available()}
97
+ layers = audit_layers(a.layer)
98
+ facts = _history(env, spec, a) if "history" in layers or view != "findings" else None
99
+ tools = view == "tools"
100
+ ctx = AuditContext(target=target, caps=caps, probe=_probe(env), window_days=a.window, version=a.version,
101
+ executor=None if tools else a.executor, steps=tuple(a.step), show_all=a.show_all, history=facts,
102
+ tool_executor=a.executor if tools else None, mcp_servers=_operator_mcp,
103
+ issue_state=_issue_state(spec))
104
+ rep = audit(spec, layers, ctx, manifest=manifest, stamp=stamp)
105
+ if tools:
106
+ return _tools(env, a, spec, rep)
107
+ if view == "decisions": # DRV-B4
108
+ from tempergraph.audit import readers
109
+ from tempergraph.audit.revisit import rows
110
+
111
+ env.out.write(json.dumps({"schema_version": 1, "workflow": spec.name, "stamped": stamp is not None,
112
+ "triggers": rows(spec, stamp, readers(ctx))}, indent=2) + "\n")
113
+ return 0
114
+ if view == "prompts":
115
+ env.out.write(json.dumps({"schema_version": 1, "workflow": spec.name, "files": prompt_rows(spec, rep, facts)},
116
+ indent=2) + "\n")
117
+ return 0
118
+ env.out.write(render(rep, a.format))
119
+ return rep.exit_code(a.fail_on)
120
+
121
+
122
+ def _tools(env: Any, a: argparse.Namespace, spec: Any, rep: AuditReport) -> int:
123
+ """TSA-B8, TSA-B5: the matrix from the surface the audit built once, the history rules listed as skipped, and the
124
+ exit code of `--fail-on` over the tool findings only."""
125
+ c4 = [f for f in rep.findings if f.rule in BY_ID and BY_ID[f.rule].family == "C4"]
126
+ rows = matrix(rep.surface, c4) if rep.surface is not None else []
127
+ if a.step:
128
+ rows = [r for r in rows if r["unit"] in set(a.step)]
129
+ skipped = [s for s in rep.rules_skipped if s["rule"] in BY_ID and BY_ID[s["rule"]].layer == "history"]
130
+ extra = {"workflow": spec.name, "executor": a.executor, "history": bool(rep.surface and rep.surface.history),
131
+ "rules_skipped": skipped}
132
+ env.out.write(render_matrix(rows, "json" if a.format == "json" else "text", extra=extra))
133
+ rep.findings = c4
134
+ return rep.exit_code(a.fail_on)
135
+
136
+
137
+ def _operator_mcp() -> set[str] | None:
138
+ """The MCP servers of the operator's own configuration (`~/.claude.json`); a project file is never read (TSA-B12)."""
139
+ try:
140
+ doc = json.loads((Path.home() / ".claude.json").read_text(encoding="utf-8"))
141
+ except FileNotFoundError:
142
+ return set()
143
+ except (OSError, ValueError):
144
+ return None
145
+ servers = doc.get("mcpServers") if isinstance(doc, dict) else None
146
+ return set(servers) if isinstance(servers, dict) else set()
147
+
148
+
149
+ def _history(env: Any, spec: Any, a: argparse.Namespace) -> HistoryFacts | None:
150
+ """The facts of the workflow's runs in the window and version; none outside a state root (AUD-B11, AUD-B15)."""
151
+ from tempergraph.store.layout import NotInRepository, state_root_path
152
+
153
+ try:
154
+ root = state_root_path(env.cwd)
155
+ except NotInRepository:
156
+ return None
157
+ return read_history(root, spec.name, a.version, a.window, dt.date.today(), current=spec.version)
158
+
159
+
160
+ def _workflow(env: Any, name: str) -> tuple[Any, Any, dict[str, Any] | None] | AuditReport | None:
161
+ from tempergraph.package.loader import PackageNotLoaded, load_package
162
+ from tempergraph.package.manifest import read_manifest
163
+ from tempergraph.package.stamp import read_stamp
164
+
165
+ spec = env.catalog.specs.get(name)
166
+ if spec is not None:
167
+ root = spec.package_root
168
+ manifest = read_manifest(root) if root is not None else None
169
+ return spec, (None if isinstance(manifest, list) else manifest), (read_stamp(root) if root else None)
170
+ p = Path(name)
171
+ p = p if p.is_absolute() else env.cwd / p
172
+ broken = env.catalog.broken.get(name)
173
+ if not (p / "tempergraph.json").is_file():
174
+ return _not_loaded(name, broken) if broken else None
175
+ try:
176
+ lp = load_package(p)
177
+ except PackageNotLoaded as exc:
178
+ return _not_loaded(name, str(exc))
179
+ return lp.spec, lp.manifests.engine, read_stamp(lp.root)
180
+
181
+
182
+ def _not_loaded(name: str, reason: str) -> AuditReport:
183
+ rep = AuditReport(workflow=name, version="", engine_version=ENGINE_VERSION)
184
+ rep.layers_skipped = [{"layer": layer, "reason": "the workflow is not loaded"}
185
+ for layer in ("definition", "host", "history")]
186
+ rep.findings = [AuditFinding(rule="validate:not_loaded", layer="definition", severity="error",
187
+ confidence="high", owner="validate", statement=reason,
188
+ remedy="Fix what stops the package loading (PKG-B11, PKG-B13, PKG-B14, PKG-B17, PKG-B18, PKG-B19, PKG-B20, PKG-B23)",
189
+ location={"file": "tempergraph.json"})]
190
+ return rep