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
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""The C4 rules of the tool surface audit (TSA-B1, TSA-B2, TSA-B4, TSA-B9 to TSA-B13) and the matrix of `audit tools`
|
|
2
|
+
(TSA-B3, TSA-B5, TSA-B8).
|
|
3
|
+
|
|
4
|
+
Every rule reads the session surface built once by `audit.surface` (the executors' tool maps, the manifest, and the
|
|
5
|
+
recorded use when there is history), the host facts the caller passes in (read-only) and `HistoryFacts`; nothing is
|
|
6
|
+
written and no model is asked. A remedy that adds a grant (a command or a tool) is marked widening: the finding
|
|
7
|
+
carries `widening` and its remedy starts with `Widens the grant:` (TSA-B13); a remedy that removes one is plain
|
|
8
|
+
advice. The matrix and the findings read one surface, so they cannot disagree.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Callable, Mapping, Sequence
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
from tempergraph import executor_compat
|
|
19
|
+
from tempergraph.audit.catalog import PARAMS, rule
|
|
20
|
+
from tempergraph.audit.history import HistoryFacts
|
|
21
|
+
from tempergraph.audit.history_rules import RuleSkipped
|
|
22
|
+
from tempergraph.audit.host import installed_skills
|
|
23
|
+
from tempergraph.audit.report import AuditFinding
|
|
24
|
+
from tempergraph.audit.surface import (
|
|
25
|
+
CLASSES,
|
|
26
|
+
SessionSurface,
|
|
27
|
+
Surface,
|
|
28
|
+
caps_of,
|
|
29
|
+
read_names,
|
|
30
|
+
step_text,
|
|
31
|
+
)
|
|
32
|
+
from tempergraph.contracts import Capabilities, WorkflowSpec
|
|
33
|
+
from tempergraph.executors.capabilities import tool_names
|
|
34
|
+
|
|
35
|
+
P = {k: v.default for k, v in PARAMS.items()}
|
|
36
|
+
DIR_CHANGE_TEXT = re.compile(r"\bcd\s+\S+\s*(?:&&|;)")
|
|
37
|
+
SHELL_READ_TEXT = re.compile(r"\b(?:use|run|via|using|with)\s+`?(?:cat|head|tail|grep|rg|find|ls)\b", re.I)
|
|
38
|
+
OUTSIDE_TEXT = re.compile(r"(?<![\w./-])(?:/(?:etc|usr|var|home|root|tmp|opt|mnt|Users)\b[\w./-]*|\.\./[\w./-]*)")
|
|
39
|
+
# How an executor holds the grant it was given: only with a run flag, by construction, or by what a probe finds.
|
|
40
|
+
ENFORCEMENT = {"claude": "flag", "agent-sdk": "always", "messages-api": "construction", "antigravity": "probe"}
|
|
41
|
+
FIX = {
|
|
42
|
+
"shell_for_read": "use the file tools to read and search",
|
|
43
|
+
"dir_change_then_command": "name the directory to the command (`git -C <dir>`)",
|
|
44
|
+
"outside_workspace": "use paths inside the workspace",
|
|
45
|
+
"undeclared_tool": "declare the tool",
|
|
46
|
+
"needed_command": "declare the command or add it to the resolver",
|
|
47
|
+
}
|
|
48
|
+
WIDENING_CLASSES = frozenset({"undeclared_tool", "needed_command"})
|
|
49
|
+
AmbientProbe = Callable[[str], list[str] | None]
|
|
50
|
+
ConfiguredServers = Callable[[], set[str] | None]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def enforcement(caps: Capabilities) -> str:
|
|
54
|
+
"""`always`, `construction`, `flag`, `probe` or `never`: when the executor holds a step's grant."""
|
|
55
|
+
if not caps.enforces_step_tools:
|
|
56
|
+
return "never"
|
|
57
|
+
return ENFORCEMENT.get(caps.name, "always")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def current_names(caps: Capabilities) -> set[str]:
|
|
61
|
+
return {n for names in caps.tool_map.values() for n in names if "{" not in n}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ToolRules:
|
|
65
|
+
def __init__(self, spec: WorkflowSpec, surface: Surface, caps: Mapping[str, Capabilities], decl: str, *,
|
|
66
|
+
stamp: dict[str, Any] | None = None, plugin_cache: Any = None,
|
|
67
|
+
mcp_servers: ConfiguredServers | None = None, ambient_tools: AmbientProbe | None = None) -> None:
|
|
68
|
+
self.spec, self.surface, self.caps, self.decl = spec, surface, caps, decl
|
|
69
|
+
self.stamp, self.plugin_cache = stamp, plugin_cache
|
|
70
|
+
self.mcp_servers, self.ambient_tools = mcp_servers, ambient_tools
|
|
71
|
+
self.found: list[AuditFinding] = []
|
|
72
|
+
self.skipped: list[dict[str, Any]] = []
|
|
73
|
+
self.facts: HistoryFacts | None = None
|
|
74
|
+
|
|
75
|
+
# -- helpers -------------------------------------------------------------------------------------------------
|
|
76
|
+
def add(self, rule_id: str, unit: str | None, statement: str, *, session: str | None = None,
|
|
77
|
+
item: str | None = None, evidence: dict[str, Any] | None = None, field: str | None = None,
|
|
78
|
+
remedy: str | None = None, widening: bool | None = None, cause: str | None = None) -> None:
|
|
79
|
+
"""One finding with the catalog's record; a widening remedy is marked and its text says so (TSA-B13)."""
|
|
80
|
+
r = rule(rule_id)
|
|
81
|
+
wide = r.widening if widening is None else widening
|
|
82
|
+
ev = dict(evidence or {})
|
|
83
|
+
if r.layer == "history" and self.facts is not None:
|
|
84
|
+
ev.update(n=self.facts.runs, window_days=self.facts.window_days)
|
|
85
|
+
loc: dict[str, Any] = {"file": self.decl}
|
|
86
|
+
if field:
|
|
87
|
+
loc["field"] = field
|
|
88
|
+
text = remedy or r.remedy
|
|
89
|
+
self.found.append(AuditFinding(
|
|
90
|
+
rule=r.id, layer=r.layer, severity=r.severity, confidence=r.confidence,
|
|
91
|
+
cause=cause or r.cause, unit=unit, item=item, session=session, statement=statement, evidence=ev,
|
|
92
|
+
remedy=("Widens the grant: " + text) if wide else text, widening=wide,
|
|
93
|
+
location=loc if r.layer != "history" else {}))
|
|
94
|
+
|
|
95
|
+
def skip(self, rule_id: str, reason: str) -> None:
|
|
96
|
+
self.skipped.append({"rule": rule_id, "reason": reason})
|
|
97
|
+
|
|
98
|
+
def steps(self) -> list[SessionSurface]:
|
|
99
|
+
return [s for s in self.surface.sessions if s.role == "step"]
|
|
100
|
+
|
|
101
|
+
def judges(self) -> list[SessionSurface]:
|
|
102
|
+
return [s for s in self.surface.sessions if s.role == "judge"]
|
|
103
|
+
|
|
104
|
+
# -- definition: grant and need (TSA-B10) ----------------------------------------------------------------------
|
|
105
|
+
def definition(self) -> list[AuditFinding]:
|
|
106
|
+
start = len(self.found)
|
|
107
|
+
for s in self.steps():
|
|
108
|
+
u = self.spec.units[s.unit]
|
|
109
|
+
st = u.step
|
|
110
|
+
if st is None:
|
|
111
|
+
continue
|
|
112
|
+
text = step_text(self.spec, s.unit)
|
|
113
|
+
field = f"units.{s.unit}.step.tools"
|
|
114
|
+
for key in s.artifacts_unwritable:
|
|
115
|
+
self.add("artifact-needs-write", s.unit, f"{s.unit} produces {key!r} ({s.produces[key]}) and declares "
|
|
116
|
+
"no tool that can write it", session="step", item=key, evidence={"artifact": key,
|
|
117
|
+
"kind": s.produces[key]},
|
|
118
|
+
field=f"units.{s.unit}.step.produces.{key}")
|
|
119
|
+
if "shell" in st.tools and not st.commands:
|
|
120
|
+
self.add("shell-without-commands", s.unit, f"{s.unit} declares `shell` with no command prefix",
|
|
121
|
+
session="step", field=f"units.{s.unit}.step.commands")
|
|
122
|
+
offenders = [c for c in st.commands if re.search(r"\bcd\b", c)]
|
|
123
|
+
if m := DIR_CHANGE_TEXT.search(text):
|
|
124
|
+
offenders.append(m.group(0))
|
|
125
|
+
for off in offenders:
|
|
126
|
+
self.add("dir-change-in-commands", s.unit, f"{s.unit} changes directory before a command ({off!r})",
|
|
127
|
+
session="step", item=off, field=f"units.{s.unit}.step.commands")
|
|
128
|
+
if "shell" in st.tools and {"read", "search"} & set(st.tools) and (m := SHELL_READ_TEXT.search(text)):
|
|
129
|
+
self.add("shell-for-read-likely", s.unit, f"the text of {s.unit} tells the step to read or search "
|
|
130
|
+
f"through shell programs ({m.group(0)!r}) while file tools are granted", session="step",
|
|
131
|
+
evidence={"text": m.group(0)}, field=field)
|
|
132
|
+
outside = OUTSIDE_TEXT.search(text) or next((m for c in st.commands if (m := OUTSIDE_TEXT.search(c))),
|
|
133
|
+
None)
|
|
134
|
+
if outside:
|
|
135
|
+
self.add("path-outside-workspace", s.unit, f"{s.unit} names the path {outside.group(0)!r}, outside "
|
|
136
|
+
"the workspace", session="step", item=outside.group(0))
|
|
137
|
+
sc = caps_of(self.caps, s.executor)
|
|
138
|
+
for cap in st.tools:
|
|
139
|
+
names = tool_names(sc, cap) if sc else ()
|
|
140
|
+
if names and not any(n in s.needed for n in names):
|
|
141
|
+
self.add("granted-not-needed", s.unit, f"{s.unit} grants {cap!r}, which its text and artifacts "
|
|
142
|
+
"never ask for", session="step", item=cap, field=field)
|
|
143
|
+
if sc is not None and st.tools and enforcement(sc) == "never":
|
|
144
|
+
self.add("not-enforced", s.unit, f"{s.executor} cannot hold {s.unit}'s grant; the step may call "
|
|
145
|
+
"any tool", session="step", item=s.executor,
|
|
146
|
+
evidence={"executor": s.executor, "enforcement": enforcement(sc)})
|
|
147
|
+
self._catalog(s, st.tools)
|
|
148
|
+
return self.found[start:]
|
|
149
|
+
|
|
150
|
+
def _catalog(self, s: SessionSurface, tools: tuple[str, ...]) -> None:
|
|
151
|
+
"""TSA-B10: a declared MCP tool the view catalog does not classify, or whose judge's executor has no MCP
|
|
152
|
+
view: either way its judge gets no view of it."""
|
|
153
|
+
from tempergraph.executors.viewcatalog import read_views
|
|
154
|
+
|
|
155
|
+
judge = self.surface.get(f"{s.unit}:judge")
|
|
156
|
+
jc = caps_of(self.caps, judge.executor) if judge else None
|
|
157
|
+
if jc is None:
|
|
158
|
+
return
|
|
159
|
+
for cap in tools:
|
|
160
|
+
if cap.startswith("mcp:") and (not jc.judge_mcp or not read_views(cap)):
|
|
161
|
+
self.add("mcp-tool-not-in-catalog", s.unit, f"{cap} is declared on {s.unit}, but its judge on "
|
|
162
|
+
f"{judge.executor if judge else '?'} gets no view of it", session="judge", item=cap,
|
|
163
|
+
field=f"units.{s.unit}.step.tools")
|
|
164
|
+
|
|
165
|
+
# -- host (TSA-B9, TSA-B12) ----------------------------------------------------------------------------------
|
|
166
|
+
def host(self) -> list[AuditFinding]:
|
|
167
|
+
start = len(self.found)
|
|
168
|
+
self._ambient()
|
|
169
|
+
self._clash()
|
|
170
|
+
self._servers()
|
|
171
|
+
self._stale()
|
|
172
|
+
self._drift()
|
|
173
|
+
return self.found[start:]
|
|
174
|
+
|
|
175
|
+
def _ambient(self) -> None:
|
|
176
|
+
if self.ambient_tools is None:
|
|
177
|
+
self.skip("judge-ambient-tool", "probe cannot list")
|
|
178
|
+
return
|
|
179
|
+
for s in self.judges():
|
|
180
|
+
listed = self.ambient_tools(s.executor)
|
|
181
|
+
if listed is None:
|
|
182
|
+
self.skip("judge-ambient-tool", "probe cannot list")
|
|
183
|
+
return
|
|
184
|
+
for name in listed:
|
|
185
|
+
if name not in s.granted:
|
|
186
|
+
self.add("judge-ambient-tool", s.unit, f"a judge on {s.executor} would hold {name!r}, outside its "
|
|
187
|
+
"view set", session="judge", item=name, evidence={"tool": name,
|
|
188
|
+
"executor": s.executor})
|
|
189
|
+
|
|
190
|
+
def _clash(self) -> None:
|
|
191
|
+
installed = installed_skills(self.plugin_cache)
|
|
192
|
+
seen: set[str] = set()
|
|
193
|
+
for s in self.steps():
|
|
194
|
+
for skill in read_names(step_text(self.spec, s.unit)).skills:
|
|
195
|
+
bare = skill.rpartition(":")[2]
|
|
196
|
+
plugins = sorted(installed.get(bare, ()))
|
|
197
|
+
if skill == bare and len(plugins) > 1 and bare not in seen:
|
|
198
|
+
seen.add(bare)
|
|
199
|
+
self.add("skill-name-clash", s.unit, f"skill {bare!r} is installed in {len(plugins)} plugins "
|
|
200
|
+
f"({', '.join(plugins)}); also found by `ref-resolves-elsewhere`", session="step",
|
|
201
|
+
item=bare, evidence={"plugins": plugins})
|
|
202
|
+
|
|
203
|
+
def _servers(self) -> None:
|
|
204
|
+
declared: dict[str, str] = {}
|
|
205
|
+
for s in self.steps():
|
|
206
|
+
for cap in s.capabilities:
|
|
207
|
+
if cap.startswith("mcp:"):
|
|
208
|
+
declared.setdefault(cap[4:].partition("/")[0], s.unit)
|
|
209
|
+
if not declared:
|
|
210
|
+
return
|
|
211
|
+
have = self.mcp_servers() if self.mcp_servers is not None else None
|
|
212
|
+
if have is None:
|
|
213
|
+
self.skip("mcp-server-not-configured", "probe cannot list")
|
|
214
|
+
return
|
|
215
|
+
for server, unit in declared.items():
|
|
216
|
+
if server not in have:
|
|
217
|
+
self.add("mcp-server-not-configured", unit, f"`mcp:{server}` is declared but your configuration has "
|
|
218
|
+
f"no server named {server!r}", session="step", item=server, evidence={"server": server})
|
|
219
|
+
|
|
220
|
+
def _stale(self) -> None:
|
|
221
|
+
table = executor_compat.table()
|
|
222
|
+
for s in self.steps():
|
|
223
|
+
renamed = dict((table.get(s.executor) or {}).get("renamed") or {})
|
|
224
|
+
for name in s.granted:
|
|
225
|
+
if name in renamed:
|
|
226
|
+
self.add("declared-tool-stale", s.unit, f"{name!r} is no longer a {s.executor} tool name; it is "
|
|
227
|
+
f"now {renamed[name]!r}", session="step", item=name,
|
|
228
|
+
evidence={"executor": s.executor, "now": renamed[name]})
|
|
229
|
+
|
|
230
|
+
def _drift(self) -> None:
|
|
231
|
+
stamped = (self.stamp or {}).get("tool_set")
|
|
232
|
+
if not isinstance(stamped, dict):
|
|
233
|
+
self.skip("tool-set-drift", "no stamp")
|
|
234
|
+
return
|
|
235
|
+
for ex in dict.fromkeys(s.executor for s in self.surface.sessions):
|
|
236
|
+
caps, before = caps_of(self.caps, ex), stamped.get(ex)
|
|
237
|
+
if caps is None or before is None:
|
|
238
|
+
continue
|
|
239
|
+
now = current_names(caps)
|
|
240
|
+
if now != set(before):
|
|
241
|
+
self.add("tool-set-drift", None, f"the tool names of {ex} differ from the last stamp", item=ex,
|
|
242
|
+
evidence={"executor": ex, "added": sorted(now - set(before)),
|
|
243
|
+
"removed": sorted(set(before) - now)})
|
|
244
|
+
|
|
245
|
+
# -- history (TSA-B1, TSA-B9, TSA-B11) ------------------------------------------------------------------------
|
|
246
|
+
def with_history(self, facts: HistoryFacts) -> ToolRules:
|
|
247
|
+
self.facts = facts
|
|
248
|
+
return self
|
|
249
|
+
|
|
250
|
+
def judge_exposed_tool(self) -> list[AuditFinding]:
|
|
251
|
+
for s in self.judges():
|
|
252
|
+
for name in sorted(s.ambient):
|
|
253
|
+
runs = s.ambient_runs.get(name, [])
|
|
254
|
+
called = (s.used or {}).get(name, {}).get("calls", 0)
|
|
255
|
+
self.add("judge-exposed-tool", s.unit, f"the judge session of {s.unit} listed {name!r} at start, "
|
|
256
|
+
f"outside its view set, in {len(runs)} runs; "
|
|
257
|
+
+ ("never called" if not called else f"called {called} times"), session="judge", item=name,
|
|
258
|
+
evidence={"tool": name, "runs": runs, "called": called})
|
|
259
|
+
return self.found
|
|
260
|
+
|
|
261
|
+
def granted_never_used(self) -> list[AuditFinding]:
|
|
262
|
+
for s in self.steps():
|
|
263
|
+
used = s.used or {}
|
|
264
|
+
sc = caps_of(self.caps, s.executor)
|
|
265
|
+
for cap in dict.fromkeys(s.capabilities):
|
|
266
|
+
names = tool_names(sc, cap) if sc is not None else ()
|
|
267
|
+
if names and not any(used.get(n, {}).get("calls", 0) for n in names):
|
|
268
|
+
self.add("granted-never-used", s.unit, f"{cap!r} is declared on {s.unit} and was never called",
|
|
269
|
+
session="step", item=cap, evidence={"capability": cap, "tools": list(names)})
|
|
270
|
+
return self.found
|
|
271
|
+
|
|
272
|
+
def undeclared_calls(self) -> list[AuditFinding]:
|
|
273
|
+
runs = self.facts.runs if self.facts else 0
|
|
274
|
+
for s in self.steps():
|
|
275
|
+
outside = {n: row["calls"] for n, row in (s.used or {}).items() if n not in s.granted and row["calls"]}
|
|
276
|
+
total = sum(outside.values())
|
|
277
|
+
if runs and total / runs >= 0.25:
|
|
278
|
+
self.add("undeclared-calls", s.unit, f"{s.unit} called {total} tools outside its grant over {runs} "
|
|
279
|
+
f"runs", session="step", evidence={"tools": outside, "per_run": round(total / runs, 2)})
|
|
280
|
+
return self.found
|
|
281
|
+
|
|
282
|
+
def refusals_by_class(self) -> list[AuditFinding]:
|
|
283
|
+
facts = self.facts
|
|
284
|
+
if facts is None or (facts.runs and facts.journal_runs == 0):
|
|
285
|
+
raise RuleSkipped("unclassified: no run has an activity journal")
|
|
286
|
+
for s in self.steps():
|
|
287
|
+
if not isinstance(s.refusals, dict) or not s.refusals:
|
|
288
|
+
continue
|
|
289
|
+
total = sum(s.refusals.values())
|
|
290
|
+
if total / max(facts.runs, 1) < 1:
|
|
291
|
+
continue
|
|
292
|
+
ranked = sorted(s.refusals.items(), key=lambda kv: (-kv[1], CLASSES.index(kv[0])
|
|
293
|
+
if kv[0] in CLASSES else 99))
|
|
294
|
+
fixes = []
|
|
295
|
+
for klass, _ in ranked:
|
|
296
|
+
fix = FIX.get(klass, "read the refusal's input summary")
|
|
297
|
+
if klass == "needed_command" and s.refusal_examples.get(klass):
|
|
298
|
+
fix = f"declare `{s.refusal_examples[klass]}` or add it to the resolver"
|
|
299
|
+
fixes.append(fix)
|
|
300
|
+
wide = any(k in WIDENING_CLASSES for k, _ in ranked)
|
|
301
|
+
self.add("refusals-by-class", s.unit, f"{s.unit} was refused {total} calls over {facts.runs} runs, "
|
|
302
|
+
f"most often as {ranked[0][0]}", session="step", cause=ranked[0][0], widening=wide,
|
|
303
|
+
evidence={"classes": dict(ranked), "per_run": round(total / max(facts.runs, 1), 2)},
|
|
304
|
+
remedy="; then ".join(fixes))
|
|
305
|
+
return self.found
|
|
306
|
+
|
|
307
|
+
def granted_at_run(self) -> list[AuditFinding]:
|
|
308
|
+
facts = self.facts
|
|
309
|
+
if facts is None:
|
|
310
|
+
return self.found
|
|
311
|
+
runs: dict[tuple[str, str], set[str]] = {}
|
|
312
|
+
for g in facts.grants:
|
|
313
|
+
if not g.capability or g.action in ("remove", "revoke", "deny"):
|
|
314
|
+
continue
|
|
315
|
+
for r in facts.sessions:
|
|
316
|
+
if r.run == g.run and r.unit == g.unit and not r.judge and any(
|
|
317
|
+
c.capability == g.capability for c in r.calls):
|
|
318
|
+
runs.setdefault((g.unit, str(g.capability)), set()).add(g.run)
|
|
319
|
+
for (unit, cap), rs in sorted(runs.items()):
|
|
320
|
+
if len(rs) >= 2:
|
|
321
|
+
self.add("granted-at-run", unit, f"a grant of {cap!r} was given and used on {unit} in {len(rs)} runs",
|
|
322
|
+
session="step", item=cap, evidence={"capability": cap, "runs": sorted(rs)})
|
|
323
|
+
return self.found
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
TOOL_HISTORY: dict[str, Callable[[ToolRules], list[AuditFinding]]] = {
|
|
327
|
+
"judge-exposed-tool": ToolRules.judge_exposed_tool, "granted-never-used": ToolRules.granted_never_used,
|
|
328
|
+
"undeclared-calls": ToolRules.undeclared_calls, "refusals-by-class": ToolRules.refusals_by_class,
|
|
329
|
+
"granted-at-run": ToolRules.granted_at_run,
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
COLUMNS = (("session", "Session"), ("tool", "Tool"), ("capability", "Capability"), ("granted", "Granted"),
|
|
334
|
+
("needed", "Needed"), ("used", "Used"), ("verdict", "Verdict"))
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _verdict(s: SessionSurface, name: str, stale: set[str | None]) -> str:
|
|
338
|
+
"""TSA-B8: `missing` (needed, not granted), `exposed` (ambient, or called without a grant), `refused`, `drift`
|
|
339
|
+
(renamed or retired), `unused` (granted, never named and never called), else `ok`."""
|
|
340
|
+
row = (s.used or {}).get(name, {})
|
|
341
|
+
granted = name in s.granted
|
|
342
|
+
if name in s.needed and not granted:
|
|
343
|
+
return "missing"
|
|
344
|
+
if name in s.ambient or (not granted and row.get("calls")):
|
|
345
|
+
return "exposed"
|
|
346
|
+
if row.get("refused"):
|
|
347
|
+
return "refused"
|
|
348
|
+
if name in stale:
|
|
349
|
+
return "drift"
|
|
350
|
+
if granted and name not in s.needed and not row.get("calls"):
|
|
351
|
+
return "unused"
|
|
352
|
+
return "ok"
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def matrix(surface: Surface, findings: Sequence[AuditFinding] = ()) -> list[dict[str, Any]]:
|
|
356
|
+
"""TSA-B8, TSA-B5: one row per session and tool, from the surface alone; `Used` is `—` without history."""
|
|
357
|
+
stale = {f.item for f in findings if f.rule in ("declared-tool-stale", "tool-set-drift")}
|
|
358
|
+
rows: list[dict[str, Any]] = []
|
|
359
|
+
for s in surface.sessions:
|
|
360
|
+
names = dict.fromkeys([*s.granted, *s.needed, *sorted(s.ambient), *(s.used or {})])
|
|
361
|
+
for name in names:
|
|
362
|
+
used = "—" if s.used is None else "{calls} calls, {refused} refused".format(
|
|
363
|
+
**{"calls": 0, "refused": 0, **s.used.get(name, {})})
|
|
364
|
+
rows.append({"session": s.session, "unit": s.unit, "tool": name,
|
|
365
|
+
"capability": s.granted.get(name) or s.known.get(name),
|
|
366
|
+
"granted": "yes" if name in s.granted else "ambient" if name in s.ambient else "no",
|
|
367
|
+
"needed": f"yes ({s.needed[name]})" if name in s.needed else "no", "used": used,
|
|
368
|
+
"verdict": _verdict(s, name, stale)})
|
|
369
|
+
return rows
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def render_matrix(rows: Sequence[Mapping[str, Any]], fmt: str, *, extra: Mapping[str, Any] | None = None) -> str:
|
|
373
|
+
"""The matrix as an aligned text table or as JSON with `extra` keys (the workflow, the skipped history rules)."""
|
|
374
|
+
if fmt == "json":
|
|
375
|
+
return json.dumps({"schema_version": 1, **(extra or {}), "rows": list(rows)}, indent=2,
|
|
376
|
+
ensure_ascii=False) + "\n"
|
|
377
|
+
cells = [[title for _, title in COLUMNS]] + [[str(r.get(key) or "-") for key, _ in COLUMNS] for r in rows]
|
|
378
|
+
widths = [max(len(c[i]) for c in cells) for i in range(len(COLUMNS))]
|
|
379
|
+
lines = [" ".join(c.ljust(w) for c, w in zip(row, widths, strict=True)).rstrip() for row in cells]
|
|
380
|
+
skipped = (extra or {}).get("rules_skipped") or []
|
|
381
|
+
if skipped:
|
|
382
|
+
lines += ["", "history rules skipped: " + ", ".join(f"{s['rule']} ({s['reason']})" for s in skipped)]
|
|
383
|
+
return "\n".join(lines) + "\n"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def run_history(tr: ToolRules, rule_id: str, facts: HistoryFacts) -> list[AuditFinding]:
|
|
387
|
+
"""One history rule of C4 on the shared surface: only the findings that rule added (`RuleSkipped` passes up)."""
|
|
388
|
+
tr.with_history(facts)
|
|
389
|
+
start = len(tr.found)
|
|
390
|
+
TOOL_HISTORY[rule_id](tr)
|
|
391
|
+
return tr.found[start:]
|