prizmkit 1.1.130 → 1.1.134

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 (119) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/adapters/claude/command-adapter.js +0 -2
  3. package/bundled/dev-pipeline/.env.example +1 -1
  4. package/bundled/dev-pipeline/assets/skill-subagent-integration.md +11 -6
  5. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +445 -8
  6. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +2 -9
  7. package/bundled/dev-pipeline/prizmkit_runtime/processes.py +21 -1
  8. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +87 -66
  9. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +53 -3
  10. package/bundled/dev-pipeline/prizmkit_runtime/runner_recovery.py +55 -25
  11. package/bundled/dev-pipeline/prizmkit_runtime/runner_status.py +4 -0
  12. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +119 -18
  13. package/bundled/dev-pipeline/prizmkit_runtime/sessions.py +3 -2
  14. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +411 -17
  15. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +57 -14
  16. package/bundled/dev-pipeline/scripts/generate-recovery-prompt.py +5 -4
  17. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +55 -2
  18. package/bundled/dev-pipeline/scripts/prompt_framework.py +152 -1
  19. package/bundled/dev-pipeline/scripts/update-bug-status.py +53 -0
  20. package/bundled/dev-pipeline/scripts/update-checkpoint.py +294 -69
  21. package/bundled/dev-pipeline/scripts/update-feature-status.py +57 -0
  22. package/bundled/dev-pipeline/scripts/update-refactor-status.py +53 -0
  23. package/bundled/dev-pipeline/templates/bootstrap-prompt.md +5 -5
  24. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +28 -22
  25. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +24 -10
  26. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +20 -2
  27. package/bundled/dev-pipeline/templates/sections/bugfix-phase-commit-report.md +2 -2
  28. package/bundled/dev-pipeline/templates/sections/bugfix-phase-diagnose-plan.md +1 -1
  29. package/bundled/dev-pipeline/templates/sections/bugfix-phase-manual-verification.md +5 -10
  30. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +9 -19
  31. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +21 -0
  32. package/bundled/dev-pipeline/templates/sections/bugfix-session-status.md +1 -1
  33. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +10 -10
  34. package/bundled/dev-pipeline/templates/sections/context-budget-rules.md +1 -1
  35. package/bundled/dev-pipeline/templates/sections/headless-commit-authorization.md +15 -0
  36. package/bundled/dev-pipeline/templates/sections/phase-commit-full.md +2 -2
  37. package/bundled/dev-pipeline/templates/sections/phase-commit.md +2 -2
  38. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +26 -23
  39. package/bundled/dev-pipeline/templates/sections/phase-review-agent.md +5 -5
  40. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +15 -11
  41. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +1 -1
  42. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +6 -6
  43. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +21 -0
  44. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +1 -1
  45. package/bundled/dev-pipeline/templates/sections/subagent-timeout-recovery.md +1 -1
  46. package/bundled/dev-pipeline/templates/sections/task-contract.md +4 -0
  47. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +362 -3
  48. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +349 -48
  49. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +129 -0
  50. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +91 -0
  51. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +567 -23
  52. package/bundled/dev-pipeline/tests/test_unified_cli.py +37 -10
  53. package/bundled/skills/_metadata.json +63 -26
  54. package/bundled/skills/app-planner/SKILL.md +4 -3
  55. package/bundled/skills/bug-fix-workflow/SKILL.md +89 -180
  56. package/bundled/skills/bug-planner/SKILL.md +12 -27
  57. package/bundled/skills/bugfix-pipeline-launcher/SKILL.md +131 -220
  58. package/bundled/skills/bugfix-pipeline-launcher/references/configuration.md +36 -90
  59. package/bundled/skills/feature-pipeline-launcher/SKILL.md +129 -271
  60. package/bundled/skills/feature-pipeline-launcher/references/configuration.md +35 -76
  61. package/bundled/skills/feature-planner/SKILL.md +27 -22
  62. package/bundled/skills/feature-planner/assets/planning-guide.md +4 -4
  63. package/bundled/skills/feature-workflow/SKILL.md +94 -121
  64. package/bundled/skills/prizmkit/SKILL.md +130 -94
  65. package/bundled/skills/prizmkit/references/workflow-state-protocol.md +181 -0
  66. package/bundled/skills/prizmkit-code-review/SKILL.md +132 -86
  67. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +243 -0
  68. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +42 -1
  69. package/bundled/skills/prizmkit-code-review/references/workflow-state-protocol.md +181 -0
  70. package/bundled/skills/prizmkit-code-review/scripts/render_review_report.py +93 -1
  71. package/bundled/skills/prizmkit-committer/SKILL.md +125 -48
  72. package/bundled/skills/prizmkit-committer/references/workflow-state-protocol.md +181 -0
  73. package/bundled/skills/prizmkit-implement/SKILL.md +99 -73
  74. package/bundled/skills/prizmkit-implement/references/implementation-subagent-procedure.md +1 -1
  75. package/bundled/skills/prizmkit-implement/references/workflow-state-protocol.md +181 -0
  76. package/bundled/skills/prizmkit-init/SKILL.md +5 -5
  77. package/bundled/skills/prizmkit-plan/SKILL.md +146 -105
  78. package/bundled/skills/prizmkit-plan/assets/plan-template.md +18 -0
  79. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +242 -0
  80. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +4 -4
  81. package/bundled/skills/prizmkit-plan/references/workflow-state-protocol.md +181 -0
  82. package/bundled/skills/prizmkit-retrospective/SKILL.md +111 -53
  83. package/bundled/skills/prizmkit-retrospective/references/knowledge-injection-steps.md +7 -6
  84. package/bundled/skills/prizmkit-retrospective/references/structural-sync-steps.md +5 -4
  85. package/bundled/skills/prizmkit-retrospective/references/workflow-state-protocol.md +181 -0
  86. package/bundled/skills/prizmkit-test/SKILL.md +52 -6
  87. package/bundled/skills/prizmkit-test/assets/authoritative-records.schema.json +63 -12
  88. package/bundled/skills/prizmkit-test/assets/evidence-manifest.schema.json +1 -1
  89. package/bundled/skills/prizmkit-test/assets/evidence-package-template.json +13 -0
  90. package/bundled/skills/prizmkit-test/references/evidence-protocol.md +6 -1
  91. package/bundled/skills/prizmkit-test/references/evidence-request-protocol.md +8 -1
  92. package/bundled/skills/prizmkit-test/references/examples.md +1 -1
  93. package/bundled/skills/prizmkit-test/references/test-generation-steps.md +4 -1
  94. package/bundled/skills/prizmkit-test/references/test-report-template.md +1 -1
  95. package/bundled/skills/prizmkit-test/references/trusted-evidence-execution.md +15 -0
  96. package/bundled/skills/prizmkit-test/references/workflow-state-protocol.md +181 -0
  97. package/bundled/skills/prizmkit-test/scripts/build_test_evidence.py +744 -23
  98. package/bundled/skills/prizmkit-test/scripts/validate_test_evidence.py +194 -15
  99. package/bundled/skills/prizmkit-workflow/SKILL.md +266 -0
  100. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +181 -0
  101. package/bundled/skills/recovery-workflow/SKILL.md +62 -241
  102. package/bundled/skills/recovery-workflow/evals/evals.json +17 -33
  103. package/bundled/skills/recovery-workflow/references/detection.md +28 -52
  104. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +105 -439
  105. package/bundled/skills/refactor-pipeline-launcher/SKILL.md +136 -275
  106. package/bundled/skills/refactor-pipeline-launcher/references/configuration.md +53 -88
  107. package/bundled/skills/refactor-planner/SKILL.md +12 -57
  108. package/bundled/skills/refactor-planner/references/behavior-preservation.md +111 -230
  109. package/bundled/skills/refactor-planner/references/error-recovery.md +37 -0
  110. package/bundled/skills/refactor-planner/references/planning-phases.md +11 -17
  111. package/bundled/skills/refactor-planner/scripts/validate-and-generate-refactor.py +1 -1
  112. package/bundled/skills/refactor-workflow/SKILL.md +98 -139
  113. package/bundled/templates/project-memory-template.md +4 -4
  114. package/package.json +1 -1
  115. package/src/index.js +4 -0
  116. package/src/prompts.js +10 -3
  117. package/src/scaffold.js +1 -1
  118. package/bundled/dev-pipeline/tests/test-deploy-safety.sh +0 -223
  119. package/bundled/skills/feature-pipeline-launcher/scripts/preflight-check.py +0 -462
