@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,554 @@
1
+ #!/usr/bin/env python3
2
+ """Report whether vBRIEF candidates are ready for concurrent swarm allocation."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import glob
8
+ import json
9
+ import sys
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
16
+
17
+ from _stdio_utf8 import reconfigure_stdio # noqa: E402
18
+ from _vbrief_story_quality import ( # noqa: E402
19
+ acceptance_texts_from_items,
20
+ as_str_list as _as_str_list,
21
+ deprecated_subitems_issues,
22
+ item_has_traces,
23
+ items_have_acceptance,
24
+ missing_required_swarm_fields,
25
+ story_quality_issues,
26
+ )
27
+
28
+ reconfigure_stdio()
29
+
30
+ LIFECYCLE_FOLDERS = ("proposed", "pending", "active", "completed", "cancelled")
31
+ READY = "ready"
32
+
33
+
34
+ @dataclass
35
+ class Candidate:
36
+ path: Path
37
+ relpath: str
38
+ data: dict[str, Any]
39
+ plan: dict[str, Any]
40
+ story_id: str
41
+ title: str
42
+ status: str
43
+ folder: str
44
+ kind: str
45
+ swarm: dict[str, Any]
46
+ missing: list[str] = field(default_factory=list)
47
+ blocked: list[str] = field(default_factory=list)
48
+ decomposition_needed: bool = False
49
+
50
+
51
+ def _load_json(path: Path) -> dict[str, Any] | None:
52
+ try:
53
+ data = json.loads(path.read_text(encoding="utf-8"))
54
+ except (OSError, json.JSONDecodeError):
55
+ return None
56
+ return data if isinstance(data, dict) else None
57
+
58
+
59
+ def _project_rel(project_root: Path, path: Path) -> str:
60
+ try:
61
+ return path.resolve().relative_to(project_root.resolve()).as_posix()
62
+ except ValueError:
63
+ return path.as_posix()
64
+
65
+
66
+ def _expand_paths(project_root: Path, patterns: list[str]) -> list[Path]:
67
+ if not patterns:
68
+ patterns = ["vbrief/active/*.vbrief.json"]
69
+ out: list[Path] = []
70
+ seen: set[Path] = set()
71
+ for pattern in patterns:
72
+ raw = Path(pattern)
73
+ matches: list[str]
74
+ if any(ch in pattern for ch in "*?["):
75
+ matches = glob.glob(str(raw if raw.is_absolute() else project_root / pattern))
76
+ else:
77
+ matches = [str(raw if raw.is_absolute() else project_root / pattern)]
78
+ for match in matches:
79
+ path = Path(match).resolve()
80
+ if path in seen or not path.is_file():
81
+ continue
82
+ seen.add(path)
83
+ out.append(path)
84
+ return sorted(out)
85
+
86
+
87
+ def _folder_for(path: Path) -> str:
88
+ return path.parent.name if path.parent.name in LIFECYCLE_FOLDERS else ""
89
+
90
+
91
+ def _plan(data: dict[str, Any]) -> dict[str, Any]:
92
+ plan = data.get("plan")
93
+ return plan if isinstance(plan, dict) else {}
94
+
95
+
96
+ def _metadata(plan: dict[str, Any]) -> dict[str, Any]:
97
+ metadata = plan.get("metadata")
98
+ return metadata if isinstance(metadata, dict) else {}
99
+
100
+
101
+ def _swarm(metadata: dict[str, Any]) -> dict[str, Any]:
102
+ swarm = metadata.get("swarm")
103
+ return swarm if isinstance(swarm, dict) else {}
104
+
105
+
106
+ def _has_child_plan_refs(plan: dict[str, Any]) -> bool:
107
+ refs = plan.get("references")
108
+ if not isinstance(refs, list):
109
+ return False
110
+ return any(isinstance(ref, dict) and ref.get("type") == "x-vbrief/plan" for ref in refs)
111
+
112
+
113
+ def _looks_like_phase(path: Path, plan: dict[str, Any]) -> bool:
114
+ title = str(plan.get("title") or "")
115
+ plan_id = str(plan.get("id") or "")
116
+ narratives = plan.get("narratives")
117
+ has_acceptance_narrative = (
118
+ isinstance(narratives, dict)
119
+ and isinstance(narratives.get("Acceptance"), str)
120
+ and bool(narratives["Acceptance"].strip())
121
+ )
122
+ has_items = bool(plan.get("items"))
123
+ stem = path.name
124
+ return (
125
+ "-ip" in stem
126
+ or title.lower().startswith("ip-")
127
+ or plan_id.lower().startswith("ip-")
128
+ or (not has_items and has_acceptance_narrative)
129
+ )
130
+
131
+
132
+ def _kind(path: Path, plan: dict[str, Any]) -> str:
133
+ metadata = _metadata(plan)
134
+ explicit = metadata.get("kind")
135
+ if explicit in {"story", "epic", "phase"}:
136
+ return str(explicit)
137
+ if _has_child_plan_refs(plan):
138
+ return "epic"
139
+ if _looks_like_phase(path, plan):
140
+ return "phase"
141
+ return "story"
142
+
143
+
144
+ def _story_id(path: Path, plan: dict[str, Any]) -> str:
145
+ value = plan.get("id")
146
+ if isinstance(value, str) and value.strip():
147
+ return value.strip()
148
+ name = path.name
149
+ return name[: -len(".vbrief.json")] if name.endswith(".vbrief.json") else path.stem
150
+
151
+
152
+ def _has_traces(plan: dict[str, Any], swarm: dict[str, Any]) -> bool:
153
+ narratives = plan.get("narratives")
154
+ if isinstance(narratives, dict):
155
+ traces = narratives.get("Traces")
156
+ if isinstance(traces, str) and traces.strip():
157
+ return True
158
+ items = plan.get("items")
159
+ if isinstance(items, list):
160
+ for item in items:
161
+ if isinstance(item, dict) and item_has_traces(item):
162
+ return True
163
+ refs = plan.get("references")
164
+ if isinstance(refs, list):
165
+ for ref in refs:
166
+ if isinstance(ref, dict) and ref.get("type") == "x-vbrief/spec-section":
167
+ return True
168
+ return bool(_as_str_list(swarm.get("missing_traces_justification")))
169
+
170
+
171
+ def _plan_narrative(plan: dict[str, Any], key: str) -> str:
172
+ narratives = plan.get("narratives")
173
+ if not isinstance(narratives, dict):
174
+ return ""
175
+ value = narratives.get(key)
176
+ return value.strip() if isinstance(value, str) and value.strip() else ""
177
+
178
+
179
+ def _acceptance_count_justification(plan: dict[str, Any], swarm: dict[str, Any]) -> str:
180
+ value = swarm.get("acceptance_criteria_justification")
181
+ if isinstance(value, str) and value.strip():
182
+ return value.strip()
183
+ return _plan_narrative(plan, "AcceptanceJustification")
184
+
185
+
186
+ def _all_scope_ids(project_root: Path) -> dict[str, tuple[Path, str]]:
187
+ ids: dict[str, tuple[Path, str]] = {}
188
+ vbrief_dir = project_root / "vbrief"
189
+ for folder in LIFECYCLE_FOLDERS:
190
+ for path in sorted((vbrief_dir / folder).glob("*.vbrief.json")):
191
+ data = _load_json(path)
192
+ if not data:
193
+ continue
194
+ plan = _plan(data)
195
+ scope_id = _story_id(path, plan)
196
+ ids[scope_id] = (path, str(plan.get("status") or ""))
197
+ name = path.name
198
+ stem = name[: -len(".vbrief.json")] if name.endswith(".vbrief.json") else path.stem
199
+ ids.setdefault(stem, (path, str(plan.get("status") or "")))
200
+ return ids
201
+
202
+
203
+ def _candidate(path: Path, project_root: Path) -> Candidate | None:
204
+ data = _load_json(path)
205
+ if not data:
206
+ return None
207
+ plan = _plan(data)
208
+ metadata = _metadata(plan)
209
+ swarm = _swarm(metadata)
210
+ return Candidate(
211
+ path=path,
212
+ relpath=_project_rel(project_root, path),
213
+ data=data,
214
+ plan=plan,
215
+ story_id=_story_id(path, plan),
216
+ title=str(plan.get("title") or path.name),
217
+ status=str(plan.get("status") or ""),
218
+ folder=_folder_for(path),
219
+ kind=_kind(path, plan),
220
+ swarm=swarm,
221
+ )
222
+
223
+
224
+ def _validate_candidate(candidate: Candidate, known_ids: dict[str, tuple[Path, str]]) -> None:
225
+ if candidate.kind in {"epic", "phase"}:
226
+ candidate.decomposition_needed = True
227
+ return
228
+ if candidate.kind != "story" or _metadata(candidate.plan).get("kind") != "story":
229
+ candidate.missing.append("plan.metadata.kind=story")
230
+ if not isinstance(candidate.plan.get("id"), str) or not candidate.plan["id"].strip():
231
+ candidate.missing.append("plan.id")
232
+ if not isinstance(candidate.plan.get("title"), str) or not candidate.plan["title"].strip():
233
+ candidate.missing.append("plan.title")
234
+ description = _plan_narrative(candidate.plan, "Description")
235
+ implementation_plan = _plan_narrative(candidate.plan, "ImplementationPlan")
236
+ user_story = _plan_narrative(candidate.plan, "UserStory")
237
+ if not description:
238
+ candidate.missing.append("plan.narratives.Description")
239
+ if not implementation_plan:
240
+ candidate.missing.append("plan.narratives.ImplementationPlan")
241
+ if not user_story:
242
+ candidate.missing.append("plan.narratives.UserStory")
243
+ if candidate.folder == "active" and candidate.status != "running":
244
+ candidate.blocked.append("active candidate plan.status must be running")
245
+ if candidate.status == "running" and candidate.folder != "active":
246
+ candidate.blocked.append("plan.status=running is only valid in vbrief/active/")
247
+ if candidate.status == "blocked":
248
+ candidate.blocked.append("plan.status=blocked")
249
+
250
+ items = candidate.plan.get("items")
251
+ if not isinstance(items, list) or not items:
252
+ candidate.missing.append("plan.items")
253
+ else:
254
+ if not items_have_acceptance(items):
255
+ candidate.missing.append("plan.items[].narrative.Acceptance")
256
+ candidate.blocked.extend(deprecated_subitems_issues(items))
257
+
258
+ if candidate.swarm.get("readiness") != READY:
259
+ candidate.missing.append("plan.metadata.swarm.readiness=ready for concurrent allocation")
260
+ parallel_safe = candidate.swarm.get("parallel_safe")
261
+ if parallel_safe is not True and parallel_safe is not False:
262
+ candidate.missing.append("plan.metadata.swarm.parallel_safe")
263
+ candidate.missing.extend(missing_required_swarm_fields(candidate.swarm))
264
+ if not _has_traces(candidate.plan, candidate.swarm):
265
+ candidate.missing.append("Traces or missing_traces_justification")
266
+ candidate.blocked.extend(
267
+ story_quality_issues(
268
+ title=candidate.title,
269
+ description=description,
270
+ implementation_plan=implementation_plan,
271
+ user_story=user_story,
272
+ acceptance_texts=acceptance_texts_from_items(items),
273
+ acceptance_count_justification=_acceptance_count_justification(
274
+ candidate.plan, candidate.swarm
275
+ ),
276
+ swarm=candidate.swarm,
277
+ concurrent_ready=candidate.swarm.get("readiness") == READY,
278
+ )
279
+ )
280
+ if candidate.swarm.get("size") == "large" and candidate.swarm.get("parallel_safe") is True:
281
+ candidate.blocked.append("size=large cannot be parallel_safe=true")
282
+
283
+ for dep in _as_str_list(candidate.swarm.get("depends_on")):
284
+ if dep not in known_ids:
285
+ candidate.blocked.append(f"dependency {dep!r} does not resolve")
286
+
287
+
288
+ def _candidate_dep_graph(
289
+ candidates: list[Candidate],
290
+ known_ids: dict[str, tuple[Path, str]],
291
+ ) -> dict[str, list[str]]:
292
+ candidate_ids = {candidate.story_id for candidate in candidates}
293
+ graph: dict[str, list[str]] = {}
294
+ for candidate in candidates:
295
+ deps: list[str] = []
296
+ for dep in _as_str_list(candidate.swarm.get("depends_on")):
297
+ if dep in candidate_ids:
298
+ deps.append(dep)
299
+ continue
300
+ known = known_ids.get(dep)
301
+ if known is None:
302
+ continue
303
+ _dep_path, dep_status = known
304
+ if dep_status not in {"completed", "failed", "cancelled"}:
305
+ candidate.blocked.append(f"dependency {dep!r} is not completed or a candidate")
306
+ graph[candidate.story_id] = deps
307
+ return graph
308
+
309
+
310
+ def _mark_cycles(candidates: list[Candidate], graph: dict[str, list[str]]) -> None:
311
+ by_id = {candidate.story_id: candidate for candidate in candidates}
312
+ visiting: set[str] = set()
313
+ visited: set[str] = set()
314
+
315
+ def visit(story_id: str, path: list[str]) -> None:
316
+ if story_id in visited:
317
+ return
318
+ if story_id in visiting:
319
+ start = path.index(story_id) if story_id in path else 0
320
+ cycle = [*path[start:], story_id]
321
+ message = f"dependency cycle: {' -> '.join(cycle)}"
322
+ for node in cycle:
323
+ if node in by_id and message not in by_id[node].blocked:
324
+ by_id[node].blocked.append(message)
325
+ return
326
+ visiting.add(story_id)
327
+ for dep in graph.get(story_id, []):
328
+ visit(dep, [*path, story_id])
329
+ visiting.remove(story_id)
330
+ visited.add(story_id)
331
+
332
+ for candidate in candidates:
333
+ visit(candidate.story_id, [])
334
+
335
+
336
+ def _propagate_blocked_dependencies(
337
+ candidates: list[Candidate],
338
+ graph: dict[str, list[str]],
339
+ ) -> None:
340
+ by_id = {candidate.story_id: candidate for candidate in candidates}
341
+ changed = True
342
+ while changed:
343
+ changed = False
344
+ for candidate in candidates:
345
+ if candidate.kind != "story":
346
+ continue
347
+ for dep in graph.get(candidate.story_id, []):
348
+ dep_candidate = by_id.get(dep)
349
+ if dep_candidate is None:
350
+ continue
351
+ if (
352
+ not dep_candidate.missing
353
+ and not dep_candidate.blocked
354
+ and not dep_candidate.decomposition_needed
355
+ ):
356
+ continue
357
+ message = f"dependency {dep!r} is blocked"
358
+ if message not in candidate.blocked:
359
+ candidate.blocked.append(message)
360
+ changed = True
361
+
362
+
363
+ def _ready_stories(candidates: list[Candidate]) -> list[Candidate]:
364
+ return [
365
+ candidate
366
+ for candidate in candidates
367
+ if candidate.kind == "story"
368
+ and not candidate.missing
369
+ and not candidate.blocked
370
+ and not candidate.decomposition_needed
371
+ ]
372
+
373
+
374
+ def _dependency_waves(candidates: list[Candidate], graph: dict[str, list[str]]) -> list[list[str]]:
375
+ ready_ids = {candidate.story_id for candidate in _ready_stories(candidates)}
376
+ remaining = set(ready_ids)
377
+ waves: list[list[str]] = []
378
+ while remaining:
379
+ wave = sorted(
380
+ story_id
381
+ for story_id in remaining
382
+ if all(dep not in remaining for dep in graph.get(story_id, []))
383
+ )
384
+ if not wave:
385
+ waves.append(sorted(remaining))
386
+ break
387
+ waves.append(wave)
388
+ remaining.difference_update(wave)
389
+ return waves
390
+
391
+
392
+ def _transitive_deps(story_id: str, graph: dict[str, list[str]]) -> set[str]:
393
+ out: set[str] = set()
394
+ stack = list(graph.get(story_id, []))
395
+ while stack:
396
+ dep = stack.pop()
397
+ if dep in out:
398
+ continue
399
+ out.add(dep)
400
+ stack.extend(graph.get(dep, []))
401
+ return out
402
+
403
+
404
+ def _file_overlaps(
405
+ candidates: list[Candidate],
406
+ graph: dict[str, list[str]],
407
+ ) -> dict[str, list[str]]:
408
+ file_to_ids: dict[str, list[str]] = defaultdict(list)
409
+ for candidate in _ready_stories(candidates):
410
+ for file_path in _as_str_list(candidate.swarm.get("file_scope")):
411
+ file_to_ids[file_path].append(candidate.story_id)
412
+
413
+ overlaps: dict[str, list[str]] = {}
414
+ for file_path, ids in file_to_ids.items():
415
+ unsafe_pairs: set[str] = set()
416
+ for index, left in enumerate(ids):
417
+ for right in ids[index + 1:]:
418
+ if right in _transitive_deps(left, graph) or left in _transitive_deps(right, graph):
419
+ continue
420
+ unsafe_pairs.add(left)
421
+ unsafe_pairs.add(right)
422
+ if unsafe_pairs:
423
+ overlaps[file_path] = sorted(unsafe_pairs)
424
+ return overlaps
425
+
426
+
427
+ def _conflict_groups(candidates: list[Candidate]) -> dict[str, list[str]]:
428
+ groups: dict[str, list[str]] = defaultdict(list)
429
+ for candidate in candidates:
430
+ group = candidate.swarm.get("conflict_group")
431
+ if isinstance(group, str) and group.strip():
432
+ groups[group].append(candidate.story_id)
433
+ return dict(sorted(groups.items()))
434
+
435
+
436
+ def _render_report(
437
+ candidates: list[Candidate],
438
+ graph: dict[str, list[str]],
439
+ overlaps: dict[str, list[str]],
440
+ ) -> str:
441
+ ready = _ready_stories(candidates)
442
+ blocked = [
443
+ candidate
444
+ for candidate in candidates
445
+ if candidate.kind == "story" and (candidate.missing or candidate.blocked)
446
+ ]
447
+ needs_decomposition = [candidate for candidate in candidates if candidate.decomposition_needed]
448
+ lines: list[str] = ["Swarm readiness report", ""]
449
+
450
+ lines.append("Ready stories:")
451
+ if ready:
452
+ for candidate in ready:
453
+ lines.append(f"- {candidate.story_id}: {candidate.title} ({candidate.relpath})")
454
+ else:
455
+ lines.append("- none")
456
+ lines.append("")
457
+
458
+ lines.append("Blocked stories:")
459
+ if blocked:
460
+ for candidate in blocked:
461
+ reasons = [*candidate.missing, *candidate.blocked]
462
+ lines.append(f"- {candidate.story_id}: {candidate.title} -- {'; '.join(reasons)}")
463
+ else:
464
+ lines.append("- none")
465
+ lines.append("")
466
+
467
+ lines.append("Decomposition-needed epics/phases:")
468
+ if needs_decomposition:
469
+ for candidate in needs_decomposition:
470
+ lines.append(f"- {candidate.story_id}: kind={candidate.kind} ({candidate.relpath})")
471
+ else:
472
+ lines.append("- none")
473
+ lines.append("")
474
+
475
+ lines.append("Dependency waves:")
476
+ waves = _dependency_waves(candidates, graph)
477
+ if waves:
478
+ for index, wave in enumerate(waves, start=1):
479
+ lines.append(f"- wave {index}: {', '.join(wave)}")
480
+ else:
481
+ lines.append("- none")
482
+ lines.append("")
483
+
484
+ lines.append("Conflict groups:")
485
+ groups = _conflict_groups(candidates)
486
+ if groups:
487
+ for group, ids in groups.items():
488
+ lines.append(f"- {group}: {', '.join(sorted(ids))}")
489
+ else:
490
+ lines.append("- none")
491
+ lines.append("")
492
+
493
+ lines.append("File overlap matrix:")
494
+ if overlaps:
495
+ for file_path, ids in sorted(overlaps.items()):
496
+ lines.append(f"- {file_path}: {', '.join(ids)}")
497
+ else:
498
+ lines.append("- none")
499
+ lines.append("")
500
+
501
+ lines.append("Missing fields:")
502
+ missing_any = False
503
+ for candidate in candidates:
504
+ if candidate.missing:
505
+ missing_any = True
506
+ lines.append(f"- {candidate.story_id}: {', '.join(candidate.missing)}")
507
+ if not missing_any:
508
+ lines.append("- none")
509
+ return "\n".join(lines)
510
+
511
+
512
+ def readiness_report(project_root: Path, paths: list[Path]) -> tuple[int, str]:
513
+ candidates = [candidate for path in paths if (candidate := _candidate(path, project_root))]
514
+ if not candidates:
515
+ return 1, "Swarm readiness report\n\nNo candidate vBRIEFs found."
516
+ known_ids = _all_scope_ids(project_root)
517
+ for candidate in candidates:
518
+ known_ids.setdefault(candidate.story_id, (candidate.path, candidate.status))
519
+ for candidate in candidates:
520
+ _validate_candidate(candidate, known_ids)
521
+ graph = _candidate_dep_graph(candidates, known_ids)
522
+ _mark_cycles(candidates, graph)
523
+ _propagate_blocked_dependencies(candidates, graph)
524
+ overlaps = _file_overlaps(candidates, graph)
525
+ report = _render_report(candidates, graph, overlaps)
526
+ failed = any(
527
+ candidate.missing
528
+ or candidate.blocked
529
+ or candidate.decomposition_needed
530
+ for candidate in candidates
531
+ ) or bool(overlaps)
532
+ return 1 if failed else 0, report
533
+
534
+
535
+ def _parse_args(argv: list[str]) -> argparse.Namespace:
536
+ parser = argparse.ArgumentParser(
537
+ description="Report whether vBRIEF candidates are ready for concurrent swarm allocation."
538
+ )
539
+ parser.add_argument("paths", nargs="*", help="Candidate vBRIEF paths or globs")
540
+ parser.add_argument("--project-root", default=".", help="Project root containing vbrief/")
541
+ return parser.parse_args(argv)
542
+
543
+
544
+ def main(argv: list[str] | None = None) -> int:
545
+ args = _parse_args(sys.argv[1:] if argv is None else argv)
546
+ project_root = Path(args.project_root).resolve()
547
+ paths = _expand_paths(project_root, args.paths)
548
+ code, report = readiness_report(project_root, paths)
549
+ print(report)
550
+ return code
551
+
552
+
553
+ if __name__ == "__main__":
554
+ raise SystemExit(main())