@deftai/directive-content 0.58.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 (187) hide show
  1. package/.githooks/pre-push +10 -9
  2. package/Taskfile.yml +57 -67
  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/rules/rules-pack-0.1.json +3 -3
  9. package/packs/skills/skills-pack-0.1.json +22 -22
  10. package/scm/github.md +20 -2
  11. package/tasks/change.yml +16 -31
  12. package/tasks/ci.yml +8 -0
  13. package/tasks/commit.yml +12 -19
  14. package/tasks/core.yml +10 -0
  15. package/tasks/engine.yml +42 -0
  16. package/tasks/framework.yml +3 -0
  17. package/tasks/install.yml +20 -19
  18. package/tasks/migrate.yml +26 -15
  19. package/tasks/project.yml +16 -0
  20. package/tasks/relocate.yml +18 -48
  21. package/tasks/toolchain.yml +15 -5
  22. package/tasks/vbrief.yml +4 -3
  23. package/tasks/verify.yml +12 -14
  24. package/templates/agents-entry.md +1 -2
  25. package/scripts/_agents_md.py +0 -494
  26. package/scripts/_cache_fetch.py +0 -635
  27. package/scripts/_cache_quota.py +0 -529
  28. package/scripts/_cache_refresh.py +0 -163
  29. package/scripts/_cache_validate.py +0 -209
  30. package/scripts/_content_root.py +0 -42
  31. package/scripts/_doctor_state.py +0 -277
  32. package/scripts/_event_detect.py +0 -305
  33. package/scripts/_events.py +0 -514
  34. package/scripts/_lifecycle_hygiene.py +0 -568
  35. package/scripts/_pathspec.py +0 -91
  36. package/scripts/_policy_show_cli.py +0 -266
  37. package/scripts/_precutover.py +0 -92
  38. package/scripts/_project_context.py +0 -224
  39. package/scripts/_project_definition_io.py +0 -164
  40. package/scripts/_relocate_snapshot.py +0 -209
  41. package/scripts/_relocate_states.py +0 -343
  42. package/scripts/_resolve_preflight_path.py +0 -152
  43. package/scripts/_safe_subprocess.py +0 -167
  44. package/scripts/_session_start_hook.py +0 -205
  45. package/scripts/_sor_gate_diff.py +0 -365
  46. package/scripts/_stdio_utf8.py +0 -59
  47. package/scripts/_triage_bootstrap_gitignore.py +0 -904
  48. package/scripts/_triage_classify_cli.py +0 -122
  49. package/scripts/_triage_queue_cli.py +0 -625
  50. package/scripts/_triage_scope_cli.py +0 -343
  51. package/scripts/_triage_scope_drift_cli.py +0 -121
  52. package/scripts/_triage_scope_ignores.py +0 -286
  53. package/scripts/_triage_scope_milestone.py +0 -432
  54. package/scripts/_triage_scope_mutations.py +0 -337
  55. package/scripts/_triage_scope_renderers.py +0 -207
  56. package/scripts/_triage_smoketest_stages.py +0 -674
  57. package/scripts/_triage_subscribe_cli.py +0 -140
  58. package/scripts/_triage_welcome_cli.py +0 -421
  59. package/scripts/_vbrief_build.py +0 -239
  60. package/scripts/_vbrief_fidelity.py +0 -479
  61. package/scripts/_vbrief_legacy.py +0 -589
  62. package/scripts/_vbrief_reconciliation.py +0 -883
  63. package/scripts/_vbrief_routing.py +0 -277
  64. package/scripts/_vbrief_safety.py +0 -778
  65. package/scripts/_vbrief_sources.py +0 -312
  66. package/scripts/_vbrief_speckit.py +0 -262
  67. package/scripts/_vbrief_story_quality.py +0 -353
  68. package/scripts/_vbrief_validation.py +0 -299
  69. package/scripts/build_dist.py +0 -412
  70. package/scripts/cache.py +0 -1078
  71. package/scripts/cache_scanner.py +0 -745
  72. package/scripts/candidates_log.py +0 -432
  73. package/scripts/capacity_backfill.py +0 -680
  74. package/scripts/capacity_show.py +0 -653
  75. package/scripts/ci_local.py +0 -689
  76. package/scripts/code_structure_validate.py +0 -765
  77. package/scripts/codebase_default_extractor.py +0 -495
  78. package/scripts/codebase_map.py +0 -304
  79. package/scripts/codebase_map_fresh.py +0 -104
  80. package/scripts/codebase_projection_registry.py +0 -94
  81. package/scripts/codebase_provider.py +0 -582
  82. package/scripts/doctor.py +0 -2551
  83. package/scripts/framework_commands.py +0 -505
  84. package/scripts/gh_rest.py +0 -882
  85. package/scripts/github_auth_modes.py +0 -437
  86. package/scripts/github_body.py +0 -292
  87. package/scripts/ip_risk.py +0 -531
  88. package/scripts/issue_emit.py +0 -670
  89. package/scripts/issue_ingest.py +0 -1064
  90. package/scripts/migrate_preflight.py +0 -418
  91. package/scripts/migrate_vbrief.py +0 -2677
  92. package/scripts/monitor_pr.py +0 -401
  93. package/scripts/pack_migrate_lessons.py +0 -336
  94. package/scripts/pack_migrate_patterns.py +0 -254
  95. package/scripts/pack_migrate_rules.py +0 -350
  96. package/scripts/pack_migrate_skills.py +0 -423
  97. package/scripts/pack_migrate_strategies.py +0 -311
  98. package/scripts/pack_migrate_swarm_spec.py +0 -250
  99. package/scripts/pack_render.py +0 -434
  100. package/scripts/packs_slice.py +0 -712
  101. package/scripts/platform_capabilities.py +0 -336
  102. package/scripts/policy.py +0 -2826
  103. package/scripts/policy_set.py +0 -324
  104. package/scripts/pr_check_closing_keywords.py +0 -524
  105. package/scripts/pr_check_protected_issues.py +0 -267
  106. package/scripts/pr_merge_readiness.py +0 -1004
  107. package/scripts/pr_wait_mergeable.py +0 -669
  108. package/scripts/prd_render.py +0 -159
  109. package/scripts/preflight_architecture_sor.py +0 -974
  110. package/scripts/preflight_branch.py +0 -289
  111. package/scripts/preflight_cache.py +0 -974
  112. package/scripts/preflight_gh.py +0 -721
  113. package/scripts/preflight_implementation.py +0 -272
  114. package/scripts/preflight_story_start.py +0 -838
  115. package/scripts/preflight_wip_cap.py +0 -149
  116. package/scripts/probe_session.py +0 -545
  117. package/scripts/project_render.py +0 -293
  118. package/scripts/quarantine_ext.py +0 -237
  119. package/scripts/reconcile_issues.py +0 -1442
  120. package/scripts/refresh-path.ps1 +0 -107
  121. package/scripts/release.py +0 -2030
  122. package/scripts/release_e2e.py +0 -1011
  123. package/scripts/release_publish.py +0 -486
  124. package/scripts/release_rollback.py +0 -980
  125. package/scripts/relocate.py +0 -1034
  126. package/scripts/resolve_changelog_unreleased.py +0 -667
  127. package/scripts/resolve_version.py +0 -490
  128. package/scripts/resume_conditions.py +0 -706
  129. package/scripts/ritual_sentinel.py +0 -609
  130. package/scripts/roadmap_render.py +0 -635
  131. package/scripts/rule_ownership_lint.py +0 -325
  132. package/scripts/scm.py +0 -591
  133. package/scripts/scope_audit_log.py +0 -387
  134. package/scripts/scope_decompose.py +0 -654
  135. package/scripts/scope_demote.py +0 -509
  136. package/scripts/scope_lifecycle.py +0 -1126
  137. package/scripts/scope_undo.py +0 -772
  138. package/scripts/session_start.py +0 -406
  139. package/scripts/setup_ghx.py +0 -339
  140. package/scripts/setup_windows.ps1 +0 -220
  141. package/scripts/slice_audit.py +0 -585
  142. package/scripts/slice_record.py +0 -530
  143. package/scripts/slice_record_existing.py +0 -692
  144. package/scripts/slug_normalize.py +0 -178
  145. package/scripts/spec_render.py +0 -477
  146. package/scripts/spec_validate.py +0 -238
  147. package/scripts/subagent_monitor.py +0 -658
  148. package/scripts/swarm_complete_cohort.py +0 -644
  149. package/scripts/swarm_launch.py +0 -1206
  150. package/scripts/swarm_readiness.py +0 -554
  151. package/scripts/swarm_verify_review_clean.py +0 -438
  152. package/scripts/swarm_worktrees.py +0 -497
  153. package/scripts/toolchain-check.py +0 -52
  154. package/scripts/triage_actions.py +0 -871
  155. package/scripts/triage_bootstrap.py +0 -1153
  156. package/scripts/triage_bulk.py +0 -630
  157. package/scripts/triage_classify.py +0 -932
  158. package/scripts/triage_help.py +0 -1685
  159. package/scripts/triage_queue.py +0 -1944
  160. package/scripts/triage_reconcile.py +0 -581
  161. package/scripts/triage_refresh.py +0 -643
  162. package/scripts/triage_scope.py +0 -999
  163. package/scripts/triage_scope_drift.py +0 -575
  164. package/scripts/triage_smoketest.py +0 -396
  165. package/scripts/triage_subscribe.py +0 -399
  166. package/scripts/triage_summary.py +0 -1011
  167. package/scripts/triage_welcome.py +0 -1178
  168. package/scripts/ts_check_lane.py +0 -86
  169. package/scripts/validate-links.py +0 -64
  170. package/scripts/validate_strategy_output.py +0 -212
  171. package/scripts/vbrief_activate.py +0 -228
  172. package/scripts/vbrief_migrate_conformance.py +0 -368
  173. package/scripts/vbrief_reconcile_graph.py +0 -306
  174. package/scripts/vbrief_reconcile_labels.py +0 -460
  175. package/scripts/vbrief_reconcile_umbrellas.py +0 -741
  176. package/scripts/vbrief_validate.py +0 -1144
  177. package/scripts/verify-stubs.py +0 -61
  178. package/scripts/verify_capacity.py +0 -160
  179. package/scripts/verify_encoding.py +0 -699
  180. package/scripts/verify_hooks_installed.py +0 -206
  181. package/scripts/verify_investigation.py +0 -360
  182. package/scripts/verify_judgment_gates.py +0 -827
  183. package/scripts/verify_no_task_runtime.py +0 -171
  184. package/scripts/verify_scm_boundary.py +0 -509
  185. package/scripts/verify_session_ritual.py +0 -389
  186. package/scripts/verify_tools.py +0 -426
  187. package/scripts/verify_vbrief_conformance.py +0 -478
@@ -1,509 +0,0 @@
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())