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,224 @@
|
|
|
1
|
+
"""The session surface of the tool audit (TSA-B6, TSA-B7, ADR `tool-audit-compares-grant-need-and-use`): for every step session and every judge session
|
|
2
|
+
the grant, the need and the use of its tools, built once per audit.
|
|
3
|
+
|
|
4
|
+
The grant comes from the executor's tool map, the declared commands and the manifest; the need is read by prompt
|
|
5
|
+
lint's name reader (`audit.prompts.read_names`, PRA-AC3) from the template, brief and criteria, and from the artifact
|
|
6
|
+
kinds produced and referenced; the use comes from the recorded tool names and calls of `HistoryFacts`, `None` when
|
|
7
|
+
there is no history. A refusal is classed from its tool name and its scrubbed input summary only, as `unclassified`
|
|
8
|
+
when none was recorded (TSA-B7). Nothing the model said is read here (TSA-AC3).
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import contextlib
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Collection, Mapping
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from tempergraph.audit.history import HistoryFacts
|
|
20
|
+
from tempergraph.audit.prompts import read_names
|
|
21
|
+
from tempergraph.contracts import Capabilities, TextRef, WorkflowSpec
|
|
22
|
+
from tempergraph.executors.capabilities import DECLARED, tool_names
|
|
23
|
+
from tempergraph.model.text import TextUnreadable, load_text, split_judge_file
|
|
24
|
+
|
|
25
|
+
READ_PROGRAMS = ("cat", "head", "tail", "grep", "rg", "find", "ls")
|
|
26
|
+
DIR_CHANGE = re.compile(r"^\s*cd\s+\S+\s*(?:&&|;)\s*\S")
|
|
27
|
+
OUTSIDE_PATH = re.compile(r"(?:^|\s)(?:/|~/|\.\./|\.\.(?:\s|$))")
|
|
28
|
+
WRITE_ARTIFACTS = frozenset({"tracker_issue", "wiki_page", "pull_request"})
|
|
29
|
+
JUDGE_VIEW = ("read", "search", "list") # the read-only view set of a judge without its own `tools` (GRD)
|
|
30
|
+
READ_FAMILY = ("read", "search", "list") # a step that writes a file is implied to look at the workspace
|
|
31
|
+
CLASSES = ("shell_for_read", "dir_change_then_command", "outside_workspace", "undeclared_tool", "needed_command")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(kw_only=True)
|
|
35
|
+
class SessionSurface:
|
|
36
|
+
"""TSA-B6: one session's executor, grant, commands, ambient names, need, use, refusals and enforcement."""
|
|
37
|
+
|
|
38
|
+
session: str # `<unit>` or `<unit>:judge`
|
|
39
|
+
unit: str
|
|
40
|
+
role: str # `step` or `judge`
|
|
41
|
+
executor: str
|
|
42
|
+
granted: dict[str, str] = field(default_factory=dict) # executor tool name -> capability
|
|
43
|
+
commands: tuple[str, ...] = ()
|
|
44
|
+
ambient: set[str] = field(default_factory=set)
|
|
45
|
+
ambient_runs: dict[str, list[str]] = field(default_factory=dict) # ambient name -> runs whose start list held it
|
|
46
|
+
needed: dict[str, str] = field(default_factory=dict) # tool name -> where it was found
|
|
47
|
+
used: dict[str, dict[str, int]] | None = None # None: no history
|
|
48
|
+
refusals: dict[str, int] | str = field(default_factory=dict) # per class, or `unclassified` without a journal
|
|
49
|
+
refusal_examples: dict[str, str] = field(default_factory=dict) # the most common scrubbed summary of each class
|
|
50
|
+
enforced: bool = False
|
|
51
|
+
artifacts_unwritable: list[str] = field(default_factory=list) # produced kinds with no tool that can write them
|
|
52
|
+
produces: dict[str, str] = field(default_factory=dict)
|
|
53
|
+
capabilities: tuple[str, ...] = () # the declared capabilities (step) or the view set (judge)
|
|
54
|
+
known: dict[str, str] = field(default_factory=dict) # every tool name of the executor's map -> its capability
|
|
55
|
+
text: str = ""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(kw_only=True)
|
|
59
|
+
class Surface:
|
|
60
|
+
sessions: list[SessionSurface] = field(default_factory=list)
|
|
61
|
+
history: bool = False # the use of tools was read from runs
|
|
62
|
+
|
|
63
|
+
def get(self, session: str) -> SessionSurface | None:
|
|
64
|
+
return next((s for s in self.sessions if s.session == session), None)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def classify_refusal(tool: str, summary: str | None, *, granted: Collection[str], shell: Collection[str],
|
|
68
|
+
file_tools: bool) -> str:
|
|
69
|
+
"""TSA-B7: one class from the tool name and the scrubbed input summary, `unclassified` when none was recorded."""
|
|
70
|
+
if tool not in granted:
|
|
71
|
+
return "undeclared_tool"
|
|
72
|
+
if not summary or not summary.strip():
|
|
73
|
+
return "unclassified"
|
|
74
|
+
if tool in shell:
|
|
75
|
+
if DIR_CHANGE.match(summary):
|
|
76
|
+
return "dir_change_then_command"
|
|
77
|
+
words = summary.split()
|
|
78
|
+
if file_tools and (words[0] in READ_PROGRAMS or summary.lstrip().startswith("sed -n")):
|
|
79
|
+
return "shell_for_read"
|
|
80
|
+
if OUTSIDE_PATH.search(summary):
|
|
81
|
+
return "outside_workspace"
|
|
82
|
+
return "needed_command"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def caps_of(caps: Mapping[str, Capabilities], name: str) -> Capabilities | None:
|
|
86
|
+
return caps.get(name) or DECLARED.get(name)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def step_text(spec: WorkflowSpec, unit: str) -> str:
|
|
90
|
+
st = spec.units[unit].step
|
|
91
|
+
if st is None or st.prompt == "default":
|
|
92
|
+
return ""
|
|
93
|
+
try:
|
|
94
|
+
return load_text(spec, st.prompt)
|
|
95
|
+
except TextUnreadable:
|
|
96
|
+
return ""
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def judge_text(spec: WorkflowSpec, unit: str) -> str:
|
|
100
|
+
u = spec.units[unit]
|
|
101
|
+
j = u.gate.judge
|
|
102
|
+
if j is None:
|
|
103
|
+
return ""
|
|
104
|
+
stance, brief = j.stance, j.brief
|
|
105
|
+
if j.file and spec.package_root is not None:
|
|
106
|
+
with contextlib.suppress(TextUnreadable):
|
|
107
|
+
stance, brief = split_judge_file(load_text(spec, TextRef(path=j.file)))
|
|
108
|
+
return "\n\n".join([stance, brief, *(c.text for c in u.gate.criteria)])
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _known(caps: Capabilities) -> dict[str, str]:
|
|
112
|
+
return {n: cap for cap, names in caps.tool_map.items() for n in names if "{" not in n}
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _grant(caps: Capabilities, capabilities: Collection[str]) -> dict[str, str]:
|
|
116
|
+
out: dict[str, str] = {}
|
|
117
|
+
for cap in capabilities:
|
|
118
|
+
for name in tool_names(caps, cap):
|
|
119
|
+
out[name] = cap
|
|
120
|
+
return out
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
Group = tuple[tuple[str, ...], str, bool] # (capabilities, where found, listed as needed even when none is granted)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _need(s: SessionSurface, caps: Capabilities, text: str, where: str, groups: list[Group]) -> None:
|
|
127
|
+
"""The need: names the reader finds in the text, then capability groups implied by artifacts and commands. A
|
|
128
|
+
group is met by any one of its capabilities; when none is granted a required group names its first (so the
|
|
129
|
+
matrix shows it missing), an optional one names nothing."""
|
|
130
|
+
mine = {n for names in caps.tool_map.values() for n in names if "{" not in n}
|
|
131
|
+
for name in read_names(text).tools:
|
|
132
|
+
if name in mine:
|
|
133
|
+
s.needed.setdefault(name, where)
|
|
134
|
+
for name in s.granted:
|
|
135
|
+
if name.startswith(("mcp__", "mcp(")) and name in text:
|
|
136
|
+
s.needed.setdefault(name, where)
|
|
137
|
+
for group, why, required in groups:
|
|
138
|
+
held = [n for n, cap in s.granted.items() if cap in group]
|
|
139
|
+
for name in held or ([n for cap in group[:1] for n in tool_names(caps, cap)] if required else []):
|
|
140
|
+
s.needed.setdefault(name, why)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def build_surface(spec: WorkflowSpec, caps: Mapping[str, Capabilities], manifest: Any, facts: HistoryFacts | None, *,
|
|
144
|
+
executor: str | None = None) -> Surface:
|
|
145
|
+
"""TSA-B6: one session per step and per judge. `executor` shows every session on that executor's tool map
|
|
146
|
+
(TSA-B3); a judge on another executor keeps it otherwise (cross-executor judging, ADR `cross-executor-judging`)."""
|
|
147
|
+
out = Surface(history=facts is not None and facts.runs > 0)
|
|
148
|
+
for unit in spec.order:
|
|
149
|
+
u = spec.units.get(unit)
|
|
150
|
+
if u is None:
|
|
151
|
+
continue
|
|
152
|
+
st, j = u.step, u.gate.judge
|
|
153
|
+
step_ex = executor or (st.executor if st else None) or spec.default_executor
|
|
154
|
+
if st is not None:
|
|
155
|
+
sc = caps_of(caps, step_ex)
|
|
156
|
+
if sc is not None:
|
|
157
|
+
s = SessionSurface(session=unit, unit=unit, role="step", executor=step_ex,
|
|
158
|
+
granted=_grant(sc, st.tools),
|
|
159
|
+
commands=tuple(dict.fromkeys((*st.commands, *spec.allow_commands))),
|
|
160
|
+
enforced=sc.enforces_step_tools, capabilities=tuple(st.tools), known=_known(sc),
|
|
161
|
+
produces={k: str(v) if isinstance(v, str) else "value"
|
|
162
|
+
for k, v in st.produces.items()})
|
|
163
|
+
groups: list[Group] = []
|
|
164
|
+
for key, kind in s.produces.items():
|
|
165
|
+
if kind == "file":
|
|
166
|
+
groups.append((("edit", "write"), f"artifact {key}", True))
|
|
167
|
+
groups.append((READ_FAMILY, f"artifact {key}", False)) # writing a file implies looking
|
|
168
|
+
elif kind in WRITE_ARTIFACTS:
|
|
169
|
+
can = [c for c in st.tools if c == "shell" or c.startswith("mcp:")]
|
|
170
|
+
if not can:
|
|
171
|
+
s.artifacts_unwritable.append(key)
|
|
172
|
+
groups.append((tuple(can) or ("shell",), f"artifact {key}", True))
|
|
173
|
+
if st.commands:
|
|
174
|
+
groups.append((("shell",), "commands", True))
|
|
175
|
+
_need(s, sc, step_text(spec, unit), "template", groups)
|
|
176
|
+
out.sessions.append(s)
|
|
177
|
+
if j is not None:
|
|
178
|
+
jex = executor or j.executor or step_ex
|
|
179
|
+
jc = caps_of(caps, jex)
|
|
180
|
+
if jc is not None:
|
|
181
|
+
view = tuple(j.tools) if j.tools is not None else JUDGE_VIEW
|
|
182
|
+
s = SessionSurface(session=f"{unit}:judge", unit=unit, role="judge", executor=jex,
|
|
183
|
+
granted=_grant(jc, view), enforced=jc.restricts_judge_tools, capabilities=view,
|
|
184
|
+
known=_known(jc))
|
|
185
|
+
refs: list[Group] = [(("read",), f"artifact {k}", True) for k in (*j.references, *j.subject)]
|
|
186
|
+
_need(s, jc, judge_text(spec, unit), "brief", refs)
|
|
187
|
+
out.sessions.append(s)
|
|
188
|
+
if facts is not None and facts.runs:
|
|
189
|
+
for s in out.sessions:
|
|
190
|
+
_use(s, facts)
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _use(s: SessionSurface, facts: HistoryFacts) -> None:
|
|
195
|
+
"""The use of tools and the refusals of the session, from the recorded names and scrubbed summaries."""
|
|
196
|
+
mine = [r for r in facts.sessions if r.unit == s.unit and r.judge == (s.role == "judge")]
|
|
197
|
+
used: dict[str, dict[str, int]] = {}
|
|
198
|
+
refusals: dict[str, int] = {}
|
|
199
|
+
seen: dict[str, dict[str, int]] = {}
|
|
200
|
+
shell = {n for n, cap in s.granted.items() if cap == "shell"}
|
|
201
|
+
file_tools = any(cap in ("read", "search", "list") for cap in s.granted.values())
|
|
202
|
+
for r in mine:
|
|
203
|
+
for name in r.started_tools or ():
|
|
204
|
+
if name not in s.granted:
|
|
205
|
+
s.ambient.add(name)
|
|
206
|
+
runs = s.ambient_runs.setdefault(name, [])
|
|
207
|
+
if r.run not in runs:
|
|
208
|
+
runs.append(r.run)
|
|
209
|
+
for c in r.calls:
|
|
210
|
+
row = used.setdefault(c.name, {"calls": 0, "ok": 0, "refused": 0, "subagent": 0})
|
|
211
|
+
row["calls"] += 1
|
|
212
|
+
row["ok"] += 1 if c.ok else 0
|
|
213
|
+
row["subagent"] += 1 if c.subagent else 0
|
|
214
|
+
for name, summary in r.denied:
|
|
215
|
+
used.setdefault(name, {"calls": 0, "ok": 0, "refused": 0, "subagent": 0})["refused"] += 1
|
|
216
|
+
klass = classify_refusal(name, summary, granted=s.granted, shell=shell, file_tools=file_tools)
|
|
217
|
+
refusals[klass] = refusals.get(klass, 0) + 1
|
|
218
|
+
if summary:
|
|
219
|
+
seen.setdefault(klass, {})[summary] = seen.get(klass, {}).get(summary, 0) + 1
|
|
220
|
+
s.refusal_examples = {k: max(v, key=lambda x: v[x]) for k, v in seen.items()}
|
|
221
|
+
s.used = used
|
|
222
|
+
s.refusals = "unclassified" if facts.runs and facts.journal_runs == 0 else refusals
|
|
223
|
+
for runs in s.ambient_runs.values():
|
|
224
|
+
runs.sort()
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"""How model-facing text is built (PRA-B12 to PRA-B14): size, rendered size, must-read size, prohibitions and reasons,
|
|
2
|
+
sentences repeated across files and the share of text under goal branches. Model-free, counted over fixed word lists;
|
|
3
|
+
the audit's own rules read these measures and the prompts matrix prints them."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Iterator, Mapping
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from tempergraph.contracts import TextRef, WorkflowSpec
|
|
14
|
+
from tempergraph.model.prompt_lint import FILE_REF
|
|
15
|
+
from tempergraph.model.text import TextUnreadable, load_text
|
|
16
|
+
|
|
17
|
+
# A prohibition tells the session what not to do; a reason says why. Both lists are fixed (PRA-B12).
|
|
18
|
+
PROHIBITION = re.compile(r"\b(never|do not|don't|must not|may not|shall not|cannot|can't|is not allowed|are not "
|
|
19
|
+
r"allowed|forbidden|no longer allowed)\b", re.I)
|
|
20
|
+
REASON = re.compile(r"\b(because|since|so that|so the|so a|in order to|otherwise|which means|that way|the reason|"
|
|
21
|
+
r"this keeps|this stops|this avoids)\b", re.I)
|
|
22
|
+
GOAL_BRANCH = re.compile(r"^(?:[-*]\s+|\d+\.\s+|#+\s+)?(?:\*\*)?(if|when|unless|for an?|in (?:the )?\S+ (?:mode|lane))\b",
|
|
23
|
+
re.I)
|
|
24
|
+
SENTENCE_END = re.compile(r"(?<=[.!?])\s+")
|
|
25
|
+
MIN_SENTENCE = 40 # shorter sentences ("Do nothing else.") repeat by nature
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Measures:
|
|
30
|
+
chars: int
|
|
31
|
+
prohibitions: int
|
|
32
|
+
reasons: int
|
|
33
|
+
goal_branch_share: float
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def prohibitions_per_reason(self) -> float:
|
|
37
|
+
return round(self.prohibitions / max(self.reasons, 1), 2)
|
|
38
|
+
|
|
39
|
+
def as_json(self) -> dict[str, Any]:
|
|
40
|
+
return {"chars": self.chars, "prohibitions": self.prohibitions, "reasons": self.reasons,
|
|
41
|
+
"prohibitions_per_reason": self.prohibitions_per_reason, "goal_branch_share": self.goal_branch_share}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def measure(text: str) -> Measures:
|
|
45
|
+
paragraphs = [p for p in re.split(r"\n\s*\n", text) if p.strip()]
|
|
46
|
+
branched = sum(len(p) for p in paragraphs if GOAL_BRANCH.match(p.strip()))
|
|
47
|
+
total = sum(len(p) for p in paragraphs)
|
|
48
|
+
return Measures(chars=len(text), prohibitions=len(PROHIBITION.findall(text)), reasons=len(REASON.findall(text)),
|
|
49
|
+
goal_branch_share=round(branched / total, 3) if total else 0.0)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def sentences(text: str) -> set[str]:
|
|
53
|
+
"""The normalized sentences of a text long enough to count as repeated text (PRA-B13)."""
|
|
54
|
+
out: set[str] = set()
|
|
55
|
+
if text.startswith("---") and (end := text.find("\n---", 3)) > 0:
|
|
56
|
+
text = text[end + 4:] # a skill's front matter is not text the session follows
|
|
57
|
+
for line in re.split(r"\n\s*\n", text):
|
|
58
|
+
flat = " ".join(line.split())
|
|
59
|
+
for s in SENTENCE_END.split(flat):
|
|
60
|
+
s = s.strip().lstrip("-*0123456789. ").strip().lower()
|
|
61
|
+
if len(s) >= MIN_SENTENCE and not s.startswith(("|", "```", "#")):
|
|
62
|
+
out.add(s)
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class TextFile:
|
|
68
|
+
file: str
|
|
69
|
+
text: str
|
|
70
|
+
used_by: list[str] = field(default_factory=list) # `unit:role`
|
|
71
|
+
role: str = "" # step, judge, skill, agent, step_file
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def model_facing(spec: WorkflowSpec) -> dict[str, TextFile]:
|
|
75
|
+
"""Every model-facing file once: templates, judge files, shipped skills and agents, and each file the package
|
|
76
|
+
declares in `step_files` (PKG-B13), with the units and roles that use it."""
|
|
77
|
+
rows: dict[str, TextFile] = {}
|
|
78
|
+
|
|
79
|
+
def add(file: str, unit: str | None, role: str, text: str) -> None:
|
|
80
|
+
row = rows.setdefault(file, TextFile(file=file, text=text, role=role))
|
|
81
|
+
if unit is not None and f"{unit}:{role}" not in row.used_by:
|
|
82
|
+
row.used_by.append(f"{unit}:{role}")
|
|
83
|
+
|
|
84
|
+
for unit in spec.order:
|
|
85
|
+
u = spec.units.get(unit)
|
|
86
|
+
if u is None:
|
|
87
|
+
continue
|
|
88
|
+
st = u.step
|
|
89
|
+
if st is not None and st.prompt != "default":
|
|
90
|
+
file = st.prompt.path if isinstance(st.prompt, TextRef) else f"inline:{unit}"
|
|
91
|
+
try:
|
|
92
|
+
add(file, unit, "step", load_text(spec, st.prompt))
|
|
93
|
+
except TextUnreadable:
|
|
94
|
+
add(file, unit, "step", "")
|
|
95
|
+
j = u.gate.judge
|
|
96
|
+
if j is not None:
|
|
97
|
+
if j.file and spec.package_root is not None:
|
|
98
|
+
try:
|
|
99
|
+
add(j.file, unit, "judge", load_text(spec, TextRef(path=j.file)))
|
|
100
|
+
except TextUnreadable:
|
|
101
|
+
add(j.file, unit, "judge", "")
|
|
102
|
+
else:
|
|
103
|
+
add(f"inline:{unit}:judge", unit, "judge", f"{j.stance}\n{j.brief}")
|
|
104
|
+
root = spec.package_root
|
|
105
|
+
if root is None:
|
|
106
|
+
return rows
|
|
107
|
+
for p in sorted([*root.glob("skills/*/SKILL.md"), *root.glob("agents/*.md")]):
|
|
108
|
+
add(p.relative_to(root).as_posix(), None, "skill" if p.name == "SKILL.md" else "agent",
|
|
109
|
+
p.read_text(encoding="utf-8"))
|
|
110
|
+
for p in step_file_paths(root):
|
|
111
|
+
rel = p.relative_to(root).as_posix()
|
|
112
|
+
if rel in rows:
|
|
113
|
+
continue
|
|
114
|
+
try:
|
|
115
|
+
add(rel, None, "step_file", p.read_text(encoding="utf-8"))
|
|
116
|
+
except (OSError, UnicodeDecodeError):
|
|
117
|
+
continue
|
|
118
|
+
templates = [(u.split(":")[0], r.text) for r in rows.values() for u in r.used_by if u.endswith(":step")]
|
|
119
|
+
for row in rows.values():
|
|
120
|
+
if row.role == "step_file":
|
|
121
|
+
for unit, text in templates:
|
|
122
|
+
if f"`{row.file}`" in text and f"{unit}:step_file" not in row.used_by:
|
|
123
|
+
row.used_by.append(f"{unit}:step_file")
|
|
124
|
+
return rows
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def step_file_paths(root: Path) -> list[Path]:
|
|
128
|
+
from tempergraph.package.manifest import declared_step_files
|
|
129
|
+
|
|
130
|
+
found: dict[Path, None] = {}
|
|
131
|
+
for pattern in declared_step_files(root):
|
|
132
|
+
for p in sorted(root.glob(pattern)):
|
|
133
|
+
if p.is_file() and p.suffix in (".md", ".txt", ".json"):
|
|
134
|
+
found.setdefault(p, None)
|
|
135
|
+
return list(found)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def named_files(text: str, rows: Mapping[str, TextFile]) -> list[str]:
|
|
139
|
+
"""The package files a template names in backticks that the audit holds as model-facing text."""
|
|
140
|
+
ticked = set(re.findall(r"`([A-Za-z0-9_./-]+)`", text))
|
|
141
|
+
by_name: dict[str, list[str]] = {}
|
|
142
|
+
for f in rows:
|
|
143
|
+
by_name.setdefault(f.rsplit("/", 1)[-1], []).append(f)
|
|
144
|
+
listed = (set(FILE_REF.findall(text)) | ticked
|
|
145
|
+
| {f for t in ticked if "/" not in t for f in by_name.get(t, ()) if len(by_name[t]) == 1})
|
|
146
|
+
return sorted(f for f in listed if f in rows)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def rendered_size(spec: WorkflowSpec, unit: str, text: str) -> int | None:
|
|
150
|
+
"""The characters of the step's prompt as the engine renders it for its first attempt (tools, artifacts and
|
|
151
|
+
criteria appended), with the first start example as the request; None when it cannot be rendered."""
|
|
152
|
+
from tempergraph.executors.capabilities import CLAUDE
|
|
153
|
+
from tempergraph.render.prompt import AttemptContext, render_step
|
|
154
|
+
|
|
155
|
+
u = spec.units.get(unit)
|
|
156
|
+
if u is None or u.step is None:
|
|
157
|
+
return None
|
|
158
|
+
example = next(iter(spec.input.examples), "")
|
|
159
|
+
fields: dict[str, str | None] = {"request": example}
|
|
160
|
+
for p in spec.input.parameters:
|
|
161
|
+
fields.setdefault(p.name, p.example or p.name)
|
|
162
|
+
try:
|
|
163
|
+
return len(render_step(unit, u, AttemptContext(template=text, fields=fields), CLAUDE).text)
|
|
164
|
+
except Exception: # noqa: BLE001 - a template the renderer refuses is reported by validate, not here
|
|
165
|
+
return None
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def repeated(rows: Mapping[str, TextFile], min_files: int) -> Iterator[tuple[str, list[str]]]:
|
|
169
|
+
"""Each sentence found in at least `min_files` files, with those files (PRA-B13)."""
|
|
170
|
+
where: dict[str, list[str]] = {}
|
|
171
|
+
for row in rows.values():
|
|
172
|
+
for s in sentences(row.text):
|
|
173
|
+
where.setdefault(s, []).append(row.file)
|
|
174
|
+
for s, files in sorted(where.items()):
|
|
175
|
+
if len(files) >= min_files:
|
|
176
|
+
yield s, sorted(files)
|