@deftai/directive-content 0.59.0 → 0.60.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 (184) hide show
  1. package/.githooks/pre-push +10 -9
  2. package/Taskfile.yml +48 -58
  3. package/UPGRADING.md +1 -1
  4. package/docs/assets/directive-lifecycle-diagram.png +0 -0
  5. package/docs/directive-lifecycle.md +73 -0
  6. package/docs/getting-started.md +5 -1
  7. package/package.json +3 -3
  8. package/packs/skills/skills-pack-0.1.json +22 -22
  9. package/scm/github.md +20 -2
  10. package/tasks/change.yml +16 -31
  11. package/tasks/ci.yml +8 -0
  12. package/tasks/commit.yml +12 -19
  13. package/tasks/core.yml +10 -0
  14. package/tasks/engine.yml +42 -0
  15. package/tasks/framework.yml +3 -0
  16. package/tasks/install.yml +20 -19
  17. package/tasks/migrate.yml +26 -15
  18. package/tasks/project.yml +16 -0
  19. package/tasks/toolchain.yml +15 -5
  20. package/tasks/vbrief.yml +4 -3
  21. package/tasks/verify.yml +12 -14
  22. package/scripts/_agents_md.py +0 -494
  23. package/scripts/_cache_fetch.py +0 -635
  24. package/scripts/_cache_quota.py +0 -529
  25. package/scripts/_cache_refresh.py +0 -163
  26. package/scripts/_cache_validate.py +0 -209
  27. package/scripts/_content_root.py +0 -42
  28. package/scripts/_doctor_state.py +0 -277
  29. package/scripts/_event_detect.py +0 -305
  30. package/scripts/_events.py +0 -514
  31. package/scripts/_lifecycle_hygiene.py +0 -568
  32. package/scripts/_pathspec.py +0 -91
  33. package/scripts/_policy_show_cli.py +0 -266
  34. package/scripts/_precutover.py +0 -92
  35. package/scripts/_project_context.py +0 -224
  36. package/scripts/_project_definition_io.py +0 -164
  37. package/scripts/_relocate_snapshot.py +0 -209
  38. package/scripts/_relocate_states.py +0 -343
  39. package/scripts/_resolve_preflight_path.py +0 -152
  40. package/scripts/_safe_subprocess.py +0 -167
  41. package/scripts/_session_start_hook.py +0 -205
  42. package/scripts/_sor_gate_diff.py +0 -365
  43. package/scripts/_stdio_utf8.py +0 -59
  44. package/scripts/_triage_bootstrap_gitignore.py +0 -904
  45. package/scripts/_triage_classify_cli.py +0 -122
  46. package/scripts/_triage_queue_cli.py +0 -625
  47. package/scripts/_triage_scope_cli.py +0 -343
  48. package/scripts/_triage_scope_drift_cli.py +0 -121
  49. package/scripts/_triage_scope_ignores.py +0 -286
  50. package/scripts/_triage_scope_milestone.py +0 -432
  51. package/scripts/_triage_scope_mutations.py +0 -337
  52. package/scripts/_triage_scope_renderers.py +0 -207
  53. package/scripts/_triage_smoketest_stages.py +0 -674
  54. package/scripts/_triage_subscribe_cli.py +0 -140
  55. package/scripts/_triage_welcome_cli.py +0 -421
  56. package/scripts/_vbrief_build.py +0 -239
  57. package/scripts/_vbrief_fidelity.py +0 -479
  58. package/scripts/_vbrief_legacy.py +0 -589
  59. package/scripts/_vbrief_reconciliation.py +0 -883
  60. package/scripts/_vbrief_routing.py +0 -277
  61. package/scripts/_vbrief_safety.py +0 -778
  62. package/scripts/_vbrief_sources.py +0 -312
  63. package/scripts/_vbrief_speckit.py +0 -262
  64. package/scripts/_vbrief_story_quality.py +0 -353
  65. package/scripts/_vbrief_validation.py +0 -299
  66. package/scripts/build_dist.py +0 -412
  67. package/scripts/cache.py +0 -1078
  68. package/scripts/cache_scanner.py +0 -745
  69. package/scripts/candidates_log.py +0 -432
  70. package/scripts/capacity_backfill.py +0 -680
  71. package/scripts/capacity_show.py +0 -653
  72. package/scripts/ci_local.py +0 -689
  73. package/scripts/code_structure_validate.py +0 -765
  74. package/scripts/codebase_default_extractor.py +0 -495
  75. package/scripts/codebase_map.py +0 -304
  76. package/scripts/codebase_map_fresh.py +0 -104
  77. package/scripts/codebase_projection_registry.py +0 -94
  78. package/scripts/codebase_provider.py +0 -582
  79. package/scripts/doctor.py +0 -2552
  80. package/scripts/framework_commands.py +0 -505
  81. package/scripts/gh_rest.py +0 -882
  82. package/scripts/github_auth_modes.py +0 -437
  83. package/scripts/github_body.py +0 -292
  84. package/scripts/ip_risk.py +0 -531
  85. package/scripts/issue_emit.py +0 -670
  86. package/scripts/issue_ingest.py +0 -1064
  87. package/scripts/migrate_preflight.py +0 -418
  88. package/scripts/migrate_vbrief.py +0 -2677
  89. package/scripts/monitor_pr.py +0 -401
  90. package/scripts/pack_migrate_lessons.py +0 -336
  91. package/scripts/pack_migrate_patterns.py +0 -254
  92. package/scripts/pack_migrate_rules.py +0 -350
  93. package/scripts/pack_migrate_skills.py +0 -423
  94. package/scripts/pack_migrate_strategies.py +0 -311
  95. package/scripts/pack_migrate_swarm_spec.py +0 -250
  96. package/scripts/pack_render.py +0 -434
  97. package/scripts/packs_slice.py +0 -712
  98. package/scripts/platform_capabilities.py +0 -336
  99. package/scripts/policy.py +0 -2826
  100. package/scripts/policy_set.py +0 -324
  101. package/scripts/pr_check_closing_keywords.py +0 -524
  102. package/scripts/pr_check_protected_issues.py +0 -267
  103. package/scripts/pr_merge_readiness.py +0 -1004
  104. package/scripts/pr_wait_mergeable.py +0 -669
  105. package/scripts/prd_render.py +0 -159
  106. package/scripts/preflight_architecture_sor.py +0 -974
  107. package/scripts/preflight_branch.py +0 -289
  108. package/scripts/preflight_cache.py +0 -974
  109. package/scripts/preflight_gh.py +0 -721
  110. package/scripts/preflight_implementation.py +0 -272
  111. package/scripts/preflight_story_start.py +0 -838
  112. package/scripts/preflight_wip_cap.py +0 -149
  113. package/scripts/probe_session.py +0 -545
  114. package/scripts/project_render.py +0 -293
  115. package/scripts/quarantine_ext.py +0 -237
  116. package/scripts/reconcile_issues.py +0 -1442
  117. package/scripts/refresh-path.ps1 +0 -107
  118. package/scripts/release.py +0 -2030
  119. package/scripts/release_e2e.py +0 -1011
  120. package/scripts/release_publish.py +0 -486
  121. package/scripts/release_rollback.py +0 -980
  122. package/scripts/relocate.py +0 -1034
  123. package/scripts/resolve_changelog_unreleased.py +0 -667
  124. package/scripts/resolve_version.py +0 -490
  125. package/scripts/resume_conditions.py +0 -706
  126. package/scripts/ritual_sentinel.py +0 -609
  127. package/scripts/roadmap_render.py +0 -635
  128. package/scripts/rule_ownership_lint.py +0 -325
  129. package/scripts/scm.py +0 -591
  130. package/scripts/scope_audit_log.py +0 -387
  131. package/scripts/scope_decompose.py +0 -654
  132. package/scripts/scope_demote.py +0 -509
  133. package/scripts/scope_lifecycle.py +0 -1126
  134. package/scripts/scope_undo.py +0 -772
  135. package/scripts/session_start.py +0 -406
  136. package/scripts/setup_ghx.py +0 -339
  137. package/scripts/setup_windows.ps1 +0 -220
  138. package/scripts/slice_audit.py +0 -585
  139. package/scripts/slice_record.py +0 -530
  140. package/scripts/slice_record_existing.py +0 -692
  141. package/scripts/slug_normalize.py +0 -178
  142. package/scripts/spec_render.py +0 -477
  143. package/scripts/spec_validate.py +0 -238
  144. package/scripts/subagent_monitor.py +0 -658
  145. package/scripts/swarm_complete_cohort.py +0 -644
  146. package/scripts/swarm_launch.py +0 -1206
  147. package/scripts/swarm_readiness.py +0 -554
  148. package/scripts/swarm_verify_review_clean.py +0 -438
  149. package/scripts/swarm_worktrees.py +0 -497
  150. package/scripts/toolchain-check.py +0 -52
  151. package/scripts/triage_actions.py +0 -871
  152. package/scripts/triage_bootstrap.py +0 -1153
  153. package/scripts/triage_bulk.py +0 -630
  154. package/scripts/triage_classify.py +0 -932
  155. package/scripts/triage_help.py +0 -1685
  156. package/scripts/triage_queue.py +0 -1944
  157. package/scripts/triage_reconcile.py +0 -581
  158. package/scripts/triage_refresh.py +0 -643
  159. package/scripts/triage_scope.py +0 -999
  160. package/scripts/triage_scope_drift.py +0 -575
  161. package/scripts/triage_smoketest.py +0 -396
  162. package/scripts/triage_subscribe.py +0 -399
  163. package/scripts/triage_summary.py +0 -1011
  164. package/scripts/triage_welcome.py +0 -1178
  165. package/scripts/ts_check_lane.py +0 -86
  166. package/scripts/validate-links.py +0 -64
  167. package/scripts/validate_strategy_output.py +0 -212
  168. package/scripts/vbrief_activate.py +0 -228
  169. package/scripts/vbrief_migrate_conformance.py +0 -368
  170. package/scripts/vbrief_reconcile_graph.py +0 -306
  171. package/scripts/vbrief_reconcile_labels.py +0 -460
  172. package/scripts/vbrief_reconcile_umbrellas.py +0 -741
  173. package/scripts/vbrief_validate.py +0 -1144
  174. package/scripts/verify-stubs.py +0 -61
  175. package/scripts/verify_capacity.py +0 -160
  176. package/scripts/verify_encoding.py +0 -699
  177. package/scripts/verify_hooks_installed.py +0 -206
  178. package/scripts/verify_investigation.py +0 -360
  179. package/scripts/verify_judgment_gates.py +0 -827
  180. package/scripts/verify_no_task_runtime.py +0 -171
  181. package/scripts/verify_scm_boundary.py +0 -509
  182. package/scripts/verify_session_ritual.py +0 -389
  183. package/scripts/verify_tools.py +0 -426
  184. package/scripts/verify_vbrief_conformance.py +0 -478