@@ -1,223 +0,0 @@
1
- #!/usr/bin/env bash
2
- # Test deploy safety check logic across different task status scenarios
3
- # Run: bash dev-pipeline/tests/test-deploy-safety.sh
4
- set -euo pipefail
5
-
6
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
7
- REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
8
-
9
- RED='\033[0;31m'
10
- GREEN='\033[0;32m'
11
- YELLOW='\033[1;33m'
12
- NC='\033[0m'
13
-
14
- PASS=0
15
- FAIL=0
16
- TOTAL=0
17
-
18
- pass() { echo -e " ${GREEN}PASS${NC} $1"; PASS=$((PASS + 1)); TOTAL=$((TOTAL + 1)); }
19
- fail() { echo -e " ${RED}FAIL${NC} $1 — $2"; FAIL=$((FAIL + 1)); TOTAL=$((TOTAL + 1)); }
20
-
21
- echo "================================="
22
- echo " Deploy Safety Check Tests"
23
- echo "================================="
24
- echo ""
25
-
26
- # --- Test 1: All tasks completed -> deploy should proceed ---
27
- echo "[Test 1] All 'completed': incomplete_count should be 0"
28
- cat > /tmp/test-deploy-all-completed.json << 'JSON'
29
- {"features": [{"id": "F-A", "status": "completed"}, {"id": "F-B", "status": "completed"}]}
30
- JSON
31
- count=$(python3 -c "
32
- import json
33
- with open('/tmp/test-deploy-all-completed.json') as f:
34
- data = json.load(f)
35
- bad = [f for f in data.get('features', [])
36
- if f.get('status') not in ('completed', 'skipped')]
37
- print(len(bad))
38
- ")
39
- if [[ "$count" == "0" ]]; then
40
- pass "incomplete_count=0, deploy proceeds"
41
- else
42
- fail "incomplete_count=$count, expected 0"
43
- fi
44
-
45
- # --- Test 2: One failed, one completed -> deploy blocked ---
46
- echo "[Test 2] Mixed 'completed' + 'failed': incomplete_count should be 1"
47
- cat > /tmp/test-deploy-mixed.json << 'JSON'
48
- {"features": [{"id": "F-A", "status": "completed"}, {"id": "F-B", "status": "failed"}]}
49
- JSON
50
- count=$(python3 -c "
51
- import json
52
- with open('/tmp/test-deploy-mixed.json') as f:
53
- data = json.load(f)
54
- bad = [f for f in data.get('features', [])
55
- if f.get('status') not in ('completed', 'skipped')]
56
- print(len(bad))
57
- ")
58
- if [[ "$count" == "1" ]]; then
59
- pass "incomplete_count=1, deploy blocked"
60
- else
61
- fail "incomplete_count=$count, expected 1"
62
- fi
63
-
64
- # --- Test 3: All skipped -> deploy proceeds (skipped is non-blocking) ---
65
- echo "[Test 3] All 'skipped': incomplete_count should be 0"
66
- cat > /tmp/test-deploy-all-skipped.json << 'JSON'
67
- {"features": [{"id": "F-A", "status": "skipped"}, {"id": "F-B", "status": "skipped"}]}
68
- JSON
69
- count=$(python3 -c "
70
- import json
71
- with open('/tmp/test-deploy-all-skipped.json') as f:
72
- data = json.load(f)
73
- bad = [f for f in data.get('features', [])
74
- if f.get('status') not in ('completed', 'skipped')]
75
- print(len(bad))
76
- ")
77
- if [[ "$count" == "0" ]]; then
78
- pass "incomplete_count=0, deploy proceeds (skipped is non-blocking)"
79
- else
80
- fail "incomplete_count=$count, expected 0"
81
- fi
82
-
83
- # --- Test 4: auto_skipped status -> deploy blocked ---
84
- echo "[Test 4] 'auto_skipped' status: incomplete_count should be 1"
85
- cat > /tmp/test-deploy-timeout.json << 'JSON'
86
- {"features": [{"id": "F-A", "status": "completed"}, {"id": "F-B", "status": "auto_skipped"}]}
87
- JSON
88
- count=$(python3 -c "
89
- import json
90
- with open('/tmp/test-deploy-timeout.json') as f:
91
- data = json.load(f)
92
- bad = [f for f in data.get('features', [])
93
- if f.get('status') not in ('completed', 'skipped')]
94
- print(len(bad))
95
- ")
96
- if [[ "$count" == "1" ]]; then
97
- pass "incomplete_count=1, deploy blocked"
98
- else
99
- fail "incomplete_count=$count, expected 1"
100
- fi
101
-
102
- # --- Test 5: tee /dev/stderr | tail -1 pattern extracts only count ---
103
- echo "[Test 5] Multi-line output extraction: only last line (integer) captured"
104
- cat > /tmp/test-deploy-tee.json << 'JSON'
105
- {"features": [{"id": "F-001", "status": "failed", "title": "Broken feature"}, {"id": "F-002", "status": "crashed", "title": "Also broken"}]}
106
- JSON
107
- result=$({ python3 -c "
108
- import json
109
- with open('/tmp/test-deploy-tee.json') as f:
110
- data = json.load(f)
111
- bad = [f for f in data.get('features', [])
112
- if f.get('status') not in ('completed', 'skipped')]
113
- for f in bad:
114
- print(f\" {f['id']}: {f.get('status', 'unknown')} — {f.get('title', '')}\")
115
- print(len(bad))
116
- " /tmp/test-deploy-tee.json 2>/dev/null || echo "0"; } | tail -1)
117
- if [[ "$result" =~ ^[0-9]+$ ]]; then
118
- pass "extracted count is integer: $result"
119
- else
120
- fail "extracted count is not a clean integer: '$result'"
121
- fi
122
-
123
- # --- Test 6: Empty feature list -> deploy proceeds ---
124
- echo "[Test 6] Empty list: incomplete_count should be 0"
125
- cat > /tmp/test-deploy-empty.json << 'JSON'
126
- {"features": []}
127
- JSON
128
- count=$(python3 -c "
129
- import json
130
- with open('/tmp/test-deploy-empty.json') as f:
131
- data = json.load(f)
132
- bad = [f for f in data.get('features', [])
133
- if f.get('status') not in ('completed', 'skipped')]
134
- print(len(bad))
135
- ")
136
- if [[ "$count" == "0" ]]; then
137
- pass "incomplete_count=0, deploy proceeds"
138
- else
139
- fail "incomplete_count=$count, expected 0"
140
- fi
141
-
142
- # --- Test 7: Bugfix variant with needs_info (non-blocking) ---
143
- echo "[Test 7] Bugfix: 'needs_info' should NOT block deploy"
144
- cat > /tmp/test-deploy-bugfix.json << 'JSON'
145
- {"bugs": [{"id": "B-001", "status": "completed"}, {"id": "B-002", "status": "needs_info"}]}
146
- JSON
147
- count=$(python3 -c "
148
- import json
149
- with open('/tmp/test-deploy-bugfix.json') as f:
150
- data = json.load(f)
151
- bad = [b for b in data.get('bugs', [])
152
- if b.get('status') not in ('completed', 'skipped', 'needs_info')]
153
- print(len(bad))
154
- ")
155
- if [[ "$count" == "0" ]]; then
156
- pass "incomplete_count=0, deploy proceeds (needs_info non-blocking)"
157
- else
158
- fail "incomplete_count=$count, expected 0"
159
- fi
160
-
161
- # --- Test 8: Refactor variant ---
162
- echo "[Test 8] Refactor: completed + skipped -> deploy proceeds"
163
- cat > /tmp/test-deploy-refactor.json << 'JSON'
164
- {"refactors": [{"id": "R-001", "status": "completed"}, {"id": "R-002", "status": "skipped"}]}
165
- JSON
166
- count=$(python3 -c "
167
- import json
168
- with open('/tmp/test-deploy-refactor.json') as f:
169
- data = json.load(f)
170
- bad = [r for r in data.get('refactors', [])
171
- if r.get('status') not in ('completed', 'skipped')]
172
- print(len(bad))
173
- ")
174
- if [[ "$count" == "0" ]]; then
175
- pass "incomplete_count=0, deploy proceeds"
176
- else
177
- fail "incomplete_count=$count, expected 0"
178
- fi
179
-
180
- # --- Test 9: Real feature-list.json ---
181
- echo "[Test 9] Real feature-list.json: both completed -> deploy proceeds"
182
- if [[ -f "$REPO_ROOT/.prizmkit/plans/feature-list.json" ]]; then
183
- count=$(python3 -c "
184
- import json
185
- with open('$REPO_ROOT/.prizmkit/plans/feature-list.json') as f:
186
- data = json.load(f)
187
- bad = [f for f in data.get('features', [])
188
- if f.get('status') not in ('completed', 'skipped')]
189
- print(len(bad))
190
- ")
191
- if [[ "$count" == "0" ]]; then
192
- pass "real list: incomplete_count=0"
193
- else
194
- fail "real list: incomplete_count=$count, expected 0"
195
- fi
196
- else
197
- echo " ${YELLOW}SKIP${NC} No real feature-list.json found"
198
- fi
199
-
200
- # --- Test 10: ENABLE_DEPLOY=0 skips the entire block ---
201
- echo "[Test 10] ENABLE_DEPLOY=0: deploy block should be skipped entirely"
202
- ENABLE_DEPLOY=0
203
- executed=false
204
- if [[ "$ENABLE_DEPLOY" == "1" ]]; then
205
- executed=true
206
- fi
207
- if [[ "$executed" == "false" ]]; then
208
- pass "ENABLE_DEPLOY=0: deploy block skipped"
209
- else
210
- fail "ENABLE_DEPLOY=0: deploy block should NOT execute"
211
- fi
212
-
213
- # --- Cleanup ---
214
- rm -f /tmp/test-deploy-*.json
215
-
216
- echo ""
217
- echo "================================="
218
- echo " Results: $PASS passed, $FAIL failed ($TOTAL total)"
219
- echo "================================="
220
-
221
- if [[ $FAIL -gt 0 ]]; then
222
- exit 1
223
- fi
@@ -1,462 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- dev-pipeline environment preflight checker.
4
-
5
- Detects database type from .prizmkit/plans/feature-list.json / .prizmkit/config.json,
6
- verifies env vars, tests connectivity, and checks migration status.
7
-
8
- Usage:
9
- python3 preflight-check.py [.prizmkit/plans/feature-list.json]
10
-
11
- Output: PREFLIGHT lines to stdout (✓ / ⚠ / ℹ), JSON summary to stderr.
12
- Exit code: 0 = all clear, 1 = warnings found, 2 = error.
13
- """
14
-
15
- import json
16
- import glob
17
- import os
18
- import re
19
- import subprocess
20
- import sys
21
-
22
- # ── Config ──────────────────────────────────────────────────────
23
-
24
- ENV_FILES = [".env.local", ".env", ".env.development.local", ".env.development"]
25
-
26
- # (group_label, regex_pattern) — matched against env var names.
27
- # IMPORTANT: use non-capturing groups (?:...) inside patterns so that
28
- # group(1) in the scan regex captures the full variable name.
29
- DB_VAR_PATTERNS = [
30
- ("SUPABASE_URL", r"(?:NEXT_PUBLIC_)?SUPABASE_URL"),
31
- ("SUPABASE_KEY", r"(?:NEXT_PUBLIC_)?SUPABASE_(?:ANON_KEY|SERVICE_ROLE_KEY)"),
32
- ("DATABASE_URL", r"DATABASE_URL"),
33
- ("DB_CONNECTION", r"DB_(?:HOST|CONNECTION|URL|PORT|NAME|USER|PASSWORD)"),
34
- ("FIREBASE", r"(?:NEXT_PUBLIC_)?FIREBASE_(?:API_KEY|PROJECT_ID|AUTH_DOMAIN)"),
35
- ("MONGODB", r"MONGO(?:DB)?_(?:URI|URL|CONNECTION)"),
36
- ("REDIS", r"REDIS_(?:URL|HOST|PORT)"),
37
- ("MYSQL", r"(?:MYSQL|PLANETSCALE)_(?:URL|HOST|DATABASE)"),
38
- ("POSTGRES", r"(?:PG|POSTGRES(?:QL)?)_(?:URL|HOST|CONNECTION)"),
39
- ]
40
-
41
- DB_KEYWORDS = [
42
- "migration", "database", "create table", "table", "rls",
43
- "storage bucket", "schema", "model", "prisma", "drizzle",
44
- "sequelize", "typeorm", "supabase", "firebase", "mongodb",
45
- "postgres", "mysql", "sqlite", "redis",
46
- ]
47
-
48
- warnings = []
49
- passes = []
50
- infos = []
51
-
52
-
53
- def out(level, msg):
54
- """Print a preflight line and collect it."""
55
- print(f"PREFLIGHT {level} {msg}")
56
- if level == "⚠":
57
- warnings.append(msg)
58
- elif level == "✓":
59
- passes.append(msg)
60
- else:
61
- infos.append(msg)
62
-
63
-
64
- # ── 1. Detect DB type and DB-related features ──────────────────
65
-
66
- def detect_db(feature_list_path):
67
- """Return (db_type_str, list_of_feature_ids_with_db)."""
68
- db_str = ""
69
- db_features = []
70
-
71
- try:
72
- with open(feature_list_path) as f:
73
- data = json.load(f)
74
- except Exception:
75
- return "", []
76
-
77
- db_str = data.get("global_context", {}).get("database", "")
78
-
79
- if not db_str:
80
- try:
81
- with open(".prizmkit/config.json") as f:
82
- cfg = json.load(f)
83
- db_str = cfg.get("tech_stack", {}).get("database", "")
84
- except Exception:
85
- pass
86
-
87
- if not db_str:
88
- return "", []
89
-
90
- for feat in data.get("features", []):
91
- desc = (feat.get("description", "") + " " + feat.get("title", "")).lower()
92
- if any(k in desc for k in DB_KEYWORDS):
93
- db_features.append(feat["id"])
94
-
95
- return db_str, db_features
96
-
97
-
98
- # ── 2. Scan env files for DB connection vars ────────────────────
99
-
100
- def scan_env_vars():
101
- """Return (env_file_used, {var_name: value})."""
102
- for env_file in ENV_FILES:
103
- if not os.path.isfile(env_file):
104
- continue
105
- found = {}
106
- with open(env_file) as f:
107
- content = f.read()
108
- for _group, pattern in DB_VAR_PATTERNS:
109
- for m in re.finditer(
110
- r"^(?!#)("+pattern + r")\s*=\s*(.+)",
111
- content,
112
- re.MULTILINE | re.IGNORECASE,
113
- ):
114
- var_name = m.group(1)
115
- var_val = m.group(2).strip().strip('"').strip("'")
116
- if var_val:
117
- found[var_name] = var_val
118
- if found:
119
- return env_file, found
120
- return None, {}
121
-
122
-
123
- # ── 3. Connectivity checks (per DB type) ───────────────────────
124
-
125
- def _curl_code(url, headers=None, timeout=10):
126
- """Run curl and return HTTP status code string."""
127
- cmd = ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
128
- "--max-time", str(timeout), url]
129
- for h in (headers or []):
130
- cmd += ["-H", h]
131
- try:
132
- r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout + 5)
133
- return r.stdout.strip()
134
- except Exception:
135
- return "000"
136
-
137
-
138
- def _get_var(env_vars, *patterns):
139
- """Find first env var matching any pattern."""
140
- for pat in patterns:
141
- for k, v in env_vars.items():
142
- if re.match(pat + "$", k, re.IGNORECASE) and v:
143
- return k, v
144
- return None, None
145
-
146
-
147
- def check_connectivity(db_type, env_vars):
148
- """Test database connectivity. Returns True if connected."""
149
- dt = db_type.lower()
150
-
151
- # ── Supabase ──
152
- if "supabase" in dt:
153
- _, url = _get_var(env_vars, r"(?:NEXT_PUBLIC_)?SUPABASE_URL")
154
- _, key = _get_var(env_vars, r"(?:NEXT_PUBLIC_)?SUPABASE_ANON_KEY")
155
- if not key:
156
- _, key = _get_var(env_vars, r"SUPABASE_SERVICE_ROLE_KEY")
157
- if not (url and key):
158
- out("⚠", "Supabase URL or anon key not found — cannot test connectivity")
159
- return False
160
- # Find a table from first migration to test against
161
- test_table = "profiles"
162
- mig_files = sorted(glob.glob("supabase/migrations/*.sql"))
163
- if mig_files:
164
- with open(mig_files[0]) as f:
165
- for line in f:
166
- m = re.search(r"CREATE TABLE\s+(?:public\.)?(\w+)", line, re.I)
167
- if m:
168
- test_table = m.group(1)
169
- break
170
- code = _curl_code(
171
- f"{url}/rest/v1/{test_table}?limit=0",
172
- [f"apikey: {key}", f"Authorization: Bearer {key}"],
173
- )
174
- if code == "200":
175
- out("✓", "Database API reachable (Supabase)")
176
- return True
177
- else:
178
- out("⚠", f"Database API unreachable (Supabase HTTP {code})")
179
- return False
180
-
181
- # ── PostgreSQL / Neon ──
182
- if any(k in dt for k in ("postgres", "pg", "neon")):
183
- _, db_url = _get_var(env_vars, r"DATABASE_URL", r"POSTGRES(QL)?_URL", r"PG_URL")
184
- if not db_url:
185
- out("⚠", "No DATABASE_URL found — cannot test PostgreSQL connectivity")
186
- return False
187
- try:
188
- r = subprocess.run(
189
- ["pg_isready", "-d", db_url],
190
- capture_output=True, text=True, timeout=10,
191
- )
192
- if r.returncode == 0:
193
- out("✓", "PostgreSQL reachable")
194
- return True
195
- out("⚠", f"PostgreSQL unreachable: {r.stderr.strip()}")
196
- return False
197
- except FileNotFoundError:
198
- out("ℹ", "pg_isready not installed — cannot verify PostgreSQL connectivity")
199
- return False
200
- except Exception as e:
201
- out("⚠", f"PostgreSQL connectivity test failed: {e}")
202
- return False
203
-
204
- # ── MySQL / PlanetScale / MariaDB ──
205
- if any(k in dt for k in ("mysql", "planetscale", "mariadb")):
206
- _, db_url = _get_var(env_vars, r"DATABASE_URL", r"MYSQL_(URL|HOST)")
207
- if not db_url:
208
- out("⚠", "No DATABASE_URL found — cannot test MySQL connectivity")
209
- return False
210
- try:
211
- hostport = db_url.split("@")[-1].split("/")[0] if "@" in db_url else db_url
212
- host = hostport.split(":")[0]
213
- port_args = ["-P", hostport.split(":")[1]] if ":" in hostport else []
214
- r = subprocess.run(
215
- ["mysqladmin", "ping", "-h", host] + port_args,
216
- capture_output=True, text=True, timeout=10,
217
- )
218
- if "alive" in r.stdout.lower():
219
- out("✓", "MySQL reachable")
220
- return True
221
- out("⚠", "MySQL unreachable")
222
- return False
223
- except FileNotFoundError:
224
- out("ℹ", "mysqladmin not installed — cannot verify MySQL connectivity")
225
- return False
226
- except Exception as e:
227
- out("⚠", f"MySQL connectivity test failed: {e}")
228
- return False
229
-
230
- # ── MongoDB ──
231
- if "mongo" in dt:
232
- _, db_url = _get_var(env_vars, r"MONGO(DB)?_(URI|URL|CONNECTION)", r"DATABASE_URL")
233
- if not db_url:
234
- out("⚠", "No MongoDB URI found — cannot test connectivity")
235
- return False
236
- try:
237
- r = subprocess.run(
238
- ["mongosh", "--eval", "db.runCommand({ping:1})", db_url, "--quiet"],
239
- capture_output=True, text=True, timeout=10,
240
- )
241
- if r.returncode == 0:
242
- out("✓", "MongoDB reachable")
243
- return True
244
- out("⚠", "MongoDB unreachable")
245
- return False
246
- except FileNotFoundError:
247
- out("ℹ", "mongosh not installed — cannot verify MongoDB connectivity")
248
- return False
249
- except Exception as e:
250
- out("⚠", f"MongoDB connectivity test failed: {e}")
251
- return False
252
-
253
- # ── Firebase ──
254
- if "firebase" in dt:
255
- _, project_id = _get_var(env_vars, r"(NEXT_PUBLIC_)?FIREBASE_PROJECT_ID")
256
- if not project_id:
257
- out("⚠", "No Firebase project ID found — cannot test connectivity")
258
- return False
259
- code = _curl_code(
260
- f"https://firestore.googleapis.com/v1/projects/{project_id}/databases/(default)/documents?pageSize=0"
261
- )
262
- if code in ("200", "401", "403"):
263
- out("✓", "Firebase project reachable")
264
- return True
265
- out("⚠", f"Firebase unreachable (HTTP {code})")
266
- return False
267
-
268
- # ── Generic DATABASE_URL fallback ──
269
- _, db_url = _get_var(env_vars, r"DATABASE_URL")
270
- if db_url and "://" in db_url:
271
- proto = db_url.split("://")[0]
272
- if proto in ("postgres", "postgresql"):
273
- try:
274
- r = subprocess.run(
275
- ["pg_isready", "-d", db_url],
276
- capture_output=True, text=True, timeout=10,
277
- )
278
- ok = r.returncode == 0
279
- out("✓" if ok else "⚠", f"PostgreSQL {'reachable' if ok else 'unreachable'}")
280
- return ok
281
- except FileNotFoundError:
282
- out("ℹ", "pg_isready not installed — cannot verify connectivity")
283
- elif proto in ("mysql", "mariadb"):
284
- out("ℹ", "MySQL DATABASE_URL found — install mysqladmin to verify connectivity")
285
- elif proto in ("mongodb", "mongodb+srv"):
286
- out("ℹ", "MongoDB DATABASE_URL found — install mongosh to verify connectivity")
287
- else:
288
- out("ℹ", f"DATABASE_URL found (protocol: {proto}) — cannot auto-verify")
289
- return False
290
-
291
- out("ℹ", f"Database type \"{db_type}\" detected but no connection variables found")
292
- return False
293
-
294
-
295
- # ── 4. Migration status ────────────────────────────────────────
296
-
297
- def check_migrations(db_type, env_vars, connected):
298
- """Check whether migrations have been applied."""
299
- dt = db_type.lower()
300
- checked = False
301
-
302
- # ── Prisma ──
303
- if os.path.isdir("prisma/migrations") or os.path.isfile("prisma/schema.prisma"):
304
- checked = True
305
- try:
306
- env = os.environ.copy()
307
- env.update(env_vars)
308
- r = subprocess.run(
309
- ["npx", "prisma", "migrate", "status"],
310
- capture_output=True, text=True, timeout=30, env=env,
311
- )
312
- if "not yet been applied" in r.stdout.lower():
313
- out("⚠", "Prisma: unapplied migrations detected")
314
- for line in r.stdout.splitlines():
315
- if "not yet been applied" in line.lower() or line.strip().startswith("- "):
316
- out("⚠", f" {line.strip()}")
317
- elif r.returncode == 0:
318
- out("✓", "Prisma: all migrations applied")
319
- else:
320
- snippet = (r.stderr or r.stdout or "").strip()[:200]
321
- snippet = re.sub(r"://[^\s]+@", "://[REDACTED]@", snippet)
322
- out("⚠", f"Prisma migrate status failed: {snippet}")
323
- except FileNotFoundError:
324
- out("ℹ", "npx not found — cannot check Prisma migration status")
325
- except Exception as e:
326
- out("⚠", f"Prisma check failed: {e}")
327
-
328
- # ── Drizzle ──
329
- if os.path.isdir("drizzle") and glob.glob("drizzle/*.sql"):
330
- checked = True
331
- out("ℹ", "Drizzle migrations found — verify with `npx drizzle-kit push` or `npx drizzle-kit migrate`")
332
-
333
- # ── Supabase raw SQL ──
334
- if os.path.isdir("supabase/migrations") and "supabase" in dt:
335
- checked = True
336
- url = env_vars.get("NEXT_PUBLIC_SUPABASE_URL", env_vars.get("SUPABASE_URL", ""))
337
- key = env_vars.get("NEXT_PUBLIC_SUPABASE_ANON_KEY", env_vars.get("SUPABASE_ANON_KEY", ""))
338
-
339
- if url and key and connected:
340
- for mig in sorted(glob.glob("supabase/migrations/*.sql")):
341
- with open(mig) as f:
342
- content = f.read()
343
- bn = os.path.basename(mig)
344
- for match in re.finditer(
345
- r"CREATE TABLE\s+(?:(public|auth|storage)\.)?(\w+)",
346
- content, re.I,
347
- ):
348
- schema = (match.group(1) or "public").lower()
349
- tbl = match.group(2)
350
- if schema != "public":
351
- continue # auth/storage tables not accessible via REST API
352
- code = _curl_code(
353
- f"{url}/rest/v1/{tbl}?limit=0",
354
- [f"apikey: {key}", f"Authorization: Bearer {key}"],
355
- timeout=5,
356
- )
357
- if code == "200":
358
- out("✓", f"{bn}: table '{tbl}' exists")
359
- else:
360
- out("⚠", f"{bn}: table '{tbl}' NOT FOUND — migration may not be applied")
361
- else:
362
- n = len(glob.glob("supabase/migrations/*.sql"))
363
- out("ℹ", f"{n} Supabase migration file(s) found — cannot verify without API connection")
364
-
365
- # ── Knex / Rails / generic ──
366
- for mig_dir in ("migrations", "db/migrate", "db/migrations"):
367
- if os.path.isdir(mig_dir) and not checked:
368
- checked = True
369
- n = len(os.listdir(mig_dir))
370
- out("ℹ", f"{n} migration file(s) in {mig_dir}/ — verify manually that all are applied")
371
-
372
- if not checked:
373
- out("ℹ", "No migration directory detected — skipping migration check")
374
-
375
-
376
- # ── 5. Dev server ──────────────────────────────────────────────
377
-
378
- def check_dev_server(feature_list_path):
379
- """Check if dev server is running (from browser_interaction URLs)."""
380
- try:
381
- with open(feature_list_path) as f:
382
- data = json.load(f)
383
- except Exception:
384
- return
385
- checked_bases = set()
386
- for feat in data.get("features", []):
387
- bi = feat.get("browser_interaction")
388
- if bi and isinstance(bi, dict) and bi.get("url"):
389
- m = re.match(r"(https?://[^/]+)", bi["url"])
390
- if m:
391
- base = m.group(1)
392
- if base in checked_bases:
393
- continue
394
- checked_bases.add(base)
395
- code = _curl_code(base, timeout=5)
396
- if code in ("200", "302"):
397
- out("✓", f"Dev server reachable at {base}")
398
- else:
399
- out("ℹ", f"Dev server not running at {base} (AI sessions can start it)")
400
-
401
-
402
- # ── Main ────────────────────────────────────────────────────────
403
-
404
- def main():
405
- feature_list = sys.argv[1] if len(sys.argv) > 1 else ".prizmkit/plans/feature-list.json"
406
-
407
- if not os.path.isfile(feature_list):
408
- print(f"PREFLIGHT ⚠ Feature list not found: {feature_list}")
409
- sys.exit(2)
410
-
411
- # 1. Detect database
412
- db_type, db_features = detect_db(feature_list)
413
- if not db_type:
414
- print("PREFLIGHT ℹ No database configured in global_context — skipping DB checks")
415
- check_dev_server(feature_list)
416
- _print_summary()
417
- return
418
- if not db_features:
419
- print(f"PREFLIGHT ℹ Database: {db_type} (no features reference DB — skipping detailed checks)")
420
- check_dev_server(feature_list)
421
- _print_summary()
422
- return
423
-
424
- print(f"PREFLIGHT ℹ Database: {db_type}")
425
- print(f"PREFLIGHT ℹ DB-related features: {', '.join(db_features)}")
426
-
427
- # 2. Env vars
428
- env_file, env_vars = scan_env_vars()
429
- if not env_file:
430
- out("⚠", "No env file found (.env.local, .env, etc.) — database connection will likely fail")
431
- elif not env_vars:
432
- out("⚠", f"{env_file} exists but no database connection variables detected")
433
- else:
434
- for var_name in sorted(env_vars.keys()):
435
- out("✓", f"{var_name} configured")
436
-
437
- # 3. Connectivity
438
- connected = check_connectivity(db_type, env_vars)
439
-
440
- # 4. Migrations
441
- check_migrations(db_type, env_vars, connected)
442
-
443
- # 5. Dev server
444
- check_dev_server(feature_list)
445
-
446
- _print_summary()
447
-
448
-
449
- def _print_summary():
450
- """Print JSON summary to stderr and set exit code."""
451
- summary = {
452
- "pass_count": len(passes),
453
- "warn_count": len(warnings),
454
- "info_count": len(infos),
455
- "warnings": warnings,
456
- }
457
- print(json.dumps(summary), file=sys.stderr)
458
- sys.exit(1 if warnings else 0)
459
-
460
-
461
- if __name__ == "__main__":
462
- main()