@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,974 @@
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())