@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,654 +0,0 @@
1
- #!/usr/bin/env python3
2
- """Apply or validate an approved epic/phase -> story decomposition draft.
3
-
4
- The command is intentionally deterministic: it never invents stories from a
5
- parent scope. A caller supplies a draft with child story definitions; this
6
- script validates that draft, writes the child story vBRIEFs, and updates the
7
- parent scope references.
8
- """
9
-
10
- from __future__ import annotations
11
-
12
- import argparse
13
- import copy
14
- import json
15
- import os
16
- import sys
17
- from datetime import UTC, datetime
18
- from pathlib import Path
19
- from typing import Any
20
-
21
- sys.path.insert(0, str(Path(__file__).resolve().parent))
22
-
23
- from _stdio_utf8 import reconfigure_stdio # noqa: E402
24
- from _vbrief_build import ( # noqa: E402
25
- EMITTED_VBRIEF_VERSION,
26
- reference_with_default_trust as _reference_with_default_trust,
27
- slugify,
28
- )
29
- from _vbrief_story_quality import ( # noqa: E402
30
- acceptance_texts_from_items,
31
- as_str_list as _as_str_list,
32
- deprecated_subitems_issues,
33
- item_has_traces,
34
- items_have_acceptance,
35
- missing_required_swarm_fields,
36
- story_quality_issues,
37
- )
38
-
39
- reconfigure_stdio()
40
-
41
- LIFECYCLE_FOLDERS = {"proposed", "pending", "active", "completed", "cancelled"}
42
- ACTIVE_DECOMPOSITION_STATUSES = {"active", "running"}
43
- READY = "ready"
44
- STORY_READINESS_STATES = {READY, "sequential", "needs_refinement"}
45
-
46
-
47
- class DecompositionError(ValueError):
48
- """Raised when a decomposition draft is not safe to apply."""
49
-
50
-
51
- def _load_json(path: Path) -> dict[str, Any]:
52
- try:
53
- data = json.loads(path.read_text(encoding="utf-8"))
54
- except OSError as exc:
55
- raise DecompositionError(f"{path}: cannot read file: {exc}") from exc
56
- except json.JSONDecodeError as exc:
57
- raise DecompositionError(f"{path}: invalid JSON: {exc}") from exc
58
- if not isinstance(data, dict):
59
- raise DecompositionError(f"{path}: expected a JSON object") from None
60
- return data
61
-
62
-
63
- def _write_json(path: Path, data: dict[str, Any]) -> None:
64
- path.parent.mkdir(parents=True, exist_ok=True)
65
- path.write_text(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
66
-
67
-
68
- def _resolve_path(project_root: Path, value: str | None) -> Path | None:
69
- if not value:
70
- return None
71
- path = Path(value)
72
- return path if path.is_absolute() else project_root / path
73
-
74
-
75
- def _is_valid_creation_date(value: str) -> bool:
76
- """Return whether value is an exact YYYY-MM-DD calendar date."""
77
- if len(value) != 10:
78
- return False
79
- try:
80
- parsed = datetime.strptime(value, "%Y-%m-%d")
81
- except ValueError:
82
- return False
83
- return parsed.strftime("%Y-%m-%d") == value
84
-
85
-
86
- def _vbrief_dir(project_root: Path) -> Path:
87
- return project_root / "vbrief"
88
-
89
-
90
- def _rel_to_vbrief(vbrief_dir: Path, path: Path) -> str:
91
- try:
92
- return path.resolve().relative_to(vbrief_dir.resolve()).as_posix()
93
- except ValueError as exc:
94
- raise DecompositionError(f"{path}: path must be inside {vbrief_dir}") from exc
95
-
96
-
97
- def _pending_scope_folder(vbrief_dir: Path) -> Path:
98
- return vbrief_dir / "pending"
99
-
100
-
101
- def _default_status_for_folder(folder: Path) -> str:
102
- return {
103
- "proposed": "proposed",
104
- "pending": "pending",
105
- "active": "running",
106
- "completed": "completed",
107
- "cancelled": "cancelled",
108
- }.get(folder.name, "pending")
109
-
110
-
111
- def _normalize_status(value: Any, default: str) -> str:
112
- if value is None:
113
- return default
114
- status = str(value).strip().lower()
115
- return status or default
116
-
117
-
118
- def _story_specs(draft: dict[str, Any]) -> list[dict[str, Any]]:
119
- stories = draft.get("stories", draft.get("children", []))
120
- if isinstance(stories, dict):
121
- stories = list(stories.values())
122
- if not isinstance(stories, list):
123
- raise DecompositionError("draft must contain a stories array")
124
- normalized: list[dict[str, Any]] = []
125
- for index, story in enumerate(stories, start=1):
126
- if not isinstance(story, dict):
127
- raise DecompositionError(f"stories[{index}] must be an object")
128
- normalized.append(story)
129
- return normalized
130
-
131
-
132
- def _story_id(story: dict[str, Any], index: int) -> str:
133
- raw = story.get("id") or story.get("story_id") or story.get("key")
134
- if isinstance(raw, str) and raw.strip():
135
- return raw.strip()
136
- title = str(story.get("title") or f"story-{index}")
137
- return slugify(title) or f"story-{index}"
138
-
139
-
140
- def _swarm_meta(story: dict[str, Any]) -> dict[str, Any]:
141
- metadata = story.get("metadata")
142
- if not isinstance(metadata, dict):
143
- metadata = {}
144
- swarm = story.get("swarm") or metadata.get("swarm") or {}
145
- if not isinstance(swarm, dict):
146
- swarm = {}
147
- # Accept the convenient draft shape where canonical swarm fields live at
148
- # the story top level, then store them under plan.metadata.swarm.
149
- for key in (
150
- "readiness",
151
- "parallel_safe",
152
- "file_scope",
153
- "verify_commands",
154
- "expected_outputs",
155
- "depends_on",
156
- "conflict_group",
157
- "size",
158
- "file_scope_confidence",
159
- "model_tier",
160
- "missing_traces_justification",
161
- ):
162
- if key in story and key not in swarm:
163
- swarm[key] = story[key]
164
- return swarm
165
-
166
-
167
- def _story_has_traces(story: dict[str, Any], items: list[Any], swarm: dict[str, Any]) -> bool:
168
- narratives = story.get("narratives")
169
- if isinstance(narratives, dict):
170
- value = narratives.get("Traces")
171
- if isinstance(value, str) and value.strip():
172
- return True
173
- if _as_str_list(story.get("traces")):
174
- return True
175
- if any(isinstance(item, dict) and item_has_traces(item) for item in items):
176
- return True
177
- if _as_str_list(swarm.get("missing_traces_justification")):
178
- return True
179
- refs = story.get("references")
180
- if isinstance(refs, list):
181
- for ref in refs:
182
- if isinstance(ref, dict) and ref.get("type") == "x-vbrief/spec-section":
183
- return True
184
- return False
185
-
186
-
187
- def _story_description(story: dict[str, Any]) -> str:
188
- narratives = story.get("narratives")
189
- if isinstance(narratives, dict):
190
- value = narratives.get("Description")
191
- if isinstance(value, str) and value.strip():
192
- return value.strip()
193
- for key in ("description", "summary"):
194
- value = story.get(key)
195
- if isinstance(value, str) and value.strip():
196
- return value.strip()
197
- return ""
198
-
199
-
200
- def _story_implementation_plan(story: dict[str, Any]) -> str:
201
- narratives = story.get("narratives")
202
- if isinstance(narratives, dict):
203
- value = narratives.get("ImplementationPlan")
204
- if isinstance(value, str) and value.strip():
205
- return value.strip()
206
- for key in ("implementation_plan", "ImplementationPlan"):
207
- values = _as_str_list(story.get(key))
208
- if values:
209
- return "\n".join(values)
210
- return ""
211
-
212
-
213
- def _story_user_story(story: dict[str, Any]) -> str:
214
- narratives = story.get("narratives")
215
- if isinstance(narratives, dict):
216
- value = narratives.get("UserStory")
217
- if isinstance(value, str) and value.strip():
218
- return value.strip()
219
- for key in ("user_story", "UserStory"):
220
- value = story.get(key)
221
- if isinstance(value, str) and value.strip():
222
- return value.strip()
223
- return ""
224
-
225
-
226
- def _acceptance_count_justification(story: dict[str, Any], swarm: dict[str, Any]) -> str:
227
- for value in (
228
- swarm.get("acceptance_criteria_justification"),
229
- story.get("acceptance_criteria_justification"),
230
- ):
231
- if isinstance(value, str) and value.strip():
232
- return value.strip()
233
- narratives = story.get("narratives")
234
- if isinstance(narratives, dict):
235
- value = narratives.get("AcceptanceJustification")
236
- if isinstance(value, str) and value.strip():
237
- return value.strip()
238
- return ""
239
-
240
-
241
- def _items_from_story(story_id: str, story: dict[str, Any]) -> list[Any]:
242
- items = story.get("items")
243
- if isinstance(items, list) and items:
244
- return items
245
- acceptance = _as_str_list(story.get("acceptance"))
246
- if not acceptance:
247
- acceptance = _as_str_list(story.get("acceptance_items"))
248
- traces = ", ".join(_as_str_list(story.get("traces")))
249
- generated: list[dict[str, Any]] = []
250
- for index, criterion in enumerate(acceptance, start=1):
251
- narrative = {"Acceptance": criterion}
252
- if traces:
253
- narrative["Traces"] = traces
254
- generated.append(
255
- {
256
- "id": f"{story_id}-a{index}",
257
- "title": criterion,
258
- "status": "pending",
259
- "narrative": narrative,
260
- }
261
- )
262
- return generated
263
-
264
-
265
- def _validate_dag(story_ids: list[str], deps_by_story: dict[str, list[str]]) -> None:
266
- known = set(story_ids)
267
- for story_id, deps in deps_by_story.items():
268
- for dep in deps:
269
- if dep not in known:
270
- raise DecompositionError(f"{story_id}: depends_on references unknown story {dep!r}")
271
-
272
- visiting: set[str] = set()
273
- visited: set[str] = set()
274
-
275
- def visit(story_id: str, path: list[str]) -> None:
276
- if story_id in visited:
277
- return
278
- if story_id in visiting:
279
- start = path.index(story_id) if story_id in path else 0
280
- cycle = " -> ".join([*path[start:], story_id])
281
- raise DecompositionError(f"dependency cycle detected: {cycle}")
282
- visiting.add(story_id)
283
- for dep in deps_by_story.get(story_id, []):
284
- visit(dep, [*path, story_id])
285
- visiting.remove(story_id)
286
- visited.add(story_id)
287
-
288
- for story_id in story_ids:
289
- visit(story_id, [])
290
-
291
-
292
- def validate_draft(stories: list[dict[str, Any]]) -> list[str]:
293
- """Validate draft story contracts and return ordered story ids."""
294
- story_ids: list[str] = []
295
- deps_by_story: dict[str, list[str]] = {}
296
- seen: set[str] = set()
297
- for index, story in enumerate(stories, start=1):
298
- story_id = _story_id(story, index)
299
- if story_id in seen:
300
- raise DecompositionError(f"duplicate story id {story_id!r}")
301
- seen.add(story_id)
302
- story_ids.append(story_id)
303
- swarm = _swarm_meta(story)
304
- deps = _as_str_list(swarm.get("depends_on") or story.get("depends_on"))
305
- deps_by_story[story_id] = deps
306
-
307
- items = _items_from_story(story_id, story)
308
- description = _story_description(story)
309
- implementation_plan = _story_implementation_plan(story)
310
- user_story = _story_user_story(story)
311
- issues: list[str] = []
312
- raw_id = story.get("id") or story.get("story_id") or story.get("key")
313
- if not isinstance(raw_id, str) or not raw_id.strip():
314
- issues.append("id")
315
- raw_title = story.get("title")
316
- if not isinstance(raw_title, str) or not raw_title.strip():
317
- issues.append("title")
318
- if not description:
319
- issues.append("plan.narratives.Description")
320
- if not implementation_plan:
321
- issues.append("plan.narratives.ImplementationPlan")
322
- if not user_story:
323
- issues.append("plan.narratives.UserStory")
324
- readiness = swarm.get("readiness")
325
- if readiness not in STORY_READINESS_STATES:
326
- issues.append("plan.metadata.swarm.readiness")
327
- parallel_safe = swarm.get("parallel_safe")
328
- if parallel_safe is not True and parallel_safe is not False:
329
- issues.append("plan.metadata.swarm.parallel_safe")
330
- if not items:
331
- issues.append("plan.items")
332
- if items and not items_have_acceptance(items):
333
- issues.append("plan.items[].narrative.Acceptance")
334
- issues.extend(deprecated_subitems_issues(items))
335
- issues.extend(missing_required_swarm_fields(swarm))
336
- if not _story_has_traces(story, items, swarm):
337
- issues.append("Traces or missing_traces_justification")
338
- issues.extend(
339
- story_quality_issues(
340
- title=str(story.get("title") or story_id),
341
- description=description,
342
- implementation_plan=implementation_plan,
343
- user_story=user_story,
344
- acceptance_texts=acceptance_texts_from_items(items),
345
- acceptance_count_justification=_acceptance_count_justification(story, swarm),
346
- swarm=swarm,
347
- concurrent_ready=readiness == READY,
348
- )
349
- )
350
- if issues:
351
- raise DecompositionError(f"{story_id}: story invalid: {', '.join(issues)}")
352
-
353
- _validate_dag(story_ids, deps_by_story)
354
- return story_ids
355
-
356
-
357
- def _normalize_references(refs: Any) -> list[dict[str, Any]]:
358
- if not isinstance(refs, list):
359
- return []
360
- normalized: list[dict[str, Any]] = []
361
- for ref in refs:
362
- if isinstance(ref, dict):
363
- normalized.append(_reference_with_default_trust(ref))
364
- return normalized
365
-
366
-
367
- def _child_provenance_references(refs: Any) -> list[dict[str, Any]]:
368
- return [
369
- ref
370
- for ref in _normalize_references(refs)
371
- if "acceptance" not in str(ref.get("type") or "").lower()
372
- ]
373
-
374
-
375
- def _dedupe_references(refs: list[dict[str, Any]]) -> list[dict[str, Any]]:
376
- out: list[dict[str, Any]] = []
377
- seen: set[tuple[str, str, str]] = set()
378
- for ref in refs:
379
- key = (
380
- str(ref.get("uri") or ref.get("url") or ""),
381
- str(ref.get("type") or ""),
382
- str(ref.get("title") or ""),
383
- )
384
- if key in seen:
385
- continue
386
- seen.add(key)
387
- out.append(ref)
388
- return out
389
-
390
-
391
- def _story_narratives(story: dict[str, Any]) -> dict[str, str]:
392
- narratives: dict[str, str] = {}
393
- raw = story.get("narratives")
394
- if isinstance(raw, dict):
395
- for key, value in raw.items():
396
- if isinstance(value, str) and value.strip():
397
- narratives[key] = value.strip()
398
- for draft_key, narrative_key in (
399
- ("description", "Description"),
400
- ("summary", "Description"),
401
- ("implementation_plan", "ImplementationPlan"),
402
- ("ImplementationPlan", "ImplementationPlan"),
403
- ("user_story", "UserStory"),
404
- ("UserStory", "UserStory"),
405
- ("traces", "Traces"),
406
- ):
407
- if narrative_key in narratives:
408
- continue
409
- values = _as_str_list(story.get(draft_key))
410
- if values:
411
- separator = "\n" if narrative_key == "ImplementationPlan" else ", "
412
- narratives[narrative_key] = separator.join(values)
413
- return narratives
414
-
415
-
416
- def _child_filename(story: dict[str, Any], story_id: str, title: str, date: str) -> str:
417
- filename = story.get("filename")
418
- if isinstance(filename, str) and filename.endswith(".vbrief.json"):
419
- return filename
420
- slug = slugify(title) or slugify(story_id) or "story"
421
- return f"{date}-{slug}.vbrief.json"
422
-
423
-
424
- def _build_child_vbrief(
425
- *,
426
- story: dict[str, Any],
427
- story_id: str,
428
- story_index: int,
429
- parent: dict[str, Any],
430
- parent_rel: str,
431
- status: str,
432
- ) -> dict[str, Any]:
433
- title = str(story.get("title") or story_id)
434
- swarm = _swarm_meta(story)
435
- items = _items_from_story(story_id, story)
436
- metadata = (
437
- copy.deepcopy(story.get("metadata"))
438
- if isinstance(story.get("metadata"), dict)
439
- else {}
440
- )
441
- metadata["kind"] = "story"
442
- metadata["swarm"] = swarm
443
-
444
- parent_plan = parent.get("plan", {}) if isinstance(parent, dict) else {}
445
- parent_refs = (
446
- _child_provenance_references(parent_plan.get("references"))
447
- if isinstance(parent_plan, dict)
448
- else []
449
- )
450
- story_refs = _normalize_references(story.get("references"))
451
-
452
- return {
453
- "vBRIEFInfo": {
454
- "version": EMITTED_VBRIEF_VERSION,
455
- "description": f"Story vBRIEF {story_index} decomposed from {parent_rel}",
456
- },
457
- "plan": {
458
- "id": story_id,
459
- "title": title,
460
- "status": status,
461
- "planRef": parent_rel,
462
- "narratives": _story_narratives(story),
463
- "items": items,
464
- "metadata": metadata,
465
- "references": _dedupe_references([*parent_refs, *story_refs]),
466
- },
467
- }
468
-
469
-
470
- def apply_decomposition(
471
- *,
472
- project_root: Path,
473
- parent_path: Path,
474
- draft_path: Path,
475
- check_only: bool,
476
- date: str,
477
- ) -> list[str]:
478
- vbrief_dir = _vbrief_dir(project_root)
479
- parent = _load_json(parent_path)
480
- draft = _load_json(draft_path)
481
- stories = _story_specs(draft)
482
- story_ids = validate_draft(stories)
483
- output_dir = _resolve_path(
484
- project_root, draft.get("output_dir") or ""
485
- ) or _pending_scope_folder(vbrief_dir)
486
- if output_dir.name not in LIFECYCLE_FOLDERS:
487
- raise DecompositionError("output_dir must be a vbrief lifecycle folder")
488
- try:
489
- output_dir.resolve().relative_to(vbrief_dir.resolve())
490
- except ValueError as exc:
491
- raise DecompositionError("output_dir must be inside vbrief/") from exc
492
- if output_dir.name == "active":
493
- raise DecompositionError(
494
- "output_dir must not be vbrief/active; write pending stories and use "
495
- "task scope:activate when work begins"
496
- ) from None
497
- status = _normalize_status(draft.get("status"), _default_status_for_folder(output_dir))
498
- if status in ACTIVE_DECOMPOSITION_STATUSES:
499
- raise DecompositionError(
500
- "decomposition cannot create active/running child stories; write pending "
501
- "stories and use task scope:activate when work begins"
502
- )
503
- parent_rel = _rel_to_vbrief(vbrief_dir, parent_path)
504
-
505
- actions = [f"VALIDATED {len(stories)} story decomposition draft"]
506
- child_paths: list[tuple[Path, str, str]] = []
507
- child_docs: list[dict[str, Any]] = []
508
- for index, story in enumerate(stories, start=1):
509
- story_id = story_ids[index - 1]
510
- title = str(story.get("title") or story_id)
511
- story_status = _normalize_status(story.get("status"), status)
512
- if story_status in ACTIVE_DECOMPOSITION_STATUSES:
513
- raise DecompositionError(
514
- f"{story_id}: decomposition cannot create active/running child stories; "
515
- "write pending stories and use task scope:activate when work begins"
516
- )
517
- filename = _child_filename(story, story_id, title, date)
518
- target = output_dir / filename
519
- if not check_only and (target.is_file() or target.is_dir() or target.is_symlink()):
520
- raise DecompositionError(
521
- f"{target}: child story path already exists; overwriting is not supported"
522
- )
523
- child = _build_child_vbrief(
524
- story=story,
525
- story_id=story_id,
526
- story_index=index,
527
- parent=parent,
528
- parent_rel=parent_rel,
529
- status=story_status,
530
- )
531
- child_paths.append((target, story_id, title))
532
- child_docs.append(child)
533
- verb = "CHECK" if check_only else "CREATE"
534
- actions.append(f"{verb} {_rel_to_vbrief(vbrief_dir, target)}")
535
-
536
- if check_only:
537
- return actions
538
-
539
- parent_plan = parent.get("plan")
540
- if parent_plan is None:
541
- parent_plan = {}
542
- parent["plan"] = parent_plan
543
- if not isinstance(parent_plan, dict):
544
- raise DecompositionError(f"{parent_path}: plan must be an object")
545
- metadata = parent_plan.get("metadata")
546
- if metadata is None:
547
- metadata = {}
548
- parent_plan["metadata"] = metadata
549
- if not isinstance(metadata, dict):
550
- raise DecompositionError(f"{parent_path}: plan.metadata must be an object")
551
- metadata.setdefault("kind", "epic")
552
- references = parent_plan.get("references")
553
- if references is None:
554
- references = []
555
- parent_plan["references"] = references
556
- if not isinstance(references, list):
557
- raise DecompositionError(f"{parent_path}: plan.references must be an array")
558
-
559
- for target, _story_id, _title in child_paths:
560
- target.parent.mkdir(parents=True, exist_ok=True)
561
- for (target, _story_id, _title), child in zip(child_paths, child_docs, strict=True):
562
- _write_json(target, child)
563
-
564
- for target, _story_id, title in child_paths:
565
- references.append(
566
- _reference_with_default_trust(
567
- {
568
- "uri": _rel_to_vbrief(vbrief_dir, target),
569
- "type": "x-vbrief/plan",
570
- "title": title,
571
- }
572
- )
573
- )
574
- parent_plan["references"] = _dedupe_references(
575
- [ref for ref in references if isinstance(ref, dict)]
576
- )
577
- _write_json(parent_path, parent)
578
- actions.append(f"UPDATE {parent_rel} references")
579
- return actions
580
-
581
-
582
- def _parse_args(argv: list[str]) -> argparse.Namespace:
583
- parser = argparse.ArgumentParser(
584
- description="Validate and apply an approved epic/phase story decomposition draft."
585
- )
586
- parser.add_argument(
587
- "parent",
588
- nargs="?",
589
- help="Parent epic/phase vBRIEF path (required with --draft; omit only for --check no-op)",
590
- )
591
- parser.add_argument(
592
- "--draft",
593
- help=(
594
- "Approved decomposition JSON draft "
595
- "(recommended: vbrief/.eval/decompositions/<parent-slug>.json)"
596
- ),
597
- )
598
- parser.add_argument("--check", action="store_true", help="Validate only; do not write")
599
- parser.add_argument("--date", help="Creation date for generated child filenames")
600
- parser.add_argument("--project-root", default=".", help="Project root containing vbrief/")
601
- return parser.parse_args(argv)
602
-
603
-
604
- def main(argv: list[str] | None = None) -> int:
605
- # N10 (#1150): structured --help via scripts/triage_help.REGISTRY.
606
- from triage_help import intercept_help
607
-
608
- rc = intercept_help("scope_decompose", argv)
609
- if rc is not None:
610
- return rc
611
- args = _parse_args(sys.argv[1:] if argv is None else argv)
612
- project_root = Path(args.project_root).resolve()
613
- parent_path = _resolve_path(project_root, args.parent)
614
- draft_path = _resolve_path(project_root, args.draft)
615
- if parent_path is None and draft_path is None:
616
- if args.check:
617
- print("OK no decomposition draft supplied; nothing to apply.")
618
- return 0
619
- print("ERROR: parent path and --draft are required", file=sys.stderr)
620
- return 2
621
- if parent_path is None or draft_path is None:
622
- print("ERROR: parent path and --draft are required", file=sys.stderr)
623
- return 2
624
- if not parent_path.is_file():
625
- print(f"ERROR: parent vBRIEF not found: {parent_path}", file=sys.stderr)
626
- return 2
627
- if not draft_path.is_file():
628
- print(f"ERROR: decomposition draft not found: {draft_path}", file=sys.stderr)
629
- return 2
630
- date = args.date or datetime.now(UTC).strftime("%Y-%m-%d")
631
- if not _is_valid_creation_date(date):
632
- print(f"ERROR: --date must be YYYY-MM-DD, got {date!r}", file=sys.stderr)
633
- return 2
634
- if not args.check and not os.access(parent_path, os.W_OK):
635
- print(f"ERROR: parent vBRIEF is not writable: {parent_path}", file=sys.stderr)
636
- return 2
637
- try:
638
- actions = apply_decomposition(
639
- project_root=project_root,
640
- parent_path=parent_path,
641
- draft_path=draft_path,
642
- check_only=args.check,
643
- date=date,
644
- )
645
- except DecompositionError as exc:
646
- print(f"ERROR: {exc}", file=sys.stderr)
647
- return 1
648
- for action in actions:
649
- print(action)
650
- return 0
651
-
652
-
653
- if __name__ == "__main__":
654
- raise SystemExit(main())