@deftai/directive-content 0.55.2 → 0.56.0

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 (217) hide show
  1. package/.githooks/pre-commit +143 -0
  2. package/.githooks/pre-push +121 -0
  3. package/QUICK-START.md +2 -2
  4. package/Taskfile.yml +934 -0
  5. package/UPGRADING.md +47 -1
  6. package/events/README.md +3 -3
  7. package/package.json +5 -4
  8. package/scripts/_agents_md.py +494 -0
  9. package/scripts/_cache_fetch.py +635 -0
  10. package/scripts/_cache_quota.py +529 -0
  11. package/scripts/_cache_refresh.py +163 -0
  12. package/scripts/_cache_validate.py +209 -0
  13. package/scripts/_content_root.py +42 -0
  14. package/scripts/_doctor_state.py +277 -0
  15. package/scripts/_event_detect.py +305 -0
  16. package/scripts/_events.py +514 -0
  17. package/scripts/_lifecycle_hygiene.py +568 -0
  18. package/scripts/_pathspec.py +91 -0
  19. package/scripts/_policy_show_cli.py +266 -0
  20. package/scripts/_precutover.py +92 -0
  21. package/scripts/_project_context.py +224 -0
  22. package/scripts/_project_definition_io.py +164 -0
  23. package/scripts/_relocate_snapshot.py +209 -0
  24. package/scripts/_relocate_states.py +343 -0
  25. package/scripts/_resolve_preflight_path.py +152 -0
  26. package/scripts/_safe_subprocess.py +167 -0
  27. package/scripts/_session_start_hook.py +205 -0
  28. package/scripts/_sor_gate_diff.py +365 -0
  29. package/scripts/_stdio_utf8.py +59 -0
  30. package/scripts/_triage_bootstrap_gitignore.py +904 -0
  31. package/scripts/_triage_classify_cli.py +122 -0
  32. package/scripts/_triage_queue_cli.py +625 -0
  33. package/scripts/_triage_scope_cli.py +343 -0
  34. package/scripts/_triage_scope_drift_cli.py +121 -0
  35. package/scripts/_triage_scope_ignores.py +286 -0
  36. package/scripts/_triage_scope_milestone.py +432 -0
  37. package/scripts/_triage_scope_mutations.py +337 -0
  38. package/scripts/_triage_scope_renderers.py +207 -0
  39. package/scripts/_triage_smoketest_stages.py +674 -0
  40. package/scripts/_triage_subscribe_cli.py +140 -0
  41. package/scripts/_triage_welcome_cli.py +421 -0
  42. package/scripts/_vbrief_build.py +239 -0
  43. package/scripts/_vbrief_fidelity.py +479 -0
  44. package/scripts/_vbrief_legacy.py +589 -0
  45. package/scripts/_vbrief_reconciliation.py +883 -0
  46. package/scripts/_vbrief_routing.py +277 -0
  47. package/scripts/_vbrief_safety.py +778 -0
  48. package/scripts/_vbrief_sources.py +312 -0
  49. package/scripts/_vbrief_speckit.py +262 -0
  50. package/scripts/_vbrief_story_quality.py +353 -0
  51. package/scripts/_vbrief_validation.py +299 -0
  52. package/scripts/build_dist.py +412 -0
  53. package/scripts/cache.py +1078 -0
  54. package/scripts/cache_scanner.py +745 -0
  55. package/scripts/candidates_log.py +432 -0
  56. package/scripts/capacity_backfill.py +680 -0
  57. package/scripts/capacity_show.py +653 -0
  58. package/scripts/ci_local.py +689 -0
  59. package/scripts/code_structure_validate.py +765 -0
  60. package/scripts/codebase_default_extractor.py +495 -0
  61. package/scripts/codebase_map.py +304 -0
  62. package/scripts/codebase_map_fresh.py +104 -0
  63. package/scripts/codebase_projection_registry.py +94 -0
  64. package/scripts/codebase_provider.py +582 -0
  65. package/scripts/doctor.py +2257 -0
  66. package/scripts/framework_commands.py +505 -0
  67. package/scripts/gh_rest.py +882 -0
  68. package/scripts/github_auth_modes.py +437 -0
  69. package/scripts/github_body.py +292 -0
  70. package/scripts/ip_risk.py +531 -0
  71. package/scripts/issue_emit.py +670 -0
  72. package/scripts/issue_ingest.py +1064 -0
  73. package/scripts/migrate_preflight.py +418 -0
  74. package/scripts/migrate_vbrief.py +2677 -0
  75. package/scripts/monitor_pr.py +401 -0
  76. package/scripts/pack_migrate_lessons.py +336 -0
  77. package/scripts/pack_migrate_patterns.py +254 -0
  78. package/scripts/pack_migrate_rules.py +350 -0
  79. package/scripts/pack_migrate_skills.py +423 -0
  80. package/scripts/pack_migrate_strategies.py +311 -0
  81. package/scripts/pack_migrate_swarm_spec.py +250 -0
  82. package/scripts/pack_render.py +434 -0
  83. package/scripts/packs_slice.py +712 -0
  84. package/scripts/platform_capabilities.py +336 -0
  85. package/scripts/policy.py +2826 -0
  86. package/scripts/policy_set.py +324 -0
  87. package/scripts/pr_check_closing_keywords.py +524 -0
  88. package/scripts/pr_check_protected_issues.py +267 -0
  89. package/scripts/pr_merge_readiness.py +1004 -0
  90. package/scripts/pr_wait_mergeable.py +669 -0
  91. package/scripts/prd_render.py +159 -0
  92. package/scripts/preflight_architecture_sor.py +974 -0
  93. package/scripts/preflight_branch.py +289 -0
  94. package/scripts/preflight_cache.py +974 -0
  95. package/scripts/preflight_gh.py +721 -0
  96. package/scripts/preflight_implementation.py +272 -0
  97. package/scripts/preflight_story_start.py +838 -0
  98. package/scripts/preflight_wip_cap.py +149 -0
  99. package/scripts/probe_session.py +545 -0
  100. package/scripts/project_render.py +293 -0
  101. package/scripts/quarantine_ext.py +237 -0
  102. package/scripts/reconcile_issues.py +1442 -0
  103. package/scripts/refresh-path.ps1 +107 -0
  104. package/scripts/release.py +2030 -0
  105. package/scripts/release_e2e.py +1011 -0
  106. package/scripts/release_publish.py +486 -0
  107. package/scripts/release_rollback.py +980 -0
  108. package/scripts/relocate.py +1034 -0
  109. package/scripts/resolve_changelog_unreleased.py +667 -0
  110. package/scripts/resolve_version.py +490 -0
  111. package/scripts/resume_conditions.py +706 -0
  112. package/scripts/ritual_sentinel.py +609 -0
  113. package/scripts/roadmap_render.py +635 -0
  114. package/scripts/rule_ownership_lint.py +325 -0
  115. package/scripts/scm.py +591 -0
  116. package/scripts/scope_audit_log.py +387 -0
  117. package/scripts/scope_decompose.py +654 -0
  118. package/scripts/scope_demote.py +509 -0
  119. package/scripts/scope_lifecycle.py +1126 -0
  120. package/scripts/scope_undo.py +772 -0
  121. package/scripts/session_start.py +406 -0
  122. package/scripts/setup_ghx.py +339 -0
  123. package/scripts/setup_windows.ps1 +220 -0
  124. package/scripts/slice_audit.py +585 -0
  125. package/scripts/slice_record.py +530 -0
  126. package/scripts/slice_record_existing.py +692 -0
  127. package/scripts/slug_normalize.py +178 -0
  128. package/scripts/spec_render.py +477 -0
  129. package/scripts/spec_validate.py +238 -0
  130. package/scripts/subagent_monitor.py +658 -0
  131. package/scripts/swarm_complete_cohort.py +644 -0
  132. package/scripts/swarm_launch.py +1206 -0
  133. package/scripts/swarm_readiness.py +554 -0
  134. package/scripts/swarm_verify_review_clean.py +438 -0
  135. package/scripts/swarm_worktrees.py +497 -0
  136. package/scripts/toolchain-check.py +52 -0
  137. package/scripts/triage_actions.py +871 -0
  138. package/scripts/triage_bootstrap.py +1153 -0
  139. package/scripts/triage_bulk.py +630 -0
  140. package/scripts/triage_classify.py +932 -0
  141. package/scripts/triage_help.py +1685 -0
  142. package/scripts/triage_queue.py +1944 -0
  143. package/scripts/triage_reconcile.py +581 -0
  144. package/scripts/triage_refresh.py +643 -0
  145. package/scripts/triage_scope.py +999 -0
  146. package/scripts/triage_scope_drift.py +575 -0
  147. package/scripts/triage_smoketest.py +396 -0
  148. package/scripts/triage_subscribe.py +399 -0
  149. package/scripts/triage_summary.py +1011 -0
  150. package/scripts/triage_welcome.py +1178 -0
  151. package/scripts/ts_check_lane.py +86 -0
  152. package/scripts/validate-links.py +64 -0
  153. package/scripts/validate_strategy_output.py +212 -0
  154. package/scripts/vbrief_activate.py +228 -0
  155. package/scripts/vbrief_migrate_conformance.py +368 -0
  156. package/scripts/vbrief_reconcile_graph.py +306 -0
  157. package/scripts/vbrief_reconcile_labels.py +460 -0
  158. package/scripts/vbrief_reconcile_umbrellas.py +741 -0
  159. package/scripts/vbrief_validate.py +1195 -0
  160. package/scripts/verify-stubs.py +61 -0
  161. package/scripts/verify_capacity.py +160 -0
  162. package/scripts/verify_encoding.py +699 -0
  163. package/scripts/verify_hooks_installed.py +206 -0
  164. package/scripts/verify_investigation.py +360 -0
  165. package/scripts/verify_judgment_gates.py +827 -0
  166. package/scripts/verify_no_task_runtime.py +171 -0
  167. package/scripts/verify_scm_boundary.py +509 -0
  168. package/scripts/verify_session_ritual.py +389 -0
  169. package/scripts/verify_tools.py +426 -0
  170. package/scripts/verify_vbrief_conformance.py +478 -0
  171. package/tasks/architecture.yml +13 -0
  172. package/tasks/cache.yml +69 -0
  173. package/tasks/capacity.yml +38 -0
  174. package/tasks/change.yml +46 -0
  175. package/tasks/changelog.yml +24 -0
  176. package/tasks/ci.yml +49 -0
  177. package/tasks/codebase.yml +47 -0
  178. package/tasks/commit.yml +30 -0
  179. package/tasks/core.yml +126 -0
  180. package/tasks/deployments.yml +54 -0
  181. package/tasks/framework.yml +74 -0
  182. package/tasks/install.yml +60 -0
  183. package/tasks/issue.yml +50 -0
  184. package/tasks/migrate.yml +73 -0
  185. package/tasks/packs.yml +92 -0
  186. package/tasks/policy.yml +75 -0
  187. package/tasks/pr.yml +89 -0
  188. package/tasks/prd.yml +39 -0
  189. package/tasks/project.yml +27 -0
  190. package/tasks/reconcile.yml +32 -0
  191. package/tasks/relocate.yml +56 -0
  192. package/tasks/roadmap.yml +28 -0
  193. package/tasks/scm.yml +126 -0
  194. package/tasks/scope-undo.yml +36 -0
  195. package/tasks/scope.yml +141 -0
  196. package/tasks/session.yml +19 -0
  197. package/tasks/setup.yml +37 -0
  198. package/tasks/slice.yml +69 -0
  199. package/tasks/spec.yml +41 -0
  200. package/tasks/swarm.yml +85 -0
  201. package/tasks/toolchain.yml +13 -0
  202. package/tasks/triage-actions.yml +94 -0
  203. package/tasks/triage-bootstrap.yml +43 -0
  204. package/tasks/triage-bulk.yml +75 -0
  205. package/tasks/triage-classify.yml +30 -0
  206. package/tasks/triage-queue.yml +50 -0
  207. package/tasks/triage-reconcile.yml +29 -0
  208. package/tasks/triage-scope-drift.yml +29 -0
  209. package/tasks/triage-scope.yml +31 -0
  210. package/tasks/triage-smoketest.yml +33 -0
  211. package/tasks/triage-subscribe.yml +36 -0
  212. package/tasks/triage-summary.yml +29 -0
  213. package/tasks/triage-welcome.yml +32 -0
  214. package/tasks/ts.yml +328 -0
  215. package/tasks/vbrief.yml +206 -0
  216. package/tasks/verify.yml +292 -0
  217. package/templates/agents-entry.md +1 -1
