@cbartens/bkit 0.0.0-stage → 5.0.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 (373) hide show
  1. package/.bkit/README.md +421 -0
  2. package/.bkit/core/.agents/context.md +95 -0
  3. package/.bkit/core/.agents/docs.md +62 -0
  4. package/.bkit/core/.agents/rules.md +147 -0
  5. package/.bkit/core/.agents/skills.md +43 -0
  6. package/.bkit/core/.bkit/LICENSE.md +151 -0
  7. package/.bkit/core/.bkit/README.md +421 -0
  8. package/.bkit/core/.bkit/cloud.md +502 -0
  9. package/.bkit/core/.bkit/comparison.md +318 -0
  10. package/.bkit/core/.bkit/install.md +496 -0
  11. package/.bkit/core/.bkit/jsonl.md +497 -0
  12. package/.bkit/core/.bkit/prompts.md +474 -0
  13. package/.bkit/core/.bkit/providers.md +598 -0
  14. package/.bkit/core/.bkit/templates.md +471 -0
  15. package/.bkit/core/.bkit/trackers.md +95 -0
  16. package/.bkit/core/.bkit/workflows.md +1546 -0
  17. package/.bkit/core/.claude/hooks/bkit-gateguard.cjs +82 -0
  18. package/.bkit/core/.claude/hooks/bkit-guardrails.cjs +93 -0
  19. package/.bkit/core/.claude/hooks/bkit-preflight.sh +74 -0
  20. package/.bkit/core/.codex/hooks/bkit-gateguard.cjs +115 -0
  21. package/.bkit/core/.codex/hooks/bkit-guardrails.cjs +135 -0
  22. package/.bkit/core/.cursor/hooks/bkit-gateguard.cjs +111 -0
  23. package/.bkit/core/.cursor/hooks/bkit-guardrails.cjs +169 -0
  24. package/.bkit/core/.cursor/hooks/bkit-preflight.sh +63 -0
  25. package/.bkit/core/.opencode/plugin/bkit-gateguard.js +225 -0
  26. package/.bkit/core/AGENTS.md +77 -0
  27. package/.bkit/core/LICENSE.md +149 -0
  28. package/.bkit/core/docs/templates/bkit-audit-accessibility.md +272 -0
  29. package/.bkit/core/docs/templates/bkit-audit-adoption.md +223 -0
  30. package/.bkit/core/docs/templates/bkit-audit-agents.md +230 -0
  31. package/.bkit/core/docs/templates/bkit-audit-aio-seo.md +227 -0
  32. package/.bkit/core/docs/templates/bkit-audit-analytics.md +266 -0
  33. package/.bkit/core/docs/templates/bkit-audit-annotations.md +230 -0
  34. package/.bkit/core/docs/templates/bkit-audit-app-performance.md +270 -0
  35. package/.bkit/core/docs/templates/bkit-audit-app-store.md +254 -0
  36. package/.bkit/core/docs/templates/bkit-audit-architecture.md +221 -0
  37. package/.bkit/core/docs/templates/bkit-audit-ci-performance.md +241 -0
  38. package/.bkit/core/docs/templates/bkit-audit-config.md +230 -0
  39. package/.bkit/core/docs/templates/bkit-audit-cost.md +218 -0
  40. package/.bkit/core/docs/templates/bkit-audit-coverage.md +221 -0
  41. package/.bkit/core/docs/templates/bkit-audit-database.md +229 -0
  42. package/.bkit/core/docs/templates/bkit-audit-dead-code.md +251 -0
  43. package/.bkit/core/docs/templates/bkit-audit-deferrals.md +283 -0
  44. package/.bkit/core/docs/templates/bkit-audit-dependencies.md +268 -0
  45. package/.bkit/core/docs/templates/bkit-audit-documentation.md +280 -0
  46. package/.bkit/core/docs/templates/bkit-audit-duplication.md +253 -0
  47. package/.bkit/core/docs/templates/bkit-audit-failures.md +259 -0
  48. package/.bkit/core/docs/templates/bkit-audit-flakes.md +237 -0
  49. package/.bkit/core/docs/templates/bkit-audit-gates.md +250 -0
  50. package/.bkit/core/docs/templates/bkit-audit-issues.md +273 -0
  51. package/.bkit/core/docs/templates/bkit-audit-llm.md +239 -0
  52. package/.bkit/core/docs/templates/bkit-audit-logs.md +266 -0
  53. package/.bkit/core/docs/templates/bkit-audit-models.md +210 -0
  54. package/.bkit/core/docs/templates/bkit-audit-privacy.md +211 -0
  55. package/.bkit/core/docs/templates/bkit-audit-prompts.md +216 -0
  56. package/.bkit/core/docs/templates/bkit-audit-red-team.md +220 -0
  57. package/.bkit/core/docs/templates/bkit-audit-reliability.md +222 -0
  58. package/.bkit/core/docs/templates/bkit-audit-repo.md +224 -0
  59. package/.bkit/core/docs/templates/bkit-audit-security.md +274 -0
  60. package/.bkit/core/docs/templates/bkit-audit-slop.md +200 -0
  61. package/.bkit/core/docs/templates/bkit-audit-testing.md +270 -0
  62. package/.bkit/core/docs/templates/bkit-audit-usability.md +237 -0
  63. package/.bkit/core/docs/templates/bkit-plan.md +476 -0
  64. package/.bkit/core/engine/checks/after/auth.ts +247 -0
  65. package/.bkit/core/engine/checks/after/ci-yml.ts +739 -0
  66. package/.bkit/core/engine/checks/after/github.ts +424 -0
  67. package/.bkit/core/engine/checks/after/index.ts +556 -0
  68. package/.bkit/core/engine/checks/after/managed.ts +217 -0
  69. package/.bkit/core/engine/checks/after/tools.ts +427 -0
  70. package/.bkit/core/engine/checks/after/vercel.ts +101 -0
  71. package/.bkit/core/engine/checks/before/context-fetch.ts +429 -0
  72. package/.bkit/core/engine/checks/before/env.ts +201 -0
  73. package/.bkit/core/engine/checks/before/files.ts +202 -0
  74. package/.bkit/core/engine/checks/before/index.ts +206 -0
  75. package/.bkit/core/engine/checks/before/mcp.ts +127 -0
  76. package/.bkit/core/engine/checks/before/repo.ts +77 -0
  77. package/.bkit/core/engine/checks/before/version.ts +67 -0
  78. package/.bkit/core/engine/checks/status-holes.ts +479 -0
  79. package/.bkit/core/engine/cli.ts +871 -0
  80. package/.bkit/core/engine/commands/analysis.ts +550 -0
  81. package/.bkit/core/engine/commands/ci/ci.ts +483 -0
  82. package/.bkit/core/engine/commands/comply.ts +415 -0
  83. package/.bkit/core/engine/commands/harvest.ts +459 -0
  84. package/.bkit/core/engine/commands/install/check.ts +70 -0
  85. package/.bkit/core/engine/commands/install/doctor.ts +247 -0
  86. package/.bkit/core/engine/commands/install/install.ts +528 -0
  87. package/.bkit/core/engine/commands/install/uninstall.ts +972 -0
  88. package/.bkit/core/engine/commands/install/upgrade.ts +1026 -0
  89. package/.bkit/core/engine/commands/launch.ts +139 -0
  90. package/.bkit/core/engine/commands/lib.ts +494 -0
  91. package/.bkit/core/engine/commands/registry.ts +53 -0
  92. package/.bkit/core/engine/commands/setup/setup.ts +184 -0
  93. package/.bkit/core/engine/commands/telemetry.ts +32 -0
  94. package/.bkit/core/engine/commands/workflow/branches.ts +1514 -0
  95. package/.bkit/core/engine/commands/workflow/context.ts +961 -0
  96. package/.bkit/core/engine/commands/workflow/counters.ts +268 -0
  97. package/.bkit/core/engine/commands/workflow/fids.ts +243 -0
  98. package/.bkit/core/engine/commands/workflow/issues.ts +675 -0
  99. package/.bkit/core/engine/commands/workflow/ledgers.ts +575 -0
  100. package/.bkit/core/engine/commands/workflow/locks.ts +478 -0
  101. package/.bkit/core/engine/commands/workflow/prs.ts +1087 -0
  102. package/.bkit/core/engine/commands/workflow/repo.ts +220 -0
  103. package/.bkit/core/engine/commands/workflow/roadmap.ts +576 -0
  104. package/.bkit/core/engine/commands/workflow/runs.ts +2140 -0
  105. package/.bkit/core/engine/commands/workflow/runtime.ts +300 -0
  106. package/.bkit/core/engine/commands/workflow/skills.ts +118 -0
  107. package/.bkit/core/engine/commands/workflow/status.ts +455 -0
  108. package/.bkit/core/engine/commands/workflow/steps.ts +1300 -0
  109. package/.bkit/core/engine/commands/workflow/tests.ts +161 -0
  110. package/.bkit/core/engine/commands/workflow/workflows.ts +1573 -0
  111. package/.bkit/core/engine/commands/workflow/workstreams.ts +164 -0
  112. package/.bkit/core/engine/commands/workflow/worktrees.ts +534 -0
  113. package/.bkit/core/engine/install/cloud-env.ts +925 -0
  114. package/.bkit/core/engine/install/managed-block.ts +212 -0
  115. package/.bkit/core/engine/install/manifest.ts +448 -0
  116. package/.bkit/core/engine/install/modules/claude.ts +362 -0
  117. package/.bkit/core/engine/install/modules/cloud.ts +174 -0
  118. package/.bkit/core/engine/install/modules/codex.ts +219 -0
  119. package/.bkit/core/engine/install/modules/core.ts +600 -0
  120. package/.bkit/core/engine/install/modules/cursor.ts +231 -0
  121. package/.bkit/core/engine/install/modules/index.ts +242 -0
  122. package/.bkit/core/engine/install/modules/opencode.ts +573 -0
  123. package/.bkit/core/engine/install/placeholders.ts +108 -0
  124. package/.bkit/core/engine/install/template-copies.ts +119 -0
  125. package/.bkit/core/engine/install/version-file.ts +284 -0
  126. package/.bkit/core/engine/install/write.ts +467 -0
  127. package/.bkit/core/engine/ledgers/clamp-log.ts +32 -0
  128. package/.bkit/core/engine/ledgers/status.ts +213 -0
  129. package/.bkit/core/engine/ledgers/telemetry.ts +1143 -0
  130. package/.bkit/core/engine/render/hosts.ts +372 -0
  131. package/.bkit/core/engine/render/models.ts +323 -0
  132. package/.bkit/core/engine/render/parts.ts +38 -0
  133. package/.bkit/core/engine/render/trackers.ts +170 -0
  134. package/.bkit/core/engine/shared/egress.ts +345 -0
  135. package/.bkit/core/engine/shared/json.ts +16 -0
  136. package/.bkit/core/engine/shared/log-prefix.ts +9 -0
  137. package/.bkit/core/engine/shared/package-json.ts +29 -0
  138. package/.bkit/core/engine/shared/package-manager.ts +38 -0
  139. package/.bkit/core/engine/shared/package-roots.ts +163 -0
  140. package/.bkit/core/engine/shared/protected-paths.ts +164 -0
  141. package/.bkit/core/engine/shared/settings.ts +72 -0
  142. package/.bkit/core/engine/shared/timeouts.ts +20 -0
  143. package/.bkit/core/engine/tools/wording.ts +748 -0
  144. package/.bkit/core/hooks/gateguard-edit-payload.js +18 -0
  145. package/.bkit/core/hooks/gateguard-engine.js +193 -0
  146. package/.bkit/core/hooks/guardrails-shell.js +154 -0
  147. package/.bkit/core/hooks/guardrails-tiers.js +68 -0
  148. package/.bkit/core/hooks/preflight-linear.sh +73 -0
  149. package/.bkit/core/prompts/bkit-audit-generate.md +66 -0
  150. package/.bkit/core/prompts/bkit-build-challenge-1.md +79 -0
  151. package/.bkit/core/prompts/bkit-build-challenge-2.md +81 -0
  152. package/.bkit/core/prompts/bkit-build-challenge-reconcile.md +68 -0
  153. package/.bkit/core/prompts/bkit-build-challenge-remediate.md +70 -0
  154. package/.bkit/core/prompts/bkit-build-challenge-tests.md +73 -0
  155. package/.bkit/core/prompts/bkit-build-install-skills.md +67 -0
  156. package/.bkit/core/prompts/bkit-build-plan-current.md +75 -0
  157. package/.bkit/core/prompts/bkit-build-plan-execute.md +72 -0
  158. package/.bkit/core/prompts/bkit-build-plan-gaps-remediate.md +73 -0
  159. package/.bkit/core/prompts/bkit-build-plan-verify.md +88 -0
  160. package/.bkit/core/prompts/bkit-build-summary.md +93 -0
  161. package/.bkit/core/prompts/bkit-debug-abort-handover.md +90 -0
  162. package/.bkit/core/prompts/bkit-debug-failure-diagnose.md +151 -0
  163. package/.bkit/core/prompts/bkit-debug-failure-remediate.md +78 -0
  164. package/.bkit/core/prompts/bkit-debug-failure-soak.md +73 -0
  165. package/.bkit/core/prompts/bkit-debug-summary.md +95 -0
  166. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-1.md +72 -0
  167. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-2.md +72 -0
  168. package/.bkit/core/prompts/bkit-design-brainstorm-ideate-3.md +75 -0
  169. package/.bkit/core/prompts/bkit-design-generate.md +110 -0
  170. package/.bkit/core/prompts/bkit-design-organise.md +85 -0
  171. package/.bkit/core/prompts/bkit-design-review-1.md +121 -0
  172. package/.bkit/core/prompts/bkit-design-review-2.md +111 -0
  173. package/.bkit/core/prompts/bkit-design-spike.md +97 -0
  174. package/.bkit/core/prompts/bkit-design-summary.md +106 -0
  175. package/.bkit/core/prompts/bkit-design-update.md +66 -0
  176. package/.bkit/core/prompts/bkit-plan-complexity-check.md +66 -0
  177. package/.bkit/core/prompts/bkit-plan-complexity-split.md +87 -0
  178. package/.bkit/core/prompts/bkit-plan-generate.md +74 -0
  179. package/.bkit/core/prompts/bkit-plan-review-1.md +90 -0
  180. package/.bkit/core/prompts/bkit-plan-review-2.md +80 -0
  181. package/.bkit/core/prompts/bkit-plan-review-3.md +92 -0
  182. package/.bkit/core/prompts/bkit-plan-scope-check-1.md +84 -0
  183. package/.bkit/core/prompts/bkit-plan-scope-check-2.md +84 -0
  184. package/.bkit/core/prompts/bkit-plan-summary.md +106 -0
  185. package/.bkit/core/prompts/bkit-plan-update.md +68 -0
  186. package/.bkit/core/prompts/bkit-ship-conflict-resolve.md +90 -0
  187. package/.bkit/core/prompts/bkit-ship-deferred-sweep.md +94 -0
  188. package/.bkit/core/prompts/bkit-ship-summary.md +77 -0
  189. package/.bkit/core/prompts/bkit-ship-update-docs.md +71 -0
  190. package/.bkit/core/prompts/bkit-utility-compress-markdown.md +91 -0
  191. package/.bkit/core/prompts/bkit-utility-update-decisions.md +75 -0
  192. package/.bkit/core/prompts/bkit-utility-update-deferrals.md +76 -0
  193. package/.bkit/core/prompts/bkit-utility-update-documentation.md +61 -0
  194. package/.bkit/core/prompts/bkit-utility-update-failures.md +76 -0
  195. package/.bkit/core/prompts/bkit-utility-update-knowledge.md +75 -0
  196. package/.bkit/core/prompts/bkit-utility-update-roadmap.md +82 -0
  197. package/.bkit/core/workflows/bkit-auto.md +121 -0
  198. package/.bkit/core/workflows/bkit-build.md +802 -0
  199. package/.bkit/core/workflows/bkit-debug.md +642 -0
  200. package/.bkit/core/workflows/bkit-design.md +495 -0
  201. package/.bkit/core/workflows/bkit-plan.md +510 -0
  202. package/.bkit/core/workflows/bkit-ship.md +650 -0
  203. package/.bkit/shared/.bkit/.env.example +108 -0
  204. package/.bkit/shared/.claude/bkit-cloud.md +117 -0
  205. package/.bkit/shared/.claude/settings.json +88 -0
  206. package/.bkit/shared/.codex/hooks.json +26 -0
  207. package/.bkit/shared/.cursor/bkit-cloud.md +84 -0
  208. package/.bkit/shared/.cursor/hooks.json +26 -0
  209. package/.bkit/shared/.cursor/mcp.json +15 -0
  210. package/.bkit/shared/.cursor/rules/bkit-rules.mdc +12 -0
  211. package/.bkit/shared/.gitattributes +37 -0
  212. package/.bkit/shared/.mcp.json +16 -0
  213. package/.bkit/shared/.opencode/opencode.json +62 -0
  214. package/.bkit/shared/CLAUDE.md +11 -0
  215. package/.bkit/shared/LICENSE.md +22 -0
  216. package/.bkit/shared/docs/architecture.md +19 -0
  217. package/.bkit/shared/docs/data-schema.md +19 -0
  218. package/.bkit/shared/docs/deployments.md +438 -0
  219. package/.bkit/shared/docs/design.md +39 -0
  220. package/.bkit/shared/docs/noise.md +19 -0
  221. package/.bkit/shared/docs/observability.md +25 -0
  222. package/.bkit/shared/docs/security.md +42 -0
  223. package/.bkit/shared/docs/setup.md +30 -0
  224. package/.bkit/shared/docs/technology.md +18 -0
  225. package/.bkit/shared/docs/testing.md +413 -0
  226. package/.bkit/shared/gitignore +92 -0
  227. package/.bkit/templates/.claude/hooks/bkit-cloud-bootstrap.sh +192 -0
  228. package/.bkit/templates/.cursor/Dockerfile +68 -0
  229. package/.bkit/templates/.cursor/environment.json +6 -0
  230. package/.bkit/templates/.cursor/settings.json +11 -0
  231. package/.bkit/templates/.envrc +7 -0
  232. package/.bkit/templates/.github/dependabot.yml +52 -0
  233. package/.bkit/templates/.github/renovate.json5 +239 -0
  234. package/.bkit/templates/.github/workflows/bkit-ci.yml +1082 -0
  235. package/.bkit/templates/.github/workflows/bkit-cloud.yml +566 -0
  236. package/.bkit/templates/.github/workflows/bkit-renovate.yml +107 -0
  237. package/.bkit/templates/.graphifyignore +108 -0
  238. package/.bkit/templates/.husky/pre-commit +16 -0
  239. package/.bkit/templates/.husky/pre-push +91 -0
  240. package/.bkit/templates/.lintstagedrc.json +3 -0
  241. package/.bkit/templates/.prettierignore +41 -0
  242. package/.bkit/templates/.serena/project.yml +243 -0
  243. package/.bkit/templates/.vale/styles/House/Filler.yml +11 -0
  244. package/.bkit/templates/.vale/styles/House/Hedging.yml +12 -0
  245. package/.bkit/templates/.vale/styles/House/LLMSlop.yml +13 -0
  246. package/.bkit/templates/.vale/styles/House/Verbose.yml +12 -0
  247. package/.bkit/templates/.vale.ini +67 -0
  248. package/.bkit/templates/LICENSE.md +22 -0
  249. package/.bkit/templates/context/bkit-cloudrun.md +84 -0
  250. package/.bkit/templates/context/bkit-expo.md +186 -0
  251. package/.bkit/templates/context/bkit-github.md +79 -0
  252. package/.bkit/templates/context/bkit-inngest.md +45 -0
  253. package/.bkit/templates/context/bkit-maestro.md +76 -0
  254. package/.bkit/templates/context/bkit-playwright.md +62 -0
  255. package/.bkit/templates/context/bkit-resend.md +36 -0
  256. package/.bkit/templates/context/bkit-sentry.md +65 -0
  257. package/.bkit/templates/context/bkit-serena.md +33 -0
  258. package/.bkit/templates/context/bkit-stripe.md +36 -0
  259. package/.bkit/templates/context/bkit-supabase.md +59 -0
  260. package/.bkit/templates/context/bkit-tavily.md +49 -0
  261. package/.bkit/templates/context/bkit-vercel.md +64 -0
  262. package/.bkit/templates/docs/capabilities.md +72 -0
  263. package/.bkit/templates/scripts/ci/accepted-divergences.json +21 -0
  264. package/.bkit/templates/scripts/ci/check-accepted-divergences.mjs +152 -0
  265. package/.bkit/templates/scripts/ci/check-accepted-divergences.test.mjs +130 -0
  266. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.mjs +98 -0
  267. package/.bkit/templates/scripts/ci/lanes/resolve-push-base.test.mjs +86 -0
  268. package/.bkit/templates/scripts/graphify/bkit-graph-drift-rules.json +23 -0
  269. package/.bkit/templates/scripts/graphify/bkit-graph-drift.py +208 -0
  270. package/.bkit/templates/scripts/graphify/bkit-graph-eager-rules.json +35 -0
  271. package/.bkit/templates/scripts/graphify/bkit-graph-eager.py +236 -0
  272. package/.bkit/templates/scripts/graphify/bkit-graph-external-rules.json +17 -0
  273. package/.bkit/templates/scripts/graphify/bkit-graph-imports.py +290 -0
  274. package/.bkit/templates/scripts/graphify/bkit-graph-pre-push.sh +19 -0
  275. package/.bkit/templates/scripts/graphify/bkit-graph-repair.py +120 -0
  276. package/.bkit/templates/scripts/graphify/bkit-graph-surface.py +232 -0
  277. package/.bkit/templates/scripts/graphify/bkit-graphify-graphml.py +36 -0
  278. package/.bkit/templates/scripts/graphify/bkit-graphify-rollup.py +927 -0
  279. package/.bkit/templates/scripts/graphify/bkit-graphify.sh +351 -0
  280. package/.bkit/templates/scripts/launchd/ai.bkit.launchd.plist +26 -0
  281. package/.bkit/templates/scripts/launchd/bkit-launchd-env.sh +53 -0
  282. package/.bkit/templates/scripts/launchd/launchd.env.example +13 -0
  283. package/.bkit/templates/scripts/prettier/bkit-insert-ignore.mjs +275 -0
  284. package/.bkit/templates/scripts/secrets/bkit-secrets.config.mjs +66 -0
  285. package/.bkit/templates/scripts/secrets/bkit-secrets.mjs +785 -0
  286. package/.bkit/templates/scripts/serena/bkit-serena-mcp.sh +30 -0
  287. package/.bkit/templates/scripts/serena/bkit-serena.mcp.json +9 -0
  288. package/.bkit/templates/scripts/slop/bkit-slop-type-suppression.mjs +286 -0
  289. package/.bkit/templates/slop-scan.config.json +120 -0
  290. package/CHANGELOG.md +1486 -0
  291. package/LICENSE.md +161 -0
  292. package/README.md +185 -2
  293. package/dist/checks/after/auth.js +232 -0
  294. package/dist/checks/after/ci-yml.js +718 -0
  295. package/dist/checks/after/github.js +400 -0
  296. package/dist/checks/after/index.js +447 -0
  297. package/dist/checks/after/managed.js +187 -0
  298. package/dist/checks/after/tools.js +351 -0
  299. package/dist/checks/after/vercel.js +102 -0
  300. package/dist/checks/before/context-fetch.js +426 -0
  301. package/dist/checks/before/env.js +173 -0
  302. package/dist/checks/before/files.js +185 -0
  303. package/dist/checks/before/index.js +162 -0
  304. package/dist/checks/before/mcp.js +111 -0
  305. package/dist/checks/before/repo.js +71 -0
  306. package/dist/checks/before/version.js +60 -0
  307. package/dist/checks/status-holes.js +393 -0
  308. package/dist/cli.js +692 -0
  309. package/dist/commands/analysis.js +325 -0
  310. package/dist/commands/ci/ci.js +438 -0
  311. package/dist/commands/comply.js +310 -0
  312. package/dist/commands/harvest.js +354 -0
  313. package/dist/commands/install/check.js +61 -0
  314. package/dist/commands/install/doctor.js +207 -0
  315. package/dist/commands/install/install.js +461 -0
  316. package/dist/commands/install/uninstall.js +815 -0
  317. package/dist/commands/install/upgrade.js +771 -0
  318. package/dist/commands/launch.js +118 -0
  319. package/dist/commands/lib.js +362 -0
  320. package/dist/commands/registry.js +50 -0
  321. package/dist/commands/setup/setup.js +158 -0
  322. package/dist/commands/telemetry.js +29 -0
  323. package/dist/commands/workflow/branches.js +1265 -0
  324. package/dist/commands/workflow/context.js +846 -0
  325. package/dist/commands/workflow/counters.js +227 -0
  326. package/dist/commands/workflow/fids.js +224 -0
  327. package/dist/commands/workflow/issues.js +585 -0
  328. package/dist/commands/workflow/ledgers.js +472 -0
  329. package/dist/commands/workflow/locks.js +364 -0
  330. package/dist/commands/workflow/prs.js +904 -0
  331. package/dist/commands/workflow/repo.js +199 -0
  332. package/dist/commands/workflow/roadmap.js +495 -0
  333. package/dist/commands/workflow/runs.js +1717 -0
  334. package/dist/commands/workflow/runtime.js +257 -0
  335. package/dist/commands/workflow/skills.js +110 -0
  336. package/dist/commands/workflow/status.js +392 -0
  337. package/dist/commands/workflow/steps.js +1093 -0
  338. package/dist/commands/workflow/tests.js +144 -0
  339. package/dist/commands/workflow/workflows.js +1342 -0
  340. package/dist/commands/workflow/workstreams.js +141 -0
  341. package/dist/commands/workflow/worktrees.js +473 -0
  342. package/dist/install/cloud-env.js +819 -0
  343. package/dist/install/managed-block.js +182 -0
  344. package/dist/install/manifest.js +376 -0
  345. package/dist/install/modules/claude.js +288 -0
  346. package/dist/install/modules/cloud.js +152 -0
  347. package/dist/install/modules/codex.js +193 -0
  348. package/dist/install/modules/core.js +511 -0
  349. package/dist/install/modules/cursor.js +186 -0
  350. package/dist/install/modules/index.js +152 -0
  351. package/dist/install/modules/opencode.js +504 -0
  352. package/dist/install/placeholders.js +87 -0
  353. package/dist/install/template-copies.js +106 -0
  354. package/dist/install/version-file.js +204 -0
  355. package/dist/install/write.js +342 -0
  356. package/dist/ledgers/clamp-log.js +27 -0
  357. package/dist/ledgers/status.js +156 -0
  358. package/dist/ledgers/telemetry.js +637 -0
  359. package/dist/render/hosts.js +339 -0
  360. package/dist/render/models.js +288 -0
  361. package/dist/render/parts.js +33 -0
  362. package/dist/render/trackers.js +135 -0
  363. package/dist/shared/egress.js +299 -0
  364. package/dist/shared/json.js +16 -0
  365. package/dist/shared/log-prefix.js +7 -0
  366. package/dist/shared/package-json.js +22 -0
  367. package/dist/shared/package-manager.js +32 -0
  368. package/dist/shared/package-roots.js +145 -0
  369. package/dist/shared/protected-paths.js +153 -0
  370. package/dist/shared/settings.js +44 -0
  371. package/dist/shared/timeouts.js +19 -0
  372. package/dist/tools/wording.js +680 -0
  373. package/package.json +101 -4
