@deftai/directive-content 0.55.2 → 0.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/.githooks/pre-commit +143 -0
  2. package/.githooks/pre-push +121 -0
  3. package/QUICK-START.md +2 -2
  4. package/Taskfile.yml +934 -0
  5. package/UPGRADING.md +47 -1
  6. package/events/README.md +3 -3
  7. package/package.json +5 -4
  8. package/scripts/_agents_md.py +494 -0
  9. package/scripts/_cache_fetch.py +635 -0
  10. package/scripts/_cache_quota.py +529 -0
  11. package/scripts/_cache_refresh.py +163 -0
  12. package/scripts/_cache_validate.py +209 -0
  13. package/scripts/_content_root.py +42 -0
  14. package/scripts/_doctor_state.py +277 -0
  15. package/scripts/_event_detect.py +305 -0
  16. package/scripts/_events.py +514 -0
  17. package/scripts/_lifecycle_hygiene.py +568 -0
  18. package/scripts/_pathspec.py +91 -0
  19. package/scripts/_policy_show_cli.py +266 -0
  20. package/scripts/_precutover.py +92 -0
  21. package/scripts/_project_context.py +224 -0
  22. package/scripts/_project_definition_io.py +164 -0
  23. package/scripts/_relocate_snapshot.py +209 -0
  24. package/scripts/_relocate_states.py +343 -0
  25. package/scripts/_resolve_preflight_path.py +152 -0
  26. package/scripts/_safe_subprocess.py +167 -0
  27. package/scripts/_session_start_hook.py +205 -0
  28. package/scripts/_sor_gate_diff.py +365 -0
  29. package/scripts/_stdio_utf8.py +59 -0
  30. package/scripts/_triage_bootstrap_gitignore.py +904 -0
  31. package/scripts/_triage_classify_cli.py +122 -0
  32. package/scripts/_triage_queue_cli.py +625 -0
  33. package/scripts/_triage_scope_cli.py +343 -0
  34. package/scripts/_triage_scope_drift_cli.py +121 -0
  35. package/scripts/_triage_scope_ignores.py +286 -0
  36. package/scripts/_triage_scope_milestone.py +432 -0
  37. package/scripts/_triage_scope_mutations.py +337 -0
  38. package/scripts/_triage_scope_renderers.py +207 -0
  39. package/scripts/_triage_smoketest_stages.py +674 -0
  40. package/scripts/_triage_subscribe_cli.py +140 -0
  41. package/scripts/_triage_welcome_cli.py +421 -0
  42. package/scripts/_vbrief_build.py +239 -0
  43. package/scripts/_vbrief_fidelity.py +479 -0
  44. package/scripts/_vbrief_legacy.py +589 -0
  45. package/scripts/_vbrief_reconciliation.py +883 -0
  46. package/scripts/_vbrief_routing.py +277 -0
  47. package/scripts/_vbrief_safety.py +778 -0
  48. package/scripts/_vbrief_sources.py +312 -0
  49. package/scripts/_vbrief_speckit.py +262 -0
  50. package/scripts/_vbrief_story_quality.py +353 -0
  51. package/scripts/_vbrief_validation.py +299 -0
  52. package/scripts/build_dist.py +412 -0
  53. package/scripts/cache.py +1078 -0
  54. package/scripts/cache_scanner.py +745 -0
  55. package/scripts/candidates_log.py +432 -0
  56. package/scripts/capacity_backfill.py +680 -0
  57. package/scripts/capacity_show.py +653 -0
  58. package/scripts/ci_local.py +689 -0
  59. package/scripts/code_structure_validate.py +765 -0
  60. package/scripts/codebase_default_extractor.py +495 -0
  61. package/scripts/codebase_map.py +304 -0
  62. package/scripts/codebase_map_fresh.py +104 -0
  63. package/scripts/codebase_projection_registry.py +94 -0
  64. package/scripts/codebase_provider.py +582 -0
  65. package/scripts/doctor.py +2257 -0
  66. package/scripts/framework_commands.py +505 -0
  67. package/scripts/gh_rest.py +882 -0
  68. package/scripts/github_auth_modes.py +437 -0
  69. package/scripts/github_body.py +292 -0
  70. package/scripts/ip_risk.py +531 -0
  71. package/scripts/issue_emit.py +670 -0
  72. package/scripts/issue_ingest.py +1064 -0
  73. package/scripts/migrate_preflight.py +418 -0
  74. package/scripts/migrate_vbrief.py +2677 -0
  75. package/scripts/monitor_pr.py +401 -0
  76. package/scripts/pack_migrate_lessons.py +336 -0
  77. package/scripts/pack_migrate_patterns.py +254 -0
  78. package/scripts/pack_migrate_rules.py +350 -0
  79. package/scripts/pack_migrate_skills.py +423 -0
  80. package/scripts/pack_migrate_strategies.py +311 -0
  81. package/scripts/pack_migrate_swarm_spec.py +250 -0
  82. package/scripts/pack_render.py +434 -0
  83. package/scripts/packs_slice.py +712 -0
  84. package/scripts/platform_capabilities.py +336 -0
  85. package/scripts/policy.py +2826 -0
  86. package/scripts/policy_set.py +324 -0
  87. package/scripts/pr_check_closing_keywords.py +524 -0
  88. package/scripts/pr_check_protected_issues.py +267 -0
  89. package/scripts/pr_merge_readiness.py +1004 -0
  90. package/scripts/pr_wait_mergeable.py +669 -0
  91. package/scripts/prd_render.py +159 -0
  92. package/scripts/preflight_architecture_sor.py +974 -0
  93. package/scripts/preflight_branch.py +289 -0
  94. package/scripts/preflight_cache.py +974 -0
  95. package/scripts/preflight_gh.py +721 -0
  96. package/scripts/preflight_implementation.py +272 -0
  97. package/scripts/preflight_story_start.py +838 -0
  98. package/scripts/preflight_wip_cap.py +149 -0
  99. package/scripts/probe_session.py +545 -0
  100. package/scripts/project_render.py +293 -0
  101. package/scripts/quarantine_ext.py +237 -0
  102. package/scripts/reconcile_issues.py +1442 -0
  103. package/scripts/refresh-path.ps1 +107 -0
  104. package/scripts/release.py +2030 -0
  105. package/scripts/release_e2e.py +1011 -0
  106. package/scripts/release_publish.py +486 -0
  107. package/scripts/release_rollback.py +980 -0
  108. package/scripts/relocate.py +1034 -0
  109. package/scripts/resolve_changelog_unreleased.py +667 -0
  110. package/scripts/resolve_version.py +490 -0
  111. package/scripts/resume_conditions.py +706 -0
  112. package/scripts/ritual_sentinel.py +609 -0
  113. package/scripts/roadmap_render.py +635 -0
  114. package/scripts/rule_ownership_lint.py +325 -0
  115. package/scripts/scm.py +591 -0
  116. package/scripts/scope_audit_log.py +387 -0
  117. package/scripts/scope_decompose.py +654 -0
  118. package/scripts/scope_demote.py +509 -0
  119. package/scripts/scope_lifecycle.py +1126 -0
  120. package/scripts/scope_undo.py +772 -0
  121. package/scripts/session_start.py +406 -0
  122. package/scripts/setup_ghx.py +339 -0
  123. package/scripts/setup_windows.ps1 +220 -0
  124. package/scripts/slice_audit.py +585 -0
  125. package/scripts/slice_record.py +530 -0
  126. package/scripts/slice_record_existing.py +692 -0
  127. package/scripts/slug_normalize.py +178 -0
  128. package/scripts/spec_render.py +477 -0
  129. package/scripts/spec_validate.py +238 -0
  130. package/scripts/subagent_monitor.py +658 -0
  131. package/scripts/swarm_complete_cohort.py +644 -0
  132. package/scripts/swarm_launch.py +1206 -0
  133. package/scripts/swarm_readiness.py +554 -0
  134. package/scripts/swarm_verify_review_clean.py +438 -0
  135. package/scripts/swarm_worktrees.py +497 -0
  136. package/scripts/toolchain-check.py +52 -0
  137. package/scripts/triage_actions.py +871 -0
  138. package/scripts/triage_bootstrap.py +1153 -0
  139. package/scripts/triage_bulk.py +630 -0
  140. package/scripts/triage_classify.py +932 -0
  141. package/scripts/triage_help.py +1685 -0
  142. package/scripts/triage_queue.py +1944 -0
  143. package/scripts/triage_reconcile.py +581 -0
  144. package/scripts/triage_refresh.py +643 -0
  145. package/scripts/triage_scope.py +999 -0
  146. package/scripts/triage_scope_drift.py +575 -0
  147. package/scripts/triage_smoketest.py +396 -0
  148. package/scripts/triage_subscribe.py +399 -0
  149. package/scripts/triage_summary.py +1011 -0
  150. package/scripts/triage_welcome.py +1178 -0
  151. package/scripts/ts_check_lane.py +86 -0
  152. package/scripts/validate-links.py +64 -0
  153. package/scripts/validate_strategy_output.py +212 -0
  154. package/scripts/vbrief_activate.py +228 -0
  155. package/scripts/vbrief_migrate_conformance.py +368 -0
  156. package/scripts/vbrief_reconcile_graph.py +306 -0
  157. package/scripts/vbrief_reconcile_labels.py +460 -0
  158. package/scripts/vbrief_reconcile_umbrellas.py +741 -0
  159. package/scripts/vbrief_validate.py +1195 -0
  160. package/scripts/verify-stubs.py +61 -0
  161. package/scripts/verify_capacity.py +160 -0
  162. package/scripts/verify_encoding.py +699 -0
  163. package/scripts/verify_hooks_installed.py +206 -0
  164. package/scripts/verify_investigation.py +360 -0
  165. package/scripts/verify_judgment_gates.py +827 -0
  166. package/scripts/verify_no_task_runtime.py +171 -0
  167. package/scripts/verify_scm_boundary.py +509 -0
  168. package/scripts/verify_session_ritual.py +389 -0
  169. package/scripts/verify_tools.py +426 -0
  170. package/scripts/verify_vbrief_conformance.py +478 -0
  171. package/tasks/architecture.yml +13 -0
  172. package/tasks/cache.yml +69 -0
  173. package/tasks/capacity.yml +38 -0
  174. package/tasks/change.yml +46 -0
  175. package/tasks/changelog.yml +24 -0
  176. package/tasks/ci.yml +49 -0
  177. package/tasks/codebase.yml +47 -0
  178. package/tasks/commit.yml +30 -0
  179. package/tasks/core.yml +126 -0
  180. package/tasks/deployments.yml +54 -0
  181. package/tasks/framework.yml +74 -0
  182. package/tasks/install.yml +60 -0
  183. package/tasks/issue.yml +50 -0
  184. package/tasks/migrate.yml +73 -0
  185. package/tasks/packs.yml +92 -0
  186. package/tasks/policy.yml +75 -0
  187. package/tasks/pr.yml +89 -0
  188. package/tasks/prd.yml +39 -0
  189. package/tasks/project.yml +27 -0
  190. package/tasks/reconcile.yml +32 -0
  191. package/tasks/relocate.yml +56 -0
  192. package/tasks/roadmap.yml +28 -0
  193. package/tasks/scm.yml +126 -0
  194. package/tasks/scope-undo.yml +36 -0
  195. package/tasks/scope.yml +141 -0
  196. package/tasks/session.yml +19 -0
  197. package/tasks/setup.yml +37 -0
  198. package/tasks/slice.yml +69 -0
  199. package/tasks/spec.yml +41 -0
  200. package/tasks/swarm.yml +85 -0
  201. package/tasks/toolchain.yml +13 -0
  202. package/tasks/triage-actions.yml +94 -0
  203. package/tasks/triage-bootstrap.yml +43 -0
  204. package/tasks/triage-bulk.yml +75 -0
  205. package/tasks/triage-classify.yml +30 -0
  206. package/tasks/triage-queue.yml +50 -0
  207. package/tasks/triage-reconcile.yml +29 -0
  208. package/tasks/triage-scope-drift.yml +29 -0
  209. package/tasks/triage-scope.yml +31 -0
  210. package/tasks/triage-smoketest.yml +33 -0
  211. package/tasks/triage-subscribe.yml +36 -0
  212. package/tasks/triage-summary.yml +29 -0
  213. package/tasks/triage-welcome.yml +32 -0
  214. package/tasks/ts.yml +328 -0
  215. package/tasks/vbrief.yml +206 -0
  216. package/tasks/verify.yml +292 -0
  217. package/templates/agents-entry.md +1 -1
