tempergraph 0.7.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. tempergraph/__init__.py +8 -0
  2. tempergraph/__main__.py +5 -0
  3. tempergraph/api.py +428 -0
  4. tempergraph/audit/__init__.py +305 -0
  5. tempergraph/audit/catalog.py +342 -0
  6. tempergraph/audit/definition.py +387 -0
  7. tempergraph/audit/history.py +414 -0
  8. tempergraph/audit/history_rules.py +268 -0
  9. tempergraph/audit/history_rules_more.py +244 -0
  10. tempergraph/audit/host.py +270 -0
  11. tempergraph/audit/owned.py +96 -0
  12. tempergraph/audit/prompts.py +89 -0
  13. tempergraph/audit/report.py +248 -0
  14. tempergraph/audit/revisit.py +220 -0
  15. tempergraph/audit/surface.py +224 -0
  16. tempergraph/audit/text_health.py +176 -0
  17. tempergraph/audit/tools.py +391 -0
  18. tempergraph/author/__init__.py +2 -0
  19. tempergraph/author/blueprint.py +346 -0
  20. tempergraph/author/compare.py +122 -0
  21. tempergraph/author/criteria_lint.py +200 -0
  22. tempergraph/author/draw.py +112 -0
  23. tempergraph/author/inventory.py +210 -0
  24. tempergraph/author/literals.py +138 -0
  25. tempergraph/author/scaffold.py +568 -0
  26. tempergraph/author/session.py +439 -0
  27. tempergraph/author/trial.py +391 -0
  28. tempergraph/author/verify.py +353 -0
  29. tempergraph/builtin/__init__.py +1 -0
  30. tempergraph/builtin/upgrade.py +288 -0
  31. tempergraph/catalog.py +134 -0
  32. tempergraph/check_helpers.py +99 -0
  33. tempergraph/cli/__init__.py +1 -0
  34. tempergraph/cli/audit.py +190 -0
  35. tempergraph/cli/author.py +361 -0
  36. tempergraph/cli/improve.py +564 -0
  37. tempergraph/cli/improve_review.py +111 -0
  38. tempergraph/cli/install.py +35 -0
  39. tempergraph/cli/main.py +1261 -0
  40. tempergraph/cli/observe_cli.py +544 -0
  41. tempergraph/cli/outcome.py +77 -0
  42. tempergraph/cli/schedule_cli.py +1090 -0
  43. tempergraph/cli/upgrade.py +126 -0
  44. tempergraph/cli/workflows.py +96 -0
  45. tempergraph/compiler/__init__.py +6 -0
  46. tempergraph/compiler/graph.py +305 -0
  47. tempergraph/compiler/state.py +229 -0
  48. tempergraph/constants.py +72 -0
  49. tempergraph/contracts.py +1025 -0
  50. tempergraph/data/executor_compat.json +11 -0
  51. tempergraph/data/promotion.json +35 -0
  52. tempergraph/data/release.json +20 -0
  53. tempergraph/detach.py +65 -0
  54. tempergraph/docs.py +90 -0
  55. tempergraph/durability/__init__.py +2 -0
  56. tempergraph/durability/alias.py +66 -0
  57. tempergraph/durability/carry.py +591 -0
  58. tempergraph/durability/checkpoint.py +179 -0
  59. tempergraph/durability/control.py +109 -0
  60. tempergraph/durability/engine_file.py +301 -0
  61. tempergraph/durability/lock.py +138 -0
  62. tempergraph/durability/status.py +390 -0
  63. tempergraph/engine_identity.py +42 -0
  64. tempergraph/executor_compat.py +56 -0
  65. tempergraph/executors/__init__.py +4 -0
  66. tempergraph/executors/binding.py +91 -0
  67. tempergraph/executors/capabilities.py +95 -0
  68. tempergraph/executors/claude.py +603 -0
  69. tempergraph/executors/launcher.py +394 -0
  70. tempergraph/executors/mcpconfig.py +156 -0
  71. tempergraph/executors/mcpproxy.py +216 -0
  72. tempergraph/executors/preflight.py +196 -0
  73. tempergraph/executors/registry.py +71 -0
  74. tempergraph/executors/scripted.py +18 -0
  75. tempergraph/executors/session.py +107 -0
  76. tempergraph/executors/standins.py +118 -0
  77. tempergraph/executors/summary.py +110 -0
  78. tempergraph/executors/viewcatalog.py +27 -0
  79. tempergraph/git.py +403 -0
  80. tempergraph/identity.py +65 -0
  81. tempergraph/improve/__init__.py +5 -0
  82. tempergraph/improve/analysis.py +437 -0
  83. tempergraph/improve/artifact.py +477 -0
  84. tempergraph/improve/autonomy.py +192 -0
  85. tempergraph/improve/bindings.py +191 -0
  86. tempergraph/improve/calibration.py +1016 -0
  87. tempergraph/improve/causes.py +416 -0
  88. tempergraph/improve/child.py +651 -0
  89. tempergraph/improve/codehost.py +520 -0
  90. tempergraph/improve/digest.py +472 -0
  91. tempergraph/improve/escape.py +100 -0
  92. tempergraph/improve/filing.py +1047 -0
  93. tempergraph/improve/harvest.py +158 -0
  94. tempergraph/improve/issue_context.py +192 -0
  95. tempergraph/improve/lenses.py +204 -0
  96. tempergraph/improve/lessons.py +233 -0
  97. tempergraph/improve/loop_report.py +138 -0
  98. tempergraph/improve/loop_summary.py +85 -0
  99. tempergraph/improve/lost.py +119 -0
  100. tempergraph/improve/measure.py +121 -0
  101. tempergraph/improve/params.py +98 -0
  102. tempergraph/improve/pause_facts.py +134 -0
  103. tempergraph/improve/pr_later.py +186 -0
  104. tempergraph/improve/prebinding.py +130 -0
  105. tempergraph/improve/promotion.py +413 -0
  106. tempergraph/improve/proposals.py +934 -0
  107. tempergraph/improve/record.py +322 -0
  108. tempergraph/improve/release.py +89 -0
  109. tempergraph/improve/reliability.py +457 -0
  110. tempergraph/improve/repeat.py +115 -0
  111. tempergraph/improve/review.py +910 -0
  112. tempergraph/improve/suites.py +586 -0
  113. tempergraph/improve/trials.py +525 -0
  114. tempergraph/install/__init__.py +11 -0
  115. tempergraph/install/bootstrap.py +133 -0
  116. tempergraph/install/environment.py +173 -0
  117. tempergraph/install/launch.py +37 -0
  118. tempergraph/install/python.py +53 -0
  119. tempergraph/install/reconcile.py +52 -0
  120. tempergraph/install/selfcheck.py +29 -0
  121. tempergraph/install/shim.py +81 -0
  122. tempergraph/install/update.py +400 -0
  123. tempergraph/model/__init__.py +0 -0
  124. tempergraph/model/diagram.py +185 -0
  125. tempergraph/model/flow.py +324 -0
  126. tempergraph/model/prompt_lint.py +203 -0
  127. tempergraph/model/retire.py +52 -0
  128. tempergraph/model/subworkflow.py +274 -0
  129. tempergraph/model/text.py +67 -0
  130. tempergraph/model/validate.py +1158 -0
  131. tempergraph/observe/__init__.py +1 -0
  132. tempergraph/observe/attention.py +196 -0
  133. tempergraph/observe/detail.py +773 -0
  134. tempergraph/observe/forget.py +138 -0
  135. tempergraph/observe/hooks.py +272 -0
  136. tempergraph/observe/labels.py +95 -0
  137. tempergraph/observe/overlay.py +46 -0
  138. tempergraph/observe/report.py +402 -0
  139. tempergraph/observe/risk_report.py +110 -0
  140. tempergraph/observe/rows.py +444 -0
  141. tempergraph/observe/sinks.py +793 -0
  142. tempergraph/observe/supervision_cost.py +797 -0
  143. tempergraph/observe/supervision_report.py +295 -0
  144. tempergraph/observe/switch_report.py +140 -0
  145. tempergraph/package/__init__.py +2 -0
  146. tempergraph/package/change_report.py +116 -0
  147. tempergraph/package/changelog.py +263 -0
  148. tempergraph/package/docs_check.py +115 -0
  149. tempergraph/package/importer.py +90 -0
  150. tempergraph/package/inventory.py +111 -0
  151. tempergraph/package/loader.py +250 -0
  152. tempergraph/package/manifest.py +256 -0
  153. tempergraph/package/readiness.py +124 -0
  154. tempergraph/package/registry.py +383 -0
  155. tempergraph/package/rules.py +128 -0
  156. tempergraph/package/scan.py +65 -0
  157. tempergraph/package/selftest.py +348 -0
  158. tempergraph/package/stamp.py +213 -0
  159. tempergraph/package/transforms.py +481 -0
  160. tempergraph/package/upgrade.py +625 -0
  161. tempergraph/provenance.py +183 -0
  162. tempergraph/py.typed +0 -0
  163. tempergraph/release.py +17 -0
  164. tempergraph/render/__init__.py +0 -0
  165. tempergraph/render/output.py +72 -0
  166. tempergraph/render/prompt.py +166 -0
  167. tempergraph/render/template.py +86 -0
  168. tempergraph/run/__init__.py +2 -0
  169. tempergraph/run/asking.py +233 -0
  170. tempergraph/run/audit.py +63 -0
  171. tempergraph/run/check_worker.py +167 -0
  172. tempergraph/run/checks.py +517 -0
  173. tempergraph/run/commands.py +210 -0
  174. tempergraph/run/complexity.py +268 -0
  175. tempergraph/run/contest.py +76 -0
  176. tempergraph/run/council.py +368 -0
  177. tempergraph/run/council_run.py +527 -0
  178. tempergraph/run/events.py +279 -0
  179. tempergraph/run/finalize.py +132 -0
  180. tempergraph/run/gate.py +747 -0
  181. tempergraph/run/guard.py +89 -0
  182. tempergraph/run/judging.py +357 -0
  183. tempergraph/run/ladder.py +230 -0
  184. tempergraph/run/log.py +600 -0
  185. tempergraph/run/mapping.py +183 -0
  186. tempergraph/run/nodes.py +2304 -0
  187. tempergraph/run/outcome.py +255 -0
  188. tempergraph/run/outcome_record.py +292 -0
  189. tempergraph/run/outcome_trust.py +99 -0
  190. tempergraph/run/rerun.py +351 -0
  191. tempergraph/run/reserve.py +85 -0
  192. tempergraph/run/resources.py +76 -0
  193. tempergraph/run/risk.py +231 -0
  194. tempergraph/run/runner.py +1579 -0
  195. tempergraph/run/scriptcache.py +178 -0
  196. tempergraph/run/selfcheck.py +105 -0
  197. tempergraph/run/session_record.py +72 -0
  198. tempergraph/run/subrun.py +278 -0
  199. tempergraph/run/supervision.py +125 -0
  200. tempergraph/run/tool_access.py +101 -0
  201. tempergraph/schedule/__init__.py +25 -0
  202. tempergraph/schedule/credentials.py +167 -0
  203. tempergraph/schedule/echo.py +169 -0
  204. tempergraph/schedule/exact.py +275 -0
  205. tempergraph/schedule/export.py +164 -0
  206. tempergraph/schedule/launch.py +89 -0
  207. tempergraph/schedule/ledger.py +133 -0
  208. tempergraph/schedule/loop.py +176 -0
  209. tempergraph/schedule/model.py +440 -0
  210. tempergraph/schedule/policies.py +414 -0
  211. tempergraph/schedule/store.py +150 -0
  212. tempergraph/schedule/tick.py +377 -0
  213. tempergraph/schedule/token.py +81 -0
  214. tempergraph/schedule/triggers.py +210 -0
  215. tempergraph/schedule/words.py +423 -0
  216. tempergraph/security/__init__.py +0 -0
  217. tempergraph/security/launch.py +25 -0
  218. tempergraph/security/scrub.py +58 -0
  219. tempergraph/settings.py +950 -0
  220. tempergraph/store/__init__.py +0 -0
  221. tempergraph/store/codelog.py +73 -0
  222. tempergraph/store/layout.py +198 -0
  223. tempergraph/store/logs.py +325 -0
  224. tempergraph/store/manifest.py +99 -0
  225. tempergraph/store/migrate.py +188 -0
  226. tempergraph/workspace.py +874 -0
  227. tempergraph-0.7.1.dist-info/METADATA +70 -0
  228. tempergraph-0.7.1.dist-info/RECORD +232 -0
  229. tempergraph-0.7.1.dist-info/WHEEL +5 -0
  230. tempergraph-0.7.1.dist-info/entry_points.txt +5 -0
  231. tempergraph-0.7.1.dist-info/top_level.txt +2 -0
  232. tempergraph_pytest_plugin.py +64 -0
