@cubis/foundry 0.3.77 → 0.3.79

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 (206) hide show
  1. package/dist/cli/build/commands.js +19 -0
  2. package/dist/cli/build/commands.js.map +1 -0
  3. package/dist/cli/commands/register.js +4 -0
  4. package/dist/cli/commands/register.js.map +1 -1
  5. package/dist/cli/core.js +1355 -46
  6. package/dist/cli/core.js.map +1 -1
  7. package/package.json +4 -3
  8. package/src/cli/build/commands.ts +39 -0
  9. package/src/cli/commands/register.ts +6 -0
  10. package/src/cli/core.ts +1689 -75
  11. package/workflows/skills/generated/skill-audit.json +11 -2
  12. package/workflows/skills/generated/skill-catalog.json +38 -4
  13. package/workflows/skills/skills_index.json +34 -0
  14. package/workflows/skills/spec-driven-delivery/SKILL.md +63 -0
  15. package/workflows/workflows/agent-environment-setup/generated/route-manifest.json +117 -4
  16. package/workflows/workflows/agent-environment-setup/manifest.json +21 -0
  17. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/accessibility.toml +10 -5
  18. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/architecture.toml +19 -0
  19. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/backend.toml +10 -5
  20. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/create.toml +10 -5
  21. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/database.toml +10 -5
  22. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/debug.toml +10 -5
  23. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/devops.toml +10 -5
  24. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/implement-track.toml +10 -5
  25. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/migrate.toml +10 -5
  26. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/mobile.toml +10 -5
  27. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/onboard.toml +10 -5
  28. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/orchestrate.toml +10 -5
  29. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/plan.toml +10 -5
  30. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/refactor.toml +10 -5
  31. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/release.toml +10 -5
  32. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/review.toml +10 -5
  33. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/security.toml +10 -5
  34. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/spec.toml +19 -0
  35. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/test.toml +10 -5
  36. package/workflows/workflows/agent-environment-setup/platforms/antigravity/commands/vercel.toml +10 -5
  37. package/workflows/workflows/agent-environment-setup/platforms/antigravity/rules/GEMINI.md +3 -1
  38. package/workflows/workflows/agent-environment-setup/platforms/antigravity/skills/spec-driven-delivery/SKILL.md +65 -0
  39. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/architecture.md +87 -0
  40. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/backend.md +3 -0
  41. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/create.md +4 -1
  42. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/database.md +3 -0
  43. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/implement-track.md +7 -1
  44. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/migrate.md +4 -1
  45. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/mobile.md +3 -0
  46. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/onboard.md +1 -0
  47. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/orchestrate.md +6 -1
  48. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/plan.md +12 -2
  49. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/refactor.md +3 -0
  50. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/release.md +3 -0
  51. package/workflows/workflows/agent-environment-setup/platforms/antigravity/workflows/spec.md +81 -0
  52. package/workflows/workflows/agent-environment-setup/platforms/claude/rules/CLAUDE.md +3 -1
  53. package/workflows/workflows/agent-environment-setup/platforms/claude/skills/skills_index.json +34 -0
  54. package/workflows/workflows/agent-environment-setup/platforms/claude/skills/spec-driven-delivery/SKILL.md +66 -0
  55. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/architecture.md +85 -0
  56. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/backend.md +3 -0
  57. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/create.md +4 -1
  58. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/database.md +3 -0
  59. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/implement-track.md +7 -1
  60. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/migrate.md +4 -1
  61. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/mobile.md +3 -0
  62. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/onboard.md +1 -0
  63. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/orchestrate.md +6 -1
  64. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/plan.md +12 -2
  65. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/refactor.md +3 -0
  66. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/release.md +3 -0
  67. package/workflows/workflows/agent-environment-setup/platforms/claude/workflows/spec.md +79 -0
  68. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/backend-specialist.md +1 -1
  69. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/code-archaeologist.md +1 -1
  70. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/database-architect.md +1 -1
  71. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/debugger.md +1 -1
  72. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/devops-engineer.md +1 -1
  73. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/documentation-writer.md +1 -1
  74. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/frontend-specialist.md +1 -1
  75. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/game-developer.md +1 -1
  76. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/mobile-developer.md +1 -1
  77. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/orchestrator.md +1 -1
  78. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/penetration-tester.md +1 -1
  79. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/performance-optimizer.md +1 -1
  80. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/product-manager.md +1 -1
  81. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/project-planner.md +1 -1
  82. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/qa-automation-engineer.md +1 -1
  83. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/researcher.md +1 -1
  84. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/security-auditor.md +1 -1
  85. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/seo-specialist.md +1 -1
  86. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/sre-engineer.md +1 -1
  87. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/test-engineer.md +1 -1
  88. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/validator.md +1 -1
  89. package/workflows/workflows/agent-environment-setup/platforms/codex/agents/vercel-expert.md +1 -1
  90. package/workflows/workflows/agent-environment-setup/platforms/codex/rules/AGENTS.md +3 -1
  91. package/workflows/workflows/agent-environment-setup/platforms/codex/skills/spec-driven-delivery/SKILL.md +65 -0
  92. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/accessibility.md +1 -1
  93. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/architecture.md +87 -0
  94. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/backend.md +4 -1
  95. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/create.md +5 -2
  96. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/database.md +4 -1
  97. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/debug.md +1 -1
  98. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/devops.md +1 -1
  99. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/implement-track.md +8 -2
  100. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/migrate.md +5 -2
  101. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/mobile.md +4 -1
  102. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/onboard.md +2 -1
  103. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/orchestrate.md +7 -2
  104. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/plan.md +13 -3
  105. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/refactor.md +4 -1
  106. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/release.md +4 -1
  107. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/review.md +1 -1
  108. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/security.md +1 -1
  109. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/spec.md +81 -0
  110. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/test.md +1 -1
  111. package/workflows/workflows/agent-environment-setup/platforms/codex/workflows/vercel.md +1 -1
  112. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-accessibility.prompt.md +9 -4
  113. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-architecture.prompt.md +18 -0
  114. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-backend.prompt.md +9 -4
  115. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-create.prompt.md +9 -4
  116. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-database.prompt.md +9 -4
  117. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-debug.prompt.md +9 -4
  118. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-devops.prompt.md +9 -4
  119. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-implement-track.prompt.md +9 -4
  120. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-migrate.prompt.md +9 -4
  121. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-mobile.prompt.md +9 -4
  122. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-onboard.prompt.md +9 -4
  123. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-orchestrate.prompt.md +9 -4
  124. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-plan.prompt.md +9 -4
  125. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-refactor.prompt.md +9 -4
  126. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-release.prompt.md +9 -4
  127. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-review.prompt.md +9 -4
  128. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-security.prompt.md +9 -4
  129. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-spec.prompt.md +18 -0
  130. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-test.prompt.md +9 -4
  131. package/workflows/workflows/agent-environment-setup/platforms/copilot/prompts/workflow-vercel.prompt.md +9 -4
  132. package/workflows/workflows/agent-environment-setup/platforms/copilot/rules/copilot-instructions.md +3 -1
  133. package/workflows/workflows/agent-environment-setup/platforms/copilot/skills/skills_index.json +34 -0
  134. package/workflows/workflows/agent-environment-setup/platforms/copilot/skills/spec-driven-delivery/SKILL.md +70 -0
  135. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/architecture.md +85 -0
  136. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/backend.md +3 -0
  137. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/create.md +4 -1
  138. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/database.md +3 -0
  139. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/implement-track.md +7 -1
  140. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/migrate.md +4 -1
  141. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/mobile.md +3 -0
  142. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/onboard.md +1 -0
  143. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/orchestrate.md +6 -1
  144. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/plan.md +12 -2
  145. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/refactor.md +3 -0
  146. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/release.md +3 -0
  147. package/workflows/workflows/agent-environment-setup/platforms/copilot/workflows/spec.md +79 -0
  148. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/accessibility.toml +10 -5
  149. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/architecture.toml +19 -0
  150. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/backend.toml +10 -5
  151. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/create.toml +10 -5
  152. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/database.toml +10 -5
  153. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/debug.toml +10 -5
  154. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/devops.toml +10 -5
  155. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/implement-track.toml +10 -5
  156. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/migrate.toml +10 -5
  157. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/mobile.toml +10 -5
  158. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/onboard.toml +10 -5
  159. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/orchestrate.toml +10 -5
  160. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/plan.toml +10 -5
  161. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/refactor.toml +10 -5
  162. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/release.toml +10 -5
  163. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/review.toml +10 -5
  164. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/security.toml +10 -5
  165. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/spec.toml +19 -0
  166. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/test.toml +10 -5
  167. package/workflows/workflows/agent-environment-setup/platforms/gemini/commands/vercel.toml +10 -5
  168. package/workflows/workflows/agent-environment-setup/platforms/gemini/rules/GEMINI.md +3 -1
  169. package/workflows/workflows/agent-environment-setup/platforms/gemini/skills/spec-driven-delivery/SKILL.md +65 -0
  170. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/architecture.md +87 -0
  171. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/backend.md +3 -0
  172. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/create.md +4 -1
  173. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/database.md +3 -0
  174. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/implement-track.md +7 -1
  175. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/migrate.md +4 -1
  176. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/mobile.md +3 -0
  177. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/onboard.md +1 -0
  178. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/orchestrate.md +6 -1
  179. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/plan.md +12 -2
  180. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/refactor.md +3 -0
  181. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/release.md +3 -0
  182. package/workflows/workflows/agent-environment-setup/platforms/gemini/workflows/spec.md +81 -0
  183. package/workflows/workflows/agent-environment-setup/shared/agents/backend-specialist.md +5 -5
  184. package/workflows/workflows/agent-environment-setup/shared/agents/database-architect.md +3 -3
  185. package/workflows/workflows/agent-environment-setup/shared/agents/orchestrator.md +8 -8
  186. package/workflows/workflows/agent-environment-setup/shared/agents/penetration-tester.md +3 -3
  187. package/workflows/workflows/agent-environment-setup/shared/agents/product-manager.md +6 -6
  188. package/workflows/workflows/agent-environment-setup/shared/agents/project-planner.md +8 -8
  189. package/workflows/workflows/agent-environment-setup/shared/agents/researcher.md +8 -8
  190. package/workflows/workflows/agent-environment-setup/shared/agents/security-auditor.md +2 -2
  191. package/workflows/workflows/agent-environment-setup/shared/rules/STEERING.md +13 -0
  192. package/workflows/workflows/agent-environment-setup/shared/rules/overrides/codex.md +3 -3
  193. package/workflows/workflows/agent-environment-setup/shared/workflows/architecture.md +85 -0
  194. package/workflows/workflows/agent-environment-setup/shared/workflows/backend.md +8 -5
  195. package/workflows/workflows/agent-environment-setup/shared/workflows/create.md +5 -2
  196. package/workflows/workflows/agent-environment-setup/shared/workflows/database.md +6 -3
  197. package/workflows/workflows/agent-environment-setup/shared/workflows/implement-track.md +12 -6
  198. package/workflows/workflows/agent-environment-setup/shared/workflows/migrate.md +7 -4
  199. package/workflows/workflows/agent-environment-setup/shared/workflows/mobile.md +3 -0
  200. package/workflows/workflows/agent-environment-setup/shared/workflows/onboard.md +6 -5
  201. package/workflows/workflows/agent-environment-setup/shared/workflows/orchestrate.md +10 -5
  202. package/workflows/workflows/agent-environment-setup/shared/workflows/plan.md +17 -7
  203. package/workflows/workflows/agent-environment-setup/shared/workflows/refactor.md +5 -2
  204. package/workflows/workflows/agent-environment-setup/shared/workflows/release.md +3 -0
  205. package/workflows/workflows/agent-environment-setup/shared/workflows/security.md +2 -2
  206. package/workflows/workflows/agent-environment-setup/shared/workflows/spec.md +79 -0
package/dist/cli/core.js CHANGED
@@ -3,6 +3,7 @@ import { confirm, input, select } from "@inquirer/prompts";
3
3
  import { parse as parseJsonc } from "jsonc-parser";
