@deftai/directive-content 0.55.1 → 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 (220) hide show
  1. package/.githooks/pre-commit +143 -0
  2. package/.githooks/pre-push +121 -0
  3. package/QUICK-START.md +13 -3
  4. package/Taskfile.yml +934 -0
  5. package/UPGRADING.md +82 -11
  6. package/events/README.md +3 -3
  7. package/package.json +5 -4
  8. package/packs/skills/skills-pack-0.1.json +22 -22
  9. package/scripts/_agents_md.py +494 -0
  10. package/scripts/_cache_fetch.py +635 -0
  11. package/scripts/_cache_quota.py +529 -0
  12. package/scripts/_cache_refresh.py +163 -0
  13. package/scripts/_cache_validate.py +209 -0
  14. package/scripts/_content_root.py +42 -0
  15. package/scripts/_doctor_state.py +277 -0
  16. package/scripts/_event_detect.py +305 -0
  17. package/scripts/_events.py +514 -0
  18. package/scripts/_lifecycle_hygiene.py +568 -0
  19. package/scripts/_pathspec.py +91 -0
  20. package/scripts/_policy_show_cli.py +266 -0
  21. package/scripts/_precutover.py +92 -0
  22. package/scripts/_project_context.py +224 -0
  23. package/scripts/_project_definition_io.py +164 -0
  24. package/scripts/_relocate_snapshot.py +209 -0
  25. package/scripts/_relocate_states.py +343 -0
  26. package/scripts/_resolve_preflight_path.py +152 -0
  27. package/scripts/_safe_subprocess.py +167 -0
  28. package/scripts/_session_start_hook.py +205 -0
  29. package/scripts/_sor_gate_diff.py +365 -0
  30. package/scripts/_stdio_utf8.py +59 -0
  31. package/scripts/_triage_bootstrap_gitignore.py +904 -0
  32. package/scripts/_triage_classify_cli.py +122 -0
  33. package/scripts/_triage_queue_cli.py +625 -0
  34. package/scripts/_triage_scope_cli.py +343 -0
  35. package/scripts/_triage_scope_drift_cli.py +121 -0
  36. package/scripts/_triage_scope_ignores.py +286 -0
  37. package/scripts/_triage_scope_milestone.py +432 -0
  38. package/scripts/_triage_scope_mutations.py +337 -0
  39. package/scripts/_triage_scope_renderers.py +207 -0
  40. package/scripts/_triage_smoketest_stages.py +674 -0
  41. package/scripts/_triage_subscribe_cli.py +140 -0
  42. package/scripts/_triage_welcome_cli.py +421 -0
  43. package/scripts/_vbrief_build.py +239 -0
  44. package/scripts/_vbrief_fidelity.py +479 -0
  45. package/scripts/_vbrief_legacy.py +589 -0
  46. package/scripts/_vbrief_reconciliation.py +883 -0
  47. package/scripts/_vbrief_routing.py +277 -0
  48. package/scripts/_vbrief_safety.py +778 -0
  49. package/scripts/_vbrief_sources.py +312 -0
  50. package/scripts/_vbrief_speckit.py +262 -0
  51. package/scripts/_vbrief_story_quality.py +353 -0
  52. package/scripts/_vbrief_validation.py +299 -0
  53. package/scripts/build_dist.py +412 -0
  54. package/scripts/cache.py +1078 -0
  55. package/scripts/cache_scanner.py +745 -0
  56. package/scripts/candidates_log.py +432 -0
  57. package/scripts/capacity_backfill.py +680 -0
  58. package/scripts/capacity_show.py +653 -0
  59. package/scripts/ci_local.py +689 -0
  60. package/scripts/code_structure_validate.py +765 -0
  61. package/scripts/codebase_default_extractor.py +495 -0
  62. package/scripts/codebase_map.py +304 -0
  63. package/scripts/codebase_map_fresh.py +104 -0
  64. package/scripts/codebase_projection_registry.py +94 -0
  65. package/scripts/codebase_provider.py +582 -0
  66. package/scripts/doctor.py +2257 -0
  67. package/scripts/framework_commands.py +505 -0
  68. package/scripts/gh_rest.py +882 -0
  69. package/scripts/github_auth_modes.py +437 -0
  70. package/scripts/github_body.py +292 -0
  71. package/scripts/ip_risk.py +531 -0
  72. package/scripts/issue_emit.py +670 -0
  73. package/scripts/issue_ingest.py +1064 -0
  74. package/scripts/migrate_preflight.py +418 -0
  75. package/scripts/migrate_vbrief.py +2677 -0
  76. package/scripts/monitor_pr.py +401 -0
  77. package/scripts/pack_migrate_lessons.py +336 -0
  78. package/scripts/pack_migrate_patterns.py +254 -0
  79. package/scripts/pack_migrate_rules.py +350 -0
  80. package/scripts/pack_migrate_skills.py +423 -0
  81. package/scripts/pack_migrate_strategies.py +311 -0
  82. package/scripts/pack_migrate_swarm_spec.py +250 -0
  83. package/scripts/pack_render.py +434 -0
  84. package/scripts/packs_slice.py +712 -0
  85. package/scripts/platform_capabilities.py +336 -0
  86. package/scripts/policy.py +2826 -0
  87. package/scripts/policy_set.py +324 -0
  88. package/scripts/pr_check_closing_keywords.py +524 -0
  89. package/scripts/pr_check_protected_issues.py +267 -0
  90. package/scripts/pr_merge_readiness.py +1004 -0
  91. package/scripts/pr_wait_mergeable.py +669 -0
  92. package/scripts/prd_render.py +159 -0
  93. package/scripts/preflight_architecture_sor.py +974 -0
  94. package/scripts/preflight_branch.py +289 -0
  95. package/scripts/preflight_cache.py +974 -0
  96. package/scripts/preflight_gh.py +721 -0
  97. package/scripts/preflight_implementation.py +272 -0
  98. package/scripts/preflight_story_start.py +838 -0
  99. package/scripts/preflight_wip_cap.py +149 -0
  100. package/scripts/probe_session.py +545 -0
  101. package/scripts/project_render.py +293 -0
  102. package/scripts/quarantine_ext.py +237 -0
  103. package/scripts/reconcile_issues.py +1442 -0
  104. package/scripts/refresh-path.ps1 +107 -0
  105. package/scripts/release.py +2030 -0
  106. package/scripts/release_e2e.py +1011 -0
  107. package/scripts/release_publish.py +486 -0
  108. package/scripts/release_rollback.py +980 -0
  109. package/scripts/relocate.py +1034 -0
  110. package/scripts/resolve_changelog_unreleased.py +667 -0
  111. package/scripts/resolve_version.py +490 -0
  112. package/scripts/resume_conditions.py +706 -0
  113. package/scripts/ritual_sentinel.py +609 -0
  114. package/scripts/roadmap_render.py +635 -0
  115. package/scripts/rule_ownership_lint.py +325 -0
  116. package/scripts/scm.py +591 -0
  117. package/scripts/scope_audit_log.py +387 -0
  118. package/scripts/scope_decompose.py +654 -0
  119. package/scripts/scope_demote.py +509 -0
  120. package/scripts/scope_lifecycle.py +1126 -0
  121. package/scripts/scope_undo.py +772 -0
  122. package/scripts/session_start.py +406 -0
  123. package/scripts/setup_ghx.py +339 -0
  124. package/scripts/setup_windows.ps1 +220 -0
  125. package/scripts/slice_audit.py +585 -0
  126. package/scripts/slice_record.py +530 -0
  127. package/scripts/slice_record_existing.py +692 -0
  128. package/scripts/slug_normalize.py +178 -0
  129. package/scripts/spec_render.py +477 -0
  130. package/scripts/spec_validate.py +238 -0
  131. package/scripts/subagent_monitor.py +658 -0
  132. package/scripts/swarm_complete_cohort.py +644 -0
  133. package/scripts/swarm_launch.py +1206 -0
  134. package/scripts/swarm_readiness.py +554 -0
  135. package/scripts/swarm_verify_review_clean.py +438 -0
  136. package/scripts/swarm_worktrees.py +497 -0
  137. package/scripts/toolchain-check.py +52 -0
  138. package/scripts/triage_actions.py +871 -0
  139. package/scripts/triage_bootstrap.py +1153 -0
  140. package/scripts/triage_bulk.py +630 -0
  141. package/scripts/triage_classify.py +932 -0
  142. package/scripts/triage_help.py +1685 -0
  143. package/scripts/triage_queue.py +1944 -0
  144. package/scripts/triage_reconcile.py +581 -0
  145. package/scripts/triage_refresh.py +643 -0
  146. package/scripts/triage_scope.py +999 -0
  147. package/scripts/triage_scope_drift.py +575 -0
  148. package/scripts/triage_smoketest.py +396 -0
  149. package/scripts/triage_subscribe.py +399 -0
  150. package/scripts/triage_summary.py +1011 -0
  151. package/scripts/triage_welcome.py +1178 -0
  152. package/scripts/ts_check_lane.py +86 -0
  153. package/scripts/validate-links.py +64 -0
  154. package/scripts/validate_strategy_output.py +212 -0
  155. package/scripts/vbrief_activate.py +228 -0
  156. package/scripts/vbrief_migrate_conformance.py +368 -0
  157. package/scripts/vbrief_reconcile_graph.py +306 -0
  158. package/scripts/vbrief_reconcile_labels.py +460 -0
  159. package/scripts/vbrief_reconcile_umbrellas.py +741 -0
  160. package/scripts/vbrief_validate.py +1195 -0
  161. package/scripts/verify-stubs.py +61 -0
  162. package/scripts/verify_capacity.py +160 -0
  163. package/scripts/verify_encoding.py +699 -0
  164. package/scripts/verify_hooks_installed.py +206 -0
  165. package/scripts/verify_investigation.py +360 -0
  166. package/scripts/verify_judgment_gates.py +827 -0
  167. package/scripts/verify_no_task_runtime.py +171 -0
  168. package/scripts/verify_scm_boundary.py +509 -0
  169. package/scripts/verify_session_ritual.py +389 -0
  170. package/scripts/verify_tools.py +426 -0
  171. package/scripts/verify_vbrief_conformance.py +478 -0
  172. package/skills/deft-directive-swarm/SKILL.md +7 -26
  173. package/skills/deft-directive-sync/SKILL.md +1 -1
  174. package/tasks/architecture.yml +13 -0
  175. package/tasks/cache.yml +69 -0
  176. package/tasks/capacity.yml +38 -0
  177. package/tasks/change.yml +46 -0
  178. package/tasks/changelog.yml +24 -0
  179. package/tasks/ci.yml +49 -0
  180. package/tasks/codebase.yml +47 -0
  181. package/tasks/commit.yml +30 -0
  182. package/tasks/core.yml +126 -0
  183. package/tasks/deployments.yml +54 -0
  184. package/tasks/framework.yml +74 -0
  185. package/tasks/install.yml +60 -0
  186. package/tasks/issue.yml +50 -0
  187. package/tasks/migrate.yml +73 -0
  188. package/tasks/packs.yml +92 -0
  189. package/tasks/policy.yml +75 -0
  190. package/tasks/pr.yml +89 -0
  191. package/tasks/prd.yml +39 -0
  192. package/tasks/project.yml +27 -0
  193. package/tasks/reconcile.yml +32 -0
  194. package/tasks/relocate.yml +56 -0
  195. package/tasks/roadmap.yml +28 -0
  196. package/tasks/scm.yml +126 -0
  197. package/tasks/scope-undo.yml +36 -0
  198. package/tasks/scope.yml +141 -0
  199. package/tasks/session.yml +19 -0
  200. package/tasks/setup.yml +37 -0
  201. package/tasks/slice.yml +69 -0
  202. package/tasks/spec.yml +41 -0
  203. package/tasks/swarm.yml +85 -0
  204. package/tasks/toolchain.yml +13 -0
  205. package/tasks/triage-actions.yml +94 -0
  206. package/tasks/triage-bootstrap.yml +43 -0
  207. package/tasks/triage-bulk.yml +75 -0
  208. package/tasks/triage-classify.yml +30 -0
  209. package/tasks/triage-queue.yml +50 -0
  210. package/tasks/triage-reconcile.yml +29 -0
  211. package/tasks/triage-scope-drift.yml +29 -0
  212. package/tasks/triage-scope.yml +31 -0
  213. package/tasks/triage-smoketest.yml +33 -0
  214. package/tasks/triage-subscribe.yml +36 -0
  215. package/tasks/triage-summary.yml +29 -0
  216. package/tasks/triage-welcome.yml +32 -0
  217. package/tasks/ts.yml +328 -0
  218. package/tasks/vbrief.yml +206 -0
  219. package/tasks/verify.yml +292 -0
  220. package/templates/agents-entry.md +2 -2
