@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,209 +0,0 @@
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"])
@@ -1,42 +0,0 @@
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
@@ -1,277 +0,0 @@
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
- ]