@@ -0,0 +1,785 @@
1
+ #!/usr/bin/env node
2
+ // Example. Copy into the repo and own it.
3
+ // bkit install does not write this file and does not overwrite a copy.
4
+ // bkit-secrets.mjs — one source for every secret, every store kept in step. See .bkit/templates.md § Secrets sync.
5
+ //
6
+ // node scripts/secrets/bkit-secrets.mjs sync --dry-run what would change, nothing written
7
+ // node scripts/secrets/bkit-secrets.mjs sync write changed values, delete names not listed
8
+ // node scripts/secrets/bkit-secrets.mjs drift read-only: does every store hold the source value?
9
+ // node scripts/secrets/bkit-secrets.mjs check [file] local only: env files vs example, copy inventory
10
+ // --allow-missing a missing key warns; only an empty one fails (subset files, CI)
11
+ // node scripts/secrets/bkit-secrets.mjs list [--store s] names each store receives, for repo tooling
12
+ // --store <name> narrow sync / drift / list to one store; always both environments
13
+ //
14
+ // Identical in every repo: bkit-secrets.config.mjs beside it holds the repo's scope.
15
+ // Needs Node >= 20 plus the CLI of each store it uses (gh, eas, gcloud); Vercel and Supabase use their REST APIs.
16
+ // Values are compared as SHA-256 fingerprints and never printed.
17
+ // Exit: 0 clean · 1 a store failed or could not be read · 2 drift, or `check` found a missing key.
18
+
19
+ import { spawnSync } from "node:child_process";
20
+ import { createHash } from "node:crypto";
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import { fileURLToPath, pathToFileURL } from "node:url";
24
+
25
+ const VERCEL_API = "https://api.vercel.com";
26
+ const SUPABASE_API = "https://api.supabase.com";
27
+ // Seconds a remote "last updated" may trail the recorded push before it counts as an outside write.
28
+ const CLOCK_SLACK = 120;
29
+ const STATE_FILE = "bkit-secrets-state.json";
30
+ const DRIFT = new Set(["missing", "differs", "not-pushed", "changed-elsewhere", "extra"]);
31
+
32
+ class Skip extends Error {}
33
+
34
+ const sha = (value) => createHash("sha256").update(value, "utf8").digest("hex");
35
+ const short = (fp) => fp.slice(0, 12);
36
+ const toArray = (v) => (v === undefined ? [] : Array.isArray(v) ? v : [v]);
37
+
38
+ // KEY=value lines, first occurrence wins, one pair of surrounding quotes stripped. No escapes, no inline comments.
39
+ export function parseEnv(text) {
40
+ const out = new Map();
41
+ for (const line of text.split(/\r?\n/)) {
42
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
43
+ if (!m || out.has(m[1])) continue;
44
+ out.set(m[1], m[2].replace(/^"(.*)"$/s, "$1").replace(/^'(.*)'$/s, "$1"));
45
+ }
46
+ return out;
47
+ }
48
+
49
+ function readEnvFile(root, rel) {
50
+ const p = path.resolve(root, rel);
51
+ return fs.existsSync(p) ? parseEnv(fs.readFileSync(p, "utf8")) : null;
52
+ }
53
+
54
+ function which(cmd) {
55
+ return (process.env.PATH ?? "")
56
+ .split(path.delimiter)
57
+ .some((dir) => dir && fs.existsSync(path.join(dir, cmd)));
58
+ }
59
+
60
+ function run(cmd, args, { input, env, cwd } = {}) {
61
+ const r = spawnSync(cmd, args, {
62
+ input,
63
+ env: env ?? process.env,
64
+ cwd,
65
+ encoding: "utf8",
66
+ maxBuffer: 64 << 20,
67
+ });
68
+ if (r.error) throw new Error(`${cmd}: ${r.error.message}`);
69
+ if (r.status !== 0) {
70
+ // CLIs lead with the cause (e.g. gcloud's "ERROR: … Please run: gcloud auth login"); keep the head.
71
+ const head = (r.stderr || r.stdout || "")
72
+ .trim()
73
+ .split("\n")
74
+ .filter((l) => l.trim())
75
+ .slice(0, 3);
76
+ throw new Error(
77
+ `${cmd} ${args.slice(0, 2).join(" ")} failed (exit ${r.status}): ${head.join(" | ")}`,
78
+ );
79
+ }
80
+ return r.stdout;
81
+ }
82
+
83
+ async function api(base, token, method, route, body) {
84
+ const res = await fetch(base + route, {
85
+ method,
86
+ headers: {
87
+ Authorization: `Bearer ${token}`,
88
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
89
+ },
90
+ body: body === undefined ? undefined : JSON.stringify(body),
91
+ });
92
+ const text = await res.text();
93
+ if (!res.ok)
94
+ throw new Error(`${method} ${route.split("?")[0]} → HTTP ${res.status}: ${text.slice(0, 200)}`);
95
+ return text ? JSON.parse(text) : null;
96
+ }
97
+
98
+ // ── Stores ────────────────────────────────────────────────────────────────────
99
+ // open(ctx) → { target, list(wanted), write(entries, onWritten), remove(names) }, or throws Skip.
100
+ // list → Map NAME → { readable, fp?, updated? }: readable=false is a write-only store (parity from
101
+ // the state file); readable with no fp means that value could not be read.
102
+
103
+ const STORES = {
104
+ github: {
105
+ label: "GitHub Actions secrets",
106
+ perEnv: false,
107
+ async open() {
108
+ if (!which("gh")) throw new Skip("gh CLI missing");
109
+ // A fine-grained PAT in GH_TOKEN 403s on /actions/secrets/public-key; use gh's stored login.
110
+ const env = { ...process.env };
111
+ delete env.GH_TOKEN;
112
+ const gh = (args, input) => run("gh", args, { env, input });
113
+ const repo = gh(["repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"]).trim();
114
+ return {
115
+ target: repo,
116
+ list() {
117
+ const out = gh([
118
+ "api",
119
+ "--paginate",
120
+ `/repos/${repo}/actions/secrets`,
121
+ "--jq",
122
+ '.secrets[] | "\\(.name)\\t\\(.updated_at)"',
123
+ ]);
124
+ const live = new Map();
125
+ for (const line of out.split("\n").filter(Boolean)) {
126
+ const [name, ts] = line.split("\t");
127
+ live.set(name, { readable: false, updated: Date.parse(ts) / 1000 });
128
+ }
129
+ return live;
130
+ },
131
+ write(entries, onWritten) {
132
+ for (const e of entries) {
133
+ gh(["secret", "set", e.name, "--repo", repo], e.value);
134
+ onWritten(e.name);
135
+ }
136
+ },
137
+ remove(names) {
138
+ for (const n of names) gh(["secret", "remove", n, "--repo", repo]);
139
+ },
140
+ };
141
+ },
142
+ },
143
+
144
+ vercel: {
145
+ label: "Vercel env vars",
146
+ perEnv: true,
147
+ async open({ env, value, store, root }) {
148
+ // Env files before the CLI login: the declared source, and a CLI login can expire unnoticed.
149
+ const token = process.env.VERCEL_TOKEN || value("VERCEL_TOKEN") || vercelCliToken();
150
+ const linked = readJson(path.resolve(root, store.project ?? ".vercel/project.json"));
151
+ const team = linked?.orgId || value("VERCEL_ORG_ID");
152
+ const project = linked?.projectId || value("VERCEL_PROJECT_ID");
153
+ if (!token || !team || !project) {
154
+ throw new Error(
155
+ "need VERCEL_TOKEN (or `vercel login`) and .vercel/project.json, or VERCEL_ORG_ID + VERCEL_PROJECT_ID",
156
+ );
157
+ }
158
+ const q = `teamId=${encodeURIComponent(team)}`;
159
+ const call = (method, route, body) => api(VERCEL_API, token, method, route, body);
160
+ // Branch-scoped preview vars (gitBranch set) are left alone.
161
+ let entries = [];
162
+ const dropTarget = (e) =>
163
+ e.target.length > 1
164
+ ? call("PATCH", `/v9/projects/${project}/env/${e.id}?${q}`, {
165
+ target: e.target.filter((t) => t !== env),
166
+ })
167
+ : call("DELETE", `/v9/projects/${project}/env/${e.id}?${q}`);
168
+ return {
169
+ target: `${project}:${env}`,
170
+ async list(wanted) {
171
+ // The list endpoint returns encrypted values still encrypted (decrypt=true is ignored);
172
+ // the per-variable endpoint decrypts. Read back only the values being compared.
173
+ const data = await call("GET", `/v10/projects/${project}/env?${q}`);
174
+ entries = (data.envs ?? data).filter(
175
+ (e) => !e.gitBranch && (e.target ?? []).includes(env),
176
+ );
177
+ const live = new Map();
178
+ for (const e of entries) {
179
+ const updated = (e.updatedAt ?? 0) / 1000;
180
+ // sensitive = write-only.
181
+ if (e.type === "sensitive" || !wanted.has(e.key)) {
182
+ live.set(e.key, { readable: e.type !== "sensitive", updated });
183
+ continue;
184
+ }
185
+ const one =
186
+ e.type === "plain"
187
+ ? e
188
+ : await call("GET", `/v1/projects/${project}/env/${e.id}?${q}`);
189
+ // Trust a value only when the API says it decrypted it; anything else is unreadable, never "differs".
190
+ const readable = one.type === "plain" || one.decrypted === true;
191
+ live.set(
192
+ e.key,
193
+ readable ? { readable, fp: sha(one.value ?? ""), updated } : { readable, updated },
194
+ );
195
+ }
196
+ return live;
197
+ },
198
+ async write(list, onWritten) {
199
+ for (const e of list) {
200
+ // An entry shared with other environments is split first, so this write touches only `env`.
201
+ const shared = entries.find((x) => x.key === e.name && x.target.length > 1);
202
+ if (shared) await dropTarget(shared);
203
+ // type=encrypted: `vercel env add` makes type=sensitive, which `vercel env pull` returns empty.
204
+ await call("POST", `/v10/projects/${project}/env?${q}&upsert=true`, {
205
+ key: e.name,
206
+ value: e.value,
207
+ type: "encrypted",
208
+ target: [env],
209
+ });
210
+ onWritten(e.name);
211
+ }
212
+ },
213
+ async remove(names) {
214
+ for (const e of entries.filter((x) => names.includes(x.key))) await dropTarget(e);
215
+ },
216
+ };
217
+ },
218
+ },
219
+
220
+ supabase: {
221
+ label: "Supabase Edge Function secrets",
222
+ perEnv: true,
223
+ // The platform's reserved namespace, auto-populated into every function.
224
+ protects: (name) => name.startsWith("SUPABASE_"),
225
+ async open({ value, store }) {
226
+ const ref = value(store.ref ?? "SUPABASE_PROJECT_ID");
227
+ const token = process.env.SUPABASE_ACCESS_TOKEN || value("SUPABASE_ACCESS_TOKEN");
228
+ if (!ref || !token)
229
+ throw new Error(
230
+ `need ${store.ref ?? "SUPABASE_PROJECT_ID"} and SUPABASE_ACCESS_TOKEN in the env files`,
231
+ );
232
+ const call = (method, body) =>
233
+ api(SUPABASE_API, token, method, `/v1/projects/${ref}/secrets`, body);
234
+ return {
235
+ target: ref,
236
+ async list() {
237
+ // The listed value is a server-side digest with no documented recipe: write-only.
238
+ const live = new Map();
239
+ for (const s of await call("GET")) {
240
+ live.set(s.name, {
241
+ readable: false,
242
+ updated: s.updated_at ? Date.parse(s.updated_at) / 1000 : undefined,
243
+ });
244
+ }
245
+ return live;
246
+ },
247
+ async write(list, onWritten) {
248
+ for (let i = 0; i < list.length; i += 100) {
249
+ const chunk = list.slice(i, i + 100);
250
+ await call(
251
+ "POST",
252
+ chunk.map((e) => ({ name: e.name, value: e.value })),
253
+ );
254
+ chunk.forEach((e) => onWritten(e.name));
255
+ }
256
+ },
257
+ async remove(names) {
258
+ if (names.length) await call("DELETE", names);
259
+ },
260
+ };
261
+ },
262
+ },
263
+
264
+ eas: {
265
+ label: "EAS environment variables",
266
+ perEnv: true,
267
+ async open({ env, value, store, root }) {
268
+ const dir = path.resolve(root, store.dir ?? "apps/mobile");
269
+ if (!which("eas")) throw new Skip("eas CLI missing — npm i -g eas-cli");
270
+ if (
271
+ !/"projectId"/.test(
272
+ fs.existsSync(path.join(dir, "app.json"))
273
+ ? fs.readFileSync(path.join(dir, "app.json"), "utf8")
274
+ : "",
275
+ )
276
+ ) {
277
+ throw new Skip(
278
+ `${path.relative(root, dir)} is not EAS-linked (no extra.eas.projectId) — run eas init`,
279
+ );
280
+ }
281
+ const token = process.env.EXPO_TOKEN || value("EXPO_TOKEN");
282
+ if (!token) throw new Error("EXPO_TOKEN not found in the env files");
283
+ const eas = (args) =>
284
+ run("eas", args, { cwd: dir, env: { ...process.env, EXPO_TOKEN: token } });
285
+ const visibility = (option) => option ?? store.visibility ?? "sensitive";
286
+ let secretNames = new Set();
287
+ return {
288
+ target: `eas:${env}`,
289
+ setOptions(options) {
290
+ secretNames = new Set(
291
+ [...options].filter(([, o]) => visibility(o) === "secret").map(([n]) => n),
292
+ );
293
+ },
294
+ list() {
295
+ // `--format short` = NAME=value lines; `secret` visibility is masked, so treated as write-only.
296
+ const live = new Map();
297
+ for (const line of eas([
298
+ "env:list",
299
+ env,
300
+ "--format",
301
+ "short",
302
+ "--include-sensitive",
303
+ ]).split("\n")) {
304
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/.exec(line);
305
+ if (!m) continue;
306
+ const readable = !secretNames.has(m[1]);
307
+ live.set(m[1], { readable, fp: readable ? sha(m[2]) : undefined });
308
+ }
309
+ return live;
310
+ },
311
+ write(list, onWritten) {
312
+ for (const e of list) {
313
+ eas([
314
+ "env:set",
315
+ "--name",
316
+ e.name,
317
+ "--value",
318
+ e.value,
319
+ "--visibility",
320
+ visibility(e.option),
321
+ "--environment",
322
+ env,
323
+ "--scope",
324
+ "project",
325
+ "--type",
326
+ "string",
327
+ "--json",
328
+ ]);
329
+ onWritten(e.name);
330
+ }
331
+ },
332
+ remove(names) {
333
+ for (const n of names)
334
+ eas([
335
+ "env:delete",
336
+ "--variable-name",
337
+ n,
338
+ "--variable-environment",
339
+ env,
340
+ "--scope",
341
+ "project",
342
+ "--non-interactive",
343
+ ]);
344
+ },
345
+ };
346
+ },
347
+ },
348
+
349
+ gcp: {
350
+ label: "GCP Secret Manager",
351
+ perEnv: true,
352
+ async open({ value, store }) {
353
+ if (!which("gcloud")) throw new Skip("gcloud CLI missing");
354
+ const project = value(store.project ?? "GCP_PROJECT_ID");
355
+ if (!project)
356
+ throw new Error(`${store.project ?? "GCP_PROJECT_ID"} not found in the env files`);
357
+ const gcloud = (args, input) => run("gcloud", [...args, `--project=${project}`], { input });
358
+ let names = new Set();
359
+ return {
360
+ target: project,
361
+ list(wanted) {
362
+ names = new Set(
363
+ gcloud(["secrets", "list", "--format=value(name)"]).split("\n").filter(Boolean),
364
+ );
365
+ const live = new Map();
366
+ for (const n of names) {
367
+ if (!wanted.has(n)) {
368
+ live.set(n, { readable: true });
369
+ continue;
370
+ }
371
+ try {
372
+ live.set(n, {
373
+ readable: true,
374
+ fp: sha(gcloud(["secrets", "versions", "access", "latest", `--secret=${n}`])),
375
+ });
376
+ } catch (err) {
377
+ live.set(n, { readable: true, error: err.message });
378
+ }
379
+ }
380
+ return live;
381
+ },
382
+ write(list, onWritten) {
383
+ for (const e of list) {
384
+ if (!names.has(e.name))
385
+ gcloud(["secrets", "create", e.name, "--replication-policy=automatic"]);
386
+ gcloud(["secrets", "versions", "add", e.name, "--data-file=-"], e.value);
387
+ onWritten(e.name);
388
+ }
389
+ },
390
+ remove(list) {
391
+ for (const n of list) gcloud(["secrets", "delete", n, "--quiet"]);
392
+ },
393
+ };
394
+ },
395
+ },
396
+ };
397
+
398
+ function readJson(p) {
399
+ return fs.existsSync(p) ? JSON.parse(fs.readFileSync(p, "utf8")) : null;
400
+ }
401
+
402
+ function vercelCliToken() {
403
+ const home = process.env.HOME ?? "";
404
+ for (const p of [
405
+ path.join(home, "Library/Application Support/com.vercel.cli/auth.json"),
406
+ path.join(
407
+ process.env.XDG_CONFIG_HOME ?? path.join(home, ".config"),
408
+ "com.vercel.cli/auth.json",
409
+ ),
410
+ ]) {
411
+ const token = readJson(p)?.token;
412
+ if (token) return token;
413
+ }
414
+ return "";
415
+ }
416
+
417
+ // ── Config ────────────────────────────────────────────────────────────────────
418
+
419
+ const CONFIG_KEYS = new Set(["sources", "stores", "protected", "optional", "secrets"]);
420
+ const SECRET_KEYS = new Set(["to", "from", "derive", "manual"]);
421
+
422
+ // Validated config for repo tooling that needs the same scope (e.g. "which keys reach EAS"):
423
+ // const cfg = await loadConfig("scripts/secrets"); secretsFor(cfg, "eas")
424
+ export async function loadConfig(dir) {
425
+ const file = path.resolve(dir, "bkit-secrets.config.mjs");
426
+ const cfg = (await import(`${pathToFileURL(file).href}?t=${Date.now()}`)).default;
427
+ for (const k of Object.keys(cfg))
428
+ if (!CONFIG_KEYS.has(k)) throw new Error(`bkit-secrets.config.mjs: unknown key "${k}"`);
429
+ if (!cfg.sources?.preview)
430
+ throw new Error("bkit-secrets.config.mjs: sources.preview is required");
431
+ const stores = Object.entries(cfg.stores ?? {}).map(([name, opts]) => {
432
+ const type = opts.type ?? name;
433
+ if (!STORES[type])
434
+ throw new Error(
435
+ `bkit-secrets.config.mjs: store "${name}" has unknown type "${type}" (known: ${Object.keys(STORES).join(", ")})`,
436
+ );
437
+ return { name, opts, adapter: STORES[type] };
438
+ });
439
+ const secrets = Object.entries(cfg.secrets ?? {}).map(([name, spec]) => {
440
+ const s = typeof spec === "string" || Array.isArray(spec) ? { to: spec } : spec;
441
+ for (const k of Object.keys(s))
442
+ if (!SECRET_KEYS.has(k))
443
+ throw new Error(`bkit-secrets.config.mjs: ${name}: unknown key "${k}"`);
444
+ const to = toArray(s.to).map((t) => {
445
+ const [store, option] = t.split(":");
446
+ if (!stores.some((x) => x.name === store))
447
+ throw new Error(`bkit-secrets.config.mjs: ${name}: unknown store "${store}"`);
448
+ return { store, option };
449
+ });
450
+ return { name, from: s.from ?? name, derive: s.derive, to, manual: toArray(s.manual) };
451
+ });
452
+ return {
453
+ sources: cfg.sources,
454
+ stores,
455
+ secrets,
456
+ protected: new Set(cfg.protected ?? []),
457
+ optional: new Set(cfg.optional ?? []),
458
+ };
459
+ }
460
+
461
+ // Rows routed to one store: [{ name, from, derive, option }], option = the row's "store:option" suffix.
462
+ export function secretsFor(cfg, storeName) {
463
+ return cfg.secrets.flatMap((s) =>
464
+ s.to
465
+ .filter((t) => t.store === storeName)
466
+ .map((t) => ({ name: s.name, from: s.from, derive: s.derive, option: t.option })),
467
+ );
468
+ }
469
+
470
+ function sourcesFor(root, cfg) {
471
+ const overlays = toArray(cfg.sources.overlays).map((f) => readEnvFile(root, f) ?? new Map());
472
+ const files = { preview: readEnvFile(root, cfg.sources.preview) };
473
+ if (cfg.sources.production) files.production = readEnvFile(root, cfg.sources.production);
474
+ const value = (key, env) => {
475
+ for (const o of overlays) if (o.get(key)) return o.get(key);
476
+ return files[env === "repo" ? "preview" : env]?.get(key) ?? "";
477
+ };
478
+ const resolve = (secret, env) =>
479
+ secret.derive === undefined
480
+ ? value(secret.from, env)
481
+ : (() => {
482
+ let empty = false;
483
+ const out = secret.derive.replace(
484
+ /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,
485
+ (_, k) => value(k, env) || ((empty = true), ""),
486
+ );
487
+ return empty ? "" : out;
488
+ })();
489
+ return { files, value, resolve };
490
+ }
491
+
492
+ // ── Engine ────────────────────────────────────────────────────────────────────
493
+
494
+ function compare(fp, live, rec) {
495
+ if (!live) return ["missing", "set in source, absent remotely"];
496
+ if (live.readable) {
497
+ if (live.fp === undefined)
498
+ return [
499
+ "unverified",
500
+ `remote value could not be read${live.error ? ` (${live.error})` : ""}`,
501
+ ];
502
+ return live.fp === fp
503
+ ? ["same", ""]
504
+ : ["differs", `remote ${short(live.fp)} vs source ${short(fp)}`];
505
+ }
506
+ if (!rec) return ["unverified", "write-only store, no recorded push"];
507
+ if (rec.fp !== fp) return ["not-pushed", "source changed since the last push"];
508
+ if (live.updated && live.updated > rec.at + CLOCK_SLACK)
509
+ return ["changed-elsewhere", "remote updated after the last push"];
510
+ return ["same", "matches last push"];
511
+ }
512
+
513
+ async function runTarget({ mode, store, env, cfg, src, state, root, log }) {
514
+ const { adapter, name: storeName, opts } = store;
515
+ const isProtected = (n) =>
516
+ cfg.protected.has(n) || toArray(opts.protect).includes(n) || Boolean(adapter.protects?.(n));
517
+ const scoped = cfg.secrets.filter((s) => s.to.some((t) => t.store === storeName));
518
+ const value = (k) => src.value(k, env);
519
+ let handle;
520
+ try {
521
+ handle = await adapter.open({ env, value, store: opts, root });
522
+ } catch (err) {
523
+ if (err instanceof Skip) {
524
+ log(
525
+ `── ${adapter.label}${adapter.perEnv ? ` (${env})` : ""} ──\n ⚠️ Skipped — ${err.message}\n`,
526
+ );
527
+ return "skipped";
528
+ }
529
+ throw err;
530
+ }
531
+ log(`── ${adapter.label} → ${handle.target}${adapter.perEnv ? ` (${env})` : ""} ──`);
532
+
533
+ const desired = [];
534
+ for (const s of scoped) {
535
+ const option = s.to.find((t) => t.store === storeName).option;
536
+ if (isProtected(s.name)) {
537
+ log(` ⚠️ ${s.name} — listed but protected here; never written`);
538
+ continue;
539
+ }
540
+ const v = src.resolve(s, env);
541
+ if (!v) {
542
+ log(
543
+ ` ⚠️ ${s.name} — empty in source; ${mode === "drift" ? "sync deletes it here" : "deleted here if present"}`,
544
+ );
545
+ continue;
546
+ }
547
+ desired.push({ name: s.name, value: v, fp: sha(v), option });
548
+ }
549
+ handle.setOptions?.(new Map(desired.map((d) => [d.name, d.option])));
550
+ const live = await handle.list(new Set(desired.map((d) => d.name)));
551
+ const key = (n) => `${storeName}|${handle.target}|${n}`;
552
+
553
+ const rows = desired.map((d) => [d, ...compare(d.fp, live.get(d.name), state[key(d.name)])]);
554
+ const extras = [...live.keys()]
555
+ .filter((n) => !isProtected(n) && !desired.some((d) => d.name === n))
556
+ .sort();
557
+
558
+ if (mode === "drift") {
559
+ let drifted = 0;
560
+ for (const [d, status, note] of rows) {
561
+ if (status === "same") log(` ✅ ${d.name}${note ? ` — ${note}` : ""}`);
562
+ else if (status === "unverified") log(` ❔ ${d.name} — ${note}`);
563
+ else log(` ❌ ${d.name} — ${status}: ${note}`);
564
+ if (DRIFT.has(status)) drifted++;
565
+ }
566
+ for (const n of extras) log(` ❌ ${n} — extra: remote only, sync deletes it`);
567
+ drifted += extras.length;
568
+ log("");
569
+ return drifted ? "drift" : "ok";
570
+ }
571
+
572
+ const dry = mode === "dry-run";
573
+ const writes = rows.filter(([, status]) => status !== "same");
574
+ for (const [d, status, note] of rows) {
575
+ if (status === "same") log(` ✅ ${d.name} — unchanged`);
576
+ else
577
+ log(
578
+ ` ⬆️ ${d.name} — ${dry ? "would write" : "write"} (${status}${note ? `: ${note}` : ""})`,
579
+ );
580
+ }
581
+ // Nothing resolved usually means a broken env file, not "delete everything".
582
+ const deletes = desired.length === 0 && scoped.length > 0 ? [] : extras;
583
+ if (deletes !== extras && extras.length)
584
+ log(` ⚠️ No listed key resolved to a value — deletes skipped`);
585
+ for (const n of deletes)
586
+ log(
587
+ ` 🗑️ ${n} — ${dry ? "would delete" : "delete"} (not listed for this store, or empty in source)`,
588
+ );
589
+ if (dry) {
590
+ log("");
591
+ return "ok";
592
+ }
593
+ const at = Math.floor(Date.now() / 1000);
594
+ try {
595
+ await handle.write(
596
+ writes.map(([d]) => d),
597
+ (n) => (state[key(n)] = { fp: desired.find((d) => d.name === n).fp, at }),
598
+ );
599
+ } catch (err) {
600
+ log(` ❌ write failed — deletes skipped: ${err.message}\n`);
601
+ return "failed";
602
+ }
603
+ await handle.remove(deletes);
604
+ for (const n of deletes) delete state[key(n)];
605
+ log("");
606
+ return "ok";
607
+ }
608
+
609
+ function check({ cfg, src, root, file, allowMissing, log }) {
610
+ let problems = 0;
611
+ log("── Sources ──");
612
+ for (const [label, rel] of [
613
+ ...toArray(cfg.sources.overlays).map((f) => ["overlay", f]),
614
+ ["preview", cfg.sources.preview],
615
+ ...(cfg.sources.production ? [["production", cfg.sources.production]] : []),
616
+ ]) {
617
+ const env = readEnvFile(root, rel);
618
+ log(env ? ` ✅ ${label}: ${rel} (${env.size} keys)` : ` ⚠️ ${label}: ${rel} not found`);
619
+ }
620
+
621
+ const exampleRel =
622
+ cfg.sources.example ?? path.join(path.dirname(cfg.sources.preview), ".env.example");
623
+ const example = readEnvFile(root, exampleRel);
624
+ const targets = file
625
+ ? [file]
626
+ : [...new Set([cfg.sources.preview, cfg.sources.production].filter(Boolean))];
627
+ if (example) {
628
+ for (const rel of targets) {
629
+ const env = readEnvFile(root, rel);
630
+ if (!env && file) {
631
+ log(`\n ❌ ${rel} not found`);
632
+ problems++;
633
+ }
634
+ if (!env || rel === exampleRel) continue;
635
+ log(`\n── ${rel} vs ${exampleRel} ──`);
636
+ let flagged = 0;
637
+ for (const k of example.keys()) {
638
+ if (cfg.optional.has(k) || cfg.protected.has(k)) continue;
639
+ if (!env.has(k)) {
640
+ // --allow-missing: a file holding a subset by design (e.g. CI's pulled env) fails on empty only.
641
+ log(` ${allowMissing ? "⚠️ " : "❌"} ${k} — missing`);
642
+ if (allowMissing) continue;
643
+ } else if (!env.get(k)) log(` ❌ ${k} — empty`);
644
+ else continue;
645
+ flagged++;
646
+ }
647
+ log(flagged ? ` ${flagged} key(s) need a value` : " ✅ every required key set");
648
+ problems += flagged;
649
+ }
650
+ }
651
+
652
+ log("\n── Copies of each secret ──");
653
+ for (const s of cfg.secrets) {
654
+ const envs = src.files.production ? ["preview", "production"] : ["preview"];
655
+ const empty = envs.filter((e) => !src.resolve(s, e));
656
+ const where = [
657
+ ...s.to.map((t) => t.store + (t.option ? `:${t.option}` : "")),
658
+ ...s.manual.map((m) => `by hand: ${m}`),
659
+ ];
660
+ log(
661
+ ` ${empty.length ? "⚠️ " : "✅"} ${s.name} → ${where.join(" · ") || "no store"}${empty.length ? ` (empty in ${empty.join(", ")})` : ""}`,
662
+ );
663
+ }
664
+ return problems ? 2 : 0;
665
+ }
666
+
667
+ export async function main(
668
+ argv,
669
+ {
670
+ root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."),
671
+ log = console.log,
672
+ } = {},
673
+ ) {
674
+ const args = [...argv];
675
+ const take = (flag) => {
676
+ const i = args.indexOf(flag);
677
+ return i === -1 ? undefined : args.splice(i, 2)[1];
678
+ };
679
+ const onlyStore = take("--store");
680
+ const dry = args.includes("--dry-run");
681
+ const allowMissing = args.includes("--allow-missing");
682
+ const [cmd = "help", file] = args.filter((a) => a !== "--dry-run" && a !== "--allow-missing");
683
+ // An ignored flag reads as obeyed: `--env preview` would sync both environments silently.
684
+ const unknown = args.filter(
685
+ (a) => a.startsWith("--") && a !== "--dry-run" && a !== "--allow-missing",
686
+ );
687
+ if (unknown.length) {
688
+ log(
689
+ `❌ unknown option ${unknown.join(" ")} — every run covers both environments; narrow with --store only`,
690
+ );
691
+ return 1;
692
+ }
693
+ const usage = () => {
694
+ log(
695
+ fs
696
+ .readFileSync(fileURLToPath(import.meta.url), "utf8")
697
+ .split("\n")
698
+ .slice(3, 12)
699
+ .map((l) => l.replace(/^\/\/ ?/, ""))
700
+ .join("\n"),
701
+ );
702
+ return cmd === "help" ? 0 : 1;
703
+ };
704
+ if (!["sync", "drift", "check", "list"].includes(cmd)) return usage();
705
+
706
+ const dir = path.join(root, "scripts", "secrets");
707
+ const cfg = await loadConfig(dir);
708
+ const src = sourcesFor(root, cfg);
709
+ if (cmd === "check") return check({ cfg, src, root, file, allowMissing, log });
710
+ if (cmd === "list") {
711
+ if (onlyStore && !cfg.stores.some((s) => s.name === onlyStore)) {
712
+ log(
713
+ `❌ unknown store "${onlyStore}" (configured: ${cfg.stores.map((s) => s.name).join(", ")})`,
714
+ );
715
+ return 1;
716
+ }
717
+ for (const s of cfg.stores.filter((x) => !onlyStore || x.name === onlyStore))
718
+ for (const r of secretsFor(cfg, s.name)) log(onlyStore ? r.name : `${s.name}\t${r.name}`);
719
+ return 0;
720
+ }
721
+ if (!src.files.preview) {
722
+ log(`❌ ${cfg.sources.preview} not found`);
723
+ return 1;
724
+ }
725
+ if (cfg.sources.production && !src.files.production) {
726
+ log(`❌ ${cfg.sources.production} not found`);
727
+ return 1;
728
+ }
729
+ if (onlyStore && !cfg.stores.some((s) => s.name === onlyStore)) {
730
+ log(
731
+ `❌ unknown store "${onlyStore}" (configured: ${cfg.stores.map((s) => s.name).join(", ")})`,
732
+ );
733
+ return 1;
734
+ }
735
+
736
+ const mode = cmd === "drift" ? "drift" : dry ? "dry-run" : "sync";
737
+ const statePath = path.join(dir, STATE_FILE);
738
+ const state = readJson(statePath) ?? {};
739
+ const envs = src.files.production ? ["preview", "production"] : ["preview"];
740
+ log(
741
+ mode === "drift"
742
+ ? "🔎 Drift: every store vs source (read-only)\n"
743
+ : `🔄 Sync${mode === "dry-run" ? " — DRY RUN, nothing written" : ""}\n`,
744
+ );
745
+
746
+ const results = [];
747
+ for (const store of cfg.stores.filter((s) => !onlyStore || s.name === onlyStore)) {
748
+ if (!cfg.secrets.some((s) => s.to.some((t) => t.store === store.name))) continue;
749
+ for (const env of store.adapter.perEnv ? envs : ["repo"]) {
750
+ let result;
751
+ try {
752
+ result = await runTarget({ mode, store, env, cfg, src, state, root, log });
753
+ } catch (err) {
754
+ log(` ❌ ${err.message}\n`);
755
+ result = "failed";
756
+ }
757
+ results.push([`${store.name}${store.adapter.perEnv ? ` (${env})` : ""}`, result]);
758
+ }
759
+ }
760
+ if (mode === "sync")
761
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 });
762
+
763
+ const manual = cfg.secrets.filter((s) => s.manual.length);
764
+ if (manual.length) {
765
+ log("❔ Copies no API reaches — update by hand on every rotation:");
766
+ for (const s of manual) for (const m of s.manual) log(` ❔ ${s.name} — ${m}`);
767
+ log("");
768
+ }
769
+ const glyph = {
770
+ ok: "✅ ok",
771
+ drift: "❌ drift",
772
+ failed: "❌ failed",
773
+ skipped: "⚠️ skipped — not checked",
774
+ };
775
+ for (const [label, result] of results) log(` ${label.padEnd(24)} ${glyph[result]}`);
776
+ return results.some(([, r]) => r === "failed")
777
+ ? 1
778
+ : results.some(([, r]) => r === "drift")
779
+ ? 2
780
+ : 0;
781
+ }
782
+
783
+ if (process.argv[1] && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href) {
784
+ process.exitCode = await main(process.argv.slice(2));
785
+ }