@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,974 +0,0 @@
1
- #!/usr/bin/env python3
2
- """preflight_architecture_sor.py -- system-of-record architecture gate.
3
-
4
- Deterministic preflight for stateful work. The gate answers one question:
5
-
6
- Is this the correct system of record for this kind of state?
7
-
8
- Two modes are supported:
9
-
10
- - Story/spec mode: ``--story-path <path>`` validates the story's
11
- ``architecture.systemOfRecord`` design record before implementation.
12
- - Diff mode: ``--base-ref <ref>`` scans changed runtime code for risky
13
- persistence signals and requires a matching design record, either supplied
14
- via ``--story-path`` or present on exactly one changed vBRIEF.
15
-
16
- Exit codes:
17
-
18
- - 0: pass
19
- - 1: architecture violation
20
- - 2: gate misconfigured or unable to inspect required inputs
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import argparse
26
- import json
27
- import re
28
- import sys
29
- from dataclasses import dataclass
30
- from pathlib import Path
31
- from typing import Any
32
-
33
- # Make sibling helper modules importable when invoked as
34
- # ``python scripts/preflight_architecture_sor.py`` from any working directory.
35
- sys.path.insert(0, str(Path(__file__).resolve().parent))
36
-
37
- STATE_CLASSIFICATIONS = frozenset(
38
- {
39
- "durable_product_state",
40
- "auth_session_state",
41
- "authorization_state",
42
- "audit_event_state",
43
- "external_integration_state",
44
- "canonical_artifact",
45
- "cache",
46
- "projection",
47
- "import_export_artifact",
48
- "dev_only_fixture",
49
- "ephemeral_ui_state",
50
- }
51
- )
52
-
53
- DURABLE_CLASSIFICATIONS = frozenset(
54
- {
55
- "durable_product_state",
56
- "auth_session_state",
57
- "authorization_state",
58
- "audit_event_state",
59
- "external_integration_state",
60
- }
61
- )
62
-
63
- SECURITY_CLASSIFICATIONS = frozenset({"auth_session_state", "authorization_state"})
64
-
65
- LOCAL_STORAGE_CLASSES = frozenset(
66
- {
67
- "json_file",
68
- "yaml_file",
69
- "toml_file",
70
- "sqlite_file",
71
- "browser_storage",
72
- "in_memory",
73
- "local_config",
74
- "filesystem",
75
- }
76
- )
77
-
78
- FILE_STORAGE_CLASSES = frozenset({"json_file", "yaml_file", "toml_file", "filesystem"})
79
-
80
- DB_STORAGE_ALIASES = frozenset(
81
- {
82
- "application_database",
83
- "database",
84
- "db",
85
- "postgres",
86
- "postgresql",
87
- "mysql",
88
- "mariadb",
89
- "sqlite",
90
- "sqlite_file",
91
- "sql",
92
- "dynamodb",
93
- "firestore",
94
- "cosmosdb",
95
- }
96
- )
97
-
98
- EXTERNAL_STORAGE_ALIASES = frozenset(
99
- {
100
- "external_service",
101
- "service",
102
- "provider",
103
- "external_provider",
104
- "third_party_provider",
105
- "api_provider",
106
- }
107
- )
108
-
109
- STORAGE_ALIASES: dict[str, frozenset[str]] = {
110
- "json_file": frozenset({"json", "json_file", "local_json", "mutable_json"}),
111
- "yaml_file": frozenset({"yaml", "yml", "yaml_file", "local_yaml", "mutable_yaml"}),
112
- "toml_file": frozenset({"toml", "toml_file", "local_toml", "mutable_toml"}),
113
- "sqlite_file": frozenset({"sqlite", "sqlite_file", "sqlite_db", "db_file", "local_db"}),
114
- "browser_storage": frozenset(
115
- {"browser_storage", "local_storage", "session_storage", "indexeddb", "indexed_db"}
116
- ),
117
- "in_memory": frozenset({"in_memory", "memory", "process_memory", "process_local"}),
118
- "filesystem": frozenset({"filesystem", "file", "files", "local_file", "local_files"}),
119
- "database": DB_STORAGE_ALIASES,
120
- "external_service": EXTERNAL_STORAGE_ALIASES,
121
- }
122
-
123
- DURABLE_REQUIRED_FIELDS = (
124
- "owner",
125
- "approvedStorage",
126
- "permissionBoundary",
127
- "migrationRequired",
128
- "auditRequired",
129
- "concurrencyRequired",
130
- "concurrencySemantics",
131
- "transactionBoundary",
132
- "recoverySemantics",
133
- "conflictDetection",
134
- "deleteSemantics",
135
- "migrationPath",
136
- )
137
-
138
- REFERENCE_EVIDENCE_GROUPS = {
139
- "persistence": frozenset({"persistence", "database", "schema", "storage", "repository"}),
140
- "auth": frozenset({"auth", "authentication", "session", "identity"}),
141
- "permission": frozenset({"permission", "authorization", "ownership", "membership", "role"}),
142
- }
143
-
144
- LOW_RISK_PATH_PREFIXES = (
145
- ".github/",
146
- "docs/",
147
- "history/",
148
- "meta/",
149
- "references/",
150
- "templates/",
151
- "tests/",
152
- "vbrief/",
153
- )
154
-
155
- LOW_RISK_SUFFIXES = frozenset({".md", ".rst", ".txt"})
156
-
157
- SCANNER_EXEMPT_PATHS = frozenset(
158
- {
159
- "scripts/preflight_architecture_sor.py",
160
- "scripts/_sor_gate_diff.py",
161
- }
162
- )
163
-
164
-
165
- @dataclass(frozen=True)
166
- class GateFinding:
167
- """Human-readable architecture violation."""
168
-
169
- reason: str
170
- required_fix: str
171
- state_surface: str | None = None
172
- classification: str | None = None
173
- detected_storage: str | None = None
174
- approved_storage: str | None = None
175
-
176
-
177
- @dataclass(frozen=True)
178
- class GateResult:
179
- """Pure-data result of a gate evaluation."""
180
-
181
- code: int
182
- message: str
183
- findings: tuple[GateFinding, ...] = ()
184
-
185
-
186
- @dataclass(frozen=True)
187
- class DetectedSignal:
188
- """Stateful signal detected in a diff."""
189
-
190
- kind: str
191
- path: str
192
- line: int | None
193
- detail: str
194
- storage: str | None = None
195
-
196
-
197
- def _norm(value: object) -> str:
198
- text = str(value).strip().lower()
199
- text = re.sub(r"[\s./:-]+", "_", text)
200
- text = re.sub(r"_+", "_", text)
201
- return text.strip("_")
202
-
203
-
204
- def _as_string_list(value: object) -> list[str]:
205
- if isinstance(value, str):
206
- return [value]
207
- if isinstance(value, list):
208
- return [item for item in value if isinstance(item, str)]
209
- return []
210
-
211
-
212
- def _non_empty(value: object) -> bool:
213
- if isinstance(value, str):
214
- return bool(value.strip())
215
- if isinstance(value, (list, tuple, dict)):
216
- return bool(value)
217
- if isinstance(value, bool):
218
- return True
219
- return value is not None
220
-
221
-
222
- def _truthy_flag(value: object) -> bool:
223
- if isinstance(value, bool):
224
- return value
225
- if isinstance(value, str):
226
- return value.strip().lower() in {"1", "true", "yes", "on", "guarded", "excluded"}
227
- return False
228
-
229
-
230
- def _contains_any(text: str, tokens: frozenset[str]) -> bool:
231
- normalised = _norm(text)
232
- return any(token in normalised for token in tokens)
233
-
234
-
235
- def _storage_matches(storage: str, declared: object) -> bool:
236
- wanted = _norm(storage)
237
- aliases = {wanted}
238
- aliases.update(STORAGE_ALIASES.get(wanted, frozenset()))
239
- if wanted in DB_STORAGE_ALIASES:
240
- aliases.update(DB_STORAGE_ALIASES)
241
- if wanted in EXTERNAL_STORAGE_ALIASES:
242
- aliases.update(EXTERNAL_STORAGE_ALIASES)
243
-
244
- long_aliases = {alias for alias in aliases if len(alias) > 6}
245
- for item in _as_string_list(declared):
246
- token = _norm(item)
247
- if token in aliases:
248
- return True
249
- if len(token) > 6 and any(alias in token for alias in long_aliases):
250
- return True
251
- return False
252
-
253
-
254
- def _approved_storage_text(surface: dict[str, Any]) -> str:
255
- values = _as_string_list(surface.get("approvedStorage"))
256
- return ", ".join(values) if values else "<missing>"
257
-
258
-
259
- def _storage_is_local_unsafe(value: object) -> bool:
260
- for item in _as_string_list(value):
261
- token = _norm(item)
262
- if token in LOCAL_STORAGE_CLASSES:
263
- return True
264
- if any(alias in token for alias in LOCAL_STORAGE_CLASSES):
265
- return True
266
- return False
267
-
268
-
269
- def _approved_database(value: object) -> bool:
270
- return any(_storage_matches("database", item) for item in _as_string_list(value))
271
-
272
-
273
- def _approved_external(value: object) -> bool:
274
- return any(_storage_matches("external_service", item) for item in _as_string_list(value))
275
-
276
-
277
- def _load_json_file(path: Path) -> tuple[dict[str, Any] | None, GateResult | None]:
278
- if not path.exists():
279
- return None, GateResult(
280
- 2,
281
- f"system-of-record gate misconfigured: story path not found: {path}",
282
- )
283
- if not path.is_file():
284
- return None, GateResult(
285
- 2,
286
- f"system-of-record gate misconfigured: story path is not a file: {path}",
287
- )
288
- try:
289
- raw = path.read_text(encoding="utf-8")
290
- except (OSError, UnicodeDecodeError) as exc:
291
- return None, GateResult(
292
- 2,
293
- f"system-of-record gate misconfigured: could not read {path}: {exc}",
294
- )
295
- try:
296
- payload = json.loads(raw)
297
- except json.JSONDecodeError as exc:
298
- return None, GateResult(
299
- 2,
300
- f"system-of-record gate misconfigured: {path} is not valid JSON: "
301
- f"{exc.msg} (line {exc.lineno})",
302
- )
303
- if not isinstance(payload, dict):
304
- return None, GateResult(
305
- 2,
306
- f"system-of-record gate misconfigured: {path} top-level value is not an object",
307
- )
308
- return payload, None
309
-
310
-
311
- def _system_of_record(payload: dict[str, Any]) -> dict[str, Any] | None:
312
- """Return the typed SOR block from a vBRIEF-like payload."""
313
- architecture = payload.get("architecture")
314
- if isinstance(architecture, dict) and isinstance(architecture.get("systemOfRecord"), dict):
315
- return architecture["systemOfRecord"]
316
-
317
- # Compatibility path for early adopters that nest extensions under plan.
318
- plan = payload.get("plan")
319
- if isinstance(plan, dict):
320
- plan_architecture = plan.get("architecture")
321
- if isinstance(plan_architecture, dict) and isinstance(
322
- plan_architecture.get("systemOfRecord"), dict
323
- ):
324
- return plan_architecture["systemOfRecord"]
325
- return None
326
-
327
-
328
- def _story_mentions_reference_app(payload: dict[str, Any]) -> bool:
329
- text = json.dumps(payload, sort_keys=True).lower()
330
- return bool(
331
- re.search(
332
- r"reference[- ]app|reference application|modeled after|modelled after|parity",
333
- text,
334
- )
335
- )
336
-
337
-
338
- def _record_surfaces(record: dict[str, Any]) -> list[dict[str, Any]]:
339
- surfaces = record.get("stateSurfaces")
340
- if not isinstance(surfaces, list):
341
- return []
342
- return [surface for surface in surfaces if isinstance(surface, dict)]
343
-
344
-
345
- def _surface_name(surface: dict[str, Any]) -> str:
346
- name = surface.get("name")
347
- return name.strip() if isinstance(name, str) and name.strip() else "<unnamed>"
348
-
349
-
350
- def _surface_classification(surface: dict[str, Any]) -> str | None:
351
- value = surface.get("classification")
352
- return value if isinstance(value, str) else None
353
-
354
-
355
- def _surface_allows_storage(surface: dict[str, Any], storage: str) -> bool:
356
- classification = _surface_classification(surface)
357
- approved = surface.get("approvedStorage")
358
-
359
- if _storage_matches(storage, approved):
360
- return True
361
-
362
- if storage == "database" and _approved_database(approved):
363
- return True
364
-
365
- if storage in FILE_STORAGE_CLASSES:
366
- return classification in {
367
- "canonical_artifact",
368
- "cache",
369
- "import_export_artifact",
370
- "dev_only_fixture",
371
- }
372
-
373
- if storage == "sqlite_file":
374
- return _storage_matches("sqlite_file", approved) or (
375
- classification in DURABLE_CLASSIFICATIONS and _approved_database(approved)
376
- )
377
-
378
- if storage == "browser_storage":
379
- return classification == "ephemeral_ui_state"
380
-
381
- if storage == "in_memory":
382
- return classification in {"ephemeral_ui_state", "cache"}
383
-
384
- if storage == "external_service":
385
- return classification == "external_integration_state" or _approved_external(approved)
386
-
387
- return False
388
-
389
-
390
- def _signal_location(signal: DetectedSignal) -> str:
391
- if signal.line is None:
392
- return signal.path
393
- return f"{signal.path}:{signal.line}"
394
-
395
-
396
- def _format_failure(findings: list[GateFinding]) -> str:
397
- first = findings[0]
398
- lines = ["system-of-record gate failed", ""]
399
- if first.state_surface is not None:
400
- lines.append(f"State surface: {first.state_surface}")
401
- if first.classification is not None:
402
- lines.append(f"Classification: {first.classification}")
403
- if first.detected_storage is not None:
404
- lines.append(f"Detected storage: {first.detected_storage}")
405
- if first.approved_storage is not None:
406
- lines.append(f"Approved storage: {first.approved_storage}")
407
- lines.extend(["", "Reason:", first.reason, "", "Required fix:", first.required_fix])
408
-
409
- if len(findings) > 1:
410
- lines.extend(["", f"Additional findings: {len(findings) - 1}"])
411
- for finding in findings[1:6]:
412
- prefix = finding.state_surface or finding.detected_storage or "record"
413
- lines.append(f"- {prefix}: {finding.reason}")
414
- if len(findings) > 6:
415
- lines.append(f"- ... {len(findings) - 6} more")
416
- return "\n".join(lines)
417
-
418
-
419
- def _validate_reference_apps(
420
- record: dict[str, Any],
421
- payload: dict[str, Any] | None,
422
- findings: list[GateFinding],
423
- ) -> None:
424
- refs = record.get("referenceApplications", [])
425
- mentions_reference = payload is not None and _story_mentions_reference_app(payload)
426
- if refs in (None, []):
427
- if mentions_reference:
428
- findings.append(
429
- GateFinding(
430
- reason=(
431
- "Reference-application parity is mentioned, but the "
432
- "system-of-record block has no referenceApplications comparison."
433
- ),
434
- required_fix=(
435
- "Add referenceApplications entries covering persistence, "
436
- "auth/session, ownership/permission, preserved behavior, "
437
- "and intentionally omitted behavior."
438
- ),
439
- )
440
- )
441
- return
442
- if not isinstance(refs, list):
443
- findings.append(
444
- GateFinding(
445
- reason="referenceApplications must be a list.",
446
- required_fix="Render referenceApplications as a list of comparison records.",
447
- )
448
- )
449
- return
450
-
451
- for idx, ref in enumerate(refs):
452
- if not isinstance(ref, dict):
453
- findings.append(
454
- GateFinding(
455
- reason=f"referenceApplications[{idx}] is not an object.",
456
- required_fix=(
457
- "Use an object with name, evidence, mustPreserve, "
458
- "and intentionallyNotCarriedForward."
459
- ),
460
- )
461
- )
462
- continue
463
- name = ref.get("name")
464
- surface = (
465
- name
466
- if isinstance(name, str) and name.strip()
467
- else f"referenceApplications[{idx}]"
468
- )
469
- evidence_text = " ".join(_as_string_list(ref.get("evidence"))).lower()
470
- for label, tokens in REFERENCE_EVIDENCE_GROUPS.items():
471
- if not any(token in evidence_text for token in tokens):
472
- findings.append(
473
- GateFinding(
474
- state_surface=surface,
475
- reason=f"Reference-app comparison omits the {label} model.",
476
- required_fix=(
477
- "Compare the reference persistence, auth/session, "
478
- "ownership/permission, and workflow/runtime model "
479
- "before implementation."
480
- ),
481
- )
482
- )
483
- if not _as_string_list(ref.get("mustPreserve")):
484
- findings.append(
485
- GateFinding(
486
- state_surface=surface,
487
- reason="Reference-app comparison omits mustPreserve behavior.",
488
- required_fix="List the persistence/auth/permission behavior being preserved.",
489
- )
490
- )
491
- if "intentionallyNotCarriedForward" not in ref or not isinstance(
492
- ref.get("intentionallyNotCarriedForward"), list
493
- ):
494
- findings.append(
495
- GateFinding(
496
- state_surface=surface,
497
- reason="Reference-app comparison omits intentionallyNotCarriedForward.",
498
- required_fix=(
499
- "Add an explicit list, even when empty, of reference behavior "
500
- "not being carried forward."
501
- ),
502
- )
503
- )
504
-
505
-
506
- def _validate_surface(surface: dict[str, Any], findings: list[GateFinding]) -> None:
507
- name = _surface_name(surface)
508
- classification = _surface_classification(surface)
509
-
510
- if not isinstance(surface.get("name"), str) or not surface["name"].strip():
511
- findings.append(
512
- GateFinding(
513
- state_surface=name,
514
- reason="State surface is missing a non-empty name.",
515
- required_fix="Add a stable state surface name.",
516
- )
517
- )
518
-
519
- if classification not in STATE_CLASSIFICATIONS:
520
- findings.append(
521
- GateFinding(
522
- state_surface=name,
523
- classification=classification,
524
- reason=f"Unknown state classification: {classification!r}.",
525
- required_fix="Use one of the documented system-of-record state classifications.",
526
- )
527
- )
528
- return
529
-
530
- approved = surface.get("approvedStorage")
531
- forbidden = surface.get("forbiddenStorage", [])
532
-
533
- if not _non_empty(surface.get("owner")) and classification != "ephemeral_ui_state":
534
- findings.append(
535
- GateFinding(
536
- state_surface=name,
537
- classification=classification,
538
- reason="State surface is missing an owner.",
539
- required_fix=(
540
- "Declare the service, database, provider, or layer that owns the state."
541
- ),
542
- )
543
- )
544
-
545
- if not _as_string_list(approved):
546
- findings.append(
547
- GateFinding(
548
- state_surface=name,
549
- classification=classification,
550
- reason="State surface is missing approvedStorage.",
551
- required_fix="Declare the approved system of record for this state.",
552
- )
553
- )
554
-
555
- for item in _as_string_list(forbidden):
556
- if _storage_matches(item, approved):
557
- findings.append(
558
- GateFinding(
559
- state_surface=name,
560
- classification=classification,
561
- detected_storage=item,
562
- approved_storage=_approved_storage_text(surface),
563
- reason="approvedStorage contradicts forbiddenStorage.",
564
- required_fix="Remove the contradiction before implementation.",
565
- )
566
- )
567
-
568
- if classification in DURABLE_CLASSIFICATIONS:
569
- if _storage_is_local_unsafe(approved):
570
- findings.append(
571
- GateFinding(
572
- state_surface=name,
573
- classification=classification,
574
- detected_storage=_approved_storage_text(surface),
575
- approved_storage="durable database, service, or external provider",
576
- reason=(
577
- "Durable, auth, authorization, audit, or integration state "
578
- "cannot be assigned to local files, browser storage, or process memory."
579
- ),
580
- required_fix=(
581
- "Use the approved durable storage layer, or reclassify this "
582
- "state as cache/dev-only/import/export with production guards."
583
- ),
584
- )
585
- )
586
- for field in DURABLE_REQUIRED_FIELDS:
587
- value = surface.get(field)
588
- if field.endswith("Required"):
589
- if not isinstance(value, bool):
590
- findings.append(
591
- GateFinding(
592
- state_surface=name,
593
- classification=classification,
594
- reason=f"Durable state is missing boolean {field}.",
595
- required_fix=(
596
- "Answer the durable-state concurrency, audit, migration, "
597
- "permission, recovery, and delete semantics before implementation."
598
- ),
599
- )
600
- )
601
- elif not _non_empty(value):
602
- findings.append(
603
- GateFinding(
604
- state_surface=name,
605
- classification=classification,
606
- reason=f"Durable state is missing {field}.",
607
- required_fix=(
608
- "Answer the durable-state concurrency, transaction, recovery, "
609
- "conflict, delete, ownership, permission, and migration questions."
610
- ),
611
- )
612
- )
613
-
614
- if classification in SECURITY_CLASSIFICATIONS and _storage_is_local_unsafe(approved):
615
- findings.append(
616
- GateFinding(
617
- state_surface=name,
618
- classification=classification,
619
- detected_storage=_approved_storage_text(surface),
620
- approved_storage="approved auth/session/permission mechanism",
621
- reason="Auth/session/permission state is backed by local or process-local storage.",
622
- required_fix="Use the approved auth/session and authorization system of record.",
623
- )
624
- )
625
-
626
- if classification == "cache":
627
- if _truthy_flag(surface.get("authoritative")):
628
- findings.append(
629
- GateFinding(
630
- state_surface=name,
631
- classification=classification,
632
- reason="Cache is marked authoritative.",
633
- required_fix=(
634
- "Point authoritative writes at the source of truth; "
635
- "keep the cache rebuildable."
636
- ),
637
- )
638
- )
639
- has_invalidation = _non_empty(surface.get("invalidation")) or _non_empty(
640
- surface.get("invalidationRules")
641
- )
642
- if not has_invalidation:
643
- findings.append(
644
- GateFinding(
645
- state_surface=name,
646
- classification=classification,
647
- reason="Cache lacks invalidation metadata.",
648
- required_fix=(
649
- "Declare invalidation rules, TTL, or source-change invalidation "
650
- "before use."
651
- ),
652
- )
653
- )
654
-
655
- if classification == "projection":
656
- if not _non_empty(surface.get("sourceOfTruth")):
657
- findings.append(
658
- GateFinding(
659
- state_surface=name,
660
- classification=classification,
661
- reason="Projection lacks sourceOfTruth.",
662
- required_fix="Declare the authoritative source that feeds this read model.",
663
- )
664
- )
665
- projection_mutable = _truthy_flag(surface.get("mutable")) or _truthy_flag(
666
- surface.get("directMutationAllowed")
667
- )
668
- if projection_mutable:
669
- findings.append(
670
- GateFinding(
671
- state_surface=name,
672
- classification=classification,
673
- reason="Projection is mutable directly.",
674
- required_fix=(
675
- "Mutate the authoritative source, then rebuild or refresh "
676
- "the projection."
677
- ),
678
- )
679
- )
680
-
681
- if classification == "dev_only_fixture" and not (
682
- _truthy_flag(surface.get("productionGuard"))
683
- or _truthy_flag(surface.get("excludedFromProduction"))
684
- ):
685
- findings.append(
686
- GateFinding(
687
- state_surface=name,
688
- classification=classification,
689
- reason="Dev-only storage lacks a production guard.",
690
- required_fix="Add an explicit productionGuard or excludedFromProduction flag.",
691
- )
692
- )
693
-
694
- if classification == "import_export_artifact" and (
695
- _truthy_flag(surface.get("liveState")) or _truthy_flag(surface.get("authoritative"))
696
- ):
697
- findings.append(
698
- GateFinding(
699
- state_surface=name,
700
- classification=classification,
701
- reason="Import/export artifact is marked as live or authoritative state.",
702
- required_fix=(
703
- "Use it only as a temporary transfer artifact, not live "
704
- "application state."
705
- ),
706
- )
707
- )
708
-
709
- if classification == "canonical_artifact" and (
710
- _truthy_flag(surface.get("mutable")) or _truthy_flag(surface.get("authoritative"))
711
- ):
712
- findings.append(
713
- GateFinding(
714
- state_surface=name,
715
- classification=classification,
716
- reason="Canonical artifact is marked mutable or authoritative app persistence.",
717
- required_fix=(
718
- "Use canonical artifacts as evidence/source-authored input, "
719
- "not mutable app records."
720
- ),
721
- )
722
- )
723
-
724
-
725
- def _validate_signals(record: dict[str, Any], signals: list[DetectedSignal]) -> list[GateFinding]:
726
- surfaces = _record_surfaces(record)
727
- findings: list[GateFinding] = []
728
- durable_surfaces = [
729
- surface
730
- for surface in surfaces
731
- if _surface_classification(surface) in DURABLE_CLASSIFICATIONS
732
- ]
733
- auth_surfaces = [
734
- surface
735
- for surface in surfaces
736
- if _surface_classification(surface) in SECURITY_CLASSIFICATIONS
737
- ]
738
-
739
- for signal in signals:
740
- if signal.storage:
741
- matching_surfaces = [
742
- surface for surface in surfaces if _surface_allows_storage(surface, signal.storage)
743
- ]
744
- forbidden_matches = [
745
- surface
746
- for surface in surfaces
747
- if any(
748
- _storage_matches(signal.storage, item)
749
- for item in _as_string_list(surface.get("forbiddenStorage"))
750
- )
751
- ]
752
- if forbidden_matches:
753
- surface = forbidden_matches[0]
754
- findings.append(
755
- GateFinding(
756
- state_surface=_surface_name(surface),
757
- classification=_surface_classification(surface),
758
- detected_storage=signal.storage,
759
- approved_storage=_approved_storage_text(surface),
760
- reason=(
761
- f"The diff implements {signal.storage} at {_signal_location(signal)}, "
762
- "but the design record forbids that storage."
763
- ),
764
- required_fix=(
765
- "Move the implementation to the approved system of record "
766
- "or update the design record before implementation."
767
- ),
768
- )
769
- )
770
- elif not matching_surfaces:
771
- findings.append(
772
- GateFinding(
773
- detected_storage=signal.storage,
774
- reason=(
775
- f"The diff implements {signal.storage} at {_signal_location(signal)} "
776
- "without a state surface that approves it."
777
- ),
778
- required_fix=(
779
- "Declare a matching state surface, or move the implementation "
780
- "to the approved system of record."
781
- ),
782
- )
783
- )
784
-
785
- if signal.kind == "mutation_endpoint" and not durable_surfaces:
786
- findings.append(
787
- GateFinding(
788
- reason=(
789
- f"Stateful create/update/delete API signal at {_signal_location(signal)} "
790
- "has no durable owner in the design record."
791
- ),
792
- required_fix=(
793
- "Declare the durable state surface that owns this mutation, including "
794
- "permission and recovery semantics."
795
- ),
796
- )
797
- )
798
-
799
- if signal.kind == "auth_state" and not auth_surfaces:
800
- findings.append(
801
- GateFinding(
802
- reason=(
803
- f"Auth/session/permission signal at {_signal_location(signal)} "
804
- "has no auth_session_state or authorization_state surface."
805
- ),
806
- required_fix=(
807
- "Declare the approved auth/session or authorization system "
808
- "of record."
809
- ),
810
- )
811
- )
812
-
813
- if signal.kind == "workflow_state" and not durable_surfaces:
814
- findings.append(
815
- GateFinding(
816
- reason=(
817
- f"Workflow/job/runtime state signal at {_signal_location(signal)} "
818
- "has no durable or service-backed owner."
819
- ),
820
- required_fix="Declare the job/workflow state owner and recovery semantics.",
821
- )
822
- )
823
-
824
- return findings
825
-
826
-
827
- def validate_record(
828
- record: dict[str, Any] | None,
829
- *,
830
- story_payload: dict[str, Any] | None = None,
831
- signals: list[DetectedSignal] | None = None,
832
- ) -> GateResult:
833
- """Validate a system-of-record design record."""
834
- if record is None:
835
- finding = GateFinding(
836
- reason="Triggered story has no architecture.systemOfRecord design record.",
837
- required_fix=(
838
- "Add a system-of-record block classifying each state surface "
839
- "before implementation."
840
- ),
841
- )
842
- return GateResult(1, _format_failure([finding]), (finding,))
843
-
844
- findings: list[GateFinding] = []
845
- surfaces = _record_surfaces(record)
846
- if not isinstance(record.get("stateSurfaces"), list) or not surfaces:
847
- findings.append(
848
- GateFinding(
849
- reason="systemOfRecord.stateSurfaces is missing or empty.",
850
- required_fix=(
851
- "Declare at least one state surface with classification "
852
- "and approvedStorage."
853
- ),
854
- )
855
- )
856
- for surface in surfaces:
857
- _validate_surface(surface, findings)
858
-
859
- _validate_reference_apps(record, story_payload, findings)
860
-
861
- if signals:
862
- findings.extend(_validate_signals(record, signals))
863
-
864
- if findings:
865
- return GateResult(1, _format_failure(findings), tuple(findings))
866
- return GateResult(0, "OK system-of-record gate passed.")
867
-
868
-
869
- def evaluate_story(story_path: Path) -> GateResult:
870
- payload, error = _load_json_file(story_path)
871
- if error is not None:
872
- return error
873
- assert payload is not None
874
- return validate_record(_system_of_record(payload), story_payload=payload)
875
-
876
-
877
- def scan_diff(diff_text: str) -> tuple[list[DetectedSignal], list[str]]:
878
- from _sor_gate_diff import scan_diff as _impl
879
-
880
- return _impl(diff_text)
881
-
882
-
883
- def evaluate_diff_text(
884
- diff_text: str,
885
- *,
886
- project_root: Path,
887
- story_path: Path | None = None,
888
- ) -> GateResult:
889
- from _sor_gate_diff import evaluate_diff_text as _impl
890
-
891
- return _impl(diff_text, project_root=project_root, story_path=story_path)
892
-
893
-
894
- def evaluate_diff(
895
- project_root: Path,
896
- base_ref: str,
897
- story_path: Path | None = None,
898
- ) -> GateResult:
899
- from _sor_gate_diff import evaluate_diff as _impl
900
-
901
- return _impl(project_root, base_ref, story_path=story_path)
902
-
903
-
904
- def _emit_json(result: GateResult) -> str:
905
- payload = {
906
- "ok": result.code == 0,
907
- "exit_code": result.code,
908
- "message": result.message,
909
- "findings": [
910
- {
911
- "state_surface": finding.state_surface,
912
- "classification": finding.classification,
913
- "detected_storage": finding.detected_storage,
914
- "approved_storage": finding.approved_storage,
915
- "reason": finding.reason,
916
- "required_fix": finding.required_fix,
917
- }
918
- for finding in result.findings
919
- ],
920
- }
921
- return json.dumps(payload, sort_keys=True)
922
-
923
-
924
- def _build_parser() -> argparse.ArgumentParser:
925
- parser = argparse.ArgumentParser(
926
- prog="preflight_architecture_sor.py",
927
- description=(
928
- "System-of-record architecture gate. Use --story-path for story-time "
929
- "preflight, or --base-ref for diff-time verification."
930
- ),
931
- )
932
- parser.add_argument("--story-path", help="Path to the story/spec vBRIEF JSON file.")
933
- parser.add_argument(
934
- "--base-ref",
935
- help="Base ref for diff-time verification, for example origin/main or upstream/master.",
936
- )
937
- parser.add_argument(
938
- "--project-root",
939
- default=".",
940
- help="Project root for diff-time verification. Defaults to current directory.",
941
- )
942
- parser.add_argument("--json", action="store_true", dest="emit_json")
943
- return parser
944
-
945
-
946
- def main(argv: list[str] | None = None) -> int:
947
- parser = _build_parser()
948
- args = parser.parse_args(argv)
949
-
950
- project_root = Path(args.project_root)
951
- story_path = Path(args.story_path) if args.story_path else None
952
-
953
- if args.base_ref:
954
- result = evaluate_diff(project_root, args.base_ref, story_path=story_path)
955
- elif story_path is not None:
956
- result = evaluate_story(story_path)
957
- else:
958
- result = GateResult(
959
- 2,
960
- "system-of-record gate misconfigured: pass --story-path, --base-ref, or both.",
961
- )
962
-
963
- if args.emit_json:
964
- print(_emit_json(result))
965
- elif result.code == 0:
966
- print(result.message)
967
- else:
968
- print(result.message, file=sys.stderr)
969
-
970
- return result.code
971
-
972
-
973
- if __name__ == "__main__":
974
- sys.exit(main())