@@ -0,0 +1,585 @@
1
+ """slice_audit.py -- business logic + renderers for slice operation flags (#1132 / D13 of #1119).
2
+
3
+ The three D13 flags on ``task triage:audit`` -- ``--orphans``,
4
+ ``--slice-stalled``, ``--slice-coverage`` -- live here so
5
+ ``scripts/triage_queue.py`` stays under the 1000-line MUST cap
6
+ documented in ``coding/coding.md``. ``scripts/_triage_queue_cli.py``
7
+ delegates to the entry points below; the renderers are pure functions
8
+ that take pre-loaded inputs so tests can drive them with synthetic
9
+ fixtures.
10
+
11
+ Public surface
12
+ --------------
13
+
14
+ * :func:`compute_orphans` -- children whose umbrella is closed while
15
+ they remain open.
16
+ * :func:`compute_stalled` -- cohorts where >=1 child has merged but
17
+ >=1 sibling has not moved in N days.
18
+ * :func:`compute_coverage` -- per-umbrella ``closed/total`` rollup.
19
+ * :func:`collect_orphan_issue_numbers` -- thin wrapper returning the
20
+ set of orphan child numbers (used by ``task triage:queue`` to wire
21
+ the ``ORPHAN`` group via :class:`QueueBuildOptions`).
22
+ * :func:`render_orphans_plain` / :func:`render_orphans_json` -- and
23
+ the analogous pairs for stalled / coverage. JSON renderers emit a
24
+ stable schema that downstream consumers can script against.
25
+
26
+ The framework's slice surface is consumer-agnostic: nothing in this
27
+ module hard-codes deft-specific labels or thresholds (the
28
+ ``--days`` default lives as :data:`DEFAULT_SLICE_STALLED_DAYS` on
29
+ :mod:`triage_queue`).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import json
35
+ from collections.abc import Iterable
36
+ from dataclasses import dataclass
37
+ from datetime import UTC, datetime
38
+ from typing import Any
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Dataclasses
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class OrphanRow:
47
+ """One row in the ``--orphans`` surface.
48
+
49
+ ``umbrella_state`` carries the cached umbrella state (``open`` /
50
+ ``closed``) so the renderer can confirm what the operator already
51
+ sees -- the orphan detection joins on `closed` umbrella + `open`
52
+ child, so this field is always ``closed`` in practice but it is
53
+ surfaced for transparency in the JSON output.
54
+ """
55
+
56
+ n: int
57
+ url: str
58
+ wave: int
59
+ role: str
60
+ umbrella: int
61
+ umbrella_url: str
62
+ umbrella_state: str
63
+ slice_id: str
64
+ sliced_at: str
65
+ actor: str
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class StalledCohortRow:
70
+ """One row in the ``--slice-stalled`` surface.
71
+
72
+ ``stalled_siblings`` lists the child numbers whose latest cached
73
+ ``updated_at`` predates the cutoff. ``progressed_siblings`` lists
74
+ the merged / closed siblings that triggered the stall detection
75
+ (Wave-1 movement that left Wave-2 idle).
76
+ """
77
+
78
+ slice_id: str
79
+ umbrella: int
80
+ umbrella_url: str
81
+ sliced_at: str
82
+ progressed_siblings: tuple[int, ...]
83
+ stalled_siblings: tuple[int, ...]
84
+
85
+
86
+ @dataclass(frozen=True)
87
+ class CoverageRow:
88
+ """One row in the ``--slice-coverage`` surface.
89
+
90
+ ``closed`` counts children whose cached ``state`` is ``closed``
91
+ (covers both merged PRs and closed-without-merge issues). ``total``
92
+ is the count of children recorded in the slices.jsonl record.
93
+ """
94
+
95
+ slice_id: str
96
+ umbrella: int
97
+ umbrella_url: str
98
+ umbrella_state: str
99
+ closed: int
100
+ total: int
101
+ last_child_activity: str | None
102
+
103
+
104
+ # ---------------------------------------------------------------------------
105
+ # Slice-record loading
106
+ # ---------------------------------------------------------------------------
107
+
108
+
109
+ def load_slice_records(
110
+ slice_records_or_module: Any,
111
+ *,
112
+ path: Any = None,
113
+ ) -> list[dict[str, Any]]:
114
+ """Load slice records, tolerating a missing slice_record module.
115
+
116
+ Accepts either:
117
+
118
+ * The :mod:`slice_record` module itself (production wiring).
119
+ * A list of dicts (test fixture).
120
+ * ``None`` (slim test checkout / pre-D13 rebase) -- returns ``[]``.
121
+
122
+ The CLI shim in ``_triage_queue_cli.py`` passes the module reference
123
+ from :mod:`triage_queue` (``tq.slice_record``); tests pass either a
124
+ list literal or a :class:`types.SimpleNamespace` with a ``read_all``
125
+ callable.
126
+ """
127
+ if slice_records_or_module is None:
128
+ return []
129
+ if isinstance(slice_records_or_module, list):
130
+ return list(slice_records_or_module)
131
+ reader = getattr(slice_records_or_module, "read_all", None)
132
+ if not callable(reader):
133
+ return []
134
+ try:
135
+ records = reader(path=path)
136
+ except TypeError:
137
+ records = reader()
138
+ return [r for r in records if isinstance(r, dict)]
139
+
140
+
141
+ # ---------------------------------------------------------------------------
142
+ # Orphan detection
143
+ # ---------------------------------------------------------------------------
144
+
145
+
146
+ def _cached_state(issue: dict[str, Any] | None) -> str:
147
+ if not isinstance(issue, dict):
148
+ return ""
149
+ state = issue.get("state")
150
+ return str(state).lower() if isinstance(state, str) else ""
151
+
152
+
153
+ def compute_orphans(
154
+ slice_records: Iterable[dict[str, Any]],
155
+ issues_by_number: dict[int, dict[str, Any]],
156
+ ) -> list[OrphanRow]:
157
+ """Return one :class:`OrphanRow` per orphan child.
158
+
159
+ An orphan is a child issue whose:
160
+
161
+ * cached ``state`` is ``open``, AND
162
+ * umbrella's cached ``state`` is ``closed``.
163
+
164
+ Children missing from the cache (e.g. cache not bootstrapped /
165
+ cache fetch missed them) are skipped so the surface is not noisy
166
+ on a fresh / partial cache.
167
+
168
+ Sort order: by ``(umbrella, n)`` for stable output across runs.
169
+ """
170
+ rows: list[OrphanRow] = []
171
+ for record in slice_records:
172
+ if not isinstance(record, dict):
173
+ continue
174
+ umbrella = record.get("umbrella")
175
+ if not isinstance(umbrella, int):
176
+ continue
177
+ umbrella_state = _cached_state(issues_by_number.get(umbrella))
178
+ if umbrella_state != "closed":
179
+ continue
180
+ children = record.get("children")
181
+ if not isinstance(children, list):
182
+ continue
183
+ for child in children:
184
+ if not isinstance(child, dict):
185
+ continue
186
+ n = child.get("n")
187
+ if not isinstance(n, int):
188
+ continue
189
+ child_state = _cached_state(issues_by_number.get(n))
190
+ if child_state != "open":
191
+ continue
192
+ rows.append(
193
+ OrphanRow(
194
+ n=n,
195
+ url=str(child.get("url", "")),
196
+ wave=int(child.get("wave", 0)) if isinstance(child.get("wave"), int) else 0,
197
+ role=str(child.get("role", "")),
198
+ umbrella=umbrella,
199
+ umbrella_url=str(record.get("umbrella_url", "")),
200
+ umbrella_state=umbrella_state,
201
+ slice_id=str(record.get("slice_id", "")),
202
+ sliced_at=str(record.get("sliced_at", "")),
203
+ actor=str(record.get("actor", "")),
204
+ )
205
+ )
206
+ rows.sort(key=lambda r: (r.umbrella, r.n))
207
+ return rows
208
+
209
+
210
+ def collect_orphan_issue_numbers(
211
+ slice_records: Iterable[dict[str, Any]],
212
+ issues_by_number: dict[int, dict[str, Any]],
213
+ ) -> frozenset[int]:
214
+ """Return the frozenset of orphan child numbers.
215
+
216
+ Wraps :func:`compute_orphans` for queue-side consumers that only
217
+ need the set membership (no per-row metadata).
218
+ """
219
+ return frozenset(r.n for r in compute_orphans(slice_records, issues_by_number))
220
+
221
+
222
+ # ---------------------------------------------------------------------------
223
+ # Stalled-cohort detection
224
+ # ---------------------------------------------------------------------------
225
+
226
+
227
+ def _parse_iso8601(value: str) -> datetime | None:
228
+ if not value:
229
+ return None
230
+ try:
231
+ if value.endswith("Z"):
232
+ return datetime.fromisoformat(value[:-1]).replace(tzinfo=UTC)
233
+ return datetime.fromisoformat(value).astimezone(UTC)
234
+ except ValueError:
235
+ return None
236
+
237
+
238
+ def compute_stalled(
239
+ slice_records: Iterable[dict[str, Any]],
240
+ issues_by_number: dict[int, dict[str, Any]],
241
+ *,
242
+ days: int,
243
+ now: datetime | None = None,
244
+ ) -> list[StalledCohortRow]:
245
+ """Return :class:`StalledCohortRow` per cohort meeting the stall criterion.
246
+
247
+ Criterion (matches the issue body's wording):
248
+
249
+ * the cohort contains >=1 ``progressed`` child (cached ``state`` is
250
+ ``closed`` -- mirrors how the queue treats a merged PR), AND
251
+ * the cohort contains >=1 ``stalled`` child (cached ``state`` is
252
+ ``open`` AND cached ``updated_at`` is older than ``days`` days).
253
+
254
+ Children missing from the cache are treated as stalled (their last
255
+ movement is unknown so we surface them as a likely-orphan candidate
256
+ rather than silently dropping them).
257
+
258
+ Sort order: by ``(umbrella, slice_id)`` for stable output.
259
+ """
260
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
261
+ cutoff_seconds = days * 86400
262
+ rows: list[StalledCohortRow] = []
263
+ for record in slice_records:
264
+ if not isinstance(record, dict):
265
+ continue
266
+ umbrella = record.get("umbrella")
267
+ if not isinstance(umbrella, int):
268
+ continue
269
+ children = record.get("children")
270
+ if not isinstance(children, list):
271
+ continue
272
+ progressed: list[int] = []
273
+ stalled: list[int] = []
274
+ for child in children:
275
+ if not isinstance(child, dict):
276
+ continue
277
+ n = child.get("n")
278
+ if not isinstance(n, int):
279
+ continue
280
+ cached = issues_by_number.get(n)
281
+ state = _cached_state(cached)
282
+ if state == "closed":
283
+ progressed.append(n)
284
+ continue
285
+ if state == "open":
286
+ updated_at_raw = cached.get("updated_at") if isinstance(cached, dict) else None
287
+ last = _parse_iso8601(str(updated_at_raw) if updated_at_raw else "")
288
+ if last is None or (moment - last).total_seconds() >= cutoff_seconds:
289
+ stalled.append(n)
290
+ continue
291
+ # Cache miss for the child -- treat as stalled candidate so
292
+ # the surface flags it rather than silently dropping.
293
+ stalled.append(n)
294
+ if progressed and stalled:
295
+ rows.append(
296
+ StalledCohortRow(
297
+ slice_id=str(record.get("slice_id", "")),
298
+ umbrella=umbrella,
299
+ umbrella_url=str(record.get("umbrella_url", "")),
300
+ sliced_at=str(record.get("sliced_at", "")),
301
+ progressed_siblings=tuple(sorted(progressed)),
302
+ stalled_siblings=tuple(sorted(stalled)),
303
+ )
304
+ )
305
+ rows.sort(key=lambda r: (r.umbrella, r.slice_id))
306
+ return rows
307
+
308
+
309
+ # ---------------------------------------------------------------------------
310
+ # Coverage rollup
311
+ # ---------------------------------------------------------------------------
312
+
313
+
314
+ def compute_coverage(
315
+ slice_records: Iterable[dict[str, Any]],
316
+ issues_by_number: dict[int, dict[str, Any]],
317
+ *,
318
+ only_open_umbrella: bool = True,
319
+ ) -> list[CoverageRow]:
320
+ """Return :class:`CoverageRow` per cohort.
321
+
322
+ By default only open-umbrella cohorts are surfaced -- the issue
323
+ body's example output ("for each open umbrella in slices.jsonl,
324
+ prints <umbrella>: <closed>/<total> merged"). Pass
325
+ ``only_open_umbrella=False`` to surface every cohort (used by JSON
326
+ consumers + the closed-umbrella orphan cross-check).
327
+
328
+ Sort order: by ``(umbrella, slice_id)`` for stable output.
329
+ """
330
+ rows: list[CoverageRow] = []
331
+ for record in slice_records:
332
+ if not isinstance(record, dict):
333
+ continue
334
+ umbrella = record.get("umbrella")
335
+ if not isinstance(umbrella, int):
336
+ continue
337
+ umbrella_state = _cached_state(issues_by_number.get(umbrella))
338
+ if only_open_umbrella and umbrella_state and umbrella_state != "open":
339
+ continue
340
+ children = record.get("children")
341
+ if not isinstance(children, list):
342
+ continue
343
+ total = 0
344
+ closed = 0
345
+ last_activity: datetime | None = None
346
+ for child in children:
347
+ if not isinstance(child, dict):
348
+ continue
349
+ n = child.get("n")
350
+ if not isinstance(n, int):
351
+ continue
352
+ total += 1
353
+ cached = issues_by_number.get(n) or {}
354
+ state = _cached_state(cached)
355
+ if state == "closed":
356
+ closed += 1
357
+ updated_at_raw = cached.get("updated_at") if isinstance(cached, dict) else None
358
+ last = _parse_iso8601(str(updated_at_raw) if updated_at_raw else "")
359
+ if last is not None and (last_activity is None or last > last_activity):
360
+ last_activity = last
361
+ if total == 0:
362
+ continue
363
+ rows.append(
364
+ CoverageRow(
365
+ slice_id=str(record.get("slice_id", "")),
366
+ umbrella=umbrella,
367
+ umbrella_url=str(record.get("umbrella_url", "")),
368
+ umbrella_state=umbrella_state or "unknown",
369
+ closed=closed,
370
+ total=total,
371
+ last_child_activity=(
372
+ last_activity.strftime("%Y-%m-%dT%H:%M:%SZ")
373
+ if last_activity is not None
374
+ else None
375
+ ),
376
+ )
377
+ )
378
+ rows.sort(key=lambda r: (r.umbrella, r.slice_id))
379
+ return rows
380
+
381
+
382
+ # ---------------------------------------------------------------------------
383
+ # Renderers
384
+ # ---------------------------------------------------------------------------
385
+
386
+
387
+ def _human_age(sliced_at: str, *, now: datetime | None = None) -> str:
388
+ moment = (now or datetime.now(UTC)).astimezone(UTC)
389
+ parsed = _parse_iso8601(sliced_at)
390
+ if parsed is None:
391
+ return ""
392
+ delta = moment - parsed
393
+ return f"{int(delta.total_seconds() // 86400)}d ago"
394
+
395
+
396
+ def render_orphans_plain(
397
+ rows: Iterable[OrphanRow],
398
+ *,
399
+ repo: str | None,
400
+ now: datetime | None = None,
401
+ ) -> str:
402
+ rows_list = list(rows)
403
+ lines: list[str] = []
404
+ header = "triage:audit --orphans"
405
+ if repo:
406
+ header += f" -- {repo}"
407
+ lines.append(header)
408
+ lines.append("")
409
+ if not rows_list:
410
+ lines.append(" (no orphans detected -- every open child still has an open umbrella)")
411
+ return "\n".join(lines)
412
+ for row in rows_list:
413
+ age = _human_age(row.sliced_at, now=now)
414
+ age_suffix = f", {age}" if age else ""
415
+ lines.append(
416
+ f" [ORPHAN] #{row.n} -- Wave-{row.wave} of #{row.umbrella} "
417
+ f"({row.actor}{age_suffix}) -- status:open umbrella:closed"
418
+ )
419
+ return "\n".join(lines)
420
+
421
+
422
+ def render_orphans_json(
423
+ rows: Iterable[OrphanRow],
424
+ *,
425
+ repo: str | None,
426
+ generated_at: datetime | None = None,
427
+ ) -> str:
428
+ rows_list = list(rows)
429
+ payload = {
430
+ "generated_at": (generated_at or datetime.now(UTC))
431
+ .astimezone(UTC)
432
+ .strftime("%Y-%m-%dT%H:%M:%SZ"),
433
+ "repo": repo,
434
+ "surface": "orphans",
435
+ "entry_count": len(rows_list),
436
+ "entries": [
437
+ {
438
+ "n": r.n,
439
+ "url": r.url,
440
+ "wave": r.wave,
441
+ "role": r.role,
442
+ "umbrella": r.umbrella,
443
+ "umbrella_url": r.umbrella_url,
444
+ "umbrella_state": r.umbrella_state,
445
+ "slice_id": r.slice_id,
446
+ "sliced_at": r.sliced_at,
447
+ "actor": r.actor,
448
+ }
449
+ for r in rows_list
450
+ ],
451
+ }
452
+ return json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True)
453
+
454
+
455
+ def render_stalled_plain(
456
+ rows: Iterable[StalledCohortRow],
457
+ *,
458
+ repo: str | None,
459
+ days: int,
460
+ ) -> str:
461
+ rows_list = list(rows)
462
+ lines: list[str] = []
463
+ header = f"triage:audit --slice-stalled --days {days}"
464
+ if repo:
465
+ header += f" -- {repo}"
466
+ lines.append(header)
467
+ lines.append("")
468
+ if not rows_list:
469
+ lines.append(" (no stalled cohorts detected)")
470
+ return "\n".join(lines)
471
+ for row in rows_list:
472
+ prog = ", ".join(f"#{n}" for n in row.progressed_siblings) or "<none>"
473
+ stalled = ", ".join(f"#{n}" for n in row.stalled_siblings) or "<none>"
474
+ lines.append(
475
+ f" [STALLED] umbrella:#{row.umbrella} slice:{row.slice_id[:8]} "
476
+ f"progressed=[{prog}] stalled=[{stalled}]"
477
+ )
478
+ return "\n".join(lines)
479
+
480
+
481
+ def render_stalled_json(
482
+ rows: Iterable[StalledCohortRow],
483
+ *,
484
+ repo: str | None,
485
+ days: int,
486
+ generated_at: datetime | None = None,
487
+ ) -> str:
488
+ rows_list = list(rows)
489
+ payload = {
490
+ "generated_at": (generated_at or datetime.now(UTC))
491
+ .astimezone(UTC)
492
+ .strftime("%Y-%m-%dT%H:%M:%SZ"),
493
+ "repo": repo,
494
+ "surface": "slice-stalled",
495
+ "days": days,
496
+ "entry_count": len(rows_list),
497
+ "entries": [
498
+ {
499
+ "slice_id": r.slice_id,
500
+ "umbrella": r.umbrella,
501
+ "umbrella_url": r.umbrella_url,
502
+ "sliced_at": r.sliced_at,
503
+ "progressed_siblings": list(r.progressed_siblings),
504
+ "stalled_siblings": list(r.stalled_siblings),
505
+ }
506
+ for r in rows_list
507
+ ],
508
+ }
509
+ return json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True)
510
+
511
+
512
+ def render_coverage_plain(
513
+ rows: Iterable[CoverageRow],
514
+ *,
515
+ repo: str | None,
516
+ now: datetime | None = None,
517
+ ) -> str:
518
+ rows_list = list(rows)
519
+ lines: list[str] = []
520
+ header = "triage:audit --slice-coverage"
521
+ if repo:
522
+ header += f" -- {repo}"
523
+ lines.append(header)
524
+ lines.append("")
525
+ if not rows_list:
526
+ lines.append(" (no open-umbrella cohorts found in slices.jsonl)")
527
+ return "\n".join(lines)
528
+ for row in rows_list:
529
+ last_hint = ""
530
+ if row.last_child_activity:
531
+ age = _human_age(row.last_child_activity, now=now)
532
+ if age:
533
+ last_hint = f" (last child activity: {age})"
534
+ lines.append(
535
+ f" #{row.umbrella}: {row.closed}/{row.total} children merged{last_hint}"
536
+ )
537
+ return "\n".join(lines)
538
+
539
+
540
+ def render_coverage_json(
541
+ rows: Iterable[CoverageRow],
542
+ *,
543
+ repo: str | None,
544
+ generated_at: datetime | None = None,
545
+ ) -> str:
546
+ rows_list = list(rows)
547
+ payload = {
548
+ "generated_at": (generated_at or datetime.now(UTC))
549
+ .astimezone(UTC)
550
+ .strftime("%Y-%m-%dT%H:%M:%SZ"),
551
+ "repo": repo,
552
+ "surface": "slice-coverage",
553
+ "entry_count": len(rows_list),
554
+ "entries": [
555
+ {
556
+ "slice_id": r.slice_id,
557
+ "umbrella": r.umbrella,
558
+ "umbrella_url": r.umbrella_url,
559
+ "umbrella_state": r.umbrella_state,
560
+ "closed": r.closed,
561
+ "total": r.total,
562
+ "last_child_activity": r.last_child_activity,
563
+ }
564
+ for r in rows_list
565
+ ],
566
+ }
567
+ return json.dumps(payload, indent=2, ensure_ascii=False, sort_keys=True)
568
+
569
+
570
+ __all__ = [
571
+ "CoverageRow",
572
+ "OrphanRow",
573
+ "StalledCohortRow",
574
+ "collect_orphan_issue_numbers",
575
+ "compute_coverage",
576
+ "compute_orphans",
577
+ "compute_stalled",
578
+ "load_slice_records",
579
+ "render_coverage_json",
580
+ "render_coverage_plain",
581
+ "render_orphans_json",
582
+ "render_orphans_plain",
583
+ "render_stalled_json",
584
+ "render_stalled_plain",
585
+ ]