@deftai/directive-content 0.59.0 → 0.61.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 (190) hide show
  1. package/.githooks/pre-commit +10 -128
  2. package/.githooks/pre-push +8 -108
  3. package/Taskfile.yml +48 -58
  4. package/UPGRADING.md +19 -3
  5. package/docs/assets/directive-lifecycle-diagram.png +0 -0
  6. package/docs/directive-lifecycle.md +73 -0
  7. package/docs/getting-started.md +5 -1
  8. package/package.json +3 -3
  9. package/packs/skills/skills-pack-0.1.json +1 -1
  10. package/packs/strategies/strategies-pack-0.1.json +19 -19
  11. package/scm/github.md +37 -6
  12. package/skills/deft-directive-setup/SKILL.md +24 -15
  13. package/strategies/speckit.md +14 -14
  14. package/strategies/v0-20-contract.md +12 -1
  15. package/tasks/change.yml +16 -31
  16. package/tasks/ci.yml +8 -0
  17. package/tasks/commit.yml +12 -19
  18. package/tasks/core.yml +10 -0
  19. package/tasks/engine.yml +42 -0
  20. package/tasks/framework.yml +3 -0
  21. package/tasks/install.yml +20 -19
  22. package/tasks/migrate.yml +26 -15
  23. package/tasks/project.yml +26 -0
  24. package/tasks/toolchain.yml +15 -5
  25. package/tasks/vbrief.yml +4 -3
  26. package/tasks/verify.yml +12 -14
  27. package/templates/agents-entry.md +1 -1
  28. package/scripts/_agents_md.py +0 -494
  29. package/scripts/_cache_fetch.py +0 -635
  30. package/scripts/_cache_quota.py +0 -529
  31. package/scripts/_cache_refresh.py +0 -163
  32. package/scripts/_cache_validate.py +0 -209
  33. package/scripts/_content_root.py +0 -42
  34. package/scripts/_doctor_state.py +0 -277
  35. package/scripts/_event_detect.py +0 -305
  36. package/scripts/_events.py +0 -514
  37. package/scripts/_lifecycle_hygiene.py +0 -568
  38. package/scripts/_pathspec.py +0 -91
  39. package/scripts/_policy_show_cli.py +0 -266
  40. package/scripts/_precutover.py +0 -92
  41. package/scripts/_project_context.py +0 -224
  42. package/scripts/_project_definition_io.py +0 -164
  43. package/scripts/_relocate_snapshot.py +0 -209
  44. package/scripts/_relocate_states.py +0 -343
  45. package/scripts/_resolve_preflight_path.py +0 -152
  46. package/scripts/_safe_subprocess.py +0 -167
  47. package/scripts/_session_start_hook.py +0 -205
  48. package/scripts/_sor_gate_diff.py +0 -365
  49. package/scripts/_stdio_utf8.py +0 -59
  50. package/scripts/_triage_bootstrap_gitignore.py +0 -904
  51. package/scripts/_triage_classify_cli.py +0 -122
  52. package/scripts/_triage_queue_cli.py +0 -625
  53. package/scripts/_triage_scope_cli.py +0 -343
  54. package/scripts/_triage_scope_drift_cli.py +0 -121
  55. package/scripts/_triage_scope_ignores.py +0 -286
  56. package/scripts/_triage_scope_milestone.py +0 -432
  57. package/scripts/_triage_scope_mutations.py +0 -337
  58. package/scripts/_triage_scope_renderers.py +0 -207
  59. package/scripts/_triage_smoketest_stages.py +0 -674
  60. package/scripts/_triage_subscribe_cli.py +0 -140
  61. package/scripts/_triage_welcome_cli.py +0 -421
  62. package/scripts/_vbrief_build.py +0 -239
  63. package/scripts/_vbrief_fidelity.py +0 -479
  64. package/scripts/_vbrief_legacy.py +0 -589
  65. package/scripts/_vbrief_reconciliation.py +0 -883
  66. package/scripts/_vbrief_routing.py +0 -277
  67. package/scripts/_vbrief_safety.py +0 -778
  68. package/scripts/_vbrief_sources.py +0 -312
  69. package/scripts/_vbrief_speckit.py +0 -262
  70. package/scripts/_vbrief_story_quality.py +0 -353
  71. package/scripts/_vbrief_validation.py +0 -299
  72. package/scripts/build_dist.py +0 -412
  73. package/scripts/cache.py +0 -1078
  74. package/scripts/cache_scanner.py +0 -745
  75. package/scripts/candidates_log.py +0 -432
  76. package/scripts/capacity_backfill.py +0 -680
  77. package/scripts/capacity_show.py +0 -653
  78. package/scripts/ci_local.py +0 -689
  79. package/scripts/code_structure_validate.py +0 -765
  80. package/scripts/codebase_default_extractor.py +0 -495
  81. package/scripts/codebase_map.py +0 -304
  82. package/scripts/codebase_map_fresh.py +0 -104
  83. package/scripts/codebase_projection_registry.py +0 -94
  84. package/scripts/codebase_provider.py +0 -582
  85. package/scripts/doctor.py +0 -2552
  86. package/scripts/framework_commands.py +0 -505
  87. package/scripts/gh_rest.py +0 -882
  88. package/scripts/github_auth_modes.py +0 -437
  89. package/scripts/github_body.py +0 -292
  90. package/scripts/ip_risk.py +0 -531
  91. package/scripts/issue_emit.py +0 -670
  92. package/scripts/issue_ingest.py +0 -1064
  93. package/scripts/migrate_preflight.py +0 -418
  94. package/scripts/migrate_vbrief.py +0 -2677
  95. package/scripts/monitor_pr.py +0 -401
  96. package/scripts/pack_migrate_lessons.py +0 -336
  97. package/scripts/pack_migrate_patterns.py +0 -254
  98. package/scripts/pack_migrate_rules.py +0 -350
  99. package/scripts/pack_migrate_skills.py +0 -423
  100. package/scripts/pack_migrate_strategies.py +0 -311
  101. package/scripts/pack_migrate_swarm_spec.py +0 -250
  102. package/scripts/pack_render.py +0 -434
  103. package/scripts/packs_slice.py +0 -712
  104. package/scripts/platform_capabilities.py +0 -336
  105. package/scripts/policy.py +0 -2826
  106. package/scripts/policy_set.py +0 -324
  107. package/scripts/pr_check_closing_keywords.py +0 -524
  108. package/scripts/pr_check_protected_issues.py +0 -267
  109. package/scripts/pr_merge_readiness.py +0 -1004
  110. package/scripts/pr_wait_mergeable.py +0 -669
  111. package/scripts/prd_render.py +0 -159
  112. package/scripts/preflight_architecture_sor.py +0 -974
  113. package/scripts/preflight_branch.py +0 -289
  114. package/scripts/preflight_cache.py +0 -974
  115. package/scripts/preflight_gh.py +0 -721
  116. package/scripts/preflight_implementation.py +0 -272
  117. package/scripts/preflight_story_start.py +0 -838
  118. package/scripts/preflight_wip_cap.py +0 -149
  119. package/scripts/probe_session.py +0 -545
  120. package/scripts/project_render.py +0 -293
  121. package/scripts/quarantine_ext.py +0 -237
  122. package/scripts/reconcile_issues.py +0 -1442
  123. package/scripts/refresh-path.ps1 +0 -107
  124. package/scripts/release.py +0 -2030
  125. package/scripts/release_e2e.py +0 -1011
  126. package/scripts/release_publish.py +0 -486
  127. package/scripts/release_rollback.py +0 -980
  128. package/scripts/relocate.py +0 -1034
  129. package/scripts/resolve_changelog_unreleased.py +0 -667
  130. package/scripts/resolve_version.py +0 -490
  131. package/scripts/resume_conditions.py +0 -706
  132. package/scripts/ritual_sentinel.py +0 -609
  133. package/scripts/roadmap_render.py +0 -635
  134. package/scripts/rule_ownership_lint.py +0 -325
  135. package/scripts/scm.py +0 -591
  136. package/scripts/scope_audit_log.py +0 -387
  137. package/scripts/scope_decompose.py +0 -654
  138. package/scripts/scope_demote.py +0 -509
  139. package/scripts/scope_lifecycle.py +0 -1126
  140. package/scripts/scope_undo.py +0 -772
  141. package/scripts/session_start.py +0 -406
  142. package/scripts/setup_ghx.py +0 -339
  143. package/scripts/setup_windows.ps1 +0 -220
  144. package/scripts/slice_audit.py +0 -585
  145. package/scripts/slice_record.py +0 -530
  146. package/scripts/slice_record_existing.py +0 -692
  147. package/scripts/slug_normalize.py +0 -178
  148. package/scripts/spec_render.py +0 -477
  149. package/scripts/spec_validate.py +0 -238
  150. package/scripts/subagent_monitor.py +0 -658
  151. package/scripts/swarm_complete_cohort.py +0 -644
  152. package/scripts/swarm_launch.py +0 -1206
  153. package/scripts/swarm_readiness.py +0 -554
  154. package/scripts/swarm_verify_review_clean.py +0 -438
  155. package/scripts/swarm_worktrees.py +0 -497
  156. package/scripts/toolchain-check.py +0 -52
  157. package/scripts/triage_actions.py +0 -871
  158. package/scripts/triage_bootstrap.py +0 -1153
  159. package/scripts/triage_bulk.py +0 -630
  160. package/scripts/triage_classify.py +0 -932
  161. package/scripts/triage_help.py +0 -1685
  162. package/scripts/triage_queue.py +0 -1944
  163. package/scripts/triage_reconcile.py +0 -581
  164. package/scripts/triage_refresh.py +0 -643
  165. package/scripts/triage_scope.py +0 -999
  166. package/scripts/triage_scope_drift.py +0 -575
  167. package/scripts/triage_smoketest.py +0 -396
  168. package/scripts/triage_subscribe.py +0 -399
  169. package/scripts/triage_summary.py +0 -1011
  170. package/scripts/triage_welcome.py +0 -1178
  171. package/scripts/ts_check_lane.py +0 -86
  172. package/scripts/validate-links.py +0 -64
  173. package/scripts/validate_strategy_output.py +0 -212
  174. package/scripts/vbrief_activate.py +0 -228
  175. package/scripts/vbrief_migrate_conformance.py +0 -368
  176. package/scripts/vbrief_reconcile_graph.py +0 -306
  177. package/scripts/vbrief_reconcile_labels.py +0 -460
  178. package/scripts/vbrief_reconcile_umbrellas.py +0 -741
  179. package/scripts/vbrief_validate.py +0 -1144
  180. package/scripts/verify-stubs.py +0 -61
  181. package/scripts/verify_capacity.py +0 -160
  182. package/scripts/verify_encoding.py +0 -699
  183. package/scripts/verify_hooks_installed.py +0 -206
  184. package/scripts/verify_investigation.py +0 -360
  185. package/scripts/verify_judgment_gates.py +0 -827
  186. package/scripts/verify_no_task_runtime.py +0 -171
  187. package/scripts/verify_scm_boundary.py +0 -509
  188. package/scripts/verify_session_ritual.py +0 -389
  189. package/scripts/verify_tools.py +0 -426
  190. package/scripts/verify_vbrief_conformance.py +0 -478
