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,416 @@
1
+ """Cause codes from run-log names and numbers only, each classed and given a side (SIL-B11, SIL-B12 to SIL-B16).
2
+
3
+ No model call and no text: a cause is derived from record kinds, enums, counts and criterion ids. A code may
4
+ carry one `:<detail>` part (a refusal class, a criterion id, an infra cause, a pause cause).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Iterable, Mapping, Sequence
11
+ from dataclasses import dataclass
12
+ from typing import Any, Literal
13
+
14
+ from tempergraph.improve import params
15
+ from tempergraph.model import flow
16
+
17
+ Klass = Literal["fault", "infra", "designed"]
18
+
19
+
20
+ @dataclass(frozen=True, kw_only=True)
21
+ class Cause:
22
+ klass: Klass
23
+ side: str # engine, workflow, executor, host; `executor` becomes `executor:<name>` on the finding
24
+ remedy: str
25
+ rate: bool = False # FRC-B16: a detector that fires at a fixed rate; its count is held to a share of threads
26
+
27
+
28
+ # The base code (before any `:`) decides the class, the side and the fixed remedy text.
29
+ CAUSES: dict[str, Cause] = {
30
+ "tool_access": Cause(klass="fault", side="workflow",
31
+ remedy="Declare the tool or command the step needed in the unit's tools or allow-list"),
32
+ "grant_missing": Cause(klass="fault", side="workflow",
33
+ remedy="Declare the granted capability on the unit; the grant stood in for it"),
34
+ "grant_unused": Cause(klass="designed", side="workflow", remedy="Recorded only: the grant was never called"),
35
+ "retries_spent": Cause(klass="fault", side="workflow",
36
+ remedy="Tighten the prompt or the check named by the blockers; the retry budget ran out"),
37
+ "loop_budget_spent": Cause(klass="fault", side="workflow",
38
+ remedy="Strengthen the serving criterion upstream; trips back ran out"),
39
+ "retry_burst": Cause(klass="fault", side="workflow",
40
+ remedy="Three or more retries in one visit: the prompt or check of the unit misses a rule"),
41
+ "judge_blocked": Cause(klass="fault", side="workflow",
42
+ remedy="The step keeps missing this criterion: state it in the prompt or add a check"),
43
+ "check_fail": Cause(klass="fault", side="workflow", rate=True,
44
+ remedy="The step's output fails the deterministic check; say what it checks in the prompt"),
45
+ "gap_escalation": Cause(klass="fault", side="workflow",
46
+ remedy="The judge could not grade a criterion: give it a reference or a check"),
47
+ "blocked_without_check": Cause(klass="fault", side="workflow",
48
+ remedy="A BLOCKED pause with an empty check: add a check that tests the blocker"),
49
+ "blocked": Cause(klass="designed", side="workflow", remedy="Recorded only: a designed BLOCKED pause"),
50
+ "no_change": Cause(klass="fault", side="workflow",
51
+ remedy="The judge found no change since the last attempt: the step cannot fix this alone"),
52
+ "escalation": Cause(klass="fault", side="workflow", remedy="An escalation with an unlisted reason"),
53
+ "refused": Cause(klass="fault", side="workflow", remedy="A permission was refused: declare it or narrow the step"),
54
+ "skill_undeclared": Cause(klass="fault", side="workflow",
55
+ remedy="The step called a skill it does not declare: declare it as `skill:` or take "
56
+ "its name out of the prompt"),
57
+ "step_timeout": Cause(klass="fault", side="workflow",
58
+ remedy="The step ran out of time: split it or raise its timeout"),
59
+ "agent_decided": Cause(klass="fault", side="workflow",
60
+ remedy="An agent answered this pause on its own: add a check or an environmental cause"),
61
+ "answer_overrode": Cause(klass="fault", side="workflow",
62
+ remedy="A decision let this gate's failure through: add or tighten the check or gate "
63
+ "criterion that it overrode"),
64
+ "upstream_confirmed": Cause(klass="fault", side="workflow",
65
+ remedy="A decision confirmed an upstream claim: strengthen the gate criterion or "
66
+ "check of the claimed unit so the fault is caught there"),
67
+ "retry_passed_unchanged": Cause(klass="fault", side="workflow",
68
+ remedy="A retry passed with nothing changed: the check or gate criterion gives "
69
+ "different answers for one result; make it decide the same way each time"),
70
+ "retry_same_failure": Cause(klass="fault", side="workflow",
71
+ remedy="A retry paused at the same unit again: the check or gate criterion cannot "
72
+ "be met by retrying; change what it asks"),
73
+ "resume_no_progress": Cause(klass="fault", side="engine",
74
+ remedy="A resume started no work and ended where it began: report the engine's "
75
+ "resume of this thread state"),
76
+ "pushback": Cause(klass="fault", side="workflow",
77
+ remedy="A person rewound, ruled or declined: the gate let this through"),
78
+ "tool_repeat": Cause(klass="fault", side="workflow",
79
+ remedy="The step repeated the same failing call: say in the prompt how to recover"),
80
+ "idle_burn": Cause(klass="fault", side="workflow", rate=True,
81
+ remedy="Tokens were spent for minutes with no workspace write: narrow the step or its context"),
82
+ "shell_for_files": Cause(klass="fault", side="workflow",
83
+ remedy="The step used the shell for file reads: prefer the declared file tools"),
84
+ "context_bloat": Cause(klass="fault", side="workflow", rate=True,
85
+ remedy="The session's context grew past its usual size: split the step or trim inputs"),
86
+ "declared_unused": Cause(klass="designed", side="workflow",
87
+ remedy="Recorded only: a declared skill or subagent type is never called"),
88
+ "subagent_heavy": Cause(klass="designed", side="workflow",
89
+ remedy="Recorded only: subagents carry most of the session's tokens"),
90
+ "timeout": Cause(klass="fault", side="workflow", remedy="The session timed out: see its shape and split the step"),
91
+ "judge_unread_pass": Cause(klass="fault", side="workflow",
92
+ remedy="The judge passed without opening a changed path: tell it what to read"),
93
+ "judge_partial_read": Cause(klass="fault", side="workflow",
94
+ remedy="The judge graded after opening only part of the change: "
95
+ "tell it what to read, or give it a stronger model"),
96
+ "retry_same_path": Cause(klass="fault", side="workflow", rate=True,
97
+ remedy="The retry repeated the previous attempt: give the step what it needs to change"),
98
+ "binding_shift": Cause(klass="fault", side="workflow",
99
+ remedy="Re-score the judge on its calibration cases and review the gate for the new binding"),
100
+ "outcome_unmet": Cause(klass="fault", side="workflow",
101
+ remedy="The outcome judge found this final criterion unmet: a gate let the gap through"),
102
+ "outcome_escape": Cause(klass="fault", side="workflow",
103
+ remedy="A gate let a run through that a person sent back after review: "
104
+ "tighten the gate that serves this unit"),
105
+ "review_repeat": Cause(klass="fault", side="workflow",
106
+ remedy="A review category was kept in several sessions or runs of this unit: fix what it names"),
107
+ "check_repeat": Cause(klass="fault", side="workflow",
108
+ remedy="The same check failure twice although the step changed files: "
109
+ "a person decides whether the check, the environment or the prompt is wrong"),
110
+ "trip_back": Cause(klass="fault", side="workflow",
111
+ remedy="Strengthen the gate criterion or the check of the unit that sent the run back, "
112
+ "so the fault is caught before the run is sent back"),
113
+ "attempt_cap": Cause(klass="fault", side="workflow",
114
+ remedy="Tighten the gate criterion or check that keeps sending the run back, "
115
+ "or raise the run's attempt cap"),
116
+ "finalizer_undelivered": Cause(klass="fault", side="workflow",
117
+ remedy="Fix the finalizer or its environment so the last stage delivers"),
118
+ "judge_unparsed": Cause(klass="fault", side="engine", remedy="The judge's answer could not be parsed twice"),
119
+ "guard": Cause(klass="fault", side="engine", remedy="The independence guard discarded a judgement"),
120
+ "engine_error": Cause(klass="fault", side="engine", remedy="The engine recorded an internal error"),
121
+ "unknown_tool_name": Cause(klass="fault", side="executor",
122
+ remedy="The executor reported a tool name outside the view catalog"),
123
+ "executor_error": Cause(klass="fault", side="executor", remedy="The executor reported an error kind it should not"),
124
+ "infra": Cause(klass="infra", side="engine", remedy="Recorded only: an infrastructure failure"),
125
+ "slow_host": Cause(klass="infra", side="host", remedy="Recorded only: the host is slow"),
126
+ "auth": Cause(klass="infra", side="host", remedy="Recorded only: the executor is not signed in"),
127
+ "environmental": Cause(klass="infra", side="host", remedy="Recorded only: the environment failed a check"),
128
+ "approval": Cause(klass="designed", side="workflow", remedy="Recorded only: a designed approval"),
129
+ "upstream": Cause(klass="designed", side="workflow", remedy="Recorded only: an upstream dependency paused it"),
130
+ "usage_limit": Cause(klass="infra", side="host",
131
+ remedy="Recorded only: the account's usage limit refused the session"),
132
+ "input": Cause(klass="designed", side="workflow", remedy="Recorded only: a designed pause for a person's input"),
133
+ "person_stop": Cause(klass="designed", side="workflow", remedy="Recorded only: a person stopped the run"),
134
+ "cost_cap": Cause(klass="designed", side="workflow", remedy="Recorded only: the run cost cap drained the run"),
135
+ }
136
+
137
+
138
+ def cause_of(code: str) -> Cause:
139
+ if code == "timeout:slow_host": # SRV-B12: the slow-host shape joins SIL's host side
140
+ return Cause(klass="infra", side="host", remedy="Recorded only: the session timed out on a slow host")
141
+ if code == "review_repeat:environment_fault": # SRV-B26: an environment fault is the host's, never the workflow's
142
+ return Cause(klass="infra", side="host", remedy="Recorded only: reviews kept an environment fault")
143
+ if code == "review_repeat:request_ambiguous":
144
+ return Cause(klass="designed", side="workflow", remedy="Recorded only: reviews kept an ambiguous request")
145
+ return CAUSES.get(code.split(":", 1)[0], Cause(klass="fault", side="engine", remedy="Unclassified cause"))
146
+
147
+
148
+ def _unit(session_key: str) -> str:
149
+ return str(session_key).split(".", 1)[0]
150
+
151
+
152
+ _WORD = re.compile(r"[^A-Za-z0-9_.:-]")
153
+ _UNCHANGED = ("prepared", "reused", "attached") # the workspace actions that say nothing changed (WTR-B28)
154
+
155
+
156
+ def _median(values: list[float]) -> float | None:
157
+ if not values:
158
+ return None
159
+ v = sorted(values)
160
+ mid = len(v) // 2
161
+ return v[mid] if len(v) % 2 else (v[mid - 1] + v[mid]) / 2
162
+
163
+
164
+ def _answers(seg: Sequence[Mapping[str, Any]], ivs: Sequence[Mapping[str, Any]]) -> list[dict[str, Any]]:
165
+ """FRC-B7 to FRC-B13, FRC-B15: the findings of the decisions that answered a pause and started this segment. A
166
+ row that lacks the fact a cause needs (`answered`, `item`) makes no finding of that cause."""
167
+ from tempergraph.improve.pause_facts import OPERATOR_REASONS
168
+
169
+ groups: dict[tuple[str, str, str], list[Mapping[str, Any]]] = {}
170
+
171
+ def put(unit: str, code: str, iv: Mapping[str, Any], from_unit: str = "") -> None:
172
+ groups.setdefault((unit, code, from_unit), []).append(iv)
173
+
174
+ def named(r: Mapping[str, Any], unit: str, child: str, item: str) -> bool:
175
+ return str(r.get("unit") or "") == unit and str(r.get("child") or "") == child \
176
+ and str(r.get("item") or "") == item
177
+
178
+ workspace = next((r for r in seg if r.get("kind") == "workspace" and r.get("mode") != "in_place"
179
+ and r.get("action") in (*_UNCHANGED, "external_change")), None)
180
+ worked = any(r.get("kind") in ("attempt_start", "script") for r in seg)
181
+ ended = next((r for r in reversed(seg) if r.get("kind") == "run_exit"), None)
182
+ idle: list[Mapping[str, Any]] = [] # the decisions of a segment that went nowhere
183
+ for iv in ivs:
184
+ word = str(iv.get("decision") or "")
185
+ base, _, target = word.partition(":")
186
+ unit = str(iv.get("unit") or "")
187
+ a = iv.get("answered")
188
+ if not unit or not base or ("item" not in iv and not isinstance(a, Mapping)):
189
+ continue # no decision at a pause: a deadline row, an infra re-open, a row of an older engine
190
+ reason = _WORD.sub("", str(iv.get("cause") or iv.get("pause_kind") or ""))[:80]
191
+ if isinstance(a, Mapping):
192
+ if base == "proceed":
193
+ kind = None
194
+ if a.get("check") == "FAIL" and a.get("environmental") is False:
195
+ kind = "check"
196
+ elif a.get("check") == "FAIL" and a.get("environmental") is True:
197
+ kind = "environment"
198
+ elif a.get("gap") is True or iv.get("cause") == "unresolved_gap":
199
+ kind = "gap"
200
+ elif iv.get("pause_kind") == "budget":
201
+ kind = "budget"
202
+ if kind:
203
+ put(unit, f"answer_overrode:{kind}", iv)
204
+ elif base == "back" and target and a.get("claim") == target:
205
+ put(target, f"upstream_confirmed:{target}", iv, from_unit=unit)
206
+ if "item" not in iv or base == "stop":
207
+ continue
208
+ owner, _, inner = unit.rpartition("/")
209
+ item = "" if iv.get("item") in (None, "", "none") else str(iv["item"])
210
+ if base == "retry":
211
+ for r in seg:
212
+ if r.get("kind") == "gate" and named(r, inner, owner, item) \
213
+ and "PROCEED" in (r.get("token"), r.get("verdict")):
214
+ if workspace is not None and workspace.get("action") in _UNCHANGED and reason:
215
+ put(unit, f"retry_passed_unchanged:{reason}", iv)
216
+ break
217
+ if r.get("kind") == "pause" and named(r, inner, owner, item):
218
+ put(unit, "retry_same_failure", iv)
219
+ break
220
+ if not worked and ended is not None and (
221
+ ended.get("exit_code") == 4 or any(
222
+ r.get("kind") == "pause" and named(r, inner, owner, item)
223
+ and str(r.get("reason") or r.get("pause_kind") or "") == str(iv.get("cause") or "")
224
+ for r in seg)):
225
+ idle.append(iv)
226
+ if idle:
227
+ groups[(str(idle[0].get("unit")), "resume_no_progress", "")] = idle
228
+ out = []
229
+ for (unit, code, from_unit), rows in groups.items():
230
+ facts = [r["answered"] for r in rows if isinstance(r.get("answered"), Mapping)]
231
+ f: dict[str, Any] = {"unit": unit, "cause": code, "count": 1 if code == "resume_no_progress" else len(rows)}
232
+ if code.startswith("answer_overrode"):
233
+ crit: dict[str, int] = {}
234
+ for fact in facts:
235
+ ids = {str(x) for k in ("failed", "blockers") for x in (fact.get(k) if isinstance(fact.get(k), list)
236
+ else ())}
237
+ for cid in ids:
238
+ crit[cid] = crit.get(cid, 0) + 1
239
+ f["criteria"] = dict(sorted(crit.items()))
240
+ f["items"] = len({str(r["item"]) for r in rows if r.get("item") not in (None, "", "none")})
241
+ if from_unit:
242
+ f["from_unit"] = from_unit
243
+ decisions: dict[str, int] = {}
244
+ reasons: dict[str, int] = {}
245
+ waits = []
246
+ for r in rows:
247
+ w = str(r.get("decision") or "").split(":", 1)[0]
248
+ decisions[w] = decisions.get(w, 0) + 1
249
+ given = r.get("operator_reason")
250
+ why = given if given in OPERATOR_REASONS else "not given"
251
+ reasons[why] = reasons.get(why, 0) + 1
252
+ if isinstance(r.get("wait_s"), int | float) and not isinstance(r.get("wait_s"), bool):
253
+ waits.append(float(r["wait_s"]))
254
+ out.append({**f, "decisions": decisions, "reasons": reasons, "wait_s_median": _median(waits)})
255
+ return out
256
+
257
+
258
+ def derive(records: Sequence[Mapping[str, Any]], interventions: Iterable[Mapping[str, Any]] = (),
259
+ grants: Iterable[Mapping[str, Any]] = (), *,
260
+ starter: Mapping[str, Any] | None = None) -> list[dict[str, Any]]:
261
+ """Causes of one segment: `{unit, cause, count, executor?, child?, class?}` with no text. A record of a
262
+ sub-workflow child's unit carries `child` (the unit's path), so a child's unit and a parent's unit of one name keep
263
+ their own causes (SWF-B9). `starter` is the caller of the thread's first `run_started`: an `agent_decided` finding
264
+ carries class `designed` when the deciding caller has the same host and recorded host session, else `fault`
265
+ (FRC-B6)."""
266
+ out: dict[tuple[str, str, str, str], int] = {}
267
+ classes: dict[tuple[str, str, str, str], str] = {}
268
+ versions: dict[tuple[str, str, str, str], str] = {} # executor causes carry the CLI version (SIL-AC4)
269
+ child = "" # the path of the child the record being read belongs to; empty for the run's own units
270
+
271
+ def add(unit: str, code: str, executor: str = "", version: str = "", n: int = 1) -> None:
272
+ key = (child, unit, code, executor)
273
+ out[key] = out.get(key, 0) + n # `n` may be 0: the finding stands with a count of none
274
+ if version:
275
+ versions[key] = version
276
+
277
+ retries: dict[tuple[str, str], int] = {}
278
+ checks: dict[tuple[str, str], Mapping[str, Any]] = {}
279
+ trips: list[dict[str, Any]] = [] # FRC-B1: one per gate verdict `BACK`; the last one is the open trip
280
+ finalized: Mapping[str, Any] = {} # FRC-B3: the finalizer's recorded result
281
+ open_fails: dict[tuple[str, str, str], int] = {} # FRC-B17: failing checks not yet repaired, by (child, unit, item)
282
+ unrepaired: set[tuple[str, str]] = set() # (child, unit) with a failure a pause or a new visit cut off
283
+ for r in records:
284
+ kind = r.get("kind")
285
+ child = str(r.get("child") or "")
286
+ unit = str(r.get("unit") or _unit(str(r.get("session_key") or "")))
287
+ own = (child, unit)
288
+ item_key = "" if r.get("item") in (None, "", "none") else str(r["item"])
289
+ if kind == "check" and r.get("result") == "PASS":
290
+ open_fails.pop((child, unit, item_key), None)
291
+ elif kind == "pause" and open_fails.pop((child, unit, item_key), None):
292
+ unrepaired.add(own)
293
+ elif kind == "unit_entered":
294
+ for k in [k for k in open_fails if k[:2] == own]:
295
+ del open_fails[k]
296
+ unrepaired.add(own)
297
+ if kind == "gate" and r.get("verdict") == "BACK" and r.get("token") == "BACK":
298
+ node = str(r.get("route_target") or "")
299
+ trips.append({"child": child, "unit": unit, "to": flow.entry_unit(node) or "", "visited": set(), "count": 0})
300
+ elif trips and kind == "unit_entered":
301
+ t = trips[-1]
302
+ if r.get("entered_from") == f"back:{t['unit']}":
303
+ t["to"] = unit
304
+ if int(r.get("visit") or 1) > 1:
305
+ t["visited"].add(own) # a unit that ran before the trip back runs again
306
+ elif trips and kind == "agent_run" and own in trips[-1]["visited"]:
307
+ trips[-1]["count"] += 1
308
+ elif kind == "finalize":
309
+ finalized = r
310
+ if kind == "unit_entered":
311
+ retries[own] = 0
312
+ elif kind == "attempt_start" and r.get("session_kind") == "retry":
313
+ retries[own] = retries.get(own, 0) + 1
314
+ if retries[own] == int(params.value("retry_burst.min_retries")):
315
+ add(unit, "retry_burst")
316
+ elif kind == "agent_run" and r.get("usage_limit"): # FRC-B4: the host's, and nothing else from this session
317
+ add(unit, "usage_limit")
318
+ elif kind == "agent_run":
319
+ if r.get("infra_cause"):
320
+ code = "slow_host" if r["infra_cause"] == "slow_host" else f"infra:{r['infra_cause']}"
321
+ add(unit, code)
322
+ if r.get("timed_out") and not r.get("infra_cause") and r.get("session_kind") in ("step", "retry"):
323
+ add(unit, "step_timeout")
324
+ if r.get("error_kind") == "unknown":
325
+ add(unit, "executor_error:unknown", str(r.get("executor") or ""), str(r.get("cli_version") or ""))
326
+ for name in r.get("unknown_tools") or ():
327
+ add(unit, f"unknown_tool_name:{name}", str(r.get("executor") or ""),
328
+ str(r.get("cli_version") or ""))
329
+ elif kind == "check":
330
+ checks[own] = r
331
+ if r.get("result") == "FAIL" and not r.get("environmental"):
332
+ add(unit, f"check_fail:{unit}")
333
+ open_fails[(child, unit, item_key)] = open_fails.get((child, unit, item_key), 0) + 1
334
+ elif kind == "judgement":
335
+ for cid in r.get("blockers") or ():
336
+ add(unit, f"judge_blocked:{cid}")
337
+ if r.get("guard") == "discarded":
338
+ add(unit, "guard:discarded")
339
+ elif kind == "gate" and r.get("verdict") is None and r.get("token") == "ESCALATE":
340
+ add(unit, "judge_unparsed")
341
+ elif kind == "engine_error":
342
+ add(unit, "engine_error")
343
+ elif kind == "pause":
344
+ pk, reason = str(r.get("pause_kind") or ""), str(r.get("reason") or "")
345
+ if reason == "usage_limit": # FRC-B4: the refused session already made `usage_limit`
346
+ pass
347
+ elif reason == "tool_access": # SIL-B14: the gate writes kind `escalation` with this reason
348
+ for t in r.get("tool_access") or [{"class": "unclassified"}]:
349
+ add(unit, f"tool_access:{t.get('class') or 'unclassified'}")
350
+ elif pk == "input": # FRC-B5: an ask unit's designed pause
351
+ add(unit, "input")
352
+ elif pk == "budget":
353
+ add(unit, "loop_budget_spent" if reason == "loop_budget" else "retries_spent")
354
+ elif pk == "approval":
355
+ add(unit, "approval")
356
+ elif reason == "blocked":
357
+ c = checks.get(own)
358
+ empty = c is None or not str(c.get("evidence") or "").strip()
359
+ add(unit, "blocked_without_check" if empty else "blocked")
360
+ elif reason in ("unresolved_gap", "gap"):
361
+ add(unit, "gap_escalation")
362
+ elif reason == "no_change":
363
+ add(unit, "no_change")
364
+ elif reason == "check_repeat": # BUD-B16, SIL-B23: the same check failure twice
365
+ add(unit, "check_repeat")
366
+ elif reason.startswith("guard:") or reason in ("refused", "auth", "environmental", "upstream"):
367
+ add(unit, reason)
368
+ elif reason == "unparsed":
369
+ add(unit, "judge_unparsed")
370
+ else:
371
+ add(unit, "gap_escalation" if "gap" in reason else f"escalation:{reason or 'unknown'}")
372
+ elif kind == "run_exit":
373
+ reason = str(r.get("reason") or "")
374
+ if reason == "budget":
375
+ add("", "retries_spent")
376
+ elif reason == "person":
377
+ add("", "person_stop")
378
+ elif reason == "cost_cap":
379
+ add("", "cost_cap")
380
+ elif reason == "attempt_cap" and r.get("exit_code") == 4: # FRC-B2
381
+ add("", "attempt_cap", n=int(r.get("trips_back", len(trips)))) # CMP-B20's figure
382
+ if r.get("exit_code") == 0 and finalized: # FRC-B3: names and numbers only, no text of a step or a reason
383
+ outcome = str(finalized.get("outcome") or "")
384
+ if finalized.get("manual_steps") or outcome in ("skipped", "error", "invalid"):
385
+ add("", f"finalizer_undelivered:{outcome}")
386
+ for t in trips: # FRC-B1: the finding of the gate's unit, with the sessions the trip back began
387
+ child = t["child"]
388
+ add(t["unit"], f"trip_back:{t['to']}", n=t["count"])
389
+ unrepaired |= {(k[0], k[1]) for k in open_fails} # a failure still open at the end of the segment
390
+ child = "" # an intervention or a grant belongs to the run's own unit of that name
391
+ ivs = list(interventions)
392
+ for iv in ivs:
393
+ c = iv.get("caller") or {}
394
+ rescue = any(t.get("class") == "rescue" for t in iv.get("touches") or [])
395
+ steer = [t for t in iv.get("touches") or [] if t.get("class") == "steer"]
396
+ if rescue and c.get("decided_by") == "agent":
397
+ unit_name = str(iv.get("unit") or "")
398
+ code = f"agent_decided:{iv.get('pause_kind') or 'escalation'}"
399
+ session = str(c.get("host_session") or "")
400
+ same = bool(session) and session == str((starter or {}).get("host_session") or "") \
401
+ and str(c.get("host") or "") == str((starter or {}).get("host") or "")
402
+ key = ("", unit_name, code, "") # one finding for the group: any decision of another agent makes it a fault
403
+ classes[key] = "designed" if same and classes.get(key, "designed") == "designed" else "fault"
404
+ add(unit_name, code)
405
+ if c.get("decided_by") == "person" and (iv.get("ruling") or any(t.get("action") in ("rewind", "rerun")
406
+ for t in steer)):
407
+ add(str(iv.get("unit") or ""), "pushback")
408
+ for g in grants:
409
+ add(str(g.get("unit") or ""), f"grant_missing:{g.get('capability') or g.get('prefix')}" if g.get("used")
410
+ else f"grant_unused:{g.get('capability') or g.get('prefix')}")
411
+ return [{"unit": u, "cause": code, "count": n, **({"child": ch} if ch else {}),
412
+ **({"executor": ex} if ex else {}),
413
+ **({"recovered": (ch, u) not in unrepaired} if code.startswith("check_fail:") else {}),
414
+ **({"class": classes[(ch, u, code, ex)]} if (ch, u, code, ex) in classes else {}),
415
+ **({"executor_version": versions[(ch, u, code, ex)]} if (ch, u, code, ex) in versions else {})}
416
+ for (ch, u, code, ex), n in out.items()] + _answers(records, ivs)