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.
- tempergraph/__init__.py +8 -0
- tempergraph/__main__.py +5 -0
- tempergraph/api.py +428 -0
- tempergraph/audit/__init__.py +305 -0
- tempergraph/audit/catalog.py +342 -0
- tempergraph/audit/definition.py +387 -0
- tempergraph/audit/history.py +414 -0
- tempergraph/audit/history_rules.py +268 -0
- tempergraph/audit/history_rules_more.py +244 -0
- tempergraph/audit/host.py +270 -0
- tempergraph/audit/owned.py +96 -0
- tempergraph/audit/prompts.py +89 -0
- tempergraph/audit/report.py +248 -0
- tempergraph/audit/revisit.py +220 -0
- tempergraph/audit/surface.py +224 -0
- tempergraph/audit/text_health.py +176 -0
- tempergraph/audit/tools.py +391 -0
- tempergraph/author/__init__.py +2 -0
- tempergraph/author/blueprint.py +346 -0
- tempergraph/author/compare.py +122 -0
- tempergraph/author/criteria_lint.py +200 -0
- tempergraph/author/draw.py +112 -0
- tempergraph/author/inventory.py +210 -0
- tempergraph/author/literals.py +138 -0
- tempergraph/author/scaffold.py +568 -0
- tempergraph/author/session.py +439 -0
- tempergraph/author/trial.py +391 -0
- tempergraph/author/verify.py +353 -0
- tempergraph/builtin/__init__.py +1 -0
- tempergraph/builtin/upgrade.py +288 -0
- tempergraph/catalog.py +134 -0
- tempergraph/check_helpers.py +99 -0
- tempergraph/cli/__init__.py +1 -0
- tempergraph/cli/audit.py +190 -0
- tempergraph/cli/author.py +361 -0
- tempergraph/cli/improve.py +564 -0
- tempergraph/cli/improve_review.py +111 -0
- tempergraph/cli/install.py +35 -0
- tempergraph/cli/main.py +1261 -0
- tempergraph/cli/observe_cli.py +544 -0
- tempergraph/cli/outcome.py +77 -0
- tempergraph/cli/schedule_cli.py +1090 -0
- tempergraph/cli/upgrade.py +126 -0
- tempergraph/cli/workflows.py +96 -0
- tempergraph/compiler/__init__.py +6 -0
- tempergraph/compiler/graph.py +305 -0
- tempergraph/compiler/state.py +229 -0
- tempergraph/constants.py +72 -0
- tempergraph/contracts.py +1025 -0
- tempergraph/data/executor_compat.json +11 -0
- tempergraph/data/promotion.json +35 -0
- tempergraph/data/release.json +20 -0
- tempergraph/detach.py +65 -0
- tempergraph/docs.py +90 -0
- tempergraph/durability/__init__.py +2 -0
- tempergraph/durability/alias.py +66 -0
- tempergraph/durability/carry.py +591 -0
- tempergraph/durability/checkpoint.py +179 -0
- tempergraph/durability/control.py +109 -0
- tempergraph/durability/engine_file.py +301 -0
- tempergraph/durability/lock.py +138 -0
- tempergraph/durability/status.py +390 -0
- tempergraph/engine_identity.py +42 -0
- tempergraph/executor_compat.py +56 -0
- tempergraph/executors/__init__.py +4 -0
- tempergraph/executors/binding.py +91 -0
- tempergraph/executors/capabilities.py +95 -0
- tempergraph/executors/claude.py +603 -0
- tempergraph/executors/launcher.py +394 -0
- tempergraph/executors/mcpconfig.py +156 -0
- tempergraph/executors/mcpproxy.py +216 -0
- tempergraph/executors/preflight.py +196 -0
- tempergraph/executors/registry.py +71 -0
- tempergraph/executors/scripted.py +18 -0
- tempergraph/executors/session.py +107 -0
- tempergraph/executors/standins.py +118 -0
- tempergraph/executors/summary.py +110 -0
- tempergraph/executors/viewcatalog.py +27 -0
- tempergraph/git.py +403 -0
- tempergraph/identity.py +65 -0
- tempergraph/improve/__init__.py +5 -0
- tempergraph/improve/analysis.py +437 -0
- tempergraph/improve/artifact.py +477 -0
- tempergraph/improve/autonomy.py +192 -0
- tempergraph/improve/bindings.py +191 -0
- tempergraph/improve/calibration.py +1016 -0
- tempergraph/improve/causes.py +416 -0
- tempergraph/improve/child.py +651 -0
- tempergraph/improve/codehost.py +520 -0
- tempergraph/improve/digest.py +472 -0
- tempergraph/improve/escape.py +100 -0
- tempergraph/improve/filing.py +1047 -0
- tempergraph/improve/harvest.py +158 -0
- tempergraph/improve/issue_context.py +192 -0
- tempergraph/improve/lenses.py +204 -0
- tempergraph/improve/lessons.py +233 -0
- tempergraph/improve/loop_report.py +138 -0
- tempergraph/improve/loop_summary.py +85 -0
- tempergraph/improve/lost.py +119 -0
- tempergraph/improve/measure.py +121 -0
- tempergraph/improve/params.py +98 -0
- tempergraph/improve/pause_facts.py +134 -0
- tempergraph/improve/pr_later.py +186 -0
- tempergraph/improve/prebinding.py +130 -0
- tempergraph/improve/promotion.py +413 -0
- tempergraph/improve/proposals.py +934 -0
- tempergraph/improve/record.py +322 -0
- tempergraph/improve/release.py +89 -0
- tempergraph/improve/reliability.py +457 -0
- tempergraph/improve/repeat.py +115 -0
- tempergraph/improve/review.py +910 -0
- tempergraph/improve/suites.py +586 -0
- tempergraph/improve/trials.py +525 -0
- tempergraph/install/__init__.py +11 -0
- tempergraph/install/bootstrap.py +133 -0
- tempergraph/install/environment.py +173 -0
- tempergraph/install/launch.py +37 -0
- tempergraph/install/python.py +53 -0
- tempergraph/install/reconcile.py +52 -0
- tempergraph/install/selfcheck.py +29 -0
- tempergraph/install/shim.py +81 -0
- tempergraph/install/update.py +400 -0
- tempergraph/model/__init__.py +0 -0
- tempergraph/model/diagram.py +185 -0
- tempergraph/model/flow.py +324 -0
- tempergraph/model/prompt_lint.py +203 -0
- tempergraph/model/retire.py +52 -0
- tempergraph/model/subworkflow.py +274 -0
- tempergraph/model/text.py +67 -0
- tempergraph/model/validate.py +1158 -0
- tempergraph/observe/__init__.py +1 -0
- tempergraph/observe/attention.py +196 -0
- tempergraph/observe/detail.py +773 -0
- tempergraph/observe/forget.py +138 -0
- tempergraph/observe/hooks.py +272 -0
- tempergraph/observe/labels.py +95 -0
- tempergraph/observe/overlay.py +46 -0
- tempergraph/observe/report.py +402 -0
- tempergraph/observe/risk_report.py +110 -0
- tempergraph/observe/rows.py +444 -0
- tempergraph/observe/sinks.py +793 -0
- tempergraph/observe/supervision_cost.py +797 -0
- tempergraph/observe/supervision_report.py +295 -0
- tempergraph/observe/switch_report.py +140 -0
- tempergraph/package/__init__.py +2 -0
- tempergraph/package/change_report.py +116 -0
- tempergraph/package/changelog.py +263 -0
- tempergraph/package/docs_check.py +115 -0
- tempergraph/package/importer.py +90 -0
- tempergraph/package/inventory.py +111 -0
- tempergraph/package/loader.py +250 -0
- tempergraph/package/manifest.py +256 -0
- tempergraph/package/readiness.py +124 -0
- tempergraph/package/registry.py +383 -0
- tempergraph/package/rules.py +128 -0
- tempergraph/package/scan.py +65 -0
- tempergraph/package/selftest.py +348 -0
- tempergraph/package/stamp.py +213 -0
- tempergraph/package/transforms.py +481 -0
- tempergraph/package/upgrade.py +625 -0
- tempergraph/provenance.py +183 -0
- tempergraph/py.typed +0 -0
- tempergraph/release.py +17 -0
- tempergraph/render/__init__.py +0 -0
- tempergraph/render/output.py +72 -0
- tempergraph/render/prompt.py +166 -0
- tempergraph/render/template.py +86 -0
- tempergraph/run/__init__.py +2 -0
- tempergraph/run/asking.py +233 -0
- tempergraph/run/audit.py +63 -0
- tempergraph/run/check_worker.py +167 -0
- tempergraph/run/checks.py +517 -0
- tempergraph/run/commands.py +210 -0
- tempergraph/run/complexity.py +268 -0
- tempergraph/run/contest.py +76 -0
- tempergraph/run/council.py +368 -0
- tempergraph/run/council_run.py +527 -0
- tempergraph/run/events.py +279 -0
- tempergraph/run/finalize.py +132 -0
- tempergraph/run/gate.py +747 -0
- tempergraph/run/guard.py +89 -0
- tempergraph/run/judging.py +357 -0
- tempergraph/run/ladder.py +230 -0
- tempergraph/run/log.py +600 -0
- tempergraph/run/mapping.py +183 -0
- tempergraph/run/nodes.py +2304 -0
- tempergraph/run/outcome.py +255 -0
- tempergraph/run/outcome_record.py +292 -0
- tempergraph/run/outcome_trust.py +99 -0
- tempergraph/run/rerun.py +351 -0
- tempergraph/run/reserve.py +85 -0
- tempergraph/run/resources.py +76 -0
- tempergraph/run/risk.py +231 -0
- tempergraph/run/runner.py +1579 -0
- tempergraph/run/scriptcache.py +178 -0
- tempergraph/run/selfcheck.py +105 -0
- tempergraph/run/session_record.py +72 -0
- tempergraph/run/subrun.py +278 -0
- tempergraph/run/supervision.py +125 -0
- tempergraph/run/tool_access.py +101 -0
- tempergraph/schedule/__init__.py +25 -0
- tempergraph/schedule/credentials.py +167 -0
- tempergraph/schedule/echo.py +169 -0
- tempergraph/schedule/exact.py +275 -0
- tempergraph/schedule/export.py +164 -0
- tempergraph/schedule/launch.py +89 -0
- tempergraph/schedule/ledger.py +133 -0
- tempergraph/schedule/loop.py +176 -0
- tempergraph/schedule/model.py +440 -0
- tempergraph/schedule/policies.py +414 -0
- tempergraph/schedule/store.py +150 -0
- tempergraph/schedule/tick.py +377 -0
- tempergraph/schedule/token.py +81 -0
- tempergraph/schedule/triggers.py +210 -0
- tempergraph/schedule/words.py +423 -0
- tempergraph/security/__init__.py +0 -0
- tempergraph/security/launch.py +25 -0
- tempergraph/security/scrub.py +58 -0
- tempergraph/settings.py +950 -0
- tempergraph/store/__init__.py +0 -0
- tempergraph/store/codelog.py +73 -0
- tempergraph/store/layout.py +198 -0
- tempergraph/store/logs.py +325 -0
- tempergraph/store/manifest.py +99 -0
- tempergraph/store/migrate.py +188 -0
- tempergraph/workspace.py +874 -0
- tempergraph-0.7.1.dist-info/METADATA +70 -0
- tempergraph-0.7.1.dist-info/RECORD +232 -0
- tempergraph-0.7.1.dist-info/WHEEL +5 -0
- tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
- tempergraph-0.7.1.dist-info/top_level.txt +2 -0
- 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)."""
|
tempergraph/cli/audit.py
ADDED
|
@@ -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
|