@@ -0,0 +1,509 @@
1
+ #!/usr/bin/env python3
2
+ """scope_demote.py -- ``task scope:demote`` driver (#1121).
3
+
4
+ Demotes a vBRIEF scope from ``pending/`` back to ``proposed/`` and records
5
+ a structured audit entry with a ``demote_meta`` block. Two modes:
6
+
7
+ 1. Single demote::
8
+
9
+ scope_demote.py <file> [--reason TEXT] [--project-root PATH]
10
+
11
+ 2. Batch demote (all ``pending/`` vBRIEFs older than N days)::
12
+
13
+ scope_demote.py --batch [--older-than-days N] [--project-root PATH]
14
+
15
+ Default ``--older-than-days`` is **45** per Current Shape decision
16
+ (deep-pass §A1 bump from the original 30; see Current Shape comment
17
+ 4471271992 on #1121).
18
+
19
+ Every demote (single or batch) appends one entry to
20
+ ``<project_root>/vbrief/.eval/scope-lifecycle.jsonl`` with the
21
+ ``demote_meta`` instrumentation block defined in
22
+ :mod:`scripts.scope_audit_log`:
23
+
24
+ * ``was_promoted`` -- bool, true if source folder was ``pending/``.
25
+ * ``original_promotion_decision_id`` -- UUID of prior promote audit entry
26
+ on the same path, ``null`` when no prior entry exists (forward-compat;
27
+ emitters that record promote entries in the future will populate this
28
+ field automatically).
29
+ * ``days_in_pending`` -- non-negative int, ``floor((now - plan.updated).days)``
30
+ with a fallback to file mtime when ``plan.updated`` is absent or unparseable.
31
+ * ``demote_reason`` -- free-form text (operator) or batch-rule name
32
+ (``"batch:older-than-days:<N>"``).
33
+ * ``demoted_from`` -- source folder name (``"pending"`` for the supported
34
+ path; left in place for future expansion to other source folders).
35
+
36
+ Out of scope (per Current Shape):
37
+
38
+ - 30%-threshold falsification gate / D17 (Decision 2: dropped).
39
+ - Lightweight metrics over the audit log (Decision 3: deferred to #1180).
40
+
41
+ Path resolution mirrors ``scope_lifecycle.py``: relative ``<file>``
42
+ arguments resolve against ``--project-root`` / ``$DEFT_PROJECT_ROOT`` / the
43
+ nearest ``vbrief|.git`` ancestor, never against ``deft/``.
44
+
45
+ Exit codes:
46
+ 0 -- demote succeeded (single) or batch completed (even with 0 demotes).
47
+ 1 -- single-demote validation or transition error.
48
+ 2 -- usage error (including undetectable project root for relative path).
49
+
50
+ Refs: #1119 (umbrella), #1121 (D1).
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import argparse
56
+ import json
57
+ import sys
58
+ from datetime import UTC, datetime
59
+ from pathlib import Path
60
+
61
+ # Make sibling helpers importable both when run as ``__main__`` and when
62
+ # imported by tests that preload sys.path.
63
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
64
+
65
+ from _project_context import resolve_project_root # noqa: E402
66
+ from _stdio_utf8 import reconfigure_stdio # noqa: E402
67
+ from scope_audit_log import ( # noqa: E402
68
+ append as audit_append,
69
+ canonical_log_path,
70
+ latest_for_path,
71
+ new_decision_id,
72
+ )
73
+
74
+ reconfigure_stdio()
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Constants
79
+ # ---------------------------------------------------------------------------
80
+
81
+ DEFAULT_OLDER_THAN_DAYS = 45
82
+ SOURCE_FOLDER = "pending"
83
+ TARGET_FOLDER = "proposed"
84
+ TARGET_STATUS = "proposed"
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Core helpers
89
+ # ---------------------------------------------------------------------------
90
+
91
+
92
+ def _canonical_relpath(file_path: Path, project_root: Path) -> str:
93
+ """Return a forward-slash, project-root-relative form for audit entries.
94
+
95
+ Falls back to the resolved absolute path string when the file is not
96
+ under *project_root* (e.g. a test fixture under tmp_path with a different
97
+ root). Forward-slash form keeps cross-platform string equality stable
98
+ against the audit log on Windows.
99
+ """
100
+ try:
101
+ rel = file_path.resolve().relative_to(project_root.resolve())
102
+ except ValueError:
103
+ return file_path.resolve().as_posix()
104
+ return rel.as_posix()
105
+
106
+
107
+ def _parse_plan_updated(text: str) -> datetime | None:
108
+ """Parse an ISO-8601 ``plan.updated`` string to a UTC datetime.
109
+
110
+ Accepts both ``YYYY-MM-DDTHH:MM:SSZ`` (the format ``scope_lifecycle``
111
+ writes) and ``YYYY-MM-DDTHH:MM:SS+00:00`` (older fixtures). Returns
112
+ ``None`` on unparseable input so the caller can fall back to file mtime.
113
+ """
114
+ if not text:
115
+ return None
116
+ candidate = text
117
+ if candidate.endswith("Z"):
118
+ candidate = candidate[:-1] + "+00:00"
119
+ try:
120
+ dt = datetime.fromisoformat(candidate)
121
+ except ValueError:
122
+ return None
123
+ if dt.tzinfo is None:
124
+ dt = dt.replace(tzinfo=UTC)
125
+ return dt.astimezone(UTC)
126
+
127
+
128
+ def _days_in_pending(file_path: Path, plan_updated: str | None, now: datetime) -> int:
129
+ """Compute integer days between *now* and the file's last-pending stamp.
130
+
131
+ Preference order:
132
+ 1. ``plan.updated`` parsed as ISO-8601 UTC (set by ``scope:promote``).
133
+ 2. File modification time.
134
+
135
+ The result is clamped to a non-negative int to keep
136
+ ``demote_meta.days_in_pending`` schema-valid even under minor clock skew.
137
+ """
138
+ parsed = _parse_plan_updated(plan_updated) if plan_updated else None
139
+ if parsed is None:
140
+ mtime = file_path.stat().st_mtime
141
+ parsed = datetime.fromtimestamp(mtime, tz=UTC)
142
+ delta = now - parsed
143
+ return max(0, delta.days)
144
+
145
+
146
+ def _resolve_file_path(
147
+ raw: str, cli_project_root: str | None
148
+ ) -> tuple[Path | None, str | None]:
149
+ """Resolve a possibly-relative *raw* path to an absolute Path.
150
+
151
+ Mirrors ``scope_lifecycle._resolve_file_path`` so the two surfaces share
152
+ a consistent path-resolution story (#535). Returns ``(path, None)`` on
153
+ success, ``(None, error_message)`` on failure.
154
+ """
155
+ stripped = raw.strip().rstrip("\\/") if raw else ""
156
+ if not stripped:
157
+ return None, (
158
+ "No vBRIEF file path provided. "
159
+ "Usage: scope_demote.py <file> [--reason TEXT] [--project-root PATH]"
160
+ )
161
+ candidate = Path(stripped)
162
+ if candidate.is_absolute():
163
+ return candidate.resolve(), None
164
+ project_root = resolve_project_root(cli_project_root)
165
+ if project_root is None:
166
+ return None, (
167
+ f"Cannot resolve relative path {stripped!r}: no project root "
168
+ "detected. Pass --project-root PATH, set $DEFT_PROJECT_ROOT, "
169
+ "or run from inside a directory tree that contains vbrief/ or "
170
+ ".git/ (#535)."
171
+ )
172
+ return (project_root / stripped).resolve(), None
173
+
174
+
175
+ def _resolve_project_root_strict(
176
+ cli_project_root: str | None,
177
+ ) -> tuple[Path | None, str | None]:
178
+ """Resolve --project-root for batch mode; both must succeed."""
179
+ project_root = resolve_project_root(cli_project_root)
180
+ if project_root is None:
181
+ return None, (
182
+ "Cannot determine project root for batch demote. Pass "
183
+ "--project-root PATH, set $DEFT_PROJECT_ROOT, or run from inside "
184
+ "a directory tree that contains vbrief/ or .git/ (#535)."
185
+ )
186
+ return project_root, None
187
+
188
+
189
+ # ---------------------------------------------------------------------------
190
+ # Single-demote engine
191
+ # ---------------------------------------------------------------------------
192
+
193
+
194
+ def demote_one(
195
+ file_path: Path,
196
+ project_root: Path,
197
+ reason: str,
198
+ *,
199
+ actor: str = "operator",
200
+ now: datetime | None = None,
201
+ log_path: Path | None = None,
202
+ batch_id: str | None = None,
203
+ ) -> tuple[bool, str, dict | None]:
204
+ """Demote a single vBRIEF file from ``pending/`` to ``proposed/``.
205
+
206
+ Returns ``(ok, message, audit_entry)``. ``audit_entry`` is the dict that
207
+ was appended to the audit log (so callers / tests can introspect it
208
+ without re-reading the file).
209
+ """
210
+ if not file_path.exists():
211
+ return False, f"File not found: {file_path}", None
212
+ if not file_path.name.endswith(".vbrief.json"):
213
+ return False, f"Not a vBRIEF file (expected .vbrief.json): {file_path.name}", None
214
+
215
+ parent = file_path.parent.name
216
+ if parent != SOURCE_FOLDER:
217
+ return (
218
+ False,
219
+ (
220
+ f"Invalid transition: 'demote' requires file in "
221
+ f"{SOURCE_FOLDER}/. File is in {parent}/."
222
+ ),
223
+ None,
224
+ )
225
+
226
+ try:
227
+ data = json.loads(file_path.read_text(encoding="utf-8"))
228
+ except json.JSONDecodeError as exc:
229
+ return False, f"Invalid JSON in {file_path}: {exc}", None
230
+
231
+ plan = data.get("plan")
232
+ if not isinstance(plan, dict):
233
+ return False, f"Missing or invalid 'plan' object in {file_path}", None
234
+
235
+ current_now = now or datetime.now(UTC)
236
+ plan_updated_before = plan.get("updated")
237
+ days = _days_in_pending(file_path, plan_updated_before, current_now)
238
+
239
+ # Determine canonical project-root-relative path used both for the audit
240
+ # entry write and for the prior-promote lookup. Lookup MUST happen before
241
+ # we move the file so the path we hash matches whatever a future emitter
242
+ # would have written when this brief was promoted.
243
+ canonical_path = _canonical_relpath(file_path, project_root)
244
+ if log_path is None:
245
+ log_path = canonical_log_path(project_root)
246
+ prior_promote = latest_for_path(canonical_path, action="promote", log_path=log_path)
247
+ original_promotion_decision_id: str | None = (
248
+ prior_promote.get("decision_id") if prior_promote else None
249
+ )
250
+
251
+ # Update plan + move file.
252
+ timestamp = current_now.strftime("%Y-%m-%dT%H:%M:%SZ")
253
+ plan["status"] = TARGET_STATUS
254
+ plan["updated"] = timestamp
255
+ file_path.write_text(
256
+ json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
257
+ )
258
+
259
+ target_dir = file_path.parent.parent / TARGET_FOLDER
260
+ target_dir.mkdir(parents=True, exist_ok=True)
261
+ target_path = target_dir / file_path.name
262
+ file_path.replace(target_path)
263
+
264
+ # Recompute canonical path AFTER the move so the audit entry references
265
+ # the brief's new home (``vbrief/proposed/...``). This makes future
266
+ # forward-trace lookups by current path naturally correct.
267
+ canonical_path_after = _canonical_relpath(target_path, project_root)
268
+
269
+ demote_meta: dict = {
270
+ "was_promoted": parent == SOURCE_FOLDER,
271
+ "original_promotion_decision_id": original_promotion_decision_id,
272
+ "days_in_pending": days,
273
+ "demote_reason": reason,
274
+ "demoted_from": parent,
275
+ }
276
+ # `batch_id` is recorded only in batch mode so the D15 scope:undo
277
+ # --batch-id verb can reverse the cohort by tag (#1134).
278
+ if batch_id is not None:
279
+ demote_meta["batch_id"] = batch_id
280
+ entry = {
281
+ "decision_id": new_decision_id(),
282
+ "timestamp": timestamp,
283
+ "action": "demote",
284
+ "vbrief_path": canonical_path_after,
285
+ "from_status": "pending",
286
+ "to_status": TARGET_STATUS,
287
+ "actor": actor,
288
+ "demote_meta": demote_meta,
289
+ }
290
+ audit_append(entry, log_path=log_path)
291
+
292
+ msg = (
293
+ f"Demoted {target_path.name}: {SOURCE_FOLDER}/ -> {TARGET_FOLDER}/ "
294
+ f"(status: {TARGET_STATUS}, days_in_pending: {days})"
295
+ )
296
+ return True, msg, entry
297
+
298
+
299
+ # ---------------------------------------------------------------------------
300
+ # Batch-demote engine
301
+ # ---------------------------------------------------------------------------
302
+
303
+
304
+ def batch_demote(
305
+ project_root: Path,
306
+ older_than_days: int,
307
+ *,
308
+ actor: str = "operator",
309
+ now: datetime | None = None,
310
+ log_path: Path | None = None,
311
+ ) -> tuple[int, list[dict], list[str]]:
312
+ """Demote every ``pending/`` vBRIEF older than *older_than_days*.
313
+
314
+ Returns ``(demoted_count, audit_entries, skipped_messages)``. Skipped
315
+ items include both ineligible-by-age and any file-level errors caught
316
+ during processing (the batch is best-effort; one bad file does not
317
+ abort the entire run).
318
+ """
319
+ if older_than_days < 0:
320
+ raise ValueError(
321
+ f"--older-than-days must be >= 0, got {older_than_days}"
322
+ )
323
+ current_now = now or datetime.now(UTC)
324
+ pending_dir = project_root / "vbrief" / SOURCE_FOLDER
325
+ if not pending_dir.exists():
326
+ return 0, [], []
327
+
328
+ reason = f"batch:older-than-days:{older_than_days}"
329
+ # Cohort-wide tag the D15 scope:undo --batch-id verb consumes (#1134).
330
+ # Lazy: only mint a UUID when we actually have something eligible to
331
+ # demote; tests + callers that need to reference the batch_id can
332
+ # introspect the returned entries.
333
+ batch_id: str | None = None
334
+ audit_entries: list[dict] = []
335
+ skipped: list[str] = []
336
+ demoted = 0
337
+
338
+ # Sort for deterministic test output / replay.
339
+ for candidate in sorted(pending_dir.glob("*.vbrief.json")):
340
+ try:
341
+ data = json.loads(candidate.read_text(encoding="utf-8"))
342
+ except (OSError, json.JSONDecodeError) as exc:
343
+ skipped.append(f"{candidate.name}: read error: {exc}")
344
+ continue
345
+ plan = data.get("plan") if isinstance(data, dict) else None
346
+ plan_updated = plan.get("updated") if isinstance(plan, dict) else None
347
+ days = _days_in_pending(candidate, plan_updated, current_now)
348
+ if days < older_than_days:
349
+ skipped.append(
350
+ f"{candidate.name}: {days} day(s) in pending (< {older_than_days})"
351
+ )
352
+ continue
353
+ if batch_id is None:
354
+ # Mint the cohort UUID on the first eligible candidate so a
355
+ # no-op batch never pollutes the audit log with a unused tag.
356
+ batch_id = new_decision_id()
357
+ ok, msg, entry = demote_one(
358
+ candidate,
359
+ project_root,
360
+ reason,
361
+ actor=actor,
362
+ now=current_now,
363
+ log_path=log_path,
364
+ batch_id=batch_id,
365
+ )
366
+ if ok and entry is not None:
367
+ audit_entries.append(entry)
368
+ demoted += 1
369
+ else:
370
+ skipped.append(f"{candidate.name}: {msg}")
371
+ return demoted, audit_entries, skipped
372
+
373
+
374
+ # ---------------------------------------------------------------------------
375
+ # CLI
376
+ # ---------------------------------------------------------------------------
377
+
378
+
379
+ def _build_parser() -> argparse.ArgumentParser:
380
+ parser = argparse.ArgumentParser(
381
+ prog="scope_demote.py",
382
+ description=(
383
+ "Demote a vBRIEF scope from vbrief/pending/ back to "
384
+ "vbrief/proposed/ (#1121). Single-file or --batch."
385
+ ),
386
+ )
387
+ parser.add_argument(
388
+ "file",
389
+ nargs="?",
390
+ help=(
391
+ "Path to a vBRIEF file (single-demote mode). Absolute paths are "
392
+ "used as-is; relative paths resolve against --project-root / "
393
+ "$DEFT_PROJECT_ROOT / the detected consumer project root."
394
+ ),
395
+ )
396
+ parser.add_argument(
397
+ "--batch",
398
+ action="store_true",
399
+ help=(
400
+ "Batch mode: demote every vbrief/pending/*.vbrief.json older "
401
+ "than --older-than-days. Mutually exclusive with a positional "
402
+ "<file>."
403
+ ),
404
+ )
405
+ parser.add_argument(
406
+ "--older-than-days",
407
+ type=int,
408
+ default=DEFAULT_OLDER_THAN_DAYS,
409
+ help=(
410
+ "Batch-mode age threshold in days (default: "
411
+ f"{DEFAULT_OLDER_THAN_DAYS}; see Current Shape Decision 4)."
412
+ ),
413
+ )
414
+ parser.add_argument(
415
+ "--reason",
416
+ default="operator-requested",
417
+ help=(
418
+ "Free-text reason recorded in demote_meta.demote_reason for "
419
+ "single-demote mode (ignored in --batch; batch uses "
420
+ "'batch:older-than-days:<N>')."
421
+ ),
422
+ )
423
+ parser.add_argument(
424
+ "--actor",
425
+ default="operator",
426
+ help="Actor identity recorded in the audit entry (default: operator).",
427
+ )
428
+ parser.add_argument(
429
+ "--project-root",
430
+ default=None,
431
+ help="Consumer project root. Overrides $DEFT_PROJECT_ROOT.",
432
+ )
433
+ return parser
434
+
435
+
436
+ def main(argv: list[str] | None = None) -> int:
437
+ # N10 (#1150): structured --help via scripts/triage_help.REGISTRY.
438
+ from triage_help import intercept_help
439
+
440
+ rc = intercept_help("scope_demote", argv)
441
+ if rc is not None:
442
+ return rc
443
+ parser = _build_parser()
444
+ try:
445
+ args = parser.parse_args(argv)
446
+ except SystemExit as exc:
447
+ return int(exc.code) if isinstance(exc.code, int) else 2
448
+
449
+ if args.batch and args.file:
450
+ print(
451
+ "Error: --batch is mutually exclusive with a positional <file>.",
452
+ file=sys.stderr,
453
+ )
454
+ return 2
455
+ if not args.batch and not args.file:
456
+ print(
457
+ "Error: provide a vBRIEF <file> or pass --batch.",
458
+ file=sys.stderr,
459
+ )
460
+ return 2
461
+ if args.older_than_days < 0:
462
+ print(
463
+ f"Error: --older-than-days must be >= 0, got {args.older_than_days}.",
464
+ file=sys.stderr,
465
+ )
466
+ return 2
467
+
468
+ if args.batch:
469
+ project_root, error = _resolve_project_root_strict(args.project_root)
470
+ if error is not None or project_root is None:
471
+ print(f"Error: {error}", file=sys.stderr)
472
+ return 2
473
+ demoted, _entries, skipped = batch_demote(
474
+ project_root,
475
+ args.older_than_days,
476
+ actor=args.actor,
477
+ )
478
+ print(
479
+ f"Batch demote: {demoted} demoted, {len(skipped)} skipped "
480
+ f"(--older-than-days {args.older_than_days})."
481
+ )
482
+ for line in skipped:
483
+ print(f" skipped: {line}")
484
+ return 0
485
+
486
+ # Single-file mode.
487
+ file_path, error = _resolve_file_path(args.file, args.project_root)
488
+ if error is not None or file_path is None:
489
+ print(f"Error: {error}", file=sys.stderr)
490
+ return 2
491
+ project_root, root_error = _resolve_project_root_strict(args.project_root)
492
+ if root_error is not None or project_root is None:
493
+ print(f"Error: {root_error}", file=sys.stderr)
494
+ return 2
495
+ ok, message, _entry = demote_one(
496
+ file_path,
497
+ project_root,
498
+ args.reason,
499
+ actor=args.actor,
500
+ )
501
+ if ok:
502
+ print(message)
503
+ return 0
504
+ print(f"Error: {message}", file=sys.stderr)
505
+ return 1
506
+
507
+
508
+ if __name__ == "__main__":
509
+ sys.exit(main())