@@ -1,312 +0,0 @@
1
- """_vbrief_sources.py -- pre-cutover source-file readers for migrate:vbrief.
2
-
3
- Extracted from ``scripts/migrate_vbrief.py`` so the migrator meets the
4
- <1000-line file-size MUST from ``deft/main.md`` after the #495/#505
5
- extractions. Pure helpers with no dependencies on the other migrator
6
- submodules (#454, #495, #505); behaviour is unchanged.
7
-
8
- Exports
9
- -------
10
- parse_roadmap_items(path)
11
- Parse ROADMAP.md into active items, phase descriptions, and completed
12
- items (replaces ``_parse_roadmap_items``).
13
- resolve_repo_url(spec_vbrief)
14
- Resolve the GitHub repository URL from spec_vbrief metadata.
15
- extract_tech_stack(project_content)
16
- Extract a tech-stack string from PROJECT.md markdown.
17
- first_prose_paragraph(content)
18
- Return the first plain prose paragraph (skipping code blocks, lists,
19
- etc.), falling back to the first H1 title.
20
- derive_overview_narrative(...)
21
- Resolution order for the Overview narrative on
22
- ``PROJECT-DEFINITION.vbrief.json`` (#417).
23
-
24
- Issue: #312 (original migrator); extracted by #495 + #505 swarm (Agent A).
25
- """
26
-
27
- from __future__ import annotations
28
-
29
- import re
30
- from pathlib import Path
31
- from urllib.parse import urlparse
32
-
33
- DEPRECATION_SENTINEL = "<!-- deft:deprecated-redirect -->"
34
-
35
-
36
- def parse_roadmap_items(
37
- roadmap_path: Path,
38
- ) -> tuple[list[dict], dict[str, str], list[dict]]:
39
- """Parse ROADMAP.md and extract items as structured data.
40
-
41
- Returns a tuple of:
42
- - active items: list of dicts with keys: number, title, phase, tier.
43
- - phase_descriptions: dict mapping phase heading -> description text.
44
- - completed items: list of dicts with keys: number, title, phase.
45
- """
46
- if not roadmap_path.exists():
47
- return [], {}, []
48
-
49
- content = roadmap_path.read_text(encoding="utf-8")
50
- items: list[dict] = []
51
- completed_items: list[dict] = []
52
- phase_descriptions: dict[str, str] = {}
53
- current_phase = ""
54
- current_tier = ""
55
- in_completed = False
56
- desc_lines: list[str] = []
57
- capturing_desc = False
58
- _synthetic_counter = 0
59
-
60
- for line in content.splitlines():
61
- phase_match = re.match(r"^##\s+(.+)", line)
62
- if phase_match:
63
- if current_phase and desc_lines:
64
- phase_descriptions[current_phase] = "\n".join(desc_lines).strip()
65
- desc_lines = []
66
- current_phase = phase_match.group(1).strip()
67
- current_tier = ""
68
- if "completed" in current_phase.lower():
69
- in_completed = True
70
- capturing_desc = False
71
- else:
72
- in_completed = False
73
- capturing_desc = True
74
- continue
75
-
76
- tier_match = re.match(r"^###\s+(.+)", line)
77
- if tier_match:
78
- if current_phase and desc_lines and capturing_desc:
79
- phase_descriptions[current_phase] = "\n".join(desc_lines).strip()
80
- desc_lines = []
81
- capturing_desc = False
82
- current_tier = tier_match.group(1).strip()
83
- continue
84
-
85
- if capturing_desc and not in_completed:
86
- stripped = line.strip()
87
- if stripped and not stripped.startswith("-"):
88
- desc_lines.append(stripped)
89
- continue
90
- if stripped.startswith("-"):
91
- if desc_lines:
92
- phase_descriptions[current_phase] = "\n".join(desc_lines).strip()
93
- desc_lines = []
94
- capturing_desc = False
95
- else:
96
- if desc_lines:
97
- desc_lines.append("")
98
- continue
99
-
100
- if not current_phase:
101
- continue
102
-
103
- if in_completed:
104
- comp_match = re.match(r"^-\s+~~(?:#?(\d+)\s*--?\s*)?(.+?)~~", line)
105
- if comp_match:
106
- comp_number = comp_match.group(1) or ""
107
- comp_title = comp_match.group(2).strip()
108
- completed_items.append({
109
- "number": comp_number,
110
- "title": comp_title,
111
- "phase": current_phase,
112
- })
113
- continue
114
-
115
- item_match = re.match(r"^-\s+\*\*#(\d+)\*\*\s+--\s+(.+)", line)
116
- if item_match:
117
- items.append({
118
- "number": item_match.group(1),
119
- "title": item_match.group(2).strip(),
120
- "phase": current_phase,
121
- "tier": current_tier,
122
- })
123
- continue
124
-
125
- task_match = re.match(
126
- r"^-\s+(?:\*\*)?`([^`]+)`(?:\*\*)?\s+(.+)", line
127
- )
128
- if task_match:
129
- task_id = task_match.group(1).strip()
130
- title = task_match.group(2).strip()
131
- items.append({
132
- "number": "",
133
- "title": title,
134
- "phase": current_phase,
135
- "tier": current_tier,
136
- "task_id": task_id,
137
- })
138
- continue
139
-
140
- generic_match = re.match(r"^-\s+(.+)", line)
141
- if generic_match:
142
- title = generic_match.group(1).strip()
143
- if not title:
144
- continue
145
- _synthetic_counter += 1
146
- items.append({
147
- "number": "",
148
- "title": title,
149
- "phase": current_phase,
150
- "tier": current_tier,
151
- "synthetic_id": f"roadmap-{_synthetic_counter}",
152
- })
153
- continue
154
-
155
- if current_phase and desc_lines and not in_completed:
156
- phase_descriptions[current_phase] = "\n".join(desc_lines).strip()
157
-
158
- return items, phase_descriptions, completed_items
159
-
160
-
161
- def resolve_repo_url(spec_vbrief: dict | None) -> str:
162
- """Resolve the GitHub repository URL from spec_vbrief metadata.
163
-
164
- Falls back to an empty string if no repository can be determined.
165
- """
166
- if spec_vbrief:
167
- repo = spec_vbrief.get("vBRIEFInfo", {}).get("repository", "")
168
- if repo:
169
- return f"https://github.com/{repo}"
170
- refs = spec_vbrief.get("plan", {}).get("references", [])
171
- for ref in refs:
172
- uri = ref.get("uri", "")
173
- if urlparse(uri).netloc in ("github.com", "www.github.com"):
174
- parts = uri.split("github.com/")[-1].split("/")
175
- if len(parts) >= 2:
176
- return f"https://github.com/{parts[0]}/{parts[1]}"
177
- return ""
178
-
179
-
180
- def extract_tech_stack(project_content: str) -> str:
181
- """Extract a tech-stack string from PROJECT.md content.
182
-
183
- Recognises ``**Tech Stack**: value``, ``## Tech Stack`` sections, and
184
- plain ``Tech Stack: value``.
185
- """
186
- match = re.search(
187
- r"\*\*Tech\s+Stack\*\*\s*:\s*(.+)", project_content, re.IGNORECASE
188
- )
189
- if match:
190
- return match.group(1).strip()
191
-
192
- section_match = re.search(
193
- r"##\s+Tech\s+Stack\s*\n(.*?)(?=\n##\s|\Z)",
194
- project_content,
195
- re.IGNORECASE | re.DOTALL,
196
- )
197
- if section_match:
198
- section = section_match.group(1).strip()
199
- if section:
200
- return section
201
-
202
- plain_match = re.search(
203
- r"Tech\s+Stack\s*:\s*(.+)", project_content, re.IGNORECASE
204
- )
205
- if plain_match:
206
- return plain_match.group(1).strip()
207
-
208
- return ""
209
-
210
-
211
- def first_prose_paragraph(content: str) -> str:
212
- """Return the first non-empty prose paragraph from markdown content."""
213
- if not content:
214
- return ""
215
- first_h1 = ""
216
- in_code_block = False
217
- paragraph_lines: list[str] = []
218
-
219
- def _flush() -> str:
220
- if paragraph_lines:
221
- return " ".join(paragraph_lines).strip()
222
- return ""
223
-
224
- for line in content.splitlines():
225
- stripped = line.strip()
226
- if stripped.startswith("```"):
227
- in_code_block = not in_code_block
228
- continue
229
- if in_code_block:
230
- continue
231
- if re.match(r"^#\s+", stripped) and not first_h1:
232
- first_h1 = re.sub(r"^#\s+", "", stripped).strip()
233
- continue
234
- if stripped.startswith("#"):
235
- para = _flush()
236
- if para:
237
- return para
238
- paragraph_lines.clear()
239
- continue
240
- if stripped.startswith(("-", "*", ">", "|")) or re.match(r"^\d+\.\s", stripped):
241
- para = _flush()
242
- if para:
243
- return para
244
- paragraph_lines.clear()
245
- continue
246
- if not stripped:
247
- para = _flush()
248
- if para:
249
- return para
250
- paragraph_lines.clear()
251
- continue
252
- paragraph_lines.append(stripped)
253
-
254
- para = _flush()
255
- if para:
256
- return para
257
- return first_h1
258
-
259
-
260
- def derive_overview_narrative(
261
- spec_vbrief: dict | None,
262
- spec_md_content: str | None,
263
- project_content: str | None,
264
- scope_item_count: int,
265
- ) -> str:
266
- """Derive an Overview narrative for PROJECT-DEFINITION.vbrief.json (#417).
267
-
268
- Resolution order:
269
- 1. ``spec_vbrief.plan.narratives['Overview']`` if non-empty.
270
- 2. First prose paragraph / H1 of ``SPECIFICATION.md`` (pre-sentinel).
271
- 3. First prose paragraph / H1 of ``PROJECT.md`` (pre-sentinel).
272
- 4. Synthesized placeholder naming the scope count.
273
- """
274
- if spec_vbrief:
275
- narratives = spec_vbrief.get("plan", {}).get("narratives", {})
276
- if isinstance(narratives, dict):
277
- ov = narratives.get("Overview")
278
- if isinstance(ov, str) and ov.strip():
279
- return ov.strip()
280
-
281
- if spec_md_content and DEPRECATION_SENTINEL not in spec_md_content:
282
- derived = first_prose_paragraph(spec_md_content)
283
- if derived:
284
- return derived
285
-
286
- if project_content and DEPRECATION_SENTINEL not in project_content:
287
- derived = first_prose_paragraph(project_content)
288
- if derived:
289
- return derived
290
-
291
- if scope_item_count > 0:
292
- return (
293
- f"Project overview was not auto-derived during migration. "
294
- f"{scope_item_count} scope item(s) were created in vbrief/pending/. "
295
- f"Update vbrief/PROJECT-DEFINITION.vbrief.json narratives['Overview'] "
296
- f"manually to describe your project."
297
- )
298
- return (
299
- "Project overview was not auto-derived during migration. "
300
- "Update vbrief/PROJECT-DEFINITION.vbrief.json narratives['Overview'] "
301
- "manually to describe your project."
302
- )
303
-
304
-
305
- __all__ = [
306
- "DEPRECATION_SENTINEL",
307
- "derive_overview_narrative",
308
- "extract_tech_stack",
309
- "first_prose_paragraph",
310
- "parse_roadmap_items",
311
- "resolve_repo_url",
312
- ]
@@ -1,262 +0,0 @@
1
- """_vbrief_speckit.py -- speckit plan.vbrief.json -> scope vBRIEFs translator.
2
-
3
- Extracted from ``scripts/migrate_vbrief.py`` so the migrator meets the
4
- <1000-line file-size MUST from ``deft/main.md`` after the #495/#505
5
- extractions. Behaviour is unchanged; import names preserved for the
6
- existing test surface.
7
-
8
- Story: #436 / #458. Extracted by #495 + #505 swarm (Agent A).
9
- """
10
-
11
- from __future__ import annotations
12
-
13
- import json
14
- import re
15
- from pathlib import Path
16
-
17
- from _vbrief_build import (
18
- EMITTED_VBRIEF_VERSION as _EMITTED_VBRIEF_VERSION,
19
- reference_with_default_trust as _reference_with_default_trust,
20
- slugify as _slugify_shared,
21
- )
22
-
23
-
24
- def edge_nodes(edge: dict) -> tuple[str, str]:
25
- """Return (from_id, to_id) for a vBRIEF edge, reading both dialects.
26
-
27
- Speckit plan edges use ``from`` / ``to`` in current drafts, but earlier
28
- drafts used ``source`` / ``target``. Prefer the current keys when they
29
- are populated and fall back to the legacy keys.
30
- """
31
- if not isinstance(edge, dict):
32
- return "", ""
33
- src = edge.get("from") or edge.get("source", "")
34
- tgt = edge.get("to") or edge.get("target", "")
35
- return str(src or ""), str(tgt or "")
36
-
37
-
38
- def dependencies_for_item(item_id: str, edges: list[dict]) -> list[str]:
39
- """Return the list of item IDs that block ``item_id`` (bilingual reader).
40
-
41
- An edge with ``type == 'blocks'`` and target equal to ``item_id`` means
42
- the edge's source blocks this item -- so the source is a dependency.
43
- """
44
- deps: list[str] = []
45
- for edge in edges or []:
46
- if not isinstance(edge, dict):
47
- continue
48
- if edge.get("type", "") != "blocks":
49
- continue
50
- src, tgt = edge_nodes(edge)
51
- if tgt == item_id and src and src not in deps:
52
- deps.append(src)
53
- return deps
54
-
55
-
56
- def speckit_ip_slug(title: str, item_id: str) -> str:
57
- """Return a slug for a speckit IP item filename."""
58
- source = (title or item_id or "").strip()
59
- source = re.sub(
60
- r"^\s*IP[\s-]*\d+\s*[:\-]\s*", "", source, flags=re.IGNORECASE
61
- )
62
- slug = _slugify_shared(source)
63
- return slug or _slugify_shared(item_id) or "ip-phase"
64
-
65
-
66
- def speckit_ip_index(item: dict, fallback_index: int) -> int:
67
- """Derive the numeric IP index for a speckit plan item."""
68
- item_id = str(item.get("id", "") or "")
69
- tail = re.search(r"(\d+)\s*$", item_id)
70
- if tail:
71
- return int(tail.group(1))
72
- title = str(item.get("title", "") or "")
73
- lead = re.search(r"IP[\s-]*(\d+)", title, flags=re.IGNORECASE)
74
- if lead:
75
- return int(lead.group(1))
76
- return fallback_index
77
-
78
-
79
- def _non_empty_text(value: object, fallback: str) -> str:
80
- text = str(value or "").strip()
81
- return text or fallback
82
-
83
-
84
- def create_speckit_scope_vbrief(
85
- item: dict,
86
- *,
87
- ip_index: int,
88
- dependencies: list[str],
89
- spec_ref: str,
90
- ) -> dict:
91
- """Build a Phase 4 scope vBRIEF dict for a speckit implementation phase.
92
-
93
- Populates the canonical narrative keys (``Description``, ``Acceptance``,
94
- ``Traces``), writes ``plan.metadata.dependencies`` at the plan level,
95
- and links back to the parent ``specification.vbrief.json`` via a
96
- ``x-vbrief/plan`` reference.
97
- """
98
- spec_ref = _vbrief_relative_spec_ref(spec_ref)
99
- fallback_title = f"IP-{ip_index}"
100
- title = _non_empty_text(item.get("title"), fallback_title)
101
- narrative = item.get("narrative") or {}
102
- if not isinstance(narrative, dict):
103
- narrative = {}
104
-
105
- def _pick(*keys: str) -> str:
106
- for key in keys:
107
- value = narrative.get(key)
108
- if isinstance(value, str) and value.strip():
109
- return value.strip()
110
- return ""
111
-
112
- description = _pick("Description", "Summary") or title or fallback_title
113
- acceptance = _pick("Acceptance", "AcceptanceCriteria")
114
- traces = _pick("Traces", "Trace", "Requirements") or fallback_title
115
-
116
- default_acceptance = (
117
- f"Acceptance criteria for IP-{ip_index} "
118
- f"(copy from specification.vbrief.json)."
119
- )
120
- narratives: dict[str, str] = {
121
- "Description": description,
122
- "Acceptance": acceptance or default_acceptance,
123
- "Traces": traces,
124
- }
125
- for extra in ("Phase", "PhaseDescription", "Tier"):
126
- value = narrative.get(extra)
127
- if isinstance(value, str) and value.strip():
128
- narratives[extra] = value.strip()
129
-
130
- references = [
131
- _reference_with_default_trust({"type": "x-vbrief/plan", "uri": spec_ref})
132
- ]
133
- for ref in item.get("references", []) or []:
134
- if isinstance(ref, dict) and ref.get("type") != "x-vbrief/plan":
135
- references.append(_reference_with_default_trust(ref))
136
-
137
- plan: dict = {
138
- "title": title,
139
- "status": "pending",
140
- "narratives": narratives,
141
- "items": [],
142
- "metadata": {"kind": "phase"},
143
- "references": references,
144
- }
145
- if dependencies:
146
- plan["metadata"]["dependencies"] = list(dependencies)
147
-
148
- return {
149
- "vBRIEFInfo": {
150
- "version": _EMITTED_VBRIEF_VERSION,
151
- "description": f"Scope vBRIEF for speckit IP-{ip_index}",
152
- },
153
- "plan": plan,
154
- }
155
-
156
-
157
- def _vbrief_relative_spec_ref(spec_ref: str) -> str:
158
- """Return a vbrief-directory-relative reference for the parent spec."""
159
- normalized = spec_ref.strip()
160
- while normalized.startswith("../"):
161
- normalized = normalized[3:]
162
- return normalized or "specification.vbrief.json"
163
-
164
-
165
- def migrate_speckit_plan(
166
- plan_path: Path,
167
- *,
168
- pending_dir: Path | None = None,
169
- date: str | None = None,
170
- spec_ref: str = "specification.vbrief.json",
171
- today: str | None = None,
172
- ) -> tuple[bool, list[str]]:
173
- """Translate a speckit-shaped ``plan.vbrief.json`` into scope vBRIEFs.
174
-
175
- Each ``plan.items`` entry becomes a file in ``pending_dir`` named
176
- ``YYYY-MM-DD-ip<NNN>-<slug>.vbrief.json``.
177
- """
178
- actions: list[str] = []
179
- if not plan_path.is_file():
180
- return False, [f"ERROR: plan.vbrief.json not found at {plan_path}"]
181
-
182
- try:
183
- plan_data = json.loads(plan_path.read_text(encoding="utf-8"))
184
- except json.JSONDecodeError as exc:
185
- return False, [f"ERROR: invalid JSON in {plan_path.name}: {exc}"]
186
-
187
- plan = plan_data.get("plan", {}) if isinstance(plan_data, dict) else {}
188
- items = plan.get("items", []) if isinstance(plan, dict) else []
189
- edges = plan.get("edges", []) if isinstance(plan, dict) else []
190
-
191
- if not items:
192
- return False, [
193
- "ERROR: plan.vbrief.json has no items to migrate (empty speckit plan?)"
194
- ]
195
-
196
- pending_dir = pending_dir or (plan_path.parent / "pending")
197
- pending_dir.mkdir(parents=True, exist_ok=True)
198
- effective_date = date or today
199
- if effective_date is None: # pragma: no cover -- caller always supplies
200
- from datetime import UTC, datetime # noqa: WPS433 -- lazy import
201
- effective_date = datetime.now(UTC).strftime("%Y-%m-%d")
202
-
203
- created_paths: list[Path] = []
204
- for idx, item in enumerate(items, start=1):
205
- if not isinstance(item, dict):
206
- continue
207
- ip_index = speckit_ip_index(item, idx)
208
- item_id = str(item.get("id", "") or f"ip-{ip_index}")
209
- dependencies = dependencies_for_item(item_id, edges)
210
- slug = speckit_ip_slug(str(item.get("title", "")), item_id)
211
- ip_token = f"ip{ip_index:03d}"
212
- filename = f"{effective_date}-{ip_token}-{slug}.vbrief.json"
213
- target = pending_dir / filename
214
- if target.exists():
215
- actions.append(f"SKIP pending/{filename} already exists")
216
- created_paths.append(target)
217
- continue
218
- scope = create_speckit_scope_vbrief(
219
- item,
220
- ip_index=ip_index,
221
- dependencies=dependencies,
222
- spec_ref=spec_ref,
223
- )
224
- target.write_text(
225
- json.dumps(scope, indent=2, ensure_ascii=False) + "\n",
226
- encoding="utf-8",
227
- )
228
- actions.append(f"CREATE pending/{filename} (IP-{ip_index})")
229
- created_paths.append(target)
230
-
231
- envelope = plan_data.get("vBRIEFInfo", {}) if isinstance(plan_data, dict) else {}
232
- # #533: force the emitted envelope to the current canonical version so a
233
- # v0.5 speckit plan migrated today produces a v0.6 session scaffold.
234
- envelope["version"] = _EMITTED_VBRIEF_VERSION
235
- envelope["description"] = (
236
- "Session-level tactical plan (migrated from speckit plan). "
237
- "Scope vBRIEFs live in vbrief/pending/."
238
- )
239
- session_plan = {
240
- "vBRIEFInfo": envelope,
241
- "plan": {
242
- "title": str(plan.get("title", "Session plan")) or "Session plan",
243
- "status": "running",
244
- "items": [],
245
- },
246
- }
247
- plan_path.write_text(
248
- json.dumps(session_plan, indent=2, ensure_ascii=False) + "\n",
249
- encoding="utf-8",
250
- )
251
- actions.append(f"REWRITE {plan_path.name} -> session-todo scaffold")
252
- return True, actions
253
-
254
-
255
- __all__ = [
256
- "create_speckit_scope_vbrief",
257
- "dependencies_for_item",
258
- "edge_nodes",
259
- "migrate_speckit_plan",
260
- "speckit_ip_index",
261
- "speckit_ip_slug",
262
- ]