4
4
  import { existsSync } from "node:fs";
5
5
  import { chmod, cp, mkdir, readdir, readFile, rm, stat, symlink, writeFile, } from "node:fs/promises";
6
+ import { createHash } from "node:crypto";
6
7
  import { createRequire } from "node:module";
7
8
  import { spawn, execFile as execFileCallback } from "node:child_process";
8
9
  import os from "node:os";
@@ -24,6 +25,16 @@ const ENGINEERING_RULES_BLOCK_START_RE = /<!--\s*cbx:engineering:auto:start[^>]*
24
25
  const ENGINEERING_RULES_BLOCK_END_RE = /<!--\s*cbx:engineering:auto:end\s*-->/g;
25
26
  const ENGINEERING_RULES_FILE_BLOCK_START_RE = /<!--\s*cbx:engineering:rules:start[^>]*-->/g;
26
27
  const ENGINEERING_RULES_FILE_BLOCK_END_RE = /<!--\s*cbx:engineering:rules:end\s*-->/g;
28
+ const ENGINEERING_ARCHITECTURE_BLOCK_START_RE = /<!--\s*cbx:architecture:rules:start[^>]*-->/g;
29
+ const ENGINEERING_ARCHITECTURE_BLOCK_END_RE = /<!--\s*cbx:architecture:rules:end\s*-->/g;
30
+ const PRODUCT_FOUNDATION_BLOCK_START_RE = /<!--\s*cbx:product:foundation:start[^>]*-->/g;
31
+ const PRODUCT_FOUNDATION_BLOCK_END_RE = /<!--\s*cbx:product:foundation:end\s*-->/g;
32
+ const ARCHITECTURE_DOC_BLOCK_START_RE = /<!--\s*cbx:architecture:doc:start[^>]*-->/g;
33
+ const ARCHITECTURE_DOC_BLOCK_END_RE = /<!--\s*cbx:architecture:doc:end\s*-->/g;
34
+ const TECH_ARCHITECTURE_BLOCK_START_RE = /<!--\s*cbx:architecture:tech:start[^>]*-->/g;
35
+ const TECH_ARCHITECTURE_BLOCK_END_RE = /<!--\s*cbx:architecture:tech:end\s*-->/g;
36
+ const ROADMAP_FOUNDATION_BLOCK_START_RE = /<!--\s*cbx:roadmap:foundation:start[^>]*-->/g;
37
+ const ROADMAP_FOUNDATION_BLOCK_END_RE = /<!--\s*cbx:roadmap:foundation:end\s*-->/g;
27
38
  const COPILOT_ALLOWED_SKILL_FRONTMATTER_KEYS = new Set([
28
39
  "compatibility",
29
40
  "description",
@@ -215,11 +226,18 @@ const PLAYWRIGHT_MCP_URL = `http://localhost:${PLAYWRIGHT_DEFAULT_PORT}/mcp`;
215
226
  const POSTMAN_WORKSPACE_MANUAL_CHOICE = "__postman_workspace_manual__";
216
227
  const CBX_CONFIG_FILENAME = "cbx_config.json";
217
228
  const CBX_CREDENTIALS_ENV_FILENAME = "credentials.env";
229
+ const ARCHITECTURE_BUILD_METADATA_FILENAME = "architecture-build.json";
218
230
  const LEGACY_POSTMAN_CONFIG_FILENAME = ["postman", "setting.json"].join("_");
219
231
  const DEFAULT_CREDENTIAL_PROFILE_NAME = "default";
220
232
  const RESERVED_CREDENTIAL_PROFILE_NAMES = new Set(["all"]);
221
233
  const CREDENTIAL_SERVICES = new Set(["postman", "stitch"]);
222
234
  const MCP_RUNTIMES = new Set(["docker", "local"]);
235
+ const ARCHITECTURE_BUILD_PLATFORMS = new Set([
236
+ "codex",
237
+ "claude",
238
+ "gemini",
239
+ "copilot",
240
+ ]);
223
241
  const MCP_FALLBACKS = new Set(["local", "fail", "skip"]);
224
242
  const MCP_UPDATE_POLICIES = new Set(["pinned", "latest"]);
225
243
  const DEFAULT_MCP_RUNTIME = "docker";
@@ -838,6 +856,395 @@ function buildAntigravityTerminalVerificationBlock({ provider, powerShellScriptP
838
856
  "<!-- cbx:terminal:verification:end -->",
839
857
  ].join("\n");
840
858
  }
859
+ function hashStableObject(value) {
860
+ return createHash("sha256")
861
+ .update(JSON.stringify(value))
862
+ .digest("hex")
863
+ .slice(0, 12);
864
+ }
865
+ function firstNonEmpty(values) {
866
+ for (const value of values || []) {
867
+ if (value)
868
+ return value;
869
+ }
870
+ return null;
871
+ }
872
+ function inferArchitectureContractProfile(snapshot) {
873
+ const allSignals = [];
874
+ for (const app of snapshot.architectureByApp || []) {
875
+ for (const signal of app.architectureSignals || []) {
876
+ if (!allSignals.includes(signal))
877
+ allSignals.push(signal);
878
+ }
879
+ }
880
+ const style = firstNonEmpty([
881
+ allSignals.find((signal) => /clean architecture/i.test(signal)),
882
+ allSignals.find((signal) => /hexagonal/i.test(signal)),
883
+ allSignals.find((signal) => /feature-first/i.test(signal)),
884
+ allSignals.find((signal) => /mvvm/i.test(signal)),
885
+ allSignals.find((signal) => /mvc/i.test(signal)),
886
+ ]) || "Undeclared — align to current repository conventions";
887
+ const moduleBoundaries = snapshot.annotatedDirs
888
+ .slice(0, 8)
889
+ .map(({ name, purpose }) => purpose ? `${name}/ (${purpose})` : `${name}/`);
890
+ const dependencyRules = [];
891
+ if (/clean architecture/i.test(style)) {
892
+ dependencyRules.push("Domain code must not depend on infrastructure, framework, or presentation layers.");
893
+ dependencyRules.push("Adapters may depend inward on domain contracts, never the reverse.");
894
+ }
895
+ else if (/hexagonal/i.test(style)) {
896
+ dependencyRules.push("Ports stay stable at the boundary; adapters implement them without leaking infrastructure concerns inward.");
897
+ }
898
+ else {
899
+ dependencyRules.push("Respect existing feature and package boundaries; avoid hidden cross-module imports.");
900
+ }
901
+ dependencyRules.push("Shared UI, data, and platform conventions belong in the declared common layer, not duplicated per feature.");
902
+ const designSystemSource = firstNonEmpty([
903
+ snapshot.topDirs.includes("components")
904
+ ? "components/ is the primary shared UI surface."
905
+ : null,
906
+ snapshot.topDirs.includes("design-system")
907
+ ? "design-system/ is the primary shared UI surface."
908
+ : null,
909
+ snapshot.topDirs.includes("app")
910
+ ? "App-level UI patterns should be centralized and reused across screens."
911
+ : null,
912
+ ]) || "No dedicated design-system directory detected; infer shared UI rules from current components and screens.";
913
+ const testingStrategy = [];
914
+ if (snapshot.keyScripts.some((script) => script.name === "lint")) {
915
+ testingStrategy.push("Linting is part of the baseline quality gate.");
916
+ }
917
+ if (snapshot.keyScripts.some((script) => script.name.includes("type"))) {
918
+ testingStrategy.push("Static typing or analysis should pass before merge when the stack supports it.");
919
+ }
920
+ if (snapshot.keyScripts.some((script) => script.name.startsWith("test"))) {
921
+ testingStrategy.push("Focused automated tests should cover the changed behavior before merge.");
922
+ }
923
+ if (testingStrategy.length === 0) {
924
+ testingStrategy.push("Add focused validation evidence for non-trivial changes even when no standard test command is detected.");
925
+ }
926
+ const scalingConstraints = inferTechnicalConstraints(snapshot, {
927
+ suggestedProfile: inferContextBudget(snapshot).suggestedProfile,
928
+ });
929
+ const docUpdateTriggers = [
930
+ "feature additions that change module boundaries or shared UI rules",
931
+ "migrations, scale changes, or deployment-shape changes",
932
+ "refactors that establish new conventions future work should follow",
933
+ ];
934
+ return {
935
+ style,
936
+ moduleBoundaries,
937
+ dependencyRules,
938
+ designSystemSource,
939
+ testingStrategy,
940
+ scalingConstraints,
941
+ docUpdateTriggers,
942
+ };
943
+ }
944
+ function buildArchitectureMermaid(snapshot) {
945
+ const topDirs = snapshot.topDirs.slice(0, 4);
946
+ const flowNodes = topDirs.length > 0 ? topDirs : ["src", "docs"];
947
+ const lines = [
948
+ "flowchart TD",
949
+ ' user["User / Entry Point"] --> app["Application Surface"]',
950
+ ];
951
+ for (let index = 0; index < flowNodes.length; index += 1) {
952
+ const nodeName = flowNodes[index].replace(/[^A-Za-z0-9]/g, "") || `N${index}`;
953
+ lines.push(` app --> ${nodeName}["${flowNodes[index]}/"]`);
954
+ }
955
+ if (snapshot.isMcpServer || snapshot.mcpSignals.length > 0) {
956
+ lines.push(' app --> mcp["MCP / Tooling Surface"]');
957
+ }
958
+ if (snapshot.cicdSignals.length > 0) {
959
+ lines.push(' app --> deploy["Delivery / Runtime"]');
960
+ }
961
+ return lines.join("\n");
962
+ }
963
+ function inferProductFoundationProfile(snapshot, specRoots = []) {
964
+ const appRoots = (snapshot.architectureByApp || [])
965
+ .map((item) => item.rootPath)
966
+ .filter((value) => value && value !== ".");
967
+ const primarySurfaces = appRoots.length > 0 ? appRoots : snapshot.topDirs.slice(0, 6);
968
+ const userPersonas = [];
969
+ if (snapshot.frameworks.includes("Flutter")) {
970
+ userPersonas.push("End users interacting through mobile or desktop app surfaces");
971
+ }
972
+ if (snapshot.frameworks.includes("Next.js") ||
973
+ snapshot.frameworks.includes("React") ||
974
+ snapshot.topDirs.includes("web")) {
975
+ userPersonas.push("Browser users and internal operators using web-facing flows");
976
+ }
977
+ if (snapshot.frameworks.includes("NestJS") || snapshot.topDirs.includes("api")) {
978
+ userPersonas.push("Internal services, operators, or partner systems consuming API boundaries");
979
+ }
980
+ if (userPersonas.length === 0) {
981
+ userPersonas.push("Project stakeholders are not obvious from the repo alone; refine personas from product context before major feature work.");
982
+ }
983
+ const coreJourneys = [];
984
+ if (specRoots.length > 0) {
985
+ coreJourneys.push(`Active implementation themes are reflected in current spec packs: ${specRoots.join(", ")}.`);
986
+ }
987
+ if (primarySurfaces.length > 0) {
988
+ coreJourneys.push(`Primary product surfaces currently live in: ${primarySurfaces.join(", ")}.`);
989
+ }
990
+ if (snapshot.isMcpServer || snapshot.mcpSignals.length > 0) {
991
+ coreJourneys.push("Tool-assisted and MCP-driven workflows are part of the operating model and should stay stable.");
992
+ }
993
+ if (coreJourneys.length === 0) {
994
+ coreJourneys.push("Repository evidence is thin; capture the primary user journeys here before scaling the codebase further.");
995
+ }
996
+ const successSignals = [
997
+ "Feature work should stay aligned to explicit user or operator value, not speculative abstractions.",
998
+ "Architecture changes should reduce onboarding, debugging, and testing cost over time.",
999
+ ];
1000
+ if (snapshot.cicdSignals.length > 0) {
1001
+ successSignals.push(`Delivery flows already rely on ${snapshot.cicdSignals.join(", ")} signals; keep release friction low for that pipeline.`);
1002
+ }
1003
+ return {
1004
+ productScope: snapshot.readmeExcerpt ||
1005
+ "No explicit product summary was detected from repo docs. Replace this with a concise product statement when better context exists.",
1006
+ primarySurfaces,
1007
+ userPersonas,
1008
+ coreJourneys,
1009
+ successSignals,
1010
+ };
1011
+ }
1012
+ function buildProductFoundationSection(snapshot, specRoots = []) {
1013
+ const profile = inferProductFoundationProfile(snapshot, specRoots);
1014
+ const hash = hashStableObject(profile);
1015
+ return [
1016
+ `<!-- cbx:product:foundation:start version=1 profile=${hash} -->`,
1017
+ "## Product Foundation (auto-managed)",
1018
+ "",
1019
+ "### Product Scope",
1020
+ profile.productScope,
1021
+ "",
1022
+ "### Primary Surfaces",
1023
+ ...(profile.primarySurfaces.length > 0
1024
+ ? profile.primarySurfaces.map((item) => `- ${item}`)
1025
+ : ["- No primary surfaces were detected automatically."]),
1026
+ "",
1027
+ "### Users and Operators",
1028
+ ...profile.userPersonas.map((item) => `- ${item}`),
1029
+ "",
1030
+ "### Core Journeys",
1031
+ ...profile.coreJourneys.map((item) => `- ${item}`),
1032
+ "",
1033
+ "### Success Signals",
1034
+ ...profile.successSignals.map((item) => `- ${item}`),
1035
+ "",
1036
+ "### Product Guardrails",
1037
+ "- Keep product intent stable across future features so agents do not optimize for the wrong user outcome.",
1038
+ "- Refresh this managed section when scope, personas, operating model, or success metrics change materially.",
1039
+ "<!-- cbx:product:foundation:end -->",
1040
+ "",
1041
+ ].join("\n");
1042
+ }
1043
+ function inferArchitectureDocProfile(snapshot, specRoots = []) {
1044
+ const contract = inferArchitectureContractProfile(snapshot);
1045
+ const architectureSignals = (snapshot.architectureByApp || []).map((item) => {
1046
+ const label = item.rootPath === "." ? "repo root" : item.rootPath;
1047
+ const signals = item.architectureSignals && item.architectureSignals.length > 0
1048
+ ? item.architectureSignals.join(", ")
1049
+ : "not enough signals to classify";
1050
+ return `${label}: ${signals}`;
1051
+ });
1052
+ const decisionAreas = [
1053
+ "Module boundaries and dependency direction",
1054
+ "Design-system ownership and reusable primitives",
1055
+ "Testing and validation expectations by runtime boundary",
1056
+ ];
1057
+ if (specRoots.length > 0) {
1058
+ decisionAreas.push(`Active specs that may influence upcoming architecture work: ${specRoots.join(", ")}.`);
1059
+ }
1060
+ return {
1061
+ style: contract.style,
1062
+ designSystemSource: contract.designSystemSource,
1063
+ moduleBoundaries: contract.moduleBoundaries,
1064
+ architectureSignals,
1065
+ decisionAreas,
1066
+ scalingConstraints: contract.scalingConstraints,
1067
+ testingStrategy: contract.testingStrategy,
1068
+ };
1069
+ }
1070
+ function buildArchitectureDocSection(snapshot, specRoots = []) {
1071
+ const profile = inferArchitectureDocProfile(snapshot, specRoots);
1072
+ const hash = hashStableObject(profile);
1073
+ return [
1074
+ `<!-- cbx:architecture:doc:start version=1 profile=${hash} -->`,
1075
+ "## Accepted Architecture Backbone (auto-managed)",
1076
+ "",
1077
+ "### System Overview",
1078
+ `- Accepted style: ${profile.style}.`,
1079
+ `- Design-system source of truth: ${profile.designSystemSource}`,
1080
+ "",
1081
+ "### Bounded Contexts and Module Boundaries",
1082
+ ...(profile.moduleBoundaries.length > 0
1083
+ ? profile.moduleBoundaries.map((item) => `- ${item}`)
1084
+ : ["- No strong top-level module boundaries were detected automatically."]),
1085
+ "",
1086
+ "### Architecture Signals by Surface",
1087
+ ...(profile.architectureSignals.length > 0
1088
+ ? profile.architectureSignals.map((item) => `- ${item}`)
1089
+ : ["- No app-level architecture signals were inferred from the repo scan."]),
1090
+ "",
1091
+ "### Decision Areas to Preserve",
1092
+ ...profile.decisionAreas.map((item) => `- ${item}`),
1093
+ "",
1094
+ "### Scalability and Reliability Notes",
1095
+ ...profile.scalingConstraints.map((item) => `- ${item}`),
1096
+ "",
1097
+ "### Testing and Operability",
1098
+ ...profile.testingStrategy.map((item) => `- ${item}`),
1099
+ "",
1100
+ "### ADR Linkage",
1101
+ "- Keep durable architecture decisions in `docs/adr/` and summarize the active decision set here.",
1102
+ "",
1103
+ "### Mermaid Diagram",
1104
+ "```mermaid",
1105
+ buildArchitectureDocMermaid(snapshot),
1106
+ "```",
1107
+ "<!-- cbx:architecture:doc:end -->",
1108
+ "",
1109
+ ].join("\n");
1110
+ }
1111
+ function buildEngineeringArchitectureSection(snapshot) {
1112
+ const profile = inferArchitectureContractProfile(snapshot);
1113
+ const hash = hashStableObject(profile);
1114
+ return [
1115
+ `<!-- cbx:architecture:rules:start version=1 profile=${hash} -->`,
1116
+ "## 10) Architecture Contract (auto-managed)",
1117
+ "",
1118
+ `- Declared style: ${profile.style}.`,
1119
+ `- Design-system source of truth: ${profile.designSystemSource}`,
1120
+ "- Dependency direction rules:",
1121
+ ...profile.dependencyRules.map((rule) => ` - ${rule}`),
1122
+ "- Module and package boundaries to preserve:",
1123
+ ...(profile.moduleBoundaries.length > 0
1124
+ ? profile.moduleBoundaries.map((rule) => ` - ${rule}`)
1125
+ : [" - No strong module boundary was detected automatically; keep new boundaries explicit in specs and ADRs."]),
1126
+ "- Testability expectations:",
1127
+ ...profile.testingStrategy.map((rule) => ` - ${rule}`),
1128
+ "- Doc refresh policy:",
1129
+ " - Update these managed sections when architecture, scale, boundaries, design-system rules, or testing strategy changes.",
1130
+ " - For non-trivial work, read PRODUCT.md, ENGINEERING_RULES.md, ARCHITECTURE.md, and TECH.md in that order when they exist.",
1131
+ "<!-- cbx:architecture:rules:end -->",
1132
+ "",
1133
+ ].join("\n");
1134
+ }
1135
+ function buildArchitectureDocMermaid(snapshot) {
1136
+ const topDirs = snapshot.topDirs.slice(0, 5);
1137
+ const lines = [
1138
+ "flowchart LR",
1139
+ ' product["Product Intent"] --> rules["Engineering Rules"]',
1140
+ ' product --> arch["Architecture Backbone"]',
1141
+ ' arch --> tech["Current Tech Snapshot"]',
1142
+ ];
1143
+ if (topDirs.length > 0) {
1144
+ for (let index = 0; index < topDirs.length; index += 1) {
1145
+ const dir = topDirs[index];
1146
+ const nodeName = `D${index}`;
1147
+ lines.push(` arch --> ${nodeName}["${dir}/"]`);
1148
+ }
1149
+ }
1150
+ lines.push(' arch --> adr["docs/adr"]');
1151
+ lines.push(' product --> specs["docs/specs"]');
1152
+ return lines.join("\n");
1153
+ }
1154
+ function buildTechArchitectureSection(snapshot) {
1155
+ const profile = inferArchitectureContractProfile(snapshot);
1156
+ const payload = {
1157
+ style: profile.style,
1158
+ topDirs: snapshot.topDirs,
1159
+ frameworks: snapshot.frameworks,
1160
+ architectureByApp: snapshot.architectureByApp,
1161
+ };
1162
+ const hash = hashStableObject(payload);
1163
+ const architectureSignals = profile.style
1164
+ ? [`- Primary inferred style: ${profile.style}.`]
1165
+ : [];
1166
+ return [
1167
+ `<!-- cbx:architecture:tech:start version=1 snapshot=${hash} -->`,
1168
+ "## Architecture Snapshot (auto-managed)",
1169
+ ...(architectureSignals.length > 0 ? ["", ...architectureSignals] : []),
1170
+ ...(snapshot.architectureByApp.length > 0
1171
+ ? [
1172
+ "- App-level structure signals:",
1173
+ ...snapshot.architectureByApp.slice(0, 6).map((item) => {
1174
+ const label = item.rootPath === "." ? "repo root" : item.rootPath;
1175
+ const signals = item.architectureSignals.length > 0
1176
+ ? item.architectureSignals.join(", ")
1177
+ : "not enough signals to classify";
1178
+ return ` - ${label}: ${signals}`;
1179
+ }),
1180
+ ]
1181
+ : ["- No app-level architecture signals detected automatically."]),
1182
+ "",
1183
+ "### Module / App Topology",
1184
+ ...(profile.moduleBoundaries.length > 0
1185
+ ? profile.moduleBoundaries.map((item) => `- ${item}`)
1186
+ : ["- No significant top-level module boundaries detected automatically."]),
1187
+ "",
1188
+ "### Flow Narratives",
1189
+ "- Describe the primary request, data, and background-job flows here when architecture generation runs.",
1190
+ "- Keep this section current when scale changes or new integration boundaries are introduced.",
1191
+ "",
1192
+ "### Mermaid Diagram",
1193
+ "```mermaid",
1194
+ buildArchitectureMermaid(snapshot),
1195
+ "```",
1196
+ "",
1197
+ "### Scaling / Deployment / Testing Snapshot",
1198
+ ...profile.scalingConstraints.map((item) => `- ${item}`),
1199
+ "",
1200
+ "### External Research Evidence",
1201
+ "- Reserved for `cbx build architecture --research auto|always` when outside evidence informs the architecture notes.",
1202
+ "<!-- cbx:architecture:tech:end -->",
1203
+ "",
1204
+ ].join("\n");
1205
+ }
1206
+ function buildRoadmapFoundationSection(snapshot, specRoots = []) {
1207
+ const payload = {
1208
+ topDirs: snapshot.topDirs,
1209
+ frameworks: snapshot.frameworks,
1210
+ specRoots,
1211
+ };
1212
+ const hash = hashStableObject(payload);
1213
+ const nowItems = specRoots.length > 0
1214
+ ? specRoots.map((item) => `Track active change planning in \`${item}\`.`)
1215
+ : [
1216
+ "No active spec packs detected. Create a spec pack before starting the next non-trivial feature or migration.",
1217
+ ];
1218
+ const nextItems = [];
1219
+ if (snapshot.frameworks.length > 0) {
1220
+ nextItems.push(`Keep shared conventions stable across the current stack: ${snapshot.frameworks.join(", ")}.`);
1221
+ }
1222
+ if (snapshot.cicdSignals.length > 0) {
1223
+ nextItems.push(`Preserve release compatibility with the detected delivery surfaces: ${snapshot.cicdSignals.join(", ")}.`);
1224
+ }
1225
+ if (nextItems.length === 0) {
1226
+ nextItems.push("Document the next scaling milestones here once product direction and architecture constraints are clearer.");
1227
+ }
1228
+ return [
1229
+ `<!-- cbx:roadmap:foundation:start version=1 profile=${hash} -->`,
1230
+ "## Delivery Backbone (auto-managed)",
1231
+ "",
1232
+ "### Now",
1233
+ ...nowItems.map((item) => `- ${item}`),
1234
+ "",
1235
+ "### Next",
1236
+ ...nextItems.map((item) => `- ${item}`),
1237
+ "",
1238
+ "### Later",
1239
+ "- Use this section for medium-term scaling themes, major migrations, or cross-team architecture investments.",
1240
+ "",
1241
+ "### Backbone Maintenance",
1242
+ "- Keep PRODUCT.md, ARCHITECTURE.md, ENGINEERING_RULES.md, and TECH.md aligned when direction or structure changes.",
1243
+ "- Link major roadmap themes back to specs and ADRs instead of burying them in chat-only planning.",
1244
+ "<!-- cbx:roadmap:foundation:end -->",
1245
+ "",
1246
+ ].join("\n");
1247
+ }
841
1248
  function buildEngineeringRulesTemplate() {
842
1249
  return [
843
1250
  "# Engineering Rules",
@@ -920,21 +1327,122 @@ function buildEngineeringRulesTemplate() {
920
1327
  "",
921
1328
  "- `TECH.md` is generated from current codebase reality.",
922
1329
  "- Re-run `cbx rules tech-md --overwrite` after major stack or architecture changes.",
1330
+ "",
1331
+ "<!-- cbx:architecture:rules:start version=1 profile=bootstrap -->",
1332
+ "## 10) Architecture Contract (auto-managed)",
1333
+ "",
1334
+ "- Declared style: bootstrap placeholder. Re-run `cbx build architecture --platform <codex|claude|gemini|copilot>` to refresh this contract from the repo.",
1335
+ "- Design-system source of truth: bootstrap placeholder.",
1336
+ "- Dependency direction rules:",
1337
+ " - Replace this placeholder with the managed architecture block when architecture generation runs.",
1338
+ "- Module and package boundaries to preserve:",
1339
+ " - Replace this placeholder with the managed architecture block when architecture generation runs.",
1340
+ "- Testability expectations:",
1341
+ " - Replace this placeholder with the managed architecture block when architecture generation runs.",
1342
+ "- Doc refresh policy:",
1343
+ " - Update this section when architecture, scale, boundaries, design-system rules, or testing strategy changes.",
1344
+ "<!-- cbx:architecture:rules:end -->",
923
1345
  "<!-- cbx:engineering:rules:end -->",
924
1346
  "",
925
1347
  ].join("\n");
926
1348
  }
927
- function buildEngineeringRulesManagedBlock({ platform, engineeringRulesFilePath, techMdFilePath, ruleFilePath, }) {
1349
+ function buildProductTemplate(snapshot, specRoots = []) {
1350
+ return [
1351
+ "# Product",
1352
+ "",
1353
+ "This file is the durable product backbone for the project.",
1354
+ "",
1355
+ buildProductFoundationSection(snapshot, specRoots).trimEnd(),
1356
+ "",
1357
+ ].join("\n");
1358
+ }
1359
+ function buildArchitectureDocTemplate(snapshot, specRoots = []) {
1360
+ return [
1361
+ "# Architecture",
1362
+ "",
1363
+ "This file captures the accepted architecture backbone for the project.",
1364
+ "",
1365
+ buildArchitectureDocSection(snapshot, specRoots).trimEnd(),
1366
+ "",
1367
+ ].join("\n");
1368
+ }
1369
+ function buildRoadmapTemplate(snapshot, specRoots = []) {
1370
+ return [
1371
+ "# Roadmap",
1372
+ "",
1373
+ "This file captures the living delivery backbone for medium-term product and architecture work.",
1374
+ "",
1375
+ buildRoadmapFoundationSection(snapshot, specRoots).trimEnd(),
1376
+ "",
1377
+ ].join("\n");
1378
+ }
1379
+ function buildAdrReadme() {
1380
+ return [
1381
+ "# Architecture Decision Records",
1382
+ "",
1383
+ "Use this directory for durable decisions that future contributors and agents need to preserve.",
1384
+ "",
1385
+ "## When to add an ADR",
1386
+ "",
1387
+ "- Architecture style or boundary changes",
1388
+ "- Data model or persistence strategy changes",
1389
+ "- Deployment or scaling model changes",
1390
+ "- Design-system ownership or shared UX pattern changes",
1391
+ "",
1392
+ "## Suggested format",
1393
+ "",
1394
+ "1. Context",
1395
+ "2. Decision",
1396
+ "3. Consequences",
1397
+ "4. Validation",
1398
+ "",
1399
+ "Start with `0000-template.md` and create numbered follow-up ADRs for accepted decisions.",
1400
+ "",
1401
+ ].join("\n");
1402
+ }
1403
+ function buildAdrTemplate() {
1404
+ return [
1405
+ "# ADR 0000: Title",
1406
+ "",
1407
+ "## Status",
1408
+ "",
1409
+ "Proposed",
1410
+ "",
1411
+ "## Context",
1412
+ "",
1413
+ "- What problem or pressure led to this decision?",
1414
+ "",
1415
+ "## Decision",
1416
+ "",
1417
+ "- What is the chosen direction?",
1418
+ "",
1419
+ "## Consequences",
1420
+ "",
1421
+ "- What tradeoffs, benefits, or costs follow from this choice?",
1422
+ "",
1423
+ "## Validation",
1424
+ "",
1425
+ "- How will the team know this decision is working?",
1426
+ "",
1427
+ ].join("\n");
1428
+ }
1429
+ function buildEngineeringRulesManagedBlock({ platform, productFilePath, architectureFilePath, engineeringRulesFilePath, techMdFilePath, roadmapFilePath, ruleFilePath, }) {
1430
+ const productRef = toPosixPath(path.resolve(productFilePath));
1431
+ const architectureRef = toPosixPath(path.resolve(architectureFilePath));
928
1432
  const engineeringRef = toPosixPath(path.resolve(engineeringRulesFilePath));
929
1433
  const techRef = toPosixPath(path.resolve(techMdFilePath));
1434
+ const roadmapRef = toPosixPath(path.resolve(roadmapFilePath));
930
1435
  const ruleRef = toPosixPath(path.resolve(ruleFilePath));
931
1436
  return [
932
1437
  `<!-- cbx:engineering:auto:start platform=${platform} version=1 -->`,
933
1438
  "## Engineering Guardrails (auto-managed)",
934
1439
  "Apply these before planning, coding, review, and release:",
935
1440
  "",
1441
+ `- Product backbone: \`${productRef}\``,
1442
+ `- Accepted architecture: \`${architectureRef}\``,
936
1443
  `- Required baseline: \`${engineeringRef}\``,
937
1444
  `- Project tech map: \`${techRef}\``,
1445
+ `- Delivery roadmap: \`${roadmapRef}\``,
938
1446
  `- Active platform rule file: \`${ruleRef}\``,
939
1447
  "",
940
1448
  "Hard policy:",
@@ -942,10 +1450,11 @@ function buildEngineeringRulesManagedBlock({ platform, engineeringRulesFilePath,
942
1450
  "2. Keep architecture simple (KISS) and avoid speculative work (YAGNI).",
943
1451
  "3. Apply SOLID pragmatically to reduce change risk, not add ceremony.",
944
1452
  "4. Use clear naming with focused responsibilities and explicit boundaries.",
945
- "5. Require validation evidence (lint/types/tests) before merge.",
946
- "6. Use Decision Log response style.",
947
- "7. Every Decision Log must include a `Skills Used` section listing skill, workflow, or agent names.",
948
- "8. If no skill loaded, `Skills Used: none` is mandatory.",
1453
+ "5. For non-trivial work, read PRODUCT.md, ENGINEERING_RULES.md, ARCHITECTURE.md, and TECH.md in that order when they exist before planning or implementation.",
1454
+ "6. Require validation evidence (lint/types/tests) before merge.",
1455
+ "7. Use Decision Log response style.",
1456
+ "8. Every Decision Log must include a `Skills Used` section listing skill, workflow, or agent names.",
1457
+ "9. If no skill loaded, `Skills Used: none` is mandatory.",
949
1458
  "",
950
1459
  "<!-- cbx:engineering:auto:end -->",
951
1460
  ].join("\n");
@@ -1032,11 +1541,14 @@ async function upsertEngineeringRulesFile({ targetPath, template, overwrite = fa
1032
1541
  filePath: targetPath,
1033
1542
  };
1034
1543
  }
1035
- async function upsertEngineeringRulesBlock({ ruleFilePath, platform, engineeringRulesFilePath, techMdFilePath, dryRun = false, }) {
1544
+ async function upsertEngineeringRulesBlock({ ruleFilePath, platform, productFilePath, architectureFilePath, engineeringRulesFilePath, techMdFilePath, roadmapFilePath, dryRun = false, }) {
1036
1545
  const block = buildEngineeringRulesManagedBlock({
1037
1546
  platform,
1547
+ productFilePath,
1548
+ architectureFilePath,
1038
1549
  engineeringRulesFilePath,
1039
1550
  techMdFilePath,
1551
+ roadmapFilePath,
1040
1552
  ruleFilePath,
1041
1553
  });
1042
1554
  const exists = await pathExists(ruleFilePath);
@@ -1080,6 +1592,160 @@ async function upsertEngineeringRulesBlock({ ruleFilePath, platform, engineering
1080
1592
  warnings,
1081
1593
  };
1082
1594
  }
1595
+ function extractTaggedMarkerAttribute(content, startPattern, key) {
1596
+ const match = String(content || "").match(startPattern);
1597
+ if (!match || !match[0])
1598
+ return null;
1599
+ const attributeMatch = match[0].match(new RegExp(`${key}=([^\\s>]+)`));
1600
+ return attributeMatch?.[1] || null;
1601
+ }
1602
+ async function upsertTaggedSectionInFile({ targetPath, initialContent, block, startPattern, endPattern, dryRun = false, }) {
1603
+ const exists = await pathExists(targetPath);
1604
+ const original = exists ? await readFile(targetPath, "utf8") : initialContent;
1605
+ const analysis = analyzeTaggedBlock(original, startPattern, endPattern);
1606
+ let nextContent = original;
1607
+ if (!exists || analysis.status === "absent") {
1608
+ const trimmed = String(original || "").trimEnd();
1609
+ nextContent =
1610
+ trimmed.length > 0 ? `${trimmed}\n\n${block}\n` : `${block}\n`;
1611
+ }
1612
+ else if (analysis.range) {
1613
+ nextContent = `${original.slice(0, analysis.range.start)}${block}${original.slice(analysis.range.end)}`;
1614
+ }
1615
+ else {
1616
+ const trimmed = String(original || "").trimEnd();
1617
+ nextContent =
1618
+ trimmed.length > 0 ? `${trimmed}\n\n${block}\n` : `${block}\n`;
1619
+ }
1620
+ if (nextContent === original) {
1621
+ return {
1622
+ action: "unchanged",
1623
+ filePath: targetPath,
1624
+ };
1625
+ }
1626
+ if (!dryRun) {
1627
+ await mkdir(path.dirname(targetPath), { recursive: true });
1628
+ await writeFile(targetPath, nextContent, "utf8");
1629
+ }
1630
+ return {
1631
+ action: exists
1632
+ ? dryRun
1633
+ ? "would-patch"
1634
+ : "patched"
1635
+ : dryRun
1636
+ ? "would-create"
1637
+ : "created",
1638
+ filePath: targetPath,
1639
+ };
1640
+ }
1641
+ function buildArchitectureBuildMetadata({ platform, researchMode, productProfileHash, architectureDocHash, rulesProfileHash, techSnapshotHash, roadmapProfileHash, }) {
1642
+ return {
1643
+ schemaVersion: 2,
1644
+ generatedBy: "cbx build architecture",
1645
+ generatedAt: new Date().toISOString(),
1646
+ platform,
1647
+ researchMode,
1648
+ productProfileHash,
1649
+ architectureDocHash,
1650
+ rulesProfileHash,
1651
+ techSnapshotHash,
1652
+ roadmapProfileHash,
1653
+ };
1654
+ }
1655
+ async function ensureArchitectureDocScaffold({ workspaceRoot, snapshot, specRoots = [], overwrite = false, dryRun = false, }) {
1656
+ const productPath = path.join(workspaceRoot, "PRODUCT.md");
1657
+ const architectureDocPath = path.join(workspaceRoot, "ARCHITECTURE.md");
1658
+ const engineeringRulesPath = path.join(workspaceRoot, "ENGINEERING_RULES.md");
1659
+ const techMdPath = path.join(workspaceRoot, "TECH.md");
1660
+ const roadmapPath = path.join(workspaceRoot, "ROADMAP.md");
1661
+ const adrDir = path.join(workspaceRoot, "docs", "adr");
1662
+ const adrReadmePath = path.join(adrDir, "README.md");
1663
+ const adrTemplatePath = path.join(adrDir, "0000-template.md");
1664
+ const productResult = await upsertTaggedSectionInFile({
1665
+ targetPath: productPath,
1666
+ initialContent: `${buildProductTemplate(snapshot, specRoots)}\n`,
1667
+ block: buildProductFoundationSection(snapshot, specRoots),
1668
+ startPattern: PRODUCT_FOUNDATION_BLOCK_START_RE,
1669
+ endPattern: PRODUCT_FOUNDATION_BLOCK_END_RE,
1670
+ dryRun,
1671
+ });
1672
+ const architectureDocResult = await upsertTaggedSectionInFile({
1673
+ targetPath: architectureDocPath,
1674
+ initialContent: `${buildArchitectureDocTemplate(snapshot, specRoots)}\n`,
1675
+ block: buildArchitectureDocSection(snapshot, specRoots),
1676
+ startPattern: ARCHITECTURE_DOC_BLOCK_START_RE,
1677
+ endPattern: ARCHITECTURE_DOC_BLOCK_END_RE,
1678
+ dryRun,
1679
+ });
1680
+ const rulesTemplate = buildEngineeringRulesTemplate();
1681
+ const rulesFileResult = await upsertEngineeringRulesFile({
1682
+ targetPath: engineeringRulesPath,
1683
+ template: rulesTemplate,
1684
+ overwrite,
1685
+ dryRun,
1686
+ });
1687
+ const rulesArchitectureResult = await upsertTaggedSectionInFile({
1688
+ targetPath: engineeringRulesPath,
1689
+ initialContent: `${rulesTemplate}\n`,
1690
+ block: buildEngineeringArchitectureSection(snapshot),
1691
+ startPattern: ENGINEERING_ARCHITECTURE_BLOCK_START_RE,
1692
+ endPattern: ENGINEERING_ARCHITECTURE_BLOCK_END_RE,
1693
+ dryRun,
1694
+ });
1695
+ const techContent = `${buildTechMd(snapshot)}\n`;
1696
+ const techResult = await writeTextFile({
1697
+ targetPath: techMdPath,
1698
+ content: techContent,
1699
+ overwrite,
1700
+ dryRun,
1701
+ });
1702
+ const techArchitectureResult = await upsertTaggedSectionInFile({
1703
+ targetPath: techMdPath,
1704
+ initialContent: techContent,
1705
+ block: buildTechArchitectureSection(snapshot),
1706
+ startPattern: TECH_ARCHITECTURE_BLOCK_START_RE,
1707
+ endPattern: TECH_ARCHITECTURE_BLOCK_END_RE,
1708
+ dryRun,
1709
+ });
1710
+ const roadmapResult = await upsertTaggedSectionInFile({
1711
+ targetPath: roadmapPath,
1712
+ initialContent: `${buildRoadmapTemplate(snapshot, specRoots)}\n`,
1713
+ block: buildRoadmapFoundationSection(snapshot, specRoots),
1714
+ startPattern: ROADMAP_FOUNDATION_BLOCK_START_RE,
1715
+ endPattern: ROADMAP_FOUNDATION_BLOCK_END_RE,
1716
+ dryRun,
1717
+ });
1718
+ const adrReadmeResult = await writeTextFile({
1719
+ targetPath: adrReadmePath,
1720
+ content: `${buildAdrReadme()}\n`,
1721
+ overwrite,
1722
+ dryRun,
1723
+ });
1724
+ const adrTemplateResult = await writeTextFile({
1725
+ targetPath: adrTemplatePath,
1726
+ content: `${buildAdrTemplate()}\n`,
1727
+ overwrite,
1728
+ dryRun,
1729
+ });
1730
+ return {
1731
+ productPath,
1732
+ architectureDocPath,
1733
+ engineeringRulesPath,
1734
+ techMdPath,
1735
+ roadmapPath,
1736
+ adrReadmePath,
1737
+ adrTemplatePath,
1738
+ productResult,
1739
+ architectureDocResult,
1740
+ rulesFileResult,
1741
+ rulesArchitectureResult,
1742
+ techResult,
1743
+ techArchitectureResult,
1744
+ roadmapResult,
1745
+ adrReadmeResult,
1746
+ adrTemplateResult,
1747
+ };
1748
+ }
1083
1749
  function normalizeTechPackageName(value) {
1084
1750
  if (value === undefined || value === null)
1085
1751
  return null;
@@ -1963,7 +2629,7 @@ function inferRecommendedSkills(snapshot) {
1963
2629
  hasFramework("TypeORM") ||
1964
2630
  hasFramework("Mongoose") ||
1965
2631
  hasFramework("SQLAlchemy")) {
1966
- recommended.add("database-skills");
2632
+ recommended.add("database-design");
1967
2633
  }
1968
2634
  if (recommended.size === 0) {
1969
2635
  recommended.add("clean-code");
@@ -2217,6 +2883,8 @@ function buildTechMd(snapshot, { compact = false } = {}) {
2217
2883
  lines.push(`- Suggested install profile: \`${contextBudget.suggestedProfile}\``);
2218
2884
  lines.push("- Use `--all-skills` only when task scope clearly requires full catalog breadth.");
2219
2885
  lines.push("");
2886
+ lines.push(buildTechArchitectureSection(snapshot).trimEnd());
2887
+ lines.push("");
2220
2888
  if (!compact) {
2221
2889
  lines.push("## Package Signals");
2222
2890
  appendTechPackageSection(lines, "JavaScript / TypeScript (package.json)", snapshot.packageSignals.javascript);
@@ -6649,14 +7317,6 @@ async function performWorkflowInstall(options, { postmanSelectionOverride = null
6649
7317
  dryRun,
6650
7318
  cwd,
6651
7319
  });
6652
- const engineeringArtifactsResult = await upsertEngineeringArtifacts({
6653
- platform,
6654
- scope: ruleScope,
6655
- overwrite: false,
6656
- dryRun,
6657
- skipTech: false,
6658
- cwd,
6659
- });
6660
7320
  const postmanSetupResult = await configurePostmanInstallArtifacts({
6661
7321
  platform,
6662
7322
  scope,
@@ -6698,7 +7358,7 @@ async function performWorkflowInstall(options, { postmanSelectionOverride = null
6698
7358
  bundleId,
6699
7359
  installResult,
6700
7360
  syncResult,
6701
- engineeringArtifactsResult,
7361
+ engineeringArtifactsResult: null,
6702
7362
  postmanSetupResult,
6703
7363
  terminalVerificationRuleResult,
6704
7364
  };
@@ -6726,10 +7386,7 @@ async function runWorkflowInstall(options) {
6726
7386
  dryRun: result.dryRun,
6727
7387
  });
6728
7388
  printRuleSyncResult(result.syncResult);
6729
- printInstallEngineeringSummary({
6730
- engineeringResults: result.engineeringArtifactsResult.engineeringResults,
6731
- techResult: result.engineeringArtifactsResult.techResult,
6732
- });
7389
+ printInstallDocumentationNotice();
6733
7390
  printPostmanSetupSummary({
6734
7391
  postmanSetup: result.postmanSetupResult,
6735
7392
  });
@@ -9588,12 +10245,24 @@ function printInstallEngineeringSummary({ engineeringResults, techResult }) {
9588
10245
  console.log(`- TECH scan files: ${techResult.snapshot.scannedFiles}`);
9589
10246
  }
9590
10247
  }
10248
+ function printInstallDocumentationNotice() {
10249
+ console.log("\nProject backbone docs:");
10250
+ console.log("- Install only wires the rule references and workflow assets.");
10251
+ console.log("- Use `cbx rules init` to scaffold ENGINEERING_RULES.md and TECH.md, or `cbx build architecture --platform <codex|claude|gemini|copilot>` to generate PRODUCT.md, ARCHITECTURE.md, ENGINEERING_RULES.md, TECH.md, ROADMAP.md, and ADR scaffolds.");
10252
+ }
9591
10253
  async function upsertEngineeringArtifacts({ platform, scope, overwrite = false, skipTech = false, dryRun = false, cwd = process.cwd(), }) {
9592
10254
  const ruleFilePath = await resolveRuleFilePath(platform, scope, cwd);
9593
10255
  if (!ruleFilePath)
9594
10256
  throw new Error(`No rule file configured for platform '${platform}'.`);
9595
10257
  const workspaceRoot = findWorkspaceRoot(cwd);
9596
- const techMdPath = path.join(workspaceRoot, "TECH.md");
10258
+ const snapshot = await collectTechSnapshot(workspaceRoot);
10259
+ const scaffold = await ensureArchitectureDocScaffold({
10260
+ workspaceRoot,
10261
+ snapshot,
10262
+ specRoots: [],
10263
+ overwrite,
10264
+ dryRun,
10265
+ });
9597
10266
  const targets = [{ ruleFilePath }];
9598
10267
  if (scope === "global") {
9599
10268
  const workspaceRuleFile = await resolveWorkspaceRuleFileForGlobalScope(platform, cwd);
@@ -9603,42 +10272,31 @@ async function upsertEngineeringArtifacts({ platform, scope, overwrite = false,
9603
10272
  targets.push({ ruleFilePath: workspaceRuleFile });
9604
10273
  }
9605
10274
  }
9606
- const template = buildEngineeringRulesTemplate();
9607
10275
  const engineeringResults = [];
9608
10276
  for (const target of targets) {
9609
- const rulesFilePath = path.join(path.dirname(target.ruleFilePath), "ENGINEERING_RULES.md");
9610
- const rulesFileResult = await upsertEngineeringRulesFile({
9611
- targetPath: rulesFilePath,
9612
- template,
9613
- overwrite,
9614
- dryRun,
9615
- });
9616
10277
  const blockResult = await upsertEngineeringRulesBlock({
9617
10278
  ruleFilePath: target.ruleFilePath,
9618
10279
  platform,
9619
- engineeringRulesFilePath: rulesFilePath,
9620
- techMdFilePath: techMdPath,
10280
+ productFilePath: scaffold.productPath,
10281
+ architectureFilePath: scaffold.architectureDocPath,
10282
+ engineeringRulesFilePath: scaffold.engineeringRulesPath,
10283
+ techMdFilePath: scaffold.techMdPath,
10284
+ roadmapFilePath: scaffold.roadmapPath,
9621
10285
  dryRun,
9622
10286
  });
9623
10287
  engineeringResults.push({
9624
10288
  ruleFilePath: target.ruleFilePath,
9625
- rulesFilePath,
9626
- rulesFileResult,
10289
+ rulesFilePath: scaffold.engineeringRulesPath,
10290
+ rulesFileResult: scaffold.rulesArchitectureResult.action === "unchanged"
10291
+ ? scaffold.rulesFileResult
10292
+ : scaffold.rulesArchitectureResult,
9627
10293
  blockResult,
9628
10294
  });
9629
10295
  }
9630
10296
  let techResult = null;
9631
10297
  if (!skipTech) {
9632
- const snapshot = await collectTechSnapshot(workspaceRoot);
9633
- const content = buildTechMd(snapshot);
9634
- const fileResult = await writeTextFile({
9635
- targetPath: techMdPath,
9636
- content: `${content}\n`,
9637
- overwrite,
9638
- dryRun,
9639
- });
9640
10298
  techResult = {
9641
- ...fileResult,
10299
+ ...scaffold.techArchitectureResult,
9642
10300
  snapshot,
9643
10301
  };
9644
10302
  }
@@ -9714,6 +10372,659 @@ async function runRulesTechMd(options) {
9714
10372
  process.exit(1);
9715
10373
  }
9716
10374
  }
10375
+ function normalizeArchitectureBuildPlatform(value) {
10376
+ const normalized = normalizePlatform(value);
10377
+ if (!normalized || !ARCHITECTURE_BUILD_PLATFORMS.has(normalized)) {
10378
+ throw new Error("Architecture build platform must be one of: codex, claude, gemini, copilot.");
10379
+ }
10380
+ return normalized;
10381
+ }
10382
+ function normalizeArchitectureResearchMode(value) {
10383
+ const normalized = String(value || "auto")
10384
+ .trim()
10385
+ .toLowerCase();
10386
+ if (!["auto", "always", "never"].includes(normalized)) {
10387
+ throw new Error("Research mode must be one of: auto, always, never.");
10388
+ }
10389
+ return normalized;
10390
+ }
10391
+ async function listSpecPackRoots(workspaceRoot) {
10392
+ const specsRoot = path.join(workspaceRoot, "docs", "specs");
10393
+ if (!(await pathExists(specsRoot)))
10394
+ return [];
10395
+ const entries = await readdir(specsRoot, { withFileTypes: true });
10396
+ return entries
10397
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
10398
+ .map((entry) => `docs/specs/${entry.name}`)
10399
+ .sort((a, b) => a.localeCompare(b))
10400
+ .slice(0, 8);
10401
+ }
10402
+ function resolveArchitectureConditionalSkills(snapshot, specRoots, researchMode) {
10403
+ const conditional = [];
10404
+ const frameworks = new Set(snapshot.frameworks || []);
10405
+ const topDirs = new Set(snapshot.topDirs || []);
10406
+ const jsPackages = new Set(snapshot.packageSignals?.javascript || []);
10407
+ if (snapshot.isMcpServer ||
10408
+ frameworks.has("Next.js") ||
10409
+ frameworks.has("NestJS") ||
10410
+ frameworks.has("FastAPI") ||
10411
+ topDirs.has("api") ||
10412
+ topDirs.has("routes") ||
10413
+ topDirs.has("controllers")) {
10414
+ conditional.push("api-design");
10415
+ }
10416
+ if (topDirs.has("db") ||
10417
+ topDirs.has("database") ||
10418
+ topDirs.has("migrations") ||
10419
+ jsPackages.has("prisma") ||
10420
+ jsPackages.has("drizzle-orm") ||
10421
+ frameworks.has("SQLAlchemy")) {
10422
+ conditional.push("database-design");
10423
+ }
10424
+ if (specRoots.length > 0) {
10425
+ conditional.push("sadd");
10426
+ }
10427
+ if (researchMode === "always") {
10428
+ conditional.push("deep-research");
10429
+ }
10430
+ else if (researchMode === "auto" &&
10431
+ !snapshot.readmeExcerpt &&
10432
+ snapshot.architectureByApp.every((item) => (item.architectureSignals || []).length === 0)) {
10433
+ conditional.push("deep-research");
10434
+ }
10435
+ return [...new Set(conditional)];
10436
+ }
10437
+ async function resolveArchitectureSkillPathHints(platform, cwd, skillIds) {
10438
+ const profilePaths = await resolveProfilePaths(platform, "project", cwd);
10439
+ const skillsDir = profilePaths.skillsDir;
10440
+ if (!skillsDir)
10441
+ return [];
10442
+ return skillIds
10443
+ .map((skillId) => path.join(skillsDir, skillId, "SKILL.md"))
10444
+ .map((filePath) => toPosixPath(path.relative(findWorkspaceRoot(cwd), filePath)));
10445
+ }
10446
+ function buildArchitecturePrompt({ platform, workspaceRoot, snapshot, specRoots, researchMode, coreSkills, conditionalSkills, skillPathHints, }) {
10447
+ const productPath = "PRODUCT.md";
10448
+ const architecturePath = "ARCHITECTURE.md";
10449
+ const rulesPath = "ENGINEERING_RULES.md";
10450
+ const techPath = "TECH.md";
10451
+ const roadmapPath = "ROADMAP.md";
10452
+ const adrReadmePath = "docs/adr/README.md";
10453
+ const architectureSignals = snapshot.architectureByApp
10454
+ .filter((item) => (item.architectureSignals || []).length > 0)
10455
+ .map((item) => {
10456
+ const label = item.rootPath === "." ? "repo root" : item.rootPath;
10457
+ return `${label}: ${item.architectureSignals.join(", ")}`;
10458
+ });
10459
+ return [
10460
+ `You are running inside ${platform}.`,
10461
+ "",
10462
+ "Objective:",
10463
+ `- Inspect the repository at ${toPosixPath(workspaceRoot)} and refresh the scalable project backbone in ${productPath}, ${architecturePath}, ${rulesPath}, ${techPath}, and ${roadmapPath}.`,
10464
+ "- Keep PRODUCT.md focused on intent, ARCHITECTURE.md on accepted structure, ENGINEERING_RULES.md on normative rules, TECH.md on current-state evidence, and ROADMAP.md on delivery themes.",
10465
+ "- Preserve manual content outside the managed `cbx:*` markers.",
10466
+ "",
10467
+ "Required skill bundle:",
10468
+ `- Load these exact skill IDs first: ${coreSkills.map((skillId) => `\`${skillId}\``).join(", ")}`,
10469
+ conditionalSkills.length > 0
10470
+ ? `- Additional skills to load now: ${conditionalSkills.map((skillId) => `\`${skillId}\``).join(", ")}`
10471
+ : "- Conditional skills to load now: none",
10472
+ skillPathHints.length > 0
10473
+ ? `- Local skill file hints if installed: ${skillPathHints.map((hint) => `\`${hint}\``).join(", ")}`
10474
+ : "- Local skill file hints if installed: none detected",
10475
+ "- Treat the route and skill bundle as already resolved. Do not begin with route discovery.",
10476
+ "",
10477
+ "Repository context:",
10478
+ `- Frameworks: ${snapshot.frameworks.length > 0 ? snapshot.frameworks.join(", ") : "none detected"}`,
10479
+ `- Top directories: ${snapshot.topDirs.length > 0 ? snapshot.topDirs.join(", ") : "none detected"}`,
10480
+ `- Existing spec packs: ${specRoots.length > 0 ? specRoots.join(", ") : "none detected"}`,
10481
+ architectureSignals.length > 0
10482
+ ? `- Architecture signals: ${architectureSignals.join(" | ")}`
10483
+ : "- Architecture signals: none confidently inferred from the repo scan",
10484
+ "",
10485
+ "Execution contract:",
10486
+ `1. Read ${productPath}, ${rulesPath}, ${architecturePath}, and ${techPath} in that order when they exist.`,
10487
+ "2. Inspect the repo before making architecture claims.",
10488
+ "3. Update only the content between the existing managed markers in the backbone docs and preserve the marker lines themselves, including their hash metadata.",
10489
+ "4. In PRODUCT.md, state product scope, primary surfaces, users or operators, core journeys, success signals, and product guardrails.",
10490
+ "5. In ARCHITECTURE.md, state accepted architecture style, bounded contexts, stable decision areas, ADR linkage, and add at least one Mermaid architecture diagram if the repo is non-trivial.",
10491
+ "6. In ENGINEERING_RULES.md, state architecture style, dependency rules, feature or module structure rules, design-system source of truth, testability expectations, and doc refresh policy.",
10492
+ "7. In TECH.md, update architecture snapshot, module or app topology, flow narratives, Mermaid diagrams, and scaling or deployment notes.",
10493
+ "8. In ROADMAP.md, capture current delivery themes, active spec-driven work, and major architecture follow-ups without turning it into a speculative wishlist.",
10494
+ researchMode === "never"
10495
+ ? "9. Stay repo-only. Do not use outside research."
10496
+ : "9. Use repo evidence first. Use official docs when needed. Treat Reddit or community sources only as labeled secondary evidence.",
10497
+ researchMode === "always"
10498
+ ? "10. Include an external research evidence subsection in TECH.md with clearly labeled primary and secondary evidence."
10499
+ : "10. Include external research notes only if they materially informed the architecture update.",
10500
+ "11. If the project clearly follows Clean Architecture, feature-first modules, or another stable structure, make that explicit so future implementation stays consistent.",
10501
+ `12. Ensure ${adrReadmePath} exists as the ADR entrypoint and mention ADR follow-up when the repo lacks decision history.`,
10502
+ "",
10503
+ "Return one JSON object on the last line with this shape:",
10504
+ '{"files_written":["PRODUCT.md","ARCHITECTURE.md","ENGINEERING_RULES.md","TECH.md","ROADMAP.md","docs/adr/README.md"],"research_used":false,"gaps":[],"next_actions":[]}',
10505
+ "",
10506
+ "Do not emit placeholder TODOs in the managed sections.",
10507
+ ].join("\n");
10508
+ }
10509
+ async function execFileCapture(command, args, options = {}) {
10510
+ try {
10511
+ const result = await execFile(command, args, {
10512
+ ...options,
10513
+ maxBuffer: 8 * 1024 * 1024,
10514
+ });
10515
+ return {
10516
+ ok: true,
10517
+ stdout: result.stdout || "",
10518
+ stderr: result.stderr || "",
10519
+ };
10520
+ }
10521
+ catch (error) {
10522
+ if (error?.code === "ENOENT") {
10523
+ throw new Error(`Required CLI '${command}' is not installed or not on PATH.`);
10524
+ }
10525
+ return {
10526
+ ok: false,
10527
+ stdout: error?.stdout || "",
10528
+ stderr: error?.stderr || "",
10529
+ code: error?.code || 1,
10530
+ };
10531
+ }
10532
+ }
10533
+ async function spawnCapture(command, args, options = {}) {
10534
+ const { cwd, env, streamOutput = false } = options;
10535
+ return await new Promise((resolve, reject) => {
10536
+ let stdout = "";
10537
+ let stderr = "";
10538
+ const child = spawn(command, args, {
10539
+ cwd,
10540
+ env,
10541
+ stdio: ["ignore", "pipe", "pipe"],
10542
+ });
10543
+ child.stdout.on("data", (chunk) => {
10544
+ const text = chunk.toString();
10545
+ stdout += text;
10546
+ if (streamOutput)
10547
+ process.stdout.write(text);
10548
+ });
10549
+ child.stderr.on("data", (chunk) => {
10550
+ const text = chunk.toString();
10551
+ stderr += text;
10552
+ if (streamOutput)
10553
+ process.stderr.write(text);
10554
+ });
10555
+ child.on("error", (error) => {
10556
+ if (error?.code === "ENOENT") {
10557
+ reject(new Error(`Required CLI '${command}' is not installed or not on PATH.`));
10558
+ return;
10559
+ }
10560
+ reject(error);
10561
+ });
10562
+ child.on("close", (code) => {
10563
+ resolve({
10564
+ ok: code === 0,
10565
+ stdout,
10566
+ stderr,
10567
+ code: code ?? 1,
10568
+ });
10569
+ });
10570
+ });
10571
+ }
10572
+ function explainArchitectureBuildFailure(platform, execution) {
10573
+ const combined = String(`${execution.stderr || ""}\n${execution.stdout || ""}`.trim());
10574
+ const notes = [];
10575
+ if (platform === "gemini") {
10576
+ if (combined.includes("Error during discovery for MCP server") ||
10577
+ combined.includes("[MCP error]")) {
10578
+ notes.push("Gemini CLI is failing while loading MCP servers from your Gemini settings. Start the required MCP runtime(s) first or disable the broken server entries in `.gemini/settings.json` before retrying.");
10579
+ }
10580
+ if (combined.includes("cloudaicompanion.companions.generateChat") ||
10581
+ combined.includes("PERMISSION_DENIED") ||
10582
+ combined.includes("403")) {
10583
+ notes.push("Gemini CLI reached Google auth, but the active account or project cannot generate chat content. Re-authenticate Gemini CLI with a permitted account or configure a supported Gemini API credential and project before retrying.");
10584
+ }
10585
+ }
10586
+ if (platform === "claude" && combined.includes("permission")) {
10587
+ notes.push("Claude CLI appears to be blocked by its own permission model. Re-run in a Claude environment that allows non-interactive edits for this workspace.");
10588
+ }
10589
+ if (notes.length === 0) {
10590
+ return `Architecture build failed via ${platform}. ${combined}`.trim();
10591
+ }
10592
+ return [
10593
+ `Architecture build failed via ${platform}.`,
10594
+ ...notes.map((note) => `- ${note}`),
10595
+ combined ? `Raw CLI output:\n${combined}` : "",
10596
+ ]
10597
+ .filter(Boolean)
10598
+ .join("\n");
10599
+ }
10600
+ async function probeArchitectureAdapter(platform, cwd) {
10601
+ if (platform === "codex") {
10602
+ const help = await execFileCapture("codex", ["exec", "--help"], { cwd });
10603
+ return {
10604
+ platform,
10605
+ binary: "codex",
10606
+ helpText: `${help.stdout}\n${help.stderr}`.trim(),
10607
+ buildInvocation(prompt) {
10608
+ const args = ["exec"];
10609
+ if (this.helpText.includes("--skip-git-repo-check")) {
10610
+ args.push("--skip-git-repo-check");
10611
+ }
10612
+ args.push(prompt);
10613
+ return args;
10614
+ },
10615
+ };
10616
+ }
10617
+ if (platform === "claude") {
10618
+ const help = await execFileCapture("claude", ["--help"], { cwd });
10619
+ const helpText = `${help.stdout}\n${help.stderr}`.trim();
10620
+ const printFlag = helpText.includes("--print")
10621
+ ? "--print"
10622
+ : helpText.includes(" -p") || helpText.includes("\n-p")
10623
+ ? "-p"
10624
+ : null;
10625
+ if (!printFlag) {
10626
+ throw new Error("Claude CLI was found, but no headless print mode was detected. Install a Claude Code build that supports --print or -p.");
10627
+ }
10628
+ return {
10629
+ platform,
10630
+ binary: "claude",
10631
+ helpText,
10632
+ buildInvocation(prompt) {
10633
+ return [printFlag, prompt];
10634
+ },
10635
+ };
10636
+ }
10637
+ if (platform === "gemini") {
10638
+ const help = await execFileCapture("gemini", ["--help"], { cwd });
10639
+ const helpText = `${help.stdout}\n${help.stderr}`.trim();
10640
+ const promptFlag = helpText.includes("--prompt")
10641
+ ? "--prompt"
10642
+ : helpText.includes(" -p") || helpText.includes("\n-p")
10643
+ ? "-p"
10644
+ : null;
10645
+ if (!promptFlag) {
10646
+ throw new Error("Gemini CLI was found, but no prompt flag was detected. Install a Gemini CLI build with --prompt or -p support.");
10647
+ }
10648
+ return {
10649
+ platform,
10650
+ binary: "gemini",
10651
+ helpText,
10652
+ buildInvocation(prompt) {
10653
+ return [promptFlag, prompt];
10654
+ },
10655
+ };
10656
+ }
10657
+ const help = await execFileCapture("copilot", ["--help"], { cwd });
10658
+ const helpText = `${help.stdout}\n${help.stderr}`.trim();
10659
+ const supportsPrompt = helpText.includes("--prompt");
10660
+ const supportsChatPrompt = helpText.includes("chat") && helpText.includes("--prompt");
10661
+ if (!supportsPrompt && !supportsChatPrompt) {
10662
+ throw new Error("Copilot CLI was found, but no headless prompt mode was detected. This command requires a native Copilot CLI surface with --prompt support.");
10663
+ }
10664
+ return {
10665
+ platform,
10666
+ binary: "copilot",
10667
+ helpText,
10668
+ buildInvocation(prompt) {
10669
+ if (supportsPrompt)
10670
+ return ["--prompt", prompt];
10671
+ return ["chat", "--prompt", prompt];
10672
+ },
10673
+ };
10674
+ }
10675
+ function normalizeArchitectureResult({ stdout, workspaceRoot, researchMode, changedFiles = [], }) {
10676
+ const trimmed = String(stdout || "").trim();
10677
+ if (trimmed) {
10678
+ const lastLine = trimmed.split(/\r?\n/).pop();
10679
+ if (lastLine && lastLine.startsWith("{") && lastLine.endsWith("}")) {
10680
+ try {
10681
+ const parsed = JSON.parse(lastLine);
10682
+ return {
10683
+ outputRoot: workspaceRoot,
10684
+ filesWritten: changedFiles.length > 0
10685
+ ? changedFiles
10686
+ : Array.isArray(parsed.files_written)
10687
+ ? parsed.files_written
10688
+ : [],
10689
+ researchUsed: typeof parsed.research_used === "boolean"
10690
+ ? parsed.research_used
10691
+ : researchMode === "always",
10692
+ gaps: Array.isArray(parsed.gaps) ? parsed.gaps : [],
10693
+ nextActions: Array.isArray(parsed.next_actions)
10694
+ ? parsed.next_actions
10695
+ : [],
10696
+ rawOutput: trimmed,
10697
+ };
10698
+ }
10699
+ catch {
10700
+ // fall through to default normalization
10701
+ }
10702
+ }
10703
+ }
10704
+ return {
10705
+ outputRoot: workspaceRoot,
10706
+ filesWritten: changedFiles,
10707
+ researchUsed: researchMode === "always",
10708
+ gaps: [],
10709
+ nextActions: [],
10710
+ rawOutput: trimmed,
10711
+ };
10712
+ }
10713
+ async function captureFileContents(filePaths) {
10714
+ const snapshot = {};
10715
+ for (const filePath of filePaths) {
10716
+ if (await pathExists(filePath)) {
10717
+ snapshot[filePath] = await readFile(filePath, "utf8");
10718
+ }
10719
+ else {
10720
+ snapshot[filePath] = null;
10721
+ }
10722
+ }
10723
+ return snapshot;
10724
+ }
10725
+ async function readArchitectureDriftStatus(workspaceRoot, snapshot) {
10726
+ const specRoots = await listSpecPackRoots(workspaceRoot);
10727
+ const productPath = path.join(workspaceRoot, "PRODUCT.md");
10728
+ const architecturePath = path.join(workspaceRoot, "ARCHITECTURE.md");
10729
+ const rulesPath = path.join(workspaceRoot, "ENGINEERING_RULES.md");
10730
+ const techPath = path.join(workspaceRoot, "TECH.md");
10731
+ const roadmapPath = path.join(workspaceRoot, "ROADMAP.md");
10732
+ const adrReadmePath = path.join(workspaceRoot, "docs", "adr", "README.md");
10733
+ const metadataPath = path.join(workspaceRoot, ".cbx", ARCHITECTURE_BUILD_METADATA_FILENAME);
10734
+ const productExists = await pathExists(productPath);
10735
+ const architectureExists = await pathExists(architecturePath);
10736
+ const rulesExists = await pathExists(rulesPath);
10737
+ const techExists = await pathExists(techPath);
10738
+ const roadmapExists = await pathExists(roadmapPath);
10739
+ const adrReadmeExists = await pathExists(adrReadmePath);
10740
+ const expectedProductHash = hashStableObject(inferProductFoundationProfile(snapshot, specRoots));
10741
+ const expectedArchitectureHash = hashStableObject(inferArchitectureDocProfile(snapshot, specRoots));
10742
+ const expectedRulesHash = hashStableObject(inferArchitectureContractProfile(snapshot));
10743
+ const expectedTechHash = hashStableObject({
10744
+ style: inferArchitectureContractProfile(snapshot).style,
10745
+ topDirs: snapshot.topDirs,
10746
+ frameworks: snapshot.frameworks,
10747
+ architectureByApp: snapshot.architectureByApp,
10748
+ });
10749
+ const expectedRoadmapHash = hashStableObject({
10750
+ topDirs: snapshot.topDirs,
10751
+ frameworks: snapshot.frameworks,
10752
+ specRoots,
10753
+ });
10754
+ const findings = [];
10755
+ let actualProductHash = null;
10756
+ let actualArchitectureHash = null;
10757
+ let actualRulesHash = null;
10758
+ let actualTechHash = null;
10759
+ let actualRoadmapHash = null;
10760
+ if (!productExists) {
10761
+ findings.push("PRODUCT.md is missing.");
10762
+ }
10763
+ else {
10764
+ const content = await readFile(productPath, "utf8");
10765
+ actualProductHash = extractTaggedMarkerAttribute(content, PRODUCT_FOUNDATION_BLOCK_START_RE, "profile");
10766
+ if (!actualProductHash) {
10767
+ findings.push("PRODUCT.md is missing the managed product foundation block.");
10768
+ }
10769
+ else if (actualProductHash !== expectedProductHash) {
10770
+ findings.push(`PRODUCT.md foundation is stale (expected ${expectedProductHash}, found ${actualProductHash}).`);
10771
+ }
10772
+ }
10773
+ if (!architectureExists) {
10774
+ findings.push("ARCHITECTURE.md is missing.");
10775
+ }
10776
+ else {
10777
+ const content = await readFile(architecturePath, "utf8");
10778
+ actualArchitectureHash = extractTaggedMarkerAttribute(content, ARCHITECTURE_DOC_BLOCK_START_RE, "profile");
10779
+ if (!actualArchitectureHash) {
10780
+ findings.push("ARCHITECTURE.md is missing the managed architecture backbone block.");
10781
+ }
10782
+ else if (actualArchitectureHash !== expectedArchitectureHash) {
10783
+ findings.push(`ARCHITECTURE.md backbone is stale (expected ${expectedArchitectureHash}, found ${actualArchitectureHash}).`);
10784
+ }
10785
+ }
10786
+ if (!rulesExists) {
10787
+ findings.push("ENGINEERING_RULES.md is missing.");
10788
+ }
10789
+ else {
10790
+ const content = await readFile(rulesPath, "utf8");
10791
+ actualRulesHash = extractTaggedMarkerAttribute(content, ENGINEERING_ARCHITECTURE_BLOCK_START_RE, "profile");
10792
+ if (!actualRulesHash) {
10793
+ findings.push("ENGINEERING_RULES.md is missing the managed architecture contract block.");
10794
+ }
10795
+ else if (actualRulesHash !== expectedRulesHash) {
10796
+ findings.push(`ENGINEERING_RULES.md architecture profile is stale (expected ${expectedRulesHash}, found ${actualRulesHash}).`);
10797
+ }
10798
+ }
10799
+ if (!techExists) {
10800
+ findings.push("TECH.md is missing.");
10801
+ }
10802
+ else {
10803
+ const content = await readFile(techPath, "utf8");
10804
+ actualTechHash = extractTaggedMarkerAttribute(content, TECH_ARCHITECTURE_BLOCK_START_RE, "snapshot");
10805
+ if (!actualTechHash) {
10806
+ findings.push("TECH.md is missing the managed architecture snapshot block.");
10807
+ }
10808
+ else if (actualTechHash !== expectedTechHash) {
10809
+ findings.push(`TECH.md architecture snapshot is stale (expected ${expectedTechHash}, found ${actualTechHash}).`);
10810
+ }
10811
+ }
10812
+ if (!roadmapExists) {
10813
+ findings.push("ROADMAP.md is missing.");
10814
+ }
10815
+ else {
10816
+ const content = await readFile(roadmapPath, "utf8");
10817
+ actualRoadmapHash = extractTaggedMarkerAttribute(content, ROADMAP_FOUNDATION_BLOCK_START_RE, "profile");
10818
+ if (!actualRoadmapHash) {
10819
+ findings.push("ROADMAP.md is missing the managed roadmap foundation block.");
10820
+ }
10821
+ else if (actualRoadmapHash !== expectedRoadmapHash) {
10822
+ findings.push(`ROADMAP.md backbone is stale (expected ${expectedRoadmapHash}, found ${actualRoadmapHash}).`);
10823
+ }
10824
+ }
10825
+ if (!adrReadmeExists) {
10826
+ findings.push("docs/adr/README.md is missing.");
10827
+ }
10828
+ const metadata = await readJsonFileIfExists(metadataPath);
10829
+ if (!metadata.exists) {
10830
+ findings.push("Architecture build metadata is missing.");
10831
+ }
10832
+ return {
10833
+ stale: findings.length > 0,
10834
+ findings,
10835
+ productPath,
10836
+ architecturePath,
10837
+ rulesPath,
10838
+ techPath,
10839
+ roadmapPath,
10840
+ adrReadmePath,
10841
+ metadataPath,
10842
+ expectedProductHash,
10843
+ expectedArchitectureHash,
10844
+ expectedRulesHash,
10845
+ expectedTechHash,
10846
+ expectedRoadmapHash,
10847
+ actualProductHash,
10848
+ actualArchitectureHash,
10849
+ actualRulesHash,
10850
+ actualTechHash,
10851
+ actualRoadmapHash,
10852
+ };
10853
+ }
10854
+ async function runBuildArchitecture(options) {
10855
+ try {
10856
+ const platform = normalizeArchitectureBuildPlatform(options.platform);
10857
+ const researchMode = normalizeArchitectureResearchMode(options.research);
10858
+ const overwrite = Boolean(options.overwrite);
10859
+ const dryRun = Boolean(options.dryRun);
10860
+ const emitJson = Boolean(options.json);
10861
+ const checkOnly = Boolean(options.check);
10862
+ const cwd = process.cwd();
10863
+ const workspaceRoot = findWorkspaceRoot(cwd);
10864
+ const snapshot = await collectTechSnapshot(workspaceRoot);
10865
+ const specRoots = await listSpecPackRoots(workspaceRoot);
10866
+ if (checkOnly) {
10867
+ const drift = await readArchitectureDriftStatus(workspaceRoot, snapshot);
10868
+ if (emitJson) {
10869
+ console.log(JSON.stringify(drift, null, 2));
10870
+ }
10871
+ else {
10872
+ console.log(`Platform: ${platform}`);
10873
+ console.log(`Workspace: ${toPosixPath(workspaceRoot)}`);
10874
+ console.log(`Status: ${drift.stale ? "stale" : "fresh"}`);
10875
+ console.log("Backbone docs: PRODUCT.md, ARCHITECTURE.md, ENGINEERING_RULES.md, TECH.md, ROADMAP.md, docs/adr/README.md");
10876
+ if (drift.findings.length > 0) {
10877
+ console.log("Findings:");
10878
+ for (const finding of drift.findings) {
10879
+ console.log(`- ${finding}`);
10880
+ }
10881
+ }
10882
+ }
10883
+ if (drift.stale)
10884
+ process.exit(1);
10885
+ return;
10886
+ }
10887
+ const managedFilePaths = [
10888
+ path.join(workspaceRoot, "PRODUCT.md"),
10889
+ path.join(workspaceRoot, "ARCHITECTURE.md"),
10890
+ path.join(workspaceRoot, "ENGINEERING_RULES.md"),
10891
+ path.join(workspaceRoot, "TECH.md"),
10892
+ path.join(workspaceRoot, "ROADMAP.md"),
10893
+ path.join(workspaceRoot, "docs", "adr", "README.md"),
10894
+ path.join(workspaceRoot, "docs", "adr", "0000-template.md"),
10895
+ ];
10896
+ const filesBefore = dryRun
10897
+ ? Object.fromEntries(managedFilePaths.map((filePath) => [filePath, null]))
10898
+ : await captureFileContents(managedFilePaths);
10899
+ const scaffold = await ensureArchitectureDocScaffold({
10900
+ workspaceRoot,
10901
+ snapshot,
10902
+ specRoots,
10903
+ overwrite,
10904
+ dryRun,
10905
+ });
10906
+ const coreSkills = [
10907
+ "architecture-doc",
10908
+ "system-design",
10909
+ "tech-doc",
10910
+ "frontend-design",
10911
+ ];
10912
+ const conditionalSkills = resolveArchitectureConditionalSkills(snapshot, specRoots, researchMode);
10913
+ const skillBundle = [...coreSkills, ...conditionalSkills];
10914
+ const skillPathHints = await resolveArchitectureSkillPathHints(platform, cwd, skillBundle);
10915
+ const prompt = buildArchitecturePrompt({
10916
+ platform,
10917
+ workspaceRoot,
10918
+ snapshot,
10919
+ specRoots,
10920
+ researchMode,
10921
+ coreSkills,
10922
+ conditionalSkills,
10923
+ skillPathHints,
10924
+ });
10925
+ const adapter = await probeArchitectureAdapter(platform, workspaceRoot);
10926
+ const args = adapter.buildInvocation(prompt);
10927
+ if (dryRun) {
10928
+ const summary = {
10929
+ platform,
10930
+ workspaceRoot: toPosixPath(workspaceRoot),
10931
+ adapter: adapter.binary,
10932
+ invocation: [adapter.binary, ...args],
10933
+ researchMode,
10934
+ managedTargets: [
10935
+ toPosixPath(scaffold.productPath),
10936
+ toPosixPath(scaffold.architectureDocPath),
10937
+ toPosixPath(scaffold.engineeringRulesPath),
10938
+ toPosixPath(scaffold.techMdPath),
10939
+ toPosixPath(scaffold.roadmapPath),
10940
+ toPosixPath(scaffold.adrReadmePath),
10941
+ toPosixPath(scaffold.adrTemplatePath),
10942
+ ],
10943
+ skillBundle,
10944
+ };
10945
+ if (emitJson) {
10946
+ console.log(JSON.stringify(summary, null, 2));
10947
+ }
10948
+ else {
10949
+ console.log(`Platform: ${platform}`);
10950
+ console.log(`Workspace: ${toPosixPath(workspaceRoot)}`);
10951
+ console.log(`Adapter: ${adapter.binary}`);
10952
+ console.log(`Research mode: ${researchMode}`);
10953
+ console.log(`Managed targets: ${toPosixPath(scaffold.engineeringRulesPath)}, ${toPosixPath(scaffold.techMdPath)}`);
10954
+ console.log(`Skill bundle: ${skillBundle.join(", ")}`);
10955
+ console.log(`Invocation: ${[adapter.binary, ...args].join(" ")}`);
10956
+ }
10957
+ return;
10958
+ }
10959
+ if (!emitJson) {
10960
+ console.log(`Streaming ${adapter.binary} output...`);
10961
+ }
10962
+ const execution = await spawnCapture(adapter.binary, args, {
10963
+ cwd: workspaceRoot,
10964
+ env: process.env,
10965
+ streamOutput: !emitJson,
10966
+ });
10967
+ if (!execution.ok) {
10968
+ throw new Error(explainArchitectureBuildFailure(platform, execution));
10969
+ }
10970
+ const filesAfter = await captureFileContents(managedFilePaths);
10971
+ const changedFiles = managedFilePaths
10972
+ .filter((filePath) => filesBefore[filePath] !== filesAfter[filePath])
10973
+ .map((filePath) => toPosixPath(path.relative(workspaceRoot, filePath)));
10974
+ const rulesContent = filesAfter[scaffold.engineeringRulesPath] ??
10975
+ (await readFile(scaffold.engineeringRulesPath, "utf8"));
10976
+ const techContent = filesAfter[scaffold.techMdPath] ?? (await readFile(scaffold.techMdPath, "utf8"));
10977
+ const productContent = filesAfter[scaffold.productPath] ?? (await readFile(scaffold.productPath, "utf8"));
10978
+ const architectureContent = filesAfter[scaffold.architectureDocPath] ??
10979
+ (await readFile(scaffold.architectureDocPath, "utf8"));
10980
+ const roadmapContent = filesAfter[scaffold.roadmapPath] ?? (await readFile(scaffold.roadmapPath, "utf8"));
10981
+ const metadataPath = path.join(workspaceRoot, ".cbx", ARCHITECTURE_BUILD_METADATA_FILENAME);
10982
+ const metadata = buildArchitectureBuildMetadata({
10983
+ platform,
10984
+ researchMode,
10985
+ productProfileHash: extractTaggedMarkerAttribute(productContent, PRODUCT_FOUNDATION_BLOCK_START_RE, "profile") || "unknown",
10986
+ architectureDocHash: extractTaggedMarkerAttribute(architectureContent, ARCHITECTURE_DOC_BLOCK_START_RE, "profile") || "unknown",
10987
+ rulesProfileHash: extractTaggedMarkerAttribute(rulesContent, ENGINEERING_ARCHITECTURE_BLOCK_START_RE, "profile") || "unknown",
10988
+ techSnapshotHash: extractTaggedMarkerAttribute(techContent, TECH_ARCHITECTURE_BLOCK_START_RE, "snapshot") || "unknown",
10989
+ roadmapProfileHash: extractTaggedMarkerAttribute(roadmapContent, ROADMAP_FOUNDATION_BLOCK_START_RE, "profile") || "unknown",
10990
+ });
10991
+ await mkdir(path.dirname(metadataPath), { recursive: true });
10992
+ await writeFile(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf8");
10993
+ const result = normalizeArchitectureResult({
10994
+ stdout: execution.stdout,
10995
+ workspaceRoot: toPosixPath(workspaceRoot),
10996
+ researchMode,
10997
+ changedFiles: [...new Set(changedFiles)],
10998
+ });
10999
+ if (emitJson) {
11000
+ console.log(JSON.stringify({
11001
+ platform,
11002
+ adapter: adapter.binary,
11003
+ skillBundle,
11004
+ result,
11005
+ }, null, 2));
11006
+ return;
11007
+ }
11008
+ console.log(`Platform: ${platform}`);
11009
+ console.log(`Adapter: ${adapter.binary}`);
11010
+ console.log(`Workspace: ${toPosixPath(workspaceRoot)}`);
11011
+ console.log("Managed docs: PRODUCT.md, ARCHITECTURE.md, ENGINEERING_RULES.md, TECH.md, ROADMAP.md");
11012
+ console.log("ADR scaffold: docs/adr/README.md, docs/adr/0000-template.md");
11013
+ console.log(`Skill bundle: ${skillBundle.join(", ")}`);
11014
+ console.log(`Files written: ${(result.filesWritten || []).join(", ") || "(none reported)"}`);
11015
+ console.log(`Research used: ${result.researchUsed ? "yes" : "no"}`);
11016
+ if (result.gaps.length > 0) {
11017
+ console.log(`Gaps: ${result.gaps.join("; ")}`);
11018
+ }
11019
+ if (result.nextActions.length > 0) {
11020
+ console.log(`Next actions: ${result.nextActions.join("; ")}`);
11021
+ }
11022
+ }
11023
+ catch (error) {
11024
+ console.error(`\nError: ${error.message}`);
11025
+ process.exit(1);
11026
+ }
11027
+ }
9717
11028
  function parseCsvOption(value) {
9718
11029
  return String(value || "")
9719
11030
  .split(",")
@@ -9919,10 +11230,7 @@ async function runInitWizard(options) {
9919
11230
  dryRun: installOutcome.dryRun,
9920
11231
  });
9921
11232
  printRuleSyncResult(installOutcome.syncResult);
9922
- printInstallEngineeringSummary({
9923
- engineeringResults: installOutcome.engineeringArtifactsResult.engineeringResults,
9924
- techResult: installOutcome.engineeringArtifactsResult.techResult,
9925
- });
11233
+ printInstallDocumentationNotice();
9926
11234
  printPostmanSetupSummary({
9927
11235
  postmanSetup: installOutcome.postmanSetupResult,
9928
11236
  });
@@ -10025,6 +11333,7 @@ export function buildCliProgram() {
10025
11333
  defaultMcpDockerContainerName: DEFAULT_MCP_DOCKER_CONTAINER_NAME,
10026
11334
  runRulesInit,
10027
11335
  runRulesTechMd,
11336
+ runBuildArchitecture,
10028
11337
  });
10029
11338
  }
10030
11339
  export async function runCli(argv = process.argv) {