@@ -1,401 +0,0 @@
1
- #!/usr/bin/env python3
2
- """monitor_pr.py -- thin "wait until ready" helper for long-running PR monitors (#1368).
3
-
4
- Background
5
- ----------
6
- Long-running monitors during the #1166 swarm cascade looped on
7
- ``scripts/pr_merge_readiness.py`` and went blind for ~15+ minutes when a
8
- single ``gh`` capture returned empty / malformed stdout under the Grok
9
- Build harness. The #1366 ``_safe_subprocess.run_text`` helper closes the
10
- ``UnicodeDecodeError`` root cause; #1368 adds a layered fallback chain to
11
- ``pr_merge_readiness.py`` so a *single* gh failure no longer blinds the
12
- monitor.
13
-
14
- This script is the consumer-side counterpart -- a small, deterministic
15
- "wait until the PR is CLEAN" loop that:
16
-
17
- * sleeps with an **adaptive cadence** (~1 minute on the first few polls,
18
- then ~3 minutes, then ~5 minutes -- mirroring the cadence prescribed
19
- in ``skills/deft-directive-review-cycle/SKILL.md`` Step 4 but at the
20
- longer timescales appropriate for a *monitor* watching a swarm
21
- cascade, not a single Greptile review pass);
22
-
23
- * **tolerates fallback responses** -- a ``via="fallback1"`` /
24
- ``via="fallback2"`` / ``via="error"`` result is treated as "keep
25
- polling", never as a terminal verdict;
26
-
27
- * **exits 0 only on a primary or fallback1 CLEAN** -- ``via="fallback2"``
28
- is the coarse last-resort signal (see ``scripts/pr_merge_readiness.py``
29
- module docstring) and is NEVER a CLEAN verdict.
30
-
31
- The helper writes one terse status line per poll to stderr so an
32
- orchestrator's transcript shows progress, and the final verdict to
33
- stdout (JSON when ``--json`` is passed, human-readable otherwise) so a
34
- machine-readable summary survives the loop.
35
-
36
- Subprocess capture routes through :func:`scripts._safe_subprocess.run_text`
37
- per the ``AGENTS.md`` `## Safe subprocess capture (#1366)` rule.
38
-
39
- Usage
40
- -----
41
- uv run python scripts/monitor_pr.py 1363 --repo deftai/directive
42
- uv run python scripts/monitor_pr.py 1363 --repo deftai/directive --cap-minutes 30 --json
43
-
44
- Exit codes
45
- ----------
46
- 0 -- PR reached a primary/fallback1 CLEAN verdict (merge-ready)
47
- 1 -- poll cap reached without a CLEAN verdict
48
- 2 -- configuration error (gh missing on the monitor host, invalid args)
49
- 3 -- PR was merged or closed before reaching CLEAN (terminal lifecycle)
50
- """
51
-
52
- from __future__ import annotations
53
-
54
- import argparse
55
- import json
56
- import os
57
- import sys
58
- import time
59
- from dataclasses import dataclass
60
- from pathlib import Path
61
-
62
- # Make sibling scripts importable both when run as __main__ and when imported by tests.
63
- sys.path.insert(0, str(Path(__file__).resolve().parent))
64
-
65
- # UTF-8-safe subprocess capture (#1366) -- per AGENTS.md
66
- # ``## Safe subprocess capture (#1366)``, any new script that captures
67
- # gh / python subprocess output MUST route the call through this helper.
68
- from _safe_subprocess import run_text # noqa: E402
69
-
70
- # ---- Exit codes -------------------------------------------------------------
71
-
72
- EXIT_CLEAN = 0
73
- EXIT_CAP_REACHED = 1
74
- EXIT_CONFIG_ERROR = 2
75
- EXIT_PR_TERMINAL = 3
76
-
77
- # ---- Adaptive cadence -------------------------------------------------------
78
-
79
- # Cadence sequence (seconds). The first few polls run at ~1 minute so
80
- # fast CLEAN exits are caught quickly; the loop then relaxes to ~3 and
81
- # ~5 minutes per poll because Greptile re-reviews on a rebase cascade
82
- # routinely take 2-5 minutes per branch and there is no value in
83
- # polling more frequently than the upstream cadence (see
84
- # ``skills/deft-directive-swarm/SKILL.md`` Phase 6 Step 1).
85
- #
86
- # Tuple shape: ``(interval_seconds, repeats)``. After all entries are
87
- # consumed the last interval is held indefinitely until the poll cap is
88
- # reached.
89
- _DEFAULT_CADENCE: tuple[tuple[int, int], ...] = (
90
- (60, 3), # 3 polls at ~1 minute
91
- (180, 3), # 3 polls at ~3 minutes
92
- (300, 99), # remaining polls at ~5 minutes
93
- )
94
-
95
-
96
- def _cadence_intervals(
97
- cadence: tuple[tuple[int, int], ...] = _DEFAULT_CADENCE,
98
- ) -> list[int]:
99
- """Expand the cadence tuple into a flat list of per-poll intervals.
100
-
101
- The last entry's repeat count is treated as a soft ceiling -- once the
102
- list is exhausted the caller is expected to break out via the
103
- ``--cap-minutes`` total-elapsed limit, not by polling forever.
104
- """
105
- intervals: list[int] = []
106
- for interval, repeats in cadence:
107
- intervals.extend([interval] * repeats)
108
- return intervals
109
-
110
-
111
- # ---- Readiness call ---------------------------------------------------------
112
-
113
-
114
- @dataclass
115
- class PollResult:
116
- """One poll iteration's outcome."""
117
- exit_code: int
118
- payload: dict
119
- raw_stdout: str
120
- raw_stderr: str
121
-
122
-
123
- def _readiness_script_path() -> Path:
124
- """Locate ``scripts/pr_merge_readiness.py`` relative to this helper."""
125
- return Path(__file__).resolve().parent / "pr_merge_readiness.py"
126
-
127
-
128
- def call_readiness(
129
- pr_number: int,
130
- repo: str,
131
- *,
132
- python_executable: str | None = None,
133
- timeout: float = 90,
134
- ) -> PollResult:
135
- """Run ``pr_merge_readiness.py --json`` once and parse the verdict.
136
-
137
- Always returns a :class:`PollResult` -- a transient gh failure becomes
138
- a ``via="error"`` payload that the caller treats as "keep polling".
139
- The helper never raises on a ``pr_merge_readiness`` non-zero exit
140
- because the monitor must be able to step forward through transient
141
- failures without going blind.
142
- """
143
- python = python_executable or sys.executable
144
- cmd = [
145
- python,
146
- str(_readiness_script_path()),
147
- str(pr_number),
148
- "--repo",
149
- repo,
150
- "--json",
151
- ]
152
- try:
153
- result = run_text(cmd, timeout=timeout)
154
- except FileNotFoundError as exc:
155
- return PollResult(
156
- exit_code=EXIT_CONFIG_ERROR,
157
- payload={
158
- "via": "error",
159
- "merge_ready": False,
160
- "error": f"python executable not found: {exc}",
161
- },
162
- raw_stdout="",
163
- raw_stderr=str(exc),
164
- )
165
- except Exception as exc: # pragma: no cover -- timeout / OS-level errors
166
- return PollResult(
167
- exit_code=EXIT_CONFIG_ERROR,
168
- payload={
169
- "via": "error",
170
- "merge_ready": False,
171
- "error": f"unexpected exception running readiness: {exc}",
172
- },
173
- raw_stdout="",
174
- raw_stderr=str(exc),
175
- )
176
-
177
- payload: dict
178
- if result.stdout.strip():
179
- try:
180
- payload = json.loads(result.stdout)
181
- except json.JSONDecodeError:
182
- payload = {
183
- "via": "error",
184
- "merge_ready": False,
185
- "error": "pr_merge_readiness emitted non-JSON stdout",
186
- "raw_stdout_excerpt": result.stdout[:200],
187
- }
188
- else:
189
- payload = {
190
- "via": "error",
191
- "merge_ready": False,
192
- "error": "pr_merge_readiness emitted empty stdout",
193
- }
194
-
195
- return PollResult(
196
- exit_code=result.returncode,
197
- payload=payload,
198
- raw_stdout=result.stdout,
199
- raw_stderr=result.stderr,
200
- )
201
-
202
-
203
- # ---- Loop -------------------------------------------------------------------
204
-
205
-
206
- def _format_poll_status(poll_index: int, poll_result: PollResult) -> str:
207
- """One-line stderr status mirror per poll."""
208
- payload = poll_result.payload
209
- via = payload.get("via", "?")
210
- merge_ready = payload.get("merge_ready", False)
211
- head_sha = payload.get("head_sha") or "<unknown>"
212
- if isinstance(head_sha, str):
213
- head_sha = head_sha[:12]
214
- failures = payload.get("failures") or []
215
- first_failure = failures[0] if failures else ""
216
- label = "CLEAN" if merge_ready else "BLOCKED"
217
- return (
218
- f"[monitor_pr] poll #{poll_index} via={via} head={head_sha} "
219
- f"{label} ({len(failures)} failures)"
220
- + (f" -- {first_failure[:80]}" if first_failure else "")
221
- )
222
-
223
-
224
- def _is_terminal_pr_state(payload: dict) -> bool:
225
- """Detect a merged / closed PR via the fallback2 partial_data.
226
-
227
- Fallback2 carries ``pr_state`` and ``merged`` so a monitor that hits
228
- the coarse-signal layer after the PR was merged out from under it
229
- can exit cleanly rather than waiting on a CLEAN that will never
230
- come.
231
- """
232
- partial = payload.get("partial_data") or {}
233
- # A closed-but-not-merged PR is also terminal -- the monitor cannot reach
234
- # CLEAN on a PR that the operator has rejected, so collapse both cases
235
- # into a single boolean expression (#1368 follow-up: ruff SIM103).
236
- return partial.get("merged") is True or partial.get("pr_state") == "closed"
237
-
238
-
239
- def monitor(
240
- pr_number: int,
241
- repo: str,
242
- *,
243
- cap_minutes: float = 60,
244
- cadence: tuple[tuple[int, int], ...] = _DEFAULT_CADENCE,
245
- sleep_fn=time.sleep,
246
- clock_fn=time.monotonic,
247
- call_readiness_fn=call_readiness,
248
- ) -> tuple[int, dict, int]:
249
- """Loop ``pr_merge_readiness`` with adaptive cadence until CLEAN / cap / terminal.
250
-
251
- Returns ``(exit_code, last_payload, poll_count)``. ``last_payload`` is
252
- the final ``pr_merge_readiness`` JSON envelope so callers can attach
253
- diagnostics to their own report.
254
-
255
- ``sleep_fn``, ``clock_fn``, and ``call_readiness_fn`` are injected for
256
- tests so the loop runs in fake-time without real ``time.sleep`` cost.
257
- """
258
- intervals = _cadence_intervals(cadence)
259
- cap_seconds = cap_minutes * 60
260
- started_at = clock_fn()
261
- poll_index = 0
262
- last_payload: dict = {}
263
- last_exit = EXIT_CAP_REACHED
264
-
265
- for interval in intervals:
266
- poll_index += 1
267
- elapsed = clock_fn() - started_at
268
- if elapsed > cap_seconds:
269
- return EXIT_CAP_REACHED, last_payload, poll_index - 1
270
-
271
- poll_result = call_readiness_fn(pr_number, repo)
272
- last_payload = poll_result.payload
273
- last_exit = poll_result.exit_code
274
-
275
- # Mirror per-poll status to stderr so the orchestrator transcript
276
- # shows progress without parsing the final JSON envelope.
277
- print(_format_poll_status(poll_index, poll_result), file=sys.stderr)
278
- if poll_result.raw_stderr.strip():
279
- # Surface the readiness script's stderr verbatim -- it carries
280
- # the gh error message a downstream operator may need.
281
- sys.stderr.write(poll_result.raw_stderr)
282
-
283
- via = last_payload.get("via")
284
- merge_ready = bool(last_payload.get("merge_ready"))
285
-
286
- # Authoritative CLEAN exit -- only primary or fallback1 can fire.
287
- if merge_ready and via in ("primary", "fallback1"):
288
- return EXIT_CLEAN, last_payload, poll_index
289
-
290
- # Terminal lifecycle -- PR merged or closed out from under us.
291
- if _is_terminal_pr_state(last_payload):
292
- return EXIT_PR_TERMINAL, last_payload, poll_index
293
-
294
- # Otherwise: keep polling. fallback2 + error are NOT terminal --
295
- # the monitor steps forward until the cap.
296
- if poll_index < len(intervals):
297
- # Time-budget guard before sleeping: if the next sleep would
298
- # push us past the cap, return the current verdict now.
299
- elapsed_after_poll = clock_fn() - started_at
300
- remaining = cap_seconds - elapsed_after_poll
301
- if remaining <= 0:
302
- return EXIT_CAP_REACHED, last_payload, poll_index
303
- sleep_fn(min(interval, max(1, int(remaining))))
304
-
305
- final_exit = (
306
- last_exit if last_exit == EXIT_CONFIG_ERROR else EXIT_CAP_REACHED
307
- )
308
- return final_exit, last_payload, poll_index
309
-
310
-
311
- # ---- CLI --------------------------------------------------------------------
312
-
313
-
314
- def _build_parser() -> argparse.ArgumentParser:
315
- parser = argparse.ArgumentParser(
316
- prog="monitor_pr",
317
- description=(
318
- "Wait-until-ready helper for long-running PR monitors. "
319
- "Loops pr_merge_readiness.py with adaptive cadence (~1m -> 3m -> "
320
- "5m) until the PR reaches a primary/fallback1 CLEAN verdict, "
321
- "the poll cap is reached, or the PR is merged/closed. "
322
- "Tolerates fallback responses; never exits CLEAN on fallback2."
323
- ),
324
- )
325
- parser.add_argument("pr_number", type=int, help="Pull request number to watch.")
326
- parser.add_argument(
327
- "--repo",
328
- default=None,
329
- metavar="OWNER/REPO",
330
- help="Repository in OWNER/REPO form. Defaults to $GH_REPO or current checkout.",
331
- )
332
- parser.add_argument(
333
- "--cap-minutes",
334
- type=float,
335
- default=60.0,
336
- help="Total wall-clock cap for the monitor in minutes (default: 60).",
337
- )
338
- parser.add_argument(
339
- "--json",
340
- dest="emit_json",
341
- action="store_true",
342
- help="Emit the final pr_merge_readiness payload as JSON on stdout.",
343
- )
344
- return parser
345
-
346
-
347
- def main(argv: list[str] | None = None) -> int:
348
- args = _build_parser().parse_args(argv)
349
-
350
- repo = args.repo or os.environ.get("GH_REPO")
351
- if not repo:
352
- print(
353
- "Error: --repo OWNER/REPO is required (or set $GH_REPO).",
354
- file=sys.stderr,
355
- )
356
- return EXIT_CONFIG_ERROR
357
-
358
- exit_code, payload, poll_count = monitor(
359
- pr_number=args.pr_number,
360
- repo=repo,
361
- cap_minutes=args.cap_minutes,
362
- )
363
-
364
- summary_label = {
365
- EXIT_CLEAN: "CLEAN",
366
- EXIT_CAP_REACHED: "CAP-REACHED",
367
- EXIT_PR_TERMINAL: "PR-TERMINAL",
368
- EXIT_CONFIG_ERROR: "CONFIG-ERROR",
369
- }.get(exit_code, "UNKNOWN")
370
- print(
371
- f"[monitor_pr] PR #{args.pr_number} repo={repo} result={summary_label} "
372
- f"polls={poll_count} via={payload.get('via', '?')}",
373
- file=sys.stderr,
374
- )
375
-
376
- if args.emit_json:
377
- # Wrap the readiness payload with monitor-level context so a
378
- # consumer parsing the stdout sees both the verdict and the
379
- # monitor outcome in one envelope.
380
- envelope = {
381
- "monitor_result": summary_label,
382
- "polls": poll_count,
383
- "readiness": payload,
384
- }
385
- print(json.dumps(envelope, indent=2))
386
- else:
387
- # Plain-text summary for human consumption.
388
- print(f"PR #{args.pr_number} monitor result: {summary_label}")
389
- print(f" polls: {poll_count}")
390
- print(f" via: {payload.get('via', '?')}")
391
- if payload.get("error"):
392
- print(f" error: {payload['error']}")
393
- if payload.get("failures"):
394
- for i, fail in enumerate(payload["failures"], 1):
395
- print(f" [{i}] {fail}")
396
-
397
- return exit_code
398
-
399
-
400
- if __name__ == "__main__":
401
- sys.exit(main())