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,255 @@
1
+ """The outcome file and each gate's criteria from it (OUT-B8 to OUT-B14, OUT-B22; PKG-B15, PKG-B16, PKG-B17 step 5).
2
+
3
+ Reading is model-free and read-only. The outcome gate, sign-off and the outcome record are T5.8.2 and T5.8.3.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import dataclasses
9
+ import json
10
+ from collections.abc import Mapping
11
+ from pathlib import Path
12
+ from typing import Any, Literal
13
+
14
+ from tempergraph.contracts import (
15
+ CallableRef,
16
+ CheckFinding,
17
+ CheckResult,
18
+ Criterion,
19
+ GateSpec,
20
+ IntermediateOutcome,
21
+ JudgeSpec,
22
+ OutcomeSpec,
23
+ StepSpec,
24
+ UnitSpec,
25
+ WorkflowSpec,
26
+ )
27
+ from tempergraph.model import flow
28
+ from tempergraph.model.validate import Finding
29
+
30
+ OUTCOME_FILE = "outcome.json"
31
+ VERIFIED_BY = frozenset({"check", "judge", "person", "none"})
32
+ SEVERITIES = frozenset({"blocker", "warning"})
33
+
34
+
35
+ def _criterion(raw: Any, where: str, out: list[Finding]) -> Criterion | None:
36
+ if not isinstance(raw, Mapping) or not raw.get("id") or not raw.get("text"):
37
+ out.append(Finding(code="outcome-criterion-invalid", unit=where, message="a criterion needs `id` and `text`"))
38
+ return None
39
+ by = raw.get("verified_by")
40
+ if by not in VERIFIED_BY:
41
+ out.append(Finding(code="outcome-criterion-invalid", unit=where,
42
+ message=f"{raw['id']}: `verified_by` must be check, judge, person or none"))
43
+ return None
44
+ sev = raw.get("severity", "blocker")
45
+ if sev not in SEVERITIES:
46
+ out.append(Finding(code="outcome-criterion-invalid", unit=where, message=f"{raw['id']}: severity {sev!r}"))
47
+ return None
48
+ verifier: Mapping[str, Any] = raw["verifier"] if isinstance(raw.get("verifier"), Mapping) else {}
49
+ if by == "none" and not str(verifier.get("reason") or "").strip():
50
+ out.append(Finding(code="outcome-none-unexplained", unit=where,
51
+ message=f"{raw['id']}: `verified_by: none` needs a reason"))
52
+ policy = raw.get("no_change_policy", "escalate")
53
+ return Criterion(id=str(raw["id"]), text=str(raw["text"]), check_method=str(raw.get("check_method") or ""),
54
+ severity=sev, no_change_policy=policy if policy in ("escalate", "retry") else "escalate",
55
+ unverified_system=raw.get("unverified_system"), mechanical=by == "check", verified_by=by,
56
+ verifier=dict(verifier), source=raw.get("source"),
57
+ serves=tuple(str(s) for s in raw.get("serves") or ()))
58
+
59
+
60
+ def parse_outcome(data: Any) -> OutcomeSpec | list[Finding]:
61
+ """OUT-B8, OUT-B9 and the file-only rows of OUT-B22."""
62
+ out: list[Finding] = []
63
+ if not isinstance(data, Mapping) or data.get("schema_version") != 1:
64
+ return [Finding(code="outcome-missing", unit=None, message="outcome.json is not a version 1 object")]
65
+ final = [c for c in (_criterion(r, "final", out) for r in data.get("final") or []) if c]
66
+ if not final and not out:
67
+ out.append(Finding(code="outcome-missing", unit=None, message="outcome.json has no final criterion"))
68
+ inter: dict[str, IntermediateOutcome] = {}
69
+ raw_inter: Mapping[str, Any] = data["intermediate"] if isinstance(data.get("intermediate"), Mapping) else {}
70
+ for unit, body in raw_inter.items():
71
+ body = body if isinstance(body, Mapping) else {}
72
+ crit = [c for c in (_criterion(r, str(unit), out) for r in body.get("criteria") or []) if c]
73
+ inter[str(unit)] = IntermediateOutcome(statement=str(body.get("statement") or ""), criteria=tuple(crit))
74
+ seen: set[str] = set()
75
+ for c in final + [c for io in inter.values() for c in io.criteria]:
76
+ if c.id in seen:
77
+ out.append(Finding(code="criterion-id-duplicate", unit=None, message=f"criterion id {c.id!r} twice"))
78
+ seen.add(str(c.id))
79
+ final_ids = {c.id for c in final}
80
+ for unit, io in inter.items():
81
+ for c in io.criteria:
82
+ for s in c.serves:
83
+ if s not in final_ids:
84
+ out.append(Finding(code="outcome-serves-unknown", unit=unit,
85
+ message=f"{c.id} serves {s!r}, which is not a final criterion"))
86
+ if out:
87
+ return out
88
+ check = data.get("check")
89
+ ref = None
90
+ if isinstance(check, str) and ":" in check:
91
+ mod, _, qual = check.partition(":")
92
+ ref = CallableRef(module=mod, qualname=qual)
93
+ return OutcomeSpec(schema_version=1, revision=int(data.get("revision") or 1),
94
+ statement=str(data.get("statement") or ""),
95
+ deliverables=tuple(dict(d) for d in data.get("deliverables") or () if isinstance(d, Mapping)),
96
+ final=tuple(final), intermediate=inter,
97
+ judge=dict(data["judge"]) if isinstance(data.get("judge"), Mapping) else None, check=ref,
98
+ assumptions=tuple(str(a) for a in data.get("assumptions") or ()),
99
+ revisions=tuple(dict(r) for r in data.get("revisions") or () if isinstance(r, Mapping)))
100
+
101
+
102
+ def read_outcome(package_path: Path) -> OutcomeSpec | list[Finding]:
103
+ """Read `<package>/outcome.json`; a missing or unreadable file is `outcome-missing`."""
104
+ try:
105
+ data = json.loads((package_path / OUTCOME_FILE).read_text(encoding="utf-8"))
106
+ except (OSError, ValueError) as exc:
107
+ return [Finding(code="outcome-missing", unit=None, message=f"outcome.json: {type(exc).__name__}")]
108
+ return parse_outcome(data)
109
+
110
+
111
+ def gate_criteria(outcome: OutcomeSpec, unit: str) -> list[Criterion]:
112
+ """The unit's intermediate criteria, `mechanical` set for `check` ones (OUT-AC2)."""
113
+ io = outcome.intermediate.get(unit)
114
+ return list(io.criteria) if io else []
115
+
116
+
117
+ def check_against(outcome: OutcomeSpec, spec: WorkflowSpec) -> list[Finding]:
118
+ """The unit rows of OUT-B22: an intermediate outcome for an unknown unit, or a model step with none."""
119
+ out: list[Finding] = []
120
+ for unit in outcome.intermediate:
121
+ if unit not in spec.units:
122
+ out.append(Finding(code="outcome-unit-unknown", unit=unit, message=f"{unit} is not in the workflow"))
123
+ for name, u in spec.units.items():
124
+ if u.kind in ("step", "map") and name not in outcome.intermediate:
125
+ out.append(Finding(code="outcome-unit-missing", unit=name, message=f"{name} has no intermediate outcome"))
126
+ for name, io in outcome.intermediate.items():
127
+ found = spec.units.get(name)
128
+ if found is not None and found.gate.check is None and any(c.verified_by == "check" for c in io.criteria):
129
+ out.append(Finding(code="mechanical-without-check", unit=name,
130
+ message="a `check` criterion needs the unit's gate to have a check (CHK-B15, CHK-B14, CHK-B10, CHK-B17)"))
131
+ return out
132
+
133
+
134
+ # ---------------------------------------------------------------------------------------------
135
+ # The outcome gate (OUT-B15, OUT-B16, OUT-B17)
136
+
137
+ OUTCOME_STANCE = "The request and the deliverables are the truth; everything a step said is a claim to verify."
138
+ _TIER = {"small": 1, "haiku": 1, "medium": 2, "sonnet": 2, "large": 3, "opus": 3}
139
+
140
+
141
+ def _strongest_judge_model(spec: WorkflowSpec) -> str | None:
142
+ models = [u.gate.judge.model for u in spec.units.values() if u.gate.judge is not None and u.gate.judge.model]
143
+ return max(models, key=lambda m: _TIER.get(str(m).lower(), 0)) if models else None
144
+
145
+
146
+ def outcome_unit(spec: WorkflowSpec) -> UnitSpec | None:
147
+ """The reserved `outcome` unit compiled from `outcome.json` with no declaration (PKG-B25, OUT-B15, OUT-B16, OUT-B17)."""
148
+ o = spec.outcome
149
+ if o is None or not o.final:
150
+ return None
151
+ graded = tuple(c for c in o.final if c.verified_by in ("judge", "check"))
152
+ sign_off = [{"id": c.id, "text": c.text, "role": (c.verifier or {}).get("role", ""),
153
+ "question": (c.verifier or {}).get("question", "")} for c in o.final if c.verified_by == "person"]
154
+ unverified = [{"id": c.id, "reason": (c.verifier or {}).get("reason", "")} for c in o.final
155
+ if c.verified_by == "none"]
156
+ jcfg = dict(o.judge or {})
157
+ made = deliverable_producers(spec)
158
+ every = _on_every_path(spec)
159
+ # a deliverable some path does not produce is an optional reference for the outcome judge (OUT-B15, OUT-B16, OUT-B17)
160
+ refs: dict[str, Literal["required", "optional"]] = {
161
+ str(d.get("key")): "required" if not made.get(str(d.get("key"))) or set(made[str(d.get("key"))]) & every
162
+ else "optional" for d in o.deliverables if d.get("key")}
163
+ refs.update({str(r): "required" for r in jcfg.get("references") or ()})
164
+ judge = None
165
+ if any(c.verified_by == "judge" for c in graded):
166
+ judge = JudgeSpec(stance=str(jcfg.get("stance") or OUTCOME_STANCE), references=refs,
167
+ executor=jcfg.get("executor"),
168
+ model=jcfg.get("model") or _strongest_judge_model(spec))
169
+ gate = GateSpec(check=CallableRef(module=__name__, qualname="outcome_check"), judge=judge, criteria=graded,
170
+ approval=bool(sign_off), back_targets=tuple(flow.outcome_back_targets(spec)), loop_budget=1,
171
+ retry_budget=0)
172
+ return UnitSpec(kind="step", gate=gate, step=StepSpec(tools=("read",)),
173
+ extra={"outcome": True, "sign_off": sign_off, "unverified": unverified})
174
+
175
+
176
+ def with_outcome(spec: WorkflowSpec) -> WorkflowSpec:
177
+ """The run-time spec: the declared units plus the compiled outcome unit, if the workflow has one."""
178
+ u = outcome_unit(spec)
179
+ if u is None or flow.OUTCOME_UNIT in spec.units:
180
+ return spec
181
+ return dataclasses.replace(spec, units={**spec.units, flow.OUTCOME_UNIT: u})
182
+
183
+
184
+ def deliverable_producers(spec: WorkflowSpec) -> dict[str, list[str]]:
185
+ """Each deliverable key and the units that declare they produce it."""
186
+ o = spec.outcome
187
+ out: dict[str, list[str]] = {}
188
+ for d in (o.deliverables if o else ()):
189
+ key = str(d.get("key") or "")
190
+ for name in spec.order:
191
+ u = spec.units[name]
192
+ keys = set(u.step.produces) if u.step else set()
193
+ for sc in ((u.step.before + u.step.after) if u.step else ()) + ((u.script,) if u.script else ()):
194
+ keys |= set(sc.produces)
195
+ if u.kind == "ask":
196
+ keys.add("answers")
197
+ if key in keys:
198
+ out.setdefault(key, []).append(name)
199
+ return out
200
+
201
+
202
+ def _on_every_path(spec: WorkflowSpec) -> set[str]:
203
+ """Units no route, switch, fallback or deadline can skip: a workflow with none of them runs all its units."""
204
+ skipping = any(u.route is not None or u.switch is not None or u.gate.fallback or name in spec.flow
205
+ or flow.deadline_node(spec, name) for name, u in spec.units.items())
206
+ return set() if skipping else set(spec.order)
207
+
208
+
209
+ def outcome_check(ctx: Any) -> CheckResult:
210
+ """The built-in check: every deliverable exists; then the workflow's own outcome check, if any."""
211
+ findings: list[CheckFinding] = []
212
+ deliverables = (ctx.settings or {}).get("deliverables") or []
213
+ arts = {k: v for vs in (ctx.artifacts or {}).values() if isinstance(vs, Mapping) for k, v in vs.items()}
214
+ vals = {k: v for vs in (ctx.values or {}).values() if isinstance(vs, Mapping) for k, v in vs.items()}
215
+ producers = (ctx.settings or {}).get("deliverable_producers") or {}
216
+ path = set((ctx.settings or {}).get("path_units") or ())
217
+ off_path = 0
218
+ for d in deliverables:
219
+ key, kind = str(d.get("key") or ""), str(d.get("kind") or "file")
220
+ made_by = producers.get(key) or []
221
+ if made_by and path and not path & set(made_by): # OUT-B15, OUT-B16, OUT-B17: required only on a path that produces it
222
+ off_path += 1
223
+ continue
224
+ present = key in arts or key in vals
225
+ if present and kind == "file" and key in arts:
226
+ present = (ctx.workdir / str(arts[key])).exists()
227
+ if not present:
228
+ findings.append(CheckFinding(status="fail", criterion=None, place=str(d.get("where") or key),
229
+ message=f"deliverable {key} is missing", fix=f"produce {key}"))
230
+ result: CheckResult = CheckResult(result="FAIL" if findings else "PASS", findings=findings,
231
+ evidence=f"{len(deliverables) - len(findings) - off_path} of "
232
+ f"{len(deliverables) - off_path} deliverables present"
233
+ + (f"; {off_path} not produced on this path" if off_path else ""))
234
+ ref = (ctx.settings or {}).get("outcome_check")
235
+ if ref and not findings:
236
+ mod, _, qual = str(ref).partition(":")
237
+ own = CallableRef(module=mod, qualname=qual).resolve()(ctx)
238
+ if isinstance(own, CheckResult):
239
+ own.evidence = (result.evidence + "\n" + own.evidence).strip()
240
+ return own
241
+ return result
242
+
243
+
244
+ def derived_back(spec: WorkflowSpec, failing: list[str], path: list[str]) -> str | None:
245
+ """OUT-B15, OUT-B16, OUT-B17: the earliest unit on the path whose criterion serves a failing final criterion."""
246
+ o = spec.outcome
247
+ if o is None:
248
+ return None
249
+ for unit in flow.effective_order(spec):
250
+ if unit not in path:
251
+ continue
252
+ io = o.intermediate.get(unit)
253
+ if io and any(set(c.serves) & set(failing) for c in io.criteria):
254
+ return unit
255
+ return None
@@ -0,0 +1,292 @@
1
+ """The outcome record of a thread and the workflow's uncorrected outcome measures (OUT-B18, OUT-B19, PKG, OUT (moved)).
2
+
3
+ Model-free and metadata only: statuses and ids, never criterion text from a session. Each criterion's trust is
4
+ computed by `run/outcome_trust.py` (OUT-B13, OUT-B14): a check is `deterministic` only with its must-pass and must-fail
5
+ fixtures, and a judge is `uncalibrated` until calibration accepts it (JCL-B17).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Iterable, Mapping
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from tempergraph.contracts import WorkflowSpec
16
+ from tempergraph.model import flow
17
+ from tempergraph.run.outcome_trust import trust
18
+
19
+ CHILD_ORIGIN = "subworkflow:" # SWF-B9: the origin of a child's outcome record from inside a parent, `subworkflow:<parent>`
20
+ PASSED = frozenset({"MET", "n_a", "signed"})
21
+ FAILED = frozenset({"UNMET", "PARTIAL", "declined"})
22
+
23
+
24
+ def _jsonl(path: Path) -> list[dict[str, Any]]:
25
+ try:
26
+ lines = path.read_text(encoding="utf-8").splitlines()
27
+ except OSError:
28
+ return []
29
+ out = []
30
+ for ln in lines:
31
+ try:
32
+ r = json.loads(ln)
33
+ except ValueError:
34
+ continue
35
+ if isinstance(r, dict):
36
+ out.append(r)
37
+ return out
38
+
39
+
40
+ def _status(raw: Any) -> str:
41
+ s = str(raw)
42
+ return "n_a" if s == "N/A" else s
43
+
44
+
45
+ def build(spec: WorkflowSpec, values: Mapping[str, Any], log_path: Path, child: str | None = None
46
+ ) -> dict[str, Any] | None:
47
+ """The `OutcomeRecord` of a thread so far; None for a workflow with no final criteria. `child` names the
48
+ sub-workflow unit whose child `spec` and `values` are, so only that child's records of the log are read (SWF-B8); a
49
+ parent's record keeps the record of each child that ran as `children[<unit>]` (OUT-B18)."""
50
+ o = spec.outcome
51
+ if o is None or not o.final:
52
+ return None
53
+ unit = flow.OUTCOME_UNIT
54
+ judged = (values.get("judgements") or {}).get(unit)
55
+ att = (values.get("attempts") or {}).get(unit) or {}
56
+ statuses = {s["id"]: _status(s.get("status")) for s in (judged or {}).get("statuses") or [] if s.get("id")}
57
+ check_failed = ((att.get("check") or {}).get("result")) == "FAIL"
58
+ humans = [r for r in _jsonl(log_path) if r.get("kind") == "human" and r.get("unit") == unit
59
+ and r.get("child") == child]
60
+ reached = bool(att) or judged is not None
61
+ from tempergraph.improve.calibration import accepted_for
62
+
63
+ accepted = accepted_for(spec) # JCL-B17: `calibrated` only for an `accepted` outcome judge
64
+ criteria: list[dict[str, Any]] = []
65
+ for c in o.final:
66
+ grader: Any = None
67
+ if not reached:
68
+ status = "not_judged"
69
+ elif c.verified_by in ("none", None):
70
+ status = "not_verified"
71
+ elif c.verified_by == "person":
72
+ last = humans[-1] if humans else None
73
+ word = str((last or {}).get("decision") or "")
74
+ status = "signed" if word == "proceed" else "declined" if word == "stop" else "not_judged"
75
+ grader = (last or {}).get("caller") if status != "not_judged" else None
76
+ else:
77
+ status = statuses.get(c.id) or ("UNMET" if check_failed else "not_judged")
78
+ grader = (c.verifier or {}).get("check") if c.verified_by == "check" else {
79
+ "executor": (judged or {}).get("judge_executor"), "alias": (judged or {}).get("alias")}
80
+ criteria.append({"id": c.id, "class": c.verified_by or "none", "severity": c.severity, "trust": trust(c, "outcome", spec.package_root, accepted),
81
+ "status": status, "grader": grader})
82
+ intermediate = []
83
+ for name, io in o.intermediate.items():
84
+ got = {s["id"]: _status(s.get("status")) for s in
85
+ ((values.get("judgements") or {}).get(name) or {}).get("statuses") or [] if s.get("id")}
86
+ for c in io.criteria:
87
+ if c.id in got:
88
+ intermediate.append({"unit": name, "id": c.id, "status": got[c.id]})
89
+ record: dict[str, Any] = {"revision": o.revision, "verdict": verdict(criteria, reached), "criteria": criteria,
90
+ "intermediate": intermediate, "later": []}
91
+ if child is not None: # SWF-B9: a child's record from inside a parent says so (`spec` carries the parent's name there)
92
+ record["origin"] = f"{CHILD_ORIGIN}{spec.name}"
93
+ kids = {name: c["outcome"] for name, c in ((values.get("run") or {}).get("children") or {}).items()
94
+ if isinstance(c, Mapping) and c.get("outcome")}
95
+ if kids:
96
+ record["children"] = kids
97
+ return record
98
+
99
+
100
+ def verdict(criteria: Iterable[Mapping[str, Any]], reached: bool = True) -> str:
101
+ """OUT-B18, OUT-B19: met, met_with_open, unmet, needs_person or not_reached."""
102
+ if not reached:
103
+ return "not_reached"
104
+ rows = list(criteria)
105
+ blockers = [c for c in rows if c.get("severity", "blocker") == "blocker"]
106
+ if any(c["status"] in FAILED for c in blockers):
107
+ return "unmet"
108
+ if any(c["status"] == "UNVERIFIABLE" or (c["class"] == "person" and c["status"] == "not_judged")
109
+ for c in blockers):
110
+ return "needs_person"
111
+ if all(c["status"] in PASSED for c in rows):
112
+ return "met"
113
+ return "met_with_open"
114
+
115
+
116
+ # ---------------------------------------------------------------------------------------------
117
+ # Measures per workflow version and revision (`outcome show --runs`)
118
+
119
+
120
+ def _latest(rows: Iterable[Mapping[str, Any]], workflow: str) -> dict[str, dict[str, Any]]:
121
+ """The last `run_segment` row of each thread of the workflow that carries an outcome, and the last
122
+ `child_outcome` row of each sub-workflow unit of a parent's thread that ran the workflow as its child (SWF-B9),
123
+ keyed `<thread>#<unit>`."""
124
+ out: dict[str, dict[str, Any]] = {}
125
+ for r in rows:
126
+ if r.get("workflow") != workflow or not r.get("outcome"):
127
+ continue
128
+ if r.get("kind") == "run_segment":
129
+ out[str(r.get("thread_id"))] = dict(r)
130
+ elif r.get("kind") == "child_outcome":
131
+ out[f"{r.get('thread_id')}#{r.get('child')}"] = dict(r)
132
+ return out
133
+
134
+
135
+ def later_entries(rows: Iterable[Mapping[str, Any]]) -> dict[str, list[dict[str, Any]]]:
136
+ """The `later[]` entries a pull request read appended (`outcome_later` rows), joined to their thread (OUT-B24)."""
137
+ out: dict[str, list[dict[str, Any]]] = {}
138
+ for r in rows:
139
+ if r.get("kind") == "outcome_later" and isinstance(r.get("entry"), Mapping):
140
+ out.setdefault(str(r.get("thread_id")), []).append(dict(r["entry"]))
141
+ return out
142
+
143
+
144
+ def _signals(entries: Iterable[Mapping[str, Any]]) -> list[str]:
145
+ found: list[str] = []
146
+ for e in entries:
147
+ if int((e.get("reviews") or {}).get("changes_requested") or 0) and "changes_requested" not in found:
148
+ found.append("changes_requested")
149
+ if int(e.get("files") or 0) and "follow_up_commit" not in found:
150
+ found.append("follow_up_commit")
151
+ return found
152
+
153
+
154
+ def escape_threads(latest: Mapping[str, Mapping[str, Any]], rows: Iterable[Mapping[str, Any]],
155
+ reruns: set[str]) -> set[str]:
156
+ """OUT-B19, OUT-B26: the threads of `latest` (keyed like `_latest`, each holding its `outcome`) that are escapes: a
157
+ `met` or `met_with_open` run that was rerun, or a `met` run whose `later[]` holds a `changes_requested` review or a
158
+ follow-up commit that changed a file the run wrote. The one escape function."""
159
+ entries = later_entries(rows)
160
+ out: set[str] = set()
161
+ for t, r in latest.items():
162
+ base = t.partition("#")[0]
163
+ verdict_ = (r.get("outcome") or {}).get("verdict")
164
+ rerun = verdict_ in ("met", "met_with_open") and base in reruns
165
+ if rerun or (verdict_ == "met" and _signals(entries.get(base, ()))):
166
+ out.add(t)
167
+ return out
168
+
169
+
170
+ def escape_records(spec: WorkflowSpec, ledger: Path) -> list[dict[str, Any]]:
171
+ """For harvest: each escape's thread, recorded pull request, last `later[]` entry, entry count and signals."""
172
+ rows = _jsonl(ledger)
173
+ latest = _latest(rows, spec.name)
174
+ reruns = {str(r.get("thread_id")) for r in rows if r.get("kind") == "intervention" and r.get("cause") == "rerun"}
175
+ entries = later_entries(rows)
176
+ pulls = {str(r.get("thread_id")): r["pull_request"] for r in rows
177
+ if r.get("kind") == "run_segment" and r.get("workflow") == spec.name
178
+ and isinstance(r.get("pull_request"), Mapping)}
179
+ out: list[dict[str, Any]] = []
180
+ for t in sorted(escape_threads(latest, rows, reruns)):
181
+ base = t.partition("#")[0]
182
+ ents = entries.get(base, [])
183
+ signals = _signals(ents)
184
+ if base in reruns:
185
+ signals.insert(0, "rerun")
186
+ out.append({"thread": t, "pull_request": dict(pulls.get(base) or {}), "entry": ents[-1] if ents else None,
187
+ "entries": len(ents), "signals": signals})
188
+ return out
189
+
190
+
191
+ def measures(spec: WorkflowSpec, ledger: Path, since: str | None = None) -> dict[str, Any]:
192
+ """OUT-B18, OUT-B19 measures, uncorrected, per revision; a revision is never pooled with another (OUT-B7)."""
193
+ rows = _jsonl(ledger)
194
+ if since:
195
+ rows = [r for r in rows if str(r.get("ts", "")) >= since]
196
+ latest = _latest(rows, spec.name)
197
+ reruns = {str(r.get("thread_id")) for r in rows if r.get("kind") == "intervention" and r.get("cause") == "rerun"}
198
+ escaped = escape_threads(latest, rows, reruns)
199
+ waits: dict[str, list[float]] = {}
200
+ for r in rows:
201
+ if (r.get("kind") == "intervention" and r.get("unit") == flow.OUTCOME_UNIT and r.get("wait_s") is not None
202
+ and r.get("pause_kind") == "approval"):
203
+ waits.setdefault(str(r.get("thread_id")), []).append(float(r["wait_s"]))
204
+ serving: dict[str, list[tuple[str, str]]] = {}
205
+ if spec.outcome is not None:
206
+ for name, io in spec.outcome.intermediate.items():
207
+ for c in io.criteria:
208
+ for f in c.serves:
209
+ serving.setdefault(f, []).append((name, str(c.id)))
210
+ by_rev: dict[int, list[tuple[str, dict[str, Any]]]] = {}
211
+ for tid, r in latest.items():
212
+ by_rev.setdefault(int(r["outcome"].get("revision") or 0), []).append((tid, r["outcome"]))
213
+ out = []
214
+ for rev, runs in sorted(by_rev.items()):
215
+ graded = [(t, o) for t, o in runs if o.get("verdict") != "not_reached"]
216
+ met = [(t, o) for t, o in graded if o.get("verdict") in ("met", "met_with_open")]
217
+ escapes = [t for t, _ in met if t in escaped]
218
+ not_verified = [t for t, o in graded if any(c.get("status") == "not_verified" for c in o.get("criteria", []))]
219
+ weak = sorted({c["id"] for _, o in graded for c in o.get("criteria", [])
220
+ if c.get("severity") == "blocker" and c.get("trust") in ("unverified", "uncalibrated")})
221
+ upstream = {}
222
+ for fid, serves in serving.items():
223
+ passed_up = failed_after = 0
224
+ for _, o in graded:
225
+ inter = {(i["unit"], i["id"]): i["status"] for i in o.get("intermediate", [])}
226
+ if serves and all(inter.get(s) == "MET" for s in serves):
227
+ passed_up += 1
228
+ final = next((c for c in o.get("criteria", []) if c["id"] == fid), None)
229
+ failed_after += bool(final and final["status"] in FAILED)
230
+ upstream[fid] = {"n": passed_up, "failed_after_upstream_passed": failed_after}
231
+ person = [c for _, o in graded for c in o.get("criteria", []) if c.get("class") == "person"]
232
+ out.append({
233
+ "revision": rev, "n": len(runs), "reached": len(graded),
234
+ "met_rate": round(len(met) / len(graded), 3) if graded else None,
235
+ "escape_rate": round(len(escapes) / len(met), 3) if met else None, "escapes": len(escapes),
236
+ "unverified_share": round(len(not_verified) / len(graded), 3) if graded else None,
237
+ "weak_blockers": weak, "upstream_agreement": upstream,
238
+ "sign_off": {"per_run": round(len(person) / len(graded), 2) if graded else None,
239
+ "wait_s": round(sum(sum(v) for v in waits.values()), 1)},
240
+ "corrected": None}) # judge-error correction waits on calibration (EVS-B15)
241
+ return {"schema_version": 1, "workflow": spec.name, "revisions": out}
242
+
243
+
244
+ UPSTREAM_LOW = 0.2 # failed after its serving criteria passed on at least this share of runs (release 1 default)
245
+ UPSTREAM_MIN_N = 5
246
+
247
+
248
+ def candidates(spec: WorkflowSpec, ledger: Path, since: str | None = None) -> dict[str, Any]:
249
+ """OUT-B20, OUT-B21 revision candidates, model-free: signals with thread ids and counts, never text."""
250
+ rows = _jsonl(ledger)
251
+ if since:
252
+ rows = [r for r in rows if str(r.get("ts", "")) >= since]
253
+ latest = _latest(rows, spec.name)
254
+ graded = {t: r["outcome"] for t, r in latest.items() if r["outcome"].get("verdict") != "not_reached"}
255
+ reruns = {str(r.get("thread_id")) for r in rows if r.get("kind") == "intervention" and r.get("cause") == "rerun"}
256
+ out: list[dict[str, Any]] = []
257
+
258
+ def add(signal: str, threads: Iterable[str], **extra: Any) -> None:
259
+ ts = sorted(set(threads))
260
+ out.append({"signal": signal, **extra, "threads": ts, "count": len(ts)})
261
+
262
+ rulings: dict[str, set[str]] = {}
263
+ for r in rows:
264
+ if r.get("kind") == "intervention" and r.get("workflow") == spec.name and r.get("ruling"):
265
+ rulings.setdefault(str(r.get("unit")), set()).add(str(r.get("thread_id")))
266
+ for unit, ts in sorted(rulings.items()):
267
+ if len(ts) >= 3:
268
+ add("recurring_ruling", ts, unit=unit)
269
+ escaped = escape_threads(latest, rows, reruns)
270
+ esc = [t for t in graded if t in escaped]
271
+ if esc:
272
+ add("escape", esc)
273
+ final = spec.outcome.final if spec.outcome else ()
274
+ for c in final:
275
+ def having(pred: Any, cid: str | None = c.id) -> list[str]:
276
+ return [t for t, o in graded.items() if any(x["id"] == cid and pred(x) for x in o.get("criteria", []))]
277
+
278
+ declined = having(lambda x: x["status"] == "declined")
279
+ if declined:
280
+ add("declined_sign_off", declined, criterion=c.id)
281
+ weak = having(lambda x: x.get("trust") == "unverified")
282
+ if graded and len(weak) * 2 > len(graded):
283
+ add("unverified", weak, criterion=c.id)
284
+ signed = having(lambda x: x["status"] == "signed")
285
+ if c.verified_by == "person" and len(graded) >= 20 and len(signed) == len(graded):
286
+ add("climb_ladder", signed, criterion=c.id) # OUT-B6: calibration cases to collect
287
+ for rev in measures(spec, ledger, since)["revisions"]:
288
+ for fid, up in rev["upstream_agreement"].items():
289
+ if up["n"] >= UPSTREAM_MIN_N and up["failed_after_upstream_passed"] / up["n"] >= UPSTREAM_LOW:
290
+ add("low_upstream_agreement", [], criterion=fid, revision=rev["revision"], n=up["n"],
291
+ failed=up["failed_after_upstream_passed"])
292
+ return {"schema_version": 1, "workflow": spec.name, "candidates": out}
@@ -0,0 +1,99 @@
1
+ """Trust and coverage of the outcome's criteria (OUT-B13, OUT-B14), computed and never stored.
2
+
3
+ | Trust | When |
4
+ |---|---|
5
+ | deterministic | `check`, with a must-pass and a must-fail fixture under `evals/checks/<unit>/` |
6
+ | calibrated | `judge` whose binding is `accepted` (JCL-B17, read from the package's scores) |
7
+ | uncalibrated | `judge` in any other state, or `check` without both fixtures |
8
+ | human | `person` |
9
+ | unverified | `none` |
10
+
11
+ Coverage, release 1 reading: a final criterion is covered when the outcome gate verifies it at deterministic,
12
+ calibrated or human trust, or when every model step and script unit with a gate has an intermediate
13
+ criterion serving it at such trust (OUT-B13, OUT-B14 says "on every path to the outcome gate"; release 1 flows are
14
+ routes and switches over `order`, so every gated unit stands in for every path). This reading lets a
15
+ workflow whose final criteria are judged, before any judge is calibrated, be covered by its units' checks
16
+ (SCF-B3); recorded in SCF-B11, SCF-B13, SCF-B15, SCF-B16, SCF-B17, SCF-B18, SCF-B19, SCF-B20, SCF-B22.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Callable
22
+ from dataclasses import dataclass, field
23
+ from pathlib import Path
24
+ from typing import Any
25
+
26
+ from tempergraph.contracts import Criterion, OutcomeSpec, Trust, WorkflowSpec
27
+
28
+ TRUSTED: frozenset[str] = frozenset({"deterministic", "calibrated", "human"})
29
+
30
+
31
+ def has_fixtures(root: Path | None, unit: str) -> bool:
32
+ if root is None:
33
+ return False
34
+ base = root / "evals" / "checks" / unit
35
+ return any((base / "must-pass").glob("*")) and any((base / "must-fail").glob("*"))
36
+
37
+
38
+ def trust(c: Criterion, unit: str, root: Path | None, accepted: Callable[[str], bool] = lambda gate: False) -> Trust:
39
+ """OUT-B13, OUT-B14 for one criterion on `unit` (`outcome` for a final criterion)."""
40
+ if c.verified_by == "person":
41
+ return "human"
42
+ if c.verified_by == "none":
43
+ return "unverified"
44
+ if c.verified_by == "check" or (c.verified_by is None and c.mechanical):
45
+ return "deterministic" if has_fixtures(root, unit) else "uncalibrated"
46
+ return "calibrated" if accepted(unit) else "uncalibrated"
47
+
48
+
49
+ @dataclass(kw_only=True)
50
+ class Coverage:
51
+ criterion: str
52
+ trust: Trust
53
+ covered: bool
54
+ serving: list[dict[str, Any]] = field(default_factory=list) # {unit, criterion, trust}
55
+ missing_units: list[str] = field(default_factory=list)
56
+
57
+
58
+ def _accepted(spec: WorkflowSpec) -> Callable[[str], bool]:
59
+ from tempergraph.improve.calibration import accepted_for
60
+
61
+ return accepted_for(spec)
62
+
63
+
64
+ def coverage(outcome: OutcomeSpec, spec: WorkflowSpec,
65
+ accepted: Callable[[str], bool] | None = None) -> list[Coverage]:
66
+ root = spec.package_root
67
+ accepted = accepted or _accepted(spec)
68
+ gated = [n for n in spec.order if (u := spec.units.get(n)) is not None
69
+ and (u.kind == "step" or u.gate.check is not None or u.gate.judge is not None)]
70
+ out = []
71
+ for fc in outcome.final:
72
+ fid = fc.id or ""
73
+ own = trust(fc, "outcome", root, accepted)
74
+ serving = []
75
+ for unit, io in outcome.intermediate.items():
76
+ for c in io.criteria:
77
+ if fid in c.serves:
78
+ serving.append({"unit": unit, "criterion": c.id, "trust": trust(c, unit, root, accepted)})
79
+ trusted_units = {s["unit"] for s in serving if s["trust"] in TRUSTED}
80
+ missing = [u for u in gated if u not in trusted_units]
81
+ out.append(Coverage(criterion=fid, trust=own, covered=own in TRUSTED or (bool(gated) and not missing),
82
+ serving=serving, missing_units=missing))
83
+ return out
84
+
85
+
86
+ def profile(outcome: OutcomeSpec, spec: WorkflowSpec, accepted: Callable[[str], bool] | None = None
87
+ ) -> dict[str, int]:
88
+ """Counts per trust over every criterion, final and intermediate (`outcome show`)."""
89
+ counts: dict[str, int] = {}
90
+ root = spec.package_root
91
+ accepted = accepted or _accepted(spec)
92
+ for c in outcome.final:
93
+ t = trust(c, "outcome", root, accepted)
94
+ counts[t] = counts.get(t, 0) + 1
95
+ for unit, io in outcome.intermediate.items():
96
+ for c in io.criteria:
97
+ t = trust(c, unit, root, accepted)
98
+ counts[t] = counts.get(t, 0) + 1
99
+ return counts