@@ -0,0 +1,118 @@
1
+ """Scripted stand-in executors (ADR `first-release-ships-the-claude-executor-only` item 2, CLAUDE.md test rule).
2
+
3
+ A stand-in carries one of the four declared capability sets and answers each session from a script
4
+ instead of a process, so the engine's gate funnel, cross-executor judging, estimate-only cost and every
5
+ refusal path are tested offline. The recorded-CLI conformance stand-in that goes through the real
6
+ launcher lives with the tests.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Callable, Iterable
12
+ from dataclasses import dataclass, field, replace
13
+ from typing import ClassVar
14
+
15
+ from tempergraph.contracts import (
16
+ Capabilities,
17
+ Event,
18
+ EventSink,
19
+ ProbeReport,
20
+ SessionRequest,
21
+ SessionResult,
22
+ ToolCall,
23
+ Usage,
24
+ ViewSet,
25
+ )
26
+ from tempergraph.executors.capabilities import DECLARED
27
+
28
+ Reply = SessionResult | Callable[[SessionRequest], SessionResult]
29
+
30
+
31
+ @dataclass(kw_only=True)
32
+ class Call:
33
+ kind: str
34
+ request: SessionRequest
35
+ views: ViewSet | None = None
36
+
37
+
38
+ @dataclass(frozen=True, kw_only=True)
39
+ class ReadCall(ToolCall):
40
+ """A scripted call that opens one path, given relative to the workspace."""
41
+
42
+ path: str = ""
43
+
44
+
45
+ @dataclass(frozen=True, kw_only=True)
46
+ class ScriptedCall(ToolCall):
47
+ """A scripted call with a capability and a target (the journal's `input_summary`); `ok` may be false."""
48
+
49
+ capability: str = ""
50
+ target: str | None = None
51
+
52
+
53
+ def answer(text: str, *, tools: Iterable[str] = (), reads: Iterable[str] = (), cost: float | None = 0.01,
54
+ session_id: str = "", tokens: tuple[int, int] = (100, 50), calls: Iterable[ToolCall] = (),
55
+ **fields: object) -> SessionResult:
56
+ """A successful scripted session with the given final text; each path of `reads` is a `read` call.
57
+
58
+ `calls` adds scripted calls as given (a `ScriptedCall` may fail); a refused tool is `denied=(<name>, ...)`.
59
+ """
60
+ usage = Usage(input_tokens=tokens[0], output_tokens=tokens[1], reported_cost_usd=cost, turns=1)
61
+ made: list[ToolCall] = [ToolCall(name=t, ok=True, call_id=f"t{i}") for i, t in enumerate(tools)]
62
+ made += [ReadCall(name="Read", ok=True, call_id=f"t{len(made) + i}", path=p) for i, p in enumerate(reads)]
63
+ made += list(calls)
64
+ return SessionResult(ok=True, text=text, session_id=session_id or None, usage=usage, tool_calls=made,
65
+ **fields) # type: ignore[arg-type]
66
+
67
+
68
+ @dataclass(kw_only=True)
69
+ class ScriptedExecutor:
70
+ scripted: ClassVar[bool] = True # makes no model call; a live suite's guard reads this (EVS-B13, EVS-B12, EVS-B14)
71
+ caps: Capabilities
72
+ steps: list[Reply] = field(default_factory=list)
73
+ judges: list[Reply] = field(default_factory=list)
74
+ probe_report: ProbeReport = field(default_factory=lambda: ProbeReport(ok=True, version="standin"))
75
+ calls: list[Call] = field(default_factory=list)
76
+
77
+ @property
78
+ def name(self) -> str:
79
+ return self.caps.name
80
+
81
+ def capabilities(self) -> Capabilities:
82
+ return replace(self.caps, version=self.probe_report.version)
83
+
84
+ def probe(self) -> ProbeReport:
85
+ return self.probe_report
86
+
87
+ def run_step(self, req: SessionRequest, sink: EventSink) -> SessionResult:
88
+ self.calls.append(Call(kind="step", request=req))
89
+ return self._reply(self.steps, req, sink, "step")
90
+
91
+ def run_judge(self, req: SessionRequest, views: ViewSet, sink: EventSink) -> SessionResult:
92
+ self.calls.append(Call(kind="judge", request=req, views=views))
93
+ return self._reply(self.judges, req, sink, "judge")
94
+
95
+ def _reply(self, queue: list[Reply], req: SessionRequest, sink: EventSink, what: str) -> SessionResult:
96
+ if not queue:
97
+ raise AssertionError(f"stand-in {self.caps.name}: no scripted {what} reply left for {req.session_key}")
98
+ item = queue.pop(0)
99
+ res = item(req) if callable(item) else item
100
+ if not self.caps.reports_cost and res.usage.reported_cost_usd is not None:
101
+ res = replace(res, usage=replace(res.usage, reported_cost_usd=None)) # estimate-only executors
102
+ sink.push(Event(kind="session_started", data={"session_id": res.session_id, "model": res.model,
103
+ "tools": list(res.tools_at_start)}))
104
+ for c in res.tool_calls:
105
+ started: dict[str, object] = {"name": c.name, "call_id": c.call_id, "subagent": c.subagent}
106
+ if isinstance(c, ReadCall):
107
+ started.update(capability="read", input_summary=c.path)
108
+ elif isinstance(c, ScriptedCall):
109
+ started.update(capability=c.capability, input_summary=c.target)
110
+ sink.push(Event(kind="tool_started", data=started))
111
+ sink.push(Event(kind="tool_finished", data={"call_id": c.call_id, "ok": c.ok}))
112
+ sink.push(Event(kind="result", data={"ok": res.ok, "usage": res.usage}))
113
+ return replace(res, cli_version=res.cli_version or self.probe_report.version)
114
+
115
+
116
+ def standin(name: str, **kw: object) -> ScriptedExecutor:
117
+ """A stand-in carrying the declared capability set of executor ``name``."""
118
+ return ScriptedExecutor(caps=DECLARED[name], **kw) # type: ignore[arg-type]
@@ -0,0 +1,110 @@
1
+ """Tool input summaries for the activity journal (EVT-B21).
2
+
3
+ One line, scrubbed by the pattern scrubber (SEC-B8 to SEC-B11), clipped to 200 characters, built by an executor's
4
+ translator from the tool's input. Summaries live only in the activity journal and the live progress file;
5
+ no run-log record, ledger row, stats row, finding, export or filed text carries them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+ from typing import Any
13
+ from urllib.parse import urlsplit
14
+
15
+ from tempergraph.contracts import Capabilities
16
+ from tempergraph.security.scrub import clip
17
+
18
+ LIMIT = 200
19
+ OUTSIDE = "<outside workspace>"
20
+
21
+ # Input keys that carry the path, pattern, URL or command, in the order they are tried, across the four
22
+ # designed executors' tool shapes (Claude Code, the Agent SDK and the Messages API tool host share names;
23
+ # Antigravity uses its own capitalised keys).
24
+ _PATH_KEYS = ("file_path", "path", "notebook_path", "AbsolutePath", "TargetFile", "DirectoryPath", "SearchPath")
25
+ _PATTERN_KEYS = ("pattern", "Query", "query", "glob")
26
+ _COMMAND_KEYS = ("command", "CommandLine", "cmd")
27
+ _CWD_KEYS = ("cwd", "Cwd", "workdir")
28
+
29
+
30
+ def capability_of(caps: Capabilities, tool_name: str) -> str | None:
31
+ """The declared capability a tool name belongs to, or None for an unknown tool."""
32
+ for cap, names in caps.tool_map.items():
33
+ if cap.endswith(":*"):
34
+ continue
35
+ if tool_name in names:
36
+ return cap
37
+ if tool_name.startswith("mcp__") or tool_name.startswith("mcp("):
38
+ return "mcp"
39
+ if tool_name in caps.tool_map.get("skill:*", ()):
40
+ return "skill"
41
+ return None
42
+
43
+
44
+ def _first(data: Mapping[str, Any], keys: tuple[str, ...]) -> str | None:
45
+ for k in keys:
46
+ v = data.get(k)
47
+ if isinstance(v, str) and v:
48
+ return v
49
+ return None
50
+
51
+
52
+ def relative(path: str, workspace: Path | None) -> str:
53
+ """A path relative to the workspace; a path outside it reads `<outside workspace>`."""
54
+ p = Path(path)
55
+ if not p.is_absolute():
56
+ if ".." in p.parts:
57
+ return OUTSIDE
58
+ return str(p)
59
+ if workspace is None:
60
+ return OUTSIDE
61
+ try:
62
+ rel = p.resolve(strict=False).relative_to(workspace.resolve(strict=False))
63
+ except ValueError:
64
+ return OUTSIDE
65
+ return str(rel) or "."
66
+
67
+
68
+ def _mcp_name(tool_name: str) -> str:
69
+ if tool_name.startswith("mcp__"):
70
+ server, _, tool = tool_name[5:].partition("__")
71
+ return f"{server}/{tool}" if tool else server
72
+ if tool_name.startswith("mcp(") and tool_name.endswith(")"):
73
+ return tool_name[4:-1]
74
+ return tool_name
75
+
76
+
77
+ def input_summary(capability: str | None, tool_name: str, data: Mapping[str, Any] | None,
78
+ workspace: Path | None = None) -> str | None:
79
+ """EVT-B21's table; None for an unknown capability."""
80
+ data = data if isinstance(data, Mapping) else {}
81
+ text: str | None
82
+ if capability == "shell":
83
+ cmd = _first(data, _COMMAND_KEYS)
84
+ if cmd is None:
85
+ return None
86
+ cwd = _first(data, _CWD_KEYS)
87
+ where = relative(cwd, workspace) if cwd else "."
88
+ text = cmd if where in (".", "") else f"{cmd} (in {where})"
89
+ elif capability in ("read", "edit", "write", "list"):
90
+ path = _first(data, _PATH_KEYS)
91
+ if path is None:
92
+ pattern = _first(data, _PATTERN_KEYS) if capability == "list" else None
93
+ return clip(pattern, LIMIT) if pattern else None
94
+ text = relative(path, workspace)
95
+ elif capability == "search":
96
+ text = _first(data, _PATTERN_KEYS)
97
+ elif capability == "web_fetch":
98
+ url = _first(data, ("url", "Url", "URL"))
99
+ text = (urlsplit(url).hostname or None) if url else None
100
+ elif capability == "web_search":
101
+ text = "query"
102
+ elif capability == "subagent":
103
+ text = _first(data, ("subagent_type", "agent_type", "type")) or "subagent"
104
+ elif capability == "mcp":
105
+ text = _mcp_name(tool_name)
106
+ elif capability == "skill":
107
+ text = _first(data, ("skill", "name")) or "skill"
108
+ else:
109
+ return None
110
+ return clip(text, LIMIT) if text else None
@@ -0,0 +1,27 @@
1
+ """The judge view catalog for MCP tools (GRD-B1, GRD-B7, GRD-AC6, ADR a-judge-reaches-an-mcp-server-only-through-the-engines-filtering-proxy).
2
+
3
+ A constant table keyed by the full tool name `mcp:<server>/<tool>`: a tracker's create or update tool maps to its
4
+ `get_issue` read view, a wiki's update tool to its `get_page` read view, and a read view maps to itself, so a step
5
+ that declares one gives its judge that same view. Nothing is inferred from a name pattern or an MCP hint; a tool
6
+ the table does not list has no view, and its judge gets nothing of it. Add newer tool names beside the old ones,
7
+ never renaming, so a workflow pinned to an older server keeps its views.
8
+
9
+ The names under `tracker` and `wiki` are the generic servers of the specs' scenarios and of the stand-in servers
10
+ the tests use.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ CATALOG: dict[str, tuple[str, ...]] = {
16
+ "mcp:tracker/create_issue": ("mcp:tracker/get_issue",),
17
+ "mcp:tracker/update_issue": ("mcp:tracker/get_issue",),
18
+ "mcp:tracker/get_issue": ("mcp:tracker/get_issue",),
19
+ "mcp:tracker/get_comments": ("mcp:tracker/get_comments",),
20
+ "mcp:wiki/update_page": ("mcp:wiki/get_page",),
21
+ "mcp:wiki/get_page": ("mcp:wiki/get_page",),
22
+ }
23
+
24
+
25
+ def read_views(tool: str) -> tuple[str, ...]:
26
+ """The read views of one declared MCP tool, or nothing when the catalog does not list it."""
27
+ return CATALOG.get(tool, ())
tempergraph/git.py ADDED
@@ -0,0 +1,403 @@
1
+ """The git reader: a sanctioned launch site (SEC-B7) for `git` with constant arguments.
2
+
3
+ Refs travel on stdin where git accepts them; callers pass only constants and refs checked by
4
+ :func:`is_safe_ref` (SEC-B4).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import re
11
+ import subprocess
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ _REF_RE = re.compile(r"^(?!.*\.\.)(?!/)(?!.*//)[A-Za-z0-9._/-]{1,200}(?<!\.lock)(?<!/)$")
17
+
18
+
19
+ class GitError(Exception):
20
+ pass
21
+
22
+
23
+ def is_safe_ref(ref: str) -> bool:
24
+ return bool(_REF_RE.match(ref)) and not ref.startswith("-")
25
+
26
+
27
+ def _env() -> dict[str, str]:
28
+ env = dict(os.environ)
29
+ env["GIT_TERMINAL_PROMPT"] = "0"
30
+ env.pop("GIT_DIR", None)
31
+ env.pop("GIT_WORK_TREE", None)
32
+ return env
33
+
34
+
35
+ def git(args: list[str], cwd: Path, *, check: bool = True, stdin: str | None = None, timeout_s: float = 120) -> str:
36
+ """Run git with list argv, no shell. Raises GitError when ``check`` and git fails, or on a timeout."""
37
+ try:
38
+ proc = subprocess.run(
39
+ ["git", *args], cwd=cwd, input=stdin, capture_output=True, text=True, env=_env(), timeout=timeout_s
40
+ )
41
+ except (OSError, subprocess.TimeoutExpired) as exc:
42
+ raise GitError(f"git {args[0] if args else ''}: {type(exc).__name__}") from None
43
+ if check and proc.returncode != 0:
44
+ raise GitError(f"git {args[0] if args else ''} exited {proc.returncode}: {proc.stderr.strip()[:300]}")
45
+ return proc.stdout
46
+
47
+
48
+ def git_bytes(args: list[str], cwd: Path) -> bytes:
49
+ """Run git and return its raw output, for a blob that is not text. Raises GitError when git fails."""
50
+ try:
51
+ proc = subprocess.run(["git", *args], cwd=cwd, capture_output=True, env=_env(), timeout=120)
52
+ except (OSError, subprocess.TimeoutExpired) as exc:
53
+ raise GitError(f"git {args[0] if args else ''}: {type(exc).__name__}") from None
54
+ if proc.returncode != 0:
55
+ raise GitError(f"git {args[0] if args else ''} exited {proc.returncode}")
56
+ return proc.stdout
57
+
58
+
59
+ def toplevel(start: Path) -> Path | None:
60
+ try:
61
+ return Path(git(["rev-parse", "--show-toplevel"], start).strip())
62
+ except GitError:
63
+ return None
64
+
65
+
66
+ def main_checkout(start: Path) -> Path | None:
67
+ """The main checkout of the repository that holds ``start``, from git's common directory."""
68
+ try:
69
+ common = git(["rev-parse", "--path-format=absolute", "--git-common-dir"], start).strip()
70
+ except GitError:
71
+ return None
72
+ common_path = Path(common)
73
+ if common_path.name == ".git":
74
+ return common_path.parent
75
+ # A bare common dir or an unusual layout: fall back to the worktree list's first entry.
76
+ try:
77
+ out = git(["worktree", "list", "--porcelain"], start)
78
+ except GitError:
79
+ return None
80
+ for line in out.splitlines():
81
+ if line.startswith("worktree "):
82
+ return Path(line[len("worktree "):])
83
+ return None
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class Fingerprint:
88
+ head: str
89
+ status: str
90
+ manifest: bool = False # outside git: `status` is the workspace manifest's digest (WSP-B15 to WSP-B18)
91
+
92
+ @property
93
+ def dirty(self) -> bool | None:
94
+ """Uncommitted changes; None outside git, where the word has no meaning."""
95
+ return None if self.manifest else bool(self.status)
96
+
97
+
98
+ def fingerprint(workdir: Path) -> Fingerprint:
99
+ if toplevel(workdir) is None: # outside git the guard compares manifests of the files (WSP-B15 to WSP-B18)
100
+ from tempergraph.store import manifest
101
+
102
+ return Fingerprint("", manifest.status(workdir), manifest=True)
103
+ try:
104
+ head = git(["rev-parse", "HEAD"], workdir, check=False).strip()
105
+ status = git(["status", "--porcelain=v1", "--untracked-files=all"], workdir, check=False)
106
+ except GitError:
107
+ return Fingerprint("", "")
108
+ lines = [ln for ln in status.splitlines() if ".tempergraph/" not in ln]
109
+ return Fingerprint(head, "\n".join(sorted(lines)))
110
+
111
+
112
+ def branch(workdir: Path) -> str:
113
+ try:
114
+ return git(["rev-parse", "--abbrev-ref", "HEAD"], workdir, check=False).strip()
115
+ except GitError:
116
+ return ""
117
+
118
+
119
+ def pushed(workdir: Path, name: str) -> bool:
120
+ """CHK-B10: the branch exists on any configured remote, by its remote-tracking refs; no network."""
121
+ if not name or not is_safe_ref(name):
122
+ return False
123
+ try:
124
+ refs = git(["for-each-ref", "--format=%(refname)", "refs/remotes"], workdir, check=False)
125
+ except Exception: # noqa: BLE001 - not a repository, or git is missing: not pushed
126
+ return False
127
+ return any(r.split("/", 3)[-1] == name for r in refs.splitlines() if r.count("/") >= 3)
128
+
129
+
130
+ def branch_commit(workdir: Path, name: str) -> str:
131
+ """CHK-B22: the commit the branch `name` points to now: the local branch, else `origin`'s remote-tracking branch;
132
+ empty when no ref names it or the name is unsafe. No fetch and no network."""
133
+ if not name or not is_safe_ref(name):
134
+ return ""
135
+ for ref in (f"refs/heads/{name}", f"refs/remotes/origin/{name}"):
136
+ try:
137
+ found = git(["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], workdir, check=False).strip()
138
+ except GitError:
139
+ return ""
140
+ if found:
141
+ return found
142
+ return ""
143
+
144
+
145
+ def own_base(workdir: Path, base: str, base_branch: str, *, head: str = "HEAD") -> str:
146
+ """WSP-B23: the commit the run's own change is measured from. After the base branch's head was merged into the
147
+ run's branch it is the merge base of `HEAD` and that head; otherwise `base`, the start commit. An empty `base`,
148
+ no base branch head, an unsafe ref, a start commit that is not an ancestor of the merge base and any git failure
149
+ give `base`, silently. So does a merge base that holds a commit of the run's own line (the first-parent line
150
+ from `HEAD` back to `base`): the base branch then holds work of the run, by a merge of the run's branch into it,
151
+ a rebase or a moved ref, and measuring from it would leave that work out."""
152
+ if not base or not is_safe_ref(base):
153
+ return base
154
+ try:
155
+ tip = branch_commit(workdir, base_branch)
156
+ if not tip:
157
+ return base
158
+ merge_base = git(["merge-base", head, tip], workdir, check=False).strip()
159
+ if not merge_base:
160
+ return base
161
+ common = git(["merge-base", base, merge_base], workdir, check=False).strip()
162
+ if not common or common != _full(workdir, base):
163
+ return base
164
+ line = git(["rev-list", "--first-parent", "--reverse", f"{base}..{head}"], workdir, check=False).split()
165
+ if line and git(["merge-base", line[0], merge_base], workdir, check=False).strip() == line[0]:
166
+ return base # the run's first commit is in the merge base's history: never measure from past it
167
+ except GitError:
168
+ return base
169
+ return merge_base
170
+
171
+
172
+ def _full(workdir: Path, ref: str) -> str:
173
+ return git(["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"], workdir, check=False).strip()
174
+
175
+
176
+ def head(workdir: Path) -> str:
177
+ """The commit `HEAD` names in `workdir`; empty when there is none."""
178
+ return git(["rev-parse", "--verify", "--quiet", "HEAD"], workdir, check=False).strip()
179
+
180
+
181
+ def _identity(workdir: Path) -> list[str]:
182
+ """The engine's own commit identity, used only where the repository configures none."""
183
+ if git(["config", "user.email"], workdir, check=False).strip():
184
+ return ["-c", "commit.gpgsign=false"]
185
+ return ["-c", "commit.gpgsign=false", "-c", "user.name=tempergraph", "-c", "user.email=tempergraph@localhost.invalid"]
186
+
187
+
188
+ def stage_all_args(workdir: Path) -> list[str]:
189
+ """The `git add` words that stage every change in `workdir` outside the state root. The state root is left out by
190
+ an exclude pathspec only when git does not already ignore it: git 2.39 refuses an exclude pathspec that names an
191
+ ignored path (exit 1, "paths are ignored by one of your .gitignore files") after staging the rest."""
192
+ ignored = git(["check-ignore", ".tempergraph/"], workdir, check=False).strip()
193
+ return ["add", "-A", "--", ".", *([] if ignored else [":(exclude).tempergraph"])]
194
+
195
+
196
+ def commit_all(workdir: Path, message: str) -> str:
197
+ """WSP-B19: commit every uncommitted change in `workdir`, new files included, outside the state root. Returns the
198
+ new commit, or an empty string when there was nothing to commit (no commit is made)."""
199
+ git(stage_all_args(workdir), workdir)
200
+ if not git(["status", "--porcelain=v1", "--untracked-files=no"], workdir).strip():
201
+ return ""
202
+ git([*_identity(workdir), "commit", "--no-verify", "--quiet", "-m", message], workdir)
203
+ return head(workdir)
204
+
205
+
206
+ def merge_no_ff(workdir: Path, ref: str, message: str) -> list[str]:
207
+ """WSP-B11, WSP-B12: merge the branch `ref` into the branch checked out in `workdir` without fast-forward. Returns
208
+ the conflicting paths, empty when the merge went through (a merge in progress is left for the caller to end)."""
209
+ try:
210
+ git([*_identity(workdir), "merge", "--no-ff", "--no-edit", "-m", message, "--end-of-options", ref], workdir)
211
+ except GitError:
212
+ paths = conflicted_paths(workdir)
213
+ if not paths:
214
+ raise
215
+ return paths
216
+ return []
217
+
218
+
219
+ def conflicted_paths(workdir: Path) -> list[str]:
220
+ """The paths a merge in progress left unmerged, sorted."""
221
+ return sorted(p for p in git(["diff", "--name-only", "--diff-filter=U"], workdir, check=False).splitlines() if p)
222
+
223
+
224
+ def merge_abort(workdir: Path) -> None:
225
+ git(["merge", "--abort"], workdir, check=False)
226
+
227
+
228
+ def reset_hard(workdir: Path, commit: str) -> None:
229
+ """Put the branch checked out in `workdir`, its index and its files back at `commit`, a full commit id (`reset`
230
+ takes no `--end-of-options` before its commit, and a hex id cannot be read as an option)."""
231
+ if not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", commit):
232
+ raise GitError("git reset: not a full commit id")
233
+ git(["reset", "--hard", "--quiet", commit], workdir)
234
+
235
+
236
+ _COMMIT_ID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
237
+
238
+
239
+ def is_commit_id(text: str) -> bool:
240
+ """Whether `text` is a full commit id (a hex id cannot be read as an option or a ref name)."""
241
+ return bool(_COMMIT_ID.fullmatch(text))
242
+
243
+
244
+ def prefix(workdir: Path) -> str:
245
+ """The folder of `workdir` inside its repository, `""` at the top, with no trailing slash."""
246
+ return git(["rev-parse", "--show-prefix"], workdir, check=False).strip().rstrip("/")
247
+
248
+
249
+ def base_checkout(workdir: Path, commit: str, dest: Path) -> Path:
250
+ """CHK-B18: a clean checkout of `commit` of the repository that holds `workdir`, in the new folder `dest` outside
251
+ both that repository and its main checkout. It shares the repository's objects and records nothing in it: no
252
+ worktree entry, branch or ref. Returns the folder of `workdir` inside the checkout. Raises GitError when `commit`
253
+ is not a full commit id or cannot be checked out."""
254
+ if not is_commit_id(commit):
255
+ raise GitError("git checkout: not a full commit id")
256
+ top = toplevel(workdir)
257
+ if top is None:
258
+ raise GitError("git clone: not a repository")
259
+ git(["clone", "--shared", "--no-checkout", "--quiet", "--", str(top), str(dest)], dest.parent)
260
+ git(["checkout", "--quiet", "--detach", commit, "--"], dest)
261
+ return dest / prefix(workdir)
262
+
263
+
264
+ def folder_in_commit(workdir: Path, commit: str, folder: str) -> bool:
265
+ """CHK-B19: whether `folder` (relative to `workdir`, as `cd` writes it) is a folder of `commit`."""
266
+ if not is_commit_id(commit):
267
+ return False
268
+ path = "/".join(p for p in (prefix(workdir), folder.strip("/")) if p and p != ".")
269
+ if not path:
270
+ return True
271
+ return git(["cat-file", "-t", f"{commit}:{path}"], workdir, check=False).strip() == "tree"
272
+
273
+
274
+ def changed_between(workdir: Path, base: str, end: str, limit: int = 500) -> list[str]:
275
+ """OUT-B28: the paths that differ between the commits `base` and `end`, sorted, never one under `.tempergraph/`,
276
+ at most `limit`. Empty when either is not a full commit id or git fails."""
277
+ if not is_commit_id(base) or not is_commit_id(end):
278
+ return []
279
+ try:
280
+ out = git(["diff", "--name-only", base, end, "--"], workdir, check=False)
281
+ except GitError:
282
+ return []
283
+ return sorted(p for p in out.splitlines() if p and not p.startswith(".tempergraph/"))[:limit]
284
+
285
+
286
+ @dataclass(frozen=True)
287
+ class FileDiff:
288
+ """One file of a diff: `status` is `added`, `modified`, `deleted` or `binary`; `added` holds `(line, text)` of the
289
+ lines the end commit adds, with their new line numbers."""
290
+
291
+ path: str
292
+ status: str
293
+ added: tuple[tuple[int, str], ...] = ()
294
+
295
+
296
+ _HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
297
+
298
+
299
+ def diff_added(workdir: Path, base: str, end: str, limit: int = 500) -> list[FileDiff] | None:
300
+ """ALN-B3: the files that differ between the commits `base` and `end`, in path order, each with the lines `end`
301
+ adds and their new line numbers. A rename is a deleted file and an added one; a deleted or binary file has no
302
+ line; paths under `.tempergraph/` are dropped; at most `limit` files. `None` when either is not a full commit id
303
+ or git fails, so a failed read is told from an empty list."""
304
+ if not is_commit_id(base) or not is_commit_id(end):
305
+ return None
306
+ try:
307
+ out = git(["-c", "core.quotepath=off", "diff", "--no-renames", "--unified=0", "--no-color", "--no-ext-diff",
308
+ "--src-prefix=a/", "--dst-prefix=b/", base, end, "--"], workdir)
309
+ except GitError:
310
+ return None
311
+ files: dict[str, dict[str, Any]] = {}
312
+ cur: dict[str, Any] | None = None
313
+ in_hunk = False
314
+ new_no = 0
315
+ for ln in out.split("\n"):
316
+ if ln.startswith("diff --git "): # a line of a hunk starts with `+`, `-` or a space, never `diff`
317
+ m = re.match(r"diff --git a/(.*) b/(.*)$", ln)
318
+ if m is None or m.group(2).startswith(".tempergraph/"):
319
+ cur = None
320
+ else:
321
+ cur = {"status": "modified", "added": []}
322
+ files[m.group(2)] = cur
323
+ in_hunk = False
324
+ elif cur is None:
325
+ continue
326
+ elif ln.startswith("@@"):
327
+ m2 = _HUNK.match(ln)
328
+ new_no = int(m2.group(1)) if m2 else 0
329
+ in_hunk = True
330
+ elif in_hunk:
331
+ if ln.startswith("+"):
332
+ cur["added"].append((new_no, ln[1:]))
333
+ new_no += 1
334
+ elif ln.startswith("new file mode"):
335
+ cur["status"] = "added"
336
+ elif ln.startswith("deleted file mode"):
337
+ cur["status"] = "deleted"
338
+ elif ln.startswith("Binary files "):
339
+ cur["status"] = "binary"
340
+ return [FileDiff(p, str(f["status"]), tuple(f["added"])) for p, f in sorted(files.items())][:limit]
341
+
342
+
343
+ def base_problem(workdir: Path, base: str) -> str | None:
344
+ """SRV-B37: why no count can be made from `base`: `outside_repository`, `no_entry_commit` or `commit_unknown`, in
345
+ that order of precedence; None when `base` is a commit of the repository that holds `workdir`."""
346
+ if git(["rev-parse", "--is-inside-work-tree"], workdir, check=False).strip() != "true":
347
+ return "outside_repository"
348
+ if not base:
349
+ return "no_entry_commit"
350
+ if not is_safe_ref(base) or git(["cat-file", "-t", base], workdir, check=False).strip() != "commit":
351
+ return "commit_unknown"
352
+ return None
353
+
354
+
355
+ def judge_changed_paths(workdir: Path, base: str, limit: int) -> list[str]:
356
+ """SRV-B39, SRV-B40: the paths a judge's count covers: those that differ from `base` and exist in the workspace,
357
+ plus the modified and untracked ones, named as the workspace holds them (git's quoting undone), never one under
358
+ `.tempergraph/` and never a deleted one; at most `limit`. `changed_paths` is not this list."""
359
+ top = prefix(workdir)
360
+ lead = f"{top}/" if top else ""
361
+ found: list[str] = []
362
+ try:
363
+ diff = git(["diff", "--name-only", "-z", "--diff-filter=d", base, "--"], workdir, check=False)
364
+ status = git(["status", "--porcelain=v1", "-z", "--untracked-files=all"], workdir, check=False)
365
+ except GitError:
366
+ return found
367
+ names = [p for p in diff.split("\0") if p]
368
+ parts = status.split("\0")
369
+ i = 0
370
+ while i < len(parts):
371
+ entry = parts[i]
372
+ i += 1
373
+ if len(entry) < 4:
374
+ continue
375
+ code, name = entry[:2], entry[3:]
376
+ if "R" in code or "C" in code:
377
+ i += 1 # the origin of a rename or a copy follows as its own field
378
+ if "D" not in code.replace(" ", ""):
379
+ names.append(name)
380
+ for p in names:
381
+ if not p.startswith(lead):
382
+ continue
383
+ rel = p[len(lead):]
384
+ if rel.startswith(".tempergraph/") or rel in found or not (workdir / rel).exists():
385
+ continue
386
+ found.append(rel)
387
+ return found[:limit]
388
+
389
+
390
+ def changed_paths(workdir: Path, base: str | None = None, limit: int = 500) -> list[str]:
391
+ paths: list[str] = []
392
+ try:
393
+ if base and is_safe_ref(base):
394
+ out = git(["diff", "--name-only", base, "--"], workdir, check=False)
395
+ paths.extend(p for p in out.splitlines() if p)
396
+ status = git(["status", "--porcelain=v1", "--untracked-files=all"], workdir, check=False)
397
+ except GitError:
398
+ return paths[:limit]
399
+ for line in status.splitlines():
400
+ p = line[3:]
401
+ if p and not p.startswith(".tempergraph/") and p not in paths:
402
+ paths.append(p)
403
+ return paths[:limit]