@@ -0,0 +1,209 @@
1
+ #!/usr/bin/env python3
2
+ """_cache_validate.py -- in-module mirror of cache-meta.schema.json (#883 Story 2).
3
+
4
+ Hand-rolled validator (no third-party ``jsonschema`` dependency) that pins
5
+ the same field set / types / enums declared in
6
+ ``vbrief/schemas/cache-meta.schema.json``. Drift between the schema file
7
+ and this validator is caught by the
8
+ ``tests/content/test_cache_schema_alignment.py`` regression suite.
9
+
10
+ Extracted from :mod:`cache` to keep the parent module under the 1000-line
11
+ MUST limit from deft/main.md (the cache module is a multi-command CLI plus
12
+ fetch orchestrator; the schema validator is a self-contained sub-surface).
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from collections.abc import Iterable
19
+ from typing import Any
20
+
21
+
22
+ class CacheValidationError(ValueError):
23
+ """meta.json failed schema validation on read or write."""
24
+
25
+
26
+ # ---------------------------------------------------------------------------
27
+ # Regex + frozen-set surface
28
+ # ---------------------------------------------------------------------------
29
+
30
+ _VALID_DATETIME_RE: re.Pattern[str] = re.compile(
31
+ r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(Z|[+-]\d{2}:\d{2})$"
32
+ )
33
+ _VALID_SEMVER_RE: re.Pattern[str] = re.compile(r"^\d+\.\d+\.\d+$")
34
+
35
+ _META_REQUIRED: tuple[str, ...] = (
36
+ "source",
37
+ "key",
38
+ "fetched_at",
39
+ "ttl_seconds",
40
+ "expires_at",
41
+ "scan_result",
42
+ "size_bytes",
43
+ "stale",
44
+ )
45
+ _META_ALLOWED: frozenset[str] = frozenset(_META_REQUIRED) | {"etag"}
46
+ _SCAN_RESULT_REQUIRED: tuple[str, ...] = (
47
+ "passed",
48
+ "scanned_at",
49
+ "scanner_version",
50
+ "flags",
51
+ )
52
+ _SCAN_RESULT_ALLOWED: frozenset[str] = frozenset(_SCAN_RESULT_REQUIRED)
53
+ _SCAN_FLAG_REQUIRED: tuple[str, ...] = ("category", "severity", "detail")
54
+ _SCAN_FLAG_ALLOWED: frozenset[str] = frozenset(_SCAN_FLAG_REQUIRED) | {"match_count"}
55
+ _SCAN_FLAG_CATEGORIES: frozenset[str] = frozenset(
56
+ {"injection-heading", "credentials", "invisible-unicode"}
57
+ )
58
+ _SCAN_FLAG_SEVERITIES: frozenset[str] = frozenset(
59
+ {"fence-and-pass", "hard-fail", "strip-and-pass"}
60
+ )
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Helpers
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ def _require_keys(obj: dict[str, Any], required: Iterable[str], path: str) -> None:
69
+ missing = [k for k in required if k not in obj]
70
+ if missing:
71
+ raise CacheValidationError(
72
+ f"meta.json validation failure at {path}: missing required keys {missing!r}"
73
+ )
74
+
75
+
76
+ def _disallow_extras(obj: dict[str, Any], allowed: frozenset[str], path: str) -> None:
77
+ extra = set(obj) - allowed
78
+ if extra:
79
+ raise CacheValidationError(
80
+ f"meta.json validation failure at {path}: unknown keys {sorted(extra)!r}"
81
+ )
82
+
83
+
84
+ def _is_non_negative_int(value: object) -> bool:
85
+ """Reject bools (which are int subclass in Python) and negative ints."""
86
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
87
+
88
+
89
+ def _validate_datetime(value: object, path: str) -> None:
90
+ if not isinstance(value, str) or not _VALID_DATETIME_RE.match(value):
91
+ raise CacheValidationError(
92
+ f"meta.json validation failure at {path}: not a UTC-suffixed "
93
+ f"ISO-8601 timestamp ({value!r})"
94
+ )
95
+
96
+
97
+ def _validate_meta_envelope(meta: dict[str, Any], allowed_sources: tuple[str, ...]) -> None:
98
+ """Top-level (source/key/timestamps/ttl/size/stale) checks. Raises on failure."""
99
+ if meta["source"] not in allowed_sources:
100
+ raise CacheValidationError(
101
+ f"meta.json validation failure at .source: {meta['source']!r} not in "
102
+ f"{sorted(allowed_sources)!r}"
103
+ )
104
+ if not isinstance(meta["key"], str) or not meta["key"]:
105
+ raise CacheValidationError(
106
+ "meta.json validation failure at .key: expected non-empty string"
107
+ )
108
+ _validate_datetime(meta["fetched_at"], ".fetched_at")
109
+ _validate_datetime(meta["expires_at"], ".expires_at")
110
+ if not _is_non_negative_int(meta["ttl_seconds"]):
111
+ raise CacheValidationError(
112
+ f"meta.json validation failure at .ttl_seconds: expected non-negative int "
113
+ f"(got {meta['ttl_seconds']!r})"
114
+ )
115
+ if not _is_non_negative_int(meta["size_bytes"]):
116
+ raise CacheValidationError(
117
+ f"meta.json validation failure at .size_bytes: expected non-negative int "
118
+ f"(got {meta['size_bytes']!r})"
119
+ )
120
+ if not isinstance(meta["stale"], bool):
121
+ raise CacheValidationError(
122
+ f"meta.json validation failure at .stale: expected bool (got {meta['stale']!r})"
123
+ )
124
+ if "etag" in meta and not isinstance(meta["etag"], str):
125
+ raise CacheValidationError(
126
+ f"meta.json validation failure at .etag: expected string when present "
127
+ f"(got {meta['etag']!r})"
128
+ )
129
+
130
+
131
+ def _validate_scan_result(scan_result: object) -> None:
132
+ if not isinstance(scan_result, dict):
133
+ raise CacheValidationError(
134
+ "meta.json validation failure at .scan_result: expected object"
135
+ )
136
+ _require_keys(scan_result, _SCAN_RESULT_REQUIRED, ".scan_result")
137
+ _disallow_extras(scan_result, _SCAN_RESULT_ALLOWED, ".scan_result")
138
+ if not isinstance(scan_result["passed"], bool):
139
+ raise CacheValidationError(
140
+ "meta.json validation failure at .scan_result.passed: expected bool"
141
+ )
142
+ _validate_datetime(scan_result["scanned_at"], ".scan_result.scanned_at")
143
+ sv = scan_result["scanner_version"]
144
+ if not isinstance(sv, str) or not _VALID_SEMVER_RE.match(sv):
145
+ raise CacheValidationError(
146
+ "meta.json validation failure at .scan_result.scanner_version: not a "
147
+ f"SemVer string ({sv!r})"
148
+ )
149
+ flags = scan_result["flags"]
150
+ if not isinstance(flags, list):
151
+ raise CacheValidationError(
152
+ "meta.json validation failure at .scan_result.flags: expected array"
153
+ )
154
+ for i, flag in enumerate(flags):
155
+ _validate_scan_flag(flag, i)
156
+
157
+
158
+ def _validate_scan_flag(flag: object, index: int) -> None:
159
+ path = f".scan_result.flags[{index}]"
160
+ if not isinstance(flag, dict):
161
+ raise CacheValidationError(
162
+ f"meta.json validation failure at {path}: expected object"
163
+ )
164
+ _require_keys(flag, _SCAN_FLAG_REQUIRED, path)
165
+ _disallow_extras(flag, _SCAN_FLAG_ALLOWED, path)
166
+ if flag["category"] not in _SCAN_FLAG_CATEGORIES:
167
+ raise CacheValidationError(
168
+ f"meta.json validation failure at {path}.category: "
169
+ f"{flag['category']!r} not in {sorted(_SCAN_FLAG_CATEGORIES)!r}"
170
+ )
171
+ if flag["severity"] not in _SCAN_FLAG_SEVERITIES:
172
+ raise CacheValidationError(
173
+ f"meta.json validation failure at {path}.severity: "
174
+ f"{flag['severity']!r} not in {sorted(_SCAN_FLAG_SEVERITIES)!r}"
175
+ )
176
+ if not isinstance(flag["detail"], str):
177
+ raise CacheValidationError(
178
+ f"meta.json validation failure at {path}.detail: expected string"
179
+ )
180
+ if "match_count" in flag and not _is_non_negative_int(flag["match_count"]):
181
+ raise CacheValidationError(
182
+ f"meta.json validation failure at {path}.match_count: expected "
183
+ f"non-negative int (got {flag['match_count']!r})"
184
+ )
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Public entry point
189
+ # ---------------------------------------------------------------------------
190
+
191
+
192
+ def validate_meta(meta: dict[str, Any], allowed_sources: tuple[str, ...]) -> None:
193
+ """Validate ``meta`` against cache-meta.schema.json. Raises :class:`CacheValidationError`.
194
+
195
+ Args:
196
+ meta: The parsed meta.json object.
197
+ allowed_sources: The cache layer's :data:`cache.ALLOWED_SOURCES` tuple. Threaded
198
+ through as a parameter (rather than imported) so this module
199
+ is independent of the parent cache module's import graph.
200
+ """
201
+ if not isinstance(meta, dict):
202
+ raise CacheValidationError(
203
+ f"meta.json validation failure at <root>: expected object, got "
204
+ f"{type(meta).__name__}"
205
+ )
206
+ _require_keys(meta, _META_REQUIRED, "<root>")
207
+ _disallow_extras(meta, _META_ALLOWED, "<root>")
208
+ _validate_meta_envelope(meta, allowed_sources)
209
+ _validate_scan_result(meta["scan_result"])
@@ -0,0 +1,42 @@
1
+ """_content_root.py -- resolve the shippable-content root across both contexts (#1875).
2
+
3
+ The #1875 "content/ move" relocated every shippable framework asset under a
4
+ single ``content/`` root in the SOURCE repository. The C1 flatten deposit
5
+ (``build_dist.py``) strips that prefix when packaging, so a CONSUMER install
6
+ sees the same ``.deft/core/<x>`` layout it always has -- there is no
7
+ ``content/`` directory in a deposited framework.
8
+
9
+ Engine scripts that read shippable content by repo-root path therefore live in
10
+ two worlds:
11
+
12
+ * SOURCE checkout: content lives at ``<framework-root>/content/<x>``.
13
+ * CONSUMER deposit: content lives at ``<framework-root>/<x>`` (flattened).
14
+
15
+ ``content_root(framework_root)`` resolves the difference by probing for the
16
+ ``content/`` directory: it returns ``<framework-root>/content`` when that
17
+ directory exists (source) and ``<framework-root>`` otherwise (consumer). Build
18
+ paths off the returned root so the same script resolves correctly in both
19
+ contexts without a code change.
20
+
21
+ Refs #1875 (content/ move), #1669 (Wave-1 LockedDecisions C1 flatten).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from pathlib import Path
27
+
28
+ CONTENT_DIRNAME = "content"
29
+
30
+
31
+ def content_root(framework_root: Path | str) -> Path:
32
+ """Return the directory that holds flattened shippable content.
33
+
34
+ ``framework_root`` is the directory that owns ``scripts/`` (i.e. two
35
+ parents up from a ``scripts/<x>.py`` module). In a source checkout the
36
+ shippable content lives under ``<framework_root>/content``; in a consumer
37
+ deposit the C1 flatten removed the prefix, so it lives directly under
38
+ ``<framework_root>``.
39
+ """
40
+ root = Path(framework_root)
41
+ candidate = root / CONTENT_DIRNAME
42
+ return candidate if candidate.is_dir() else root
@@ -0,0 +1,277 @@
1
+ """scripts/_doctor_state.py -- doctor throttle state read/write (#1308).
2
+
3
+ Schema for ``vbrief/.eval/doctor-state.json``::
4
+
5
+ {
6
+ "last_run_at": "2026-05-22T13:00:00Z", # UTC ISO-8601, seconds
7
+ "last_exit_code": 0,
8
+ "last_finding_count": 0,
9
+ "last_error_count": 0
10
+ }
11
+
12
+ Count semantics (#1316): ``last_finding_count`` is the count of findings
13
+ that *mattered* -- it EXCLUDES ``severity == "skip"`` findings. A skip
14
+ (e.g. doctor's AGENTS.md-freshness check reporting "no managed-section
15
+ markers (likely maintainer repo)") carries neither error nor warning
16
+ weight, so it must not inflate the persisted tally. The caller
17
+ (``scripts/doctor.py::_persist_doctor_state``) is responsible for
18
+ filtering skips before calling :func:`write_state`. This keeps the
19
+ throttle-skip status line correct: ``_render_doctor_status_line``
20
+ derives the warning tally as ``last_finding_count - last_error_count``,
21
+ and a counted skip would over-report warnings by one on a dirty
22
+ throttle-skip.
23
+
24
+ Throttle rules:
25
+
26
+ * 24h after a clean previous run (``last_error_count == 0``).
27
+ * 4h after a dirty previous run (``last_error_count > 0``).
28
+ * Warnings alone count toward the 24h window so stable-warning installs
29
+ (consumer without ``node`` who does not need it, etc.) are not
30
+ perpetually re-probed.
31
+ * Corrupt state file (malformed JSON / missing keys / bad types) is
32
+ treated as no-state -- the caller runs a full check.
33
+
34
+ The default state-file path is ``<project_root>/vbrief/.eval/doctor-state.json``.
35
+ Tests and other callers MAY set the ``DEFT_DOCTOR_STATE_PATH`` environment
36
+ variable to redirect the path -- this is the seam ``tests/cli/test_doctor_throttle.py``
37
+ uses to isolate per-test state without touching the live framework
38
+ checkout's state file.
39
+
40
+ Pure stdlib. Best-effort: read / write helpers NEVER raise; they
41
+ silently degrade to the no-state path so the doctor itself never breaks
42
+ because of a state-file bug.
43
+
44
+ Story: #1308 -- consolidated ``run doctor`` + ``task doctor`` throttle.
45
+ """
46
+
47
+ from __future__ import annotations
48
+
49
+ import json
50
+ import os
51
+ from dataclasses import dataclass
52
+ from datetime import UTC, datetime, timedelta
53
+ from pathlib import Path
54
+
55
+ STATE_FILENAME = "doctor-state.json"
56
+ STATE_PARENT = Path("vbrief") / ".eval"
57
+
58
+ CLEAN_WINDOW_HOURS = 24
59
+ DIRTY_WINDOW_HOURS = 4
60
+
61
+ _ENV_STATE_PATH = "DEFT_DOCTOR_STATE_PATH"
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class DoctorState:
66
+ """Parsed doctor-state.json payload (UTC-aware)."""
67
+
68
+ last_run_at: datetime
69
+ last_exit_code: int
70
+ last_finding_count: int
71
+ last_error_count: int
72
+
73
+
74
+ @dataclass(frozen=True)
75
+ class ThrottleDecision:
76
+ """Result of :func:`decide_throttle`.
77
+
78
+ ``skip`` is True when the throttle window has not yet expired AND the
79
+ caller has not bypassed the gate (``--full``). ``dirty`` distinguishes
80
+ the clean (``last_error_count == 0``) and dirty (``last_error_count > 0``)
81
+ branches so the CLI emits the right status line and exit code.
82
+
83
+ When ``state`` is ``None`` (first run / corrupt state file), ``skip``
84
+ is False and every numeric field is 0; ``last_run_at`` and
85
+ ``next_eligible_at`` are ``None``.
86
+ """
87
+
88
+ skip: bool
89
+ dirty: bool
90
+ last_run_at: datetime | None
91
+ last_exit_code: int
92
+ last_finding_count: int
93
+ last_error_count: int
94
+ next_eligible_at: datetime | None
95
+ age_hours: float
96
+
97
+
98
+ def state_path(project_root: Path) -> Path:
99
+ """Return the doctor-state.json path for ``project_root``.
100
+
101
+ Honors the ``DEFT_DOCTOR_STATE_PATH`` env override so callers (tests,
102
+ cron jobs, multi-project setups) can redirect the state file without
103
+ monkeypatching this module.
104
+ """
105
+ override = os.environ.get(_ENV_STATE_PATH, "").strip()
106
+ if override:
107
+ return Path(override).expanduser()
108
+ return project_root / STATE_PARENT / STATE_FILENAME
109
+
110
+
111
+ def _parse_iso(ts: object) -> datetime | None:
112
+ """Parse an ISO-8601 timestamp; return None on any malformed input.
113
+
114
+ Mirrors ``run::_parse_iso_utc`` so the doctor's throttle parser stays
115
+ in lockstep with the remote-probe throttle parser without importing
116
+ ``run`` (which has heavy import-time side effects).
117
+ """
118
+ if not isinstance(ts, str) or not ts:
119
+ return None
120
+ candidate = ts.strip()
121
+ if candidate.endswith("Z"):
122
+ candidate = candidate[:-1] + "+00:00"
123
+ try:
124
+ parsed = datetime.fromisoformat(candidate)
125
+ except (TypeError, ValueError):
126
+ return None
127
+ if parsed.tzinfo is None:
128
+ parsed = parsed.replace(tzinfo=UTC)
129
+ return parsed.astimezone(UTC)
130
+
131
+
132
+ def read_state(project_root: Path) -> DoctorState | None:
133
+ """Best-effort read of doctor-state.json.
134
+
135
+ Returns the parsed :class:`DoctorState` on a well-formed file, or
136
+ ``None`` on any failure mode (missing file, malformed JSON, missing
137
+ keys, bad value types). Per the #1308 contract, corrupt state is
138
+ indistinguishable from no-state -- both routes converge on \"run the
139
+ full check\".
140
+ """
141
+ path = state_path(project_root)
142
+ if not path.is_file():
143
+ return None
144
+ try:
145
+ data = json.loads(path.read_text(encoding="utf-8"))
146
+ except (OSError, ValueError):
147
+ return None
148
+ if not isinstance(data, dict):
149
+ return None
150
+ last_run_at = _parse_iso(data.get("last_run_at"))
151
+ if last_run_at is None:
152
+ return None
153
+ try:
154
+ last_exit_code = int(data.get("last_exit_code", 0))
155
+ last_finding_count = int(data.get("last_finding_count", 0))
156
+ last_error_count = int(data.get("last_error_count", 0))
157
+ except (TypeError, ValueError):
158
+ return None
159
+ return DoctorState(
160
+ last_run_at=last_run_at,
161
+ last_exit_code=last_exit_code,
162
+ last_finding_count=last_finding_count,
163
+ last_error_count=last_error_count,
164
+ )
165
+
166
+
167
+ def write_state(
168
+ project_root: Path,
169
+ *,
170
+ exit_code: int,
171
+ finding_count: int,
172
+ error_count: int,
173
+ now: datetime | None = None,
174
+ ) -> Path | None:
175
+ """Best-effort write of doctor-state.json.
176
+
177
+ Returns the persisted path on success, ``None`` on any OSError
178
+ (read-only filesystem, permission denied, missing parent dir we
179
+ cannot create, ...). Never raises -- a state-file write failure
180
+ MUST NOT break the doctor.
181
+
182
+ ``now`` is exposed so tests can pin the timestamp without
183
+ monkeypatching ``datetime.now``.
184
+ """
185
+ when = now if now is not None else _now_utc()
186
+ payload = {
187
+ "last_run_at": _format_utc_iso(when),
188
+ "last_exit_code": int(exit_code),
189
+ "last_finding_count": int(finding_count),
190
+ "last_error_count": int(error_count),
191
+ }
192
+ path = state_path(project_root)
193
+ try:
194
+ path.parent.mkdir(parents=True, exist_ok=True)
195
+ path.write_text(
196
+ json.dumps(payload, sort_keys=True, indent=2) + "\n",
197
+ encoding="utf-8",
198
+ )
199
+ except OSError:
200
+ return None
201
+ return path
202
+
203
+
204
+ def decide_throttle(
205
+ state: DoctorState | None,
206
+ *,
207
+ now: datetime | None = None,
208
+ ) -> ThrottleDecision:
209
+ """Compute whether the doctor's full check should be skipped.
210
+
211
+ Pure -- no I/O. The caller resolves the state via :func:`read_state`
212
+ and feeds it in so tests can build synthetic states without
213
+ touching the filesystem.
214
+
215
+ Window rules (per the #1308 spec):
216
+
217
+ * Clean previous (``last_error_count == 0``) -> 24h window.
218
+ * Dirty previous (``last_error_count > 0``) -> 4h window.
219
+
220
+ ``now < state.last_run_at + window`` => skip. ``--full`` bypass is
221
+ the caller's responsibility -- this helper makes the rule decision
222
+ on the state alone so it stays deterministic and unit-testable.
223
+ """
224
+ when = now if now is not None else _now_utc()
225
+ if state is None:
226
+ return ThrottleDecision(
227
+ skip=False,
228
+ dirty=False,
229
+ last_run_at=None,
230
+ last_exit_code=0,
231
+ last_finding_count=0,
232
+ last_error_count=0,
233
+ next_eligible_at=None,
234
+ age_hours=0.0,
235
+ )
236
+ is_dirty = state.last_error_count > 0
237
+ window_hours = DIRTY_WINDOW_HOURS if is_dirty else CLEAN_WINDOW_HOURS
238
+ eligible_at = state.last_run_at + timedelta(hours=window_hours)
239
+ age = when - state.last_run_at
240
+ age_hours = age.total_seconds() / 3600.0
241
+ skip = when < eligible_at
242
+ return ThrottleDecision(
243
+ skip=skip,
244
+ dirty=is_dirty,
245
+ last_run_at=state.last_run_at,
246
+ last_exit_code=state.last_exit_code,
247
+ last_finding_count=state.last_finding_count,
248
+ last_error_count=state.last_error_count,
249
+ next_eligible_at=eligible_at,
250
+ age_hours=age_hours,
251
+ )
252
+
253
+
254
+ def _now_utc() -> datetime:
255
+ """UTC-aware ``datetime.now`` (split out so tests can monkeypatch)."""
256
+ return datetime.now(UTC)
257
+
258
+
259
+ def _format_utc_iso(when: datetime) -> str:
260
+ """Format a UTC datetime as ``YYYY-MM-DDTHH:MM:SSZ``."""
261
+ if when.tzinfo is None:
262
+ when = when.replace(tzinfo=UTC)
263
+ return when.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
264
+
265
+
266
+ __all__ = [
267
+ "CLEAN_WINDOW_HOURS",
268
+ "DIRTY_WINDOW_HOURS",
269
+ "DoctorState",
270
+ "STATE_FILENAME",
271
+ "STATE_PARENT",
272
+ "ThrottleDecision",
273
+ "decide_throttle",
274
+ "read_state",
275
+ "state_path",
276
+ "write_state",
277
+ ]