@warpgogol/forge 2.8.0 → 2.8.2

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 (271) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +23 -13
  3. package/README.uk.md +19 -12
  4. package/dist/os/session/handlers/validate.d.ts.map +1 -1
  5. package/dist/os/session/handlers/validate.js +23 -1
  6. package/dist/os/session/handlers/validate.js.map +1 -1
  7. package/dist/os/session/types.d.ts +31 -1
  8. package/dist/os/session/types.d.ts.map +1 -1
  9. package/dist/os/session/types.js +7 -0
  10. package/dist/os/session/types.js.map +1 -1
  11. package/os/adr/adr.module.ts +158 -0
  12. package/os/adr/frontmatter-io.ts +80 -0
  13. package/os/adr/handlers/archive.ts +244 -0
  14. package/os/adr/handlers/implement-stamp.ts +331 -0
  15. package/os/adr/handlers/list-create.ts +207 -0
  16. package/os/adr/handlers/validate.test.ts +232 -0
  17. package/os/adr/handlers/validate.ts +429 -0
  18. package/os/adr/index.ts +33 -0
  19. package/os/adr/types.ts +141 -0
  20. package/os/audit/audit.module.ts +48 -0
  21. package/os/audit/frontmatter-io.ts +84 -0
  22. package/os/audit/handlers/archive.ts +239 -0
  23. package/os/audit/index.ts +23 -0
  24. package/os/audit/types.ts +29 -0
  25. package/os/compass/compass.module.ts +186 -0
  26. package/os/compass/handlers/compass-audit-handler.ts +382 -0
  27. package/os/compass/handlers/compass-change-summary-handler.ts +272 -0
  28. package/os/compass/handlers/compass-inventory-handler.ts +294 -0
  29. package/os/compass/handlers/compass-inventory.ts +521 -0
  30. package/os/compass/handlers/git-revision.ts +137 -0
  31. package/os/compass/handlers/resolve-scan-root-workpiece.test.ts +65 -0
  32. package/os/compass/handlers/resolve-scan-root.ts +79 -0
  33. package/os/compass/index.ts +33 -0
  34. package/os/core/core.module.ts +948 -0
  35. package/os/core/handlers/assets-check.ts +122 -0
  36. package/os/core/handlers/assets-helpers.ts +174 -0
  37. package/os/core/handlers/assets-list.ts +99 -0
  38. package/os/core/handlers/build.ts +155 -0
  39. package/os/core/handlers/determinism-check.ts +354 -0
  40. package/os/core/handlers/dev.ts +127 -0
  41. package/os/core/handlers/invariant-engine.test.ts +681 -0
  42. package/os/core/handlers/knowledge-compact.ts +248 -0
  43. package/os/core/handlers/lifecycle-handlers.test.ts +524 -0
  44. package/os/core/handlers/note-frontmatter-validate.test.ts +93 -0
  45. package/os/core/handlers/note-link-validate.test.ts +117 -0
  46. package/os/core/handlers/note-orphan-detect.test.ts +94 -0
  47. package/os/core/handlers/package-health.test.ts +226 -0
  48. package/os/core/handlers/package-health.ts +231 -0
  49. package/os/core/handlers/pinned-check.ts +200 -0
  50. package/os/core/handlers/pinned-init.ts +333 -0
  51. package/os/core/handlers/pinned-types.ts +50 -0
  52. package/os/core/handlers/pinned-validate.ts +301 -0
  53. package/os/core/handlers/profile-resolve.ts +92 -0
  54. package/os/core/handlers/release-prepare.ts +294 -0
  55. package/os/core/handlers/release-publish.ts +211 -0
  56. package/os/core/handlers/validate.ts +262 -0
  57. package/os/core/handlers/workspace-deps.ts +55 -0
  58. package/os/core/index.ts +13 -0
  59. package/os/exploration/exploration.module.ts +90 -0
  60. package/os/exploration/frontmatter-io.ts +77 -0
  61. package/os/exploration/handlers/archive.ts +159 -0
  62. package/os/exploration/handlers/list.ts +77 -0
  63. package/os/exploration/handlers/show.ts +107 -0
  64. package/os/exploration/index.ts +25 -0
  65. package/os/exploration/types.ts +65 -0
  66. package/os/mission/handlers/archive.test.ts +391 -0
  67. package/os/mission/handlers/archive.ts +453 -0
  68. package/os/mission/index.ts +1 -0
  69. package/os/mission/mission.module.ts +48 -0
  70. package/os/mission/types.ts +41 -0
  71. package/os/naming/index.ts +14 -0
  72. package/os/naming/naming-convention.test.ts +163 -0
  73. package/os/naming/naming-convention.ts +378 -0
  74. package/os/naming/naming.module.ts +36 -0
  75. package/os/notes/index.ts +10 -0
  76. package/os/notes/notes.module.ts +109 -0
  77. package/os/plan/frontmatter-io.ts +82 -0
  78. package/os/plan/handlers/archive.ts +238 -0
  79. package/os/plan/index.ts +23 -0
  80. package/os/plan/plan.module.ts +48 -0
  81. package/os/plan/types.ts +29 -0
  82. package/os/program/discovery.ts +294 -0
  83. package/os/program/handlers/complete.ts +419 -0
  84. package/os/program/handlers/lease.ts +433 -0
  85. package/os/program/handlers/seal.ts +332 -0
  86. package/os/program/handlers/validate.ts +213 -0
  87. package/os/program/lease.ts +156 -0
  88. package/os/program/program.module.ts +212 -0
  89. package/os/program/schemas.ts +218 -0
  90. package/os/program/state.ts +264 -0
  91. package/os/rfc/acceptance.ts +344 -0
  92. package/os/rfc/decision-log.ts +310 -0
  93. package/os/rfc/dna-trace.ts +280 -0
  94. package/os/rfc/frontmatter-io.test.ts +132 -0
  95. package/os/rfc/frontmatter-io.ts +130 -0
  96. package/os/rfc/handlers/archive.ts +300 -0
  97. package/os/rfc/handlers/check.ts +238 -0
  98. package/os/rfc/handlers/implement-stamp.ts +515 -0
  99. package/os/rfc/handlers/index-graph.ts +237 -0
  100. package/os/rfc/handlers/lifecycle.test.ts +127 -0
  101. package/os/rfc/handlers/lifecycle.ts +249 -0
  102. package/os/rfc/handlers/list-create.ts +296 -0
  103. package/os/rfc/handlers/pipeline-status.ts +173 -0
  104. package/os/rfc/handlers/shared.ts +121 -0
  105. package/os/rfc/handlers/supersede-propose.ts +241 -0
  106. package/os/rfc/handlers/validate-rules.test.ts +891 -0
  107. package/os/rfc/handlers/validate-rules.ts +984 -0
  108. package/os/rfc/handlers/validate.ts +166 -0
  109. package/os/rfc/handlers.ts +19 -0
  110. package/os/rfc/index.ts +97 -0
  111. package/os/rfc/rfc.module.ts +416 -0
  112. package/os/rfc/types.ts +596 -0
  113. package/os/rfc/verification-evidence.ts +244 -0
  114. package/os/session/atif-parser.ts +166 -0
  115. package/os/session/frontmatter-io.ts +163 -0
  116. package/os/session/handlers/archive.ts +288 -0
  117. package/os/session/handlers/list.ts +174 -0
  118. package/os/session/handlers/save.ts +348 -0
  119. package/os/session/handlers/validate.ts +250 -0
  120. package/os/session/index.ts +50 -0
  121. package/os/session/session.module.ts +126 -0
  122. package/os/session/types.ts +203 -0
  123. package/os/spec/live-spec-list-show-validate.test.ts +257 -0
  124. package/os/spec/live-spec-list.ts +78 -0
  125. package/os/spec/live-spec-merge.test.ts +261 -0
  126. package/os/spec/live-spec-merge.ts +413 -0
  127. package/os/spec/live-spec-show.ts +117 -0
  128. package/os/spec/live-spec-types.ts +93 -0
  129. package/os/spec/live-spec-validate.ts +170 -0
  130. package/os/spec/spec-materialize.ts +390 -0
  131. package/os/spec/spec-schema.ts +174 -0
  132. package/os/spec/spec-status.ts +284 -0
  133. package/os/spec/spec-validate.ts +513 -0
  134. package/os/spec/spec.module.ts +135 -0
  135. package/os/werkstatt/handlers/lock.ts +168 -0
  136. package/os/werkstatt/handlers/schema.ts +47 -0
  137. package/os/werkstatt/handlers/werkstatt-lock-recover.ts +175 -0
  138. package/os/werkstatt/handlers/werkstatt-lock-status.ts +73 -0
  139. package/os/werkstatt/handlers/werkstatt-operation-validate.ts +104 -0
  140. package/os/werkstatt/index.ts +39 -0
  141. package/os/werkstatt/werkstatt.module.ts +62 -0
  142. package/os/workflow/handlers.ts +304 -0
  143. package/os/workflow/index.ts +28 -0
  144. package/os/workflow/types.ts +99 -0
  145. package/os/workflow/workflow.module.ts +54 -0
  146. package/package.json +3 -3
  147. package/profiles/godot-csharp.yaml +4 -4
  148. package/profiles/knowledge-typescript-turborepo.yaml +110 -0
  149. package/profiles/phaser-turborepo.yaml +5 -5
  150. package/skills/_shared/fo-session-summary.md +132 -16
  151. package/skills/fo/fo-add-tests/pbt-guide.md +13 -13
  152. package/skills/fo/fo-doc-audit/SKILL.md +6 -6
  153. package/skills/fo/fo-handoff/SKILL.md +5 -0
  154. package/skills/fo/fo-idea/SKILL.md +1 -1
  155. package/skills/fo/fo-review/SKILL.md +1 -1
  156. package/skills/fo/fo-session-retro/SKILL.md +8 -0
  157. package/skills/fo/fo-session-save/SKILL.md +8 -0
  158. package/src/cli-output.ts +59 -0
  159. package/src/config/__tests__/resolve-terminology.test.ts +45 -0
  160. package/src/config/forge-config.ts +524 -0
  161. package/src/forge-module.ts +39 -0
  162. package/src/index.ts +172 -0
  163. package/src/knowledge/__tests__/promote.test.ts +219 -0
  164. package/src/knowledge/__tests__/serialize.test.ts +192 -0
  165. package/src/knowledge/budgets.ts +202 -0
  166. package/src/knowledge/compact.ts +405 -0
  167. package/src/knowledge/index.ts +53 -0
  168. package/src/knowledge/parse.ts +227 -0
  169. package/src/knowledge/promote.ts +156 -0
  170. package/src/knowledge/schema.ts +112 -0
  171. package/src/knowledge/serialize.ts +72 -0
  172. package/src/migration-adapters/__tests__/ignored-files.test.ts +51 -0
  173. package/src/migration-adapters/__tests__/registry.test.ts +131 -0
  174. package/src/migration-adapters/__tests__/types.test.ts +86 -0
  175. package/src/migration-adapters/git-utils.ts +71 -0
  176. package/src/migration-adapters/ignored-files.ts +221 -0
  177. package/src/migration-adapters/index.ts +21 -0
  178. package/src/migration-adapters/node-typescript-pnpm/index.ts +189 -0
  179. package/src/migration-adapters/phaser-pnpm/index.ts +189 -0
  180. package/src/migration-adapters/registry.ts +61 -0
  181. package/src/migration-adapters/types.ts +68 -0
  182. package/src/onboarding/__tests__/workspace-discovery.test.ts +134 -0
  183. package/src/onboarding/agents-generate.ts +443 -0
  184. package/src/onboarding/create.ts +427 -0
  185. package/src/onboarding/doctor.ts +1297 -0
  186. package/src/onboarding/init.ts +337 -0
  187. package/src/onboarding/invariant-engine.ts +448 -0
  188. package/src/onboarding/memory-scaffold.ts +189 -0
  189. package/src/onboarding/nested-agents-generate.ts +93 -0
  190. package/src/onboarding/nested-agents-templates.ts +233 -0
  191. package/src/onboarding/profile-validate.ts +139 -0
  192. package/src/onboarding/scaffold-project.ts +299 -0
  193. package/src/onboarding/scaffold.ts +143 -0
  194. package/src/onboarding/upgrade.ts +558 -0
  195. package/src/onboarding/workspace-discovery.ts +167 -0
  196. package/src/profiles/__tests__/profile-schema.test.ts +228 -0
  197. package/src/profiles/__tests__/stack-profile.test.ts +190 -0
  198. package/src/profiles/__tests__/terminology-utils.test.ts +71 -0
  199. package/src/profiles/profile-schema.ts +350 -0
  200. package/src/profiles/stack-profile.ts +188 -0
  201. package/src/profiles/terminology-utils.ts +36 -0
  202. package/src/registry.ts +185 -0
  203. package/src/skill-schema.ts +37 -0
  204. package/src/tests/acceptance-criteria.test.ts +99 -0
  205. package/src/tests/adr-implement-stamp.test.ts +368 -0
  206. package/src/tests/agents-generate-domain.test.ts +317 -0
  207. package/src/tests/agents-generate.test.ts +458 -0
  208. package/src/tests/bindings-schema.test.ts +314 -0
  209. package/src/tests/budgets.test.ts +213 -0
  210. package/src/tests/cli-output.test.ts +196 -0
  211. package/src/tests/compact.test.ts +796 -0
  212. package/src/tests/create.test.ts +289 -0
  213. package/src/tests/doctor-autonomy.test.ts +98 -0
  214. package/src/tests/doctor-bindings.test.ts +286 -0
  215. package/src/tests/doctor-domain.test.ts +113 -0
  216. package/src/tests/exploration-handlers.test.ts +256 -0
  217. package/src/tests/fixtures/agents-generate-business-before.txt +288 -0
  218. package/src/tests/forge-config.test.ts +420 -0
  219. package/src/tests/fs-atomic.test.ts +96 -0
  220. package/src/tests/fs.test.ts +103 -0
  221. package/src/tests/generated-marker.test.ts +161 -0
  222. package/src/tests/hash.test.ts +37 -0
  223. package/src/tests/implement-stamp.test.ts +505 -0
  224. package/src/tests/init-bindings.test.ts +183 -0
  225. package/src/tests/knowledge-parse.test.ts +307 -0
  226. package/src/tests/knowledge-pbt.test.ts +164 -0
  227. package/src/tests/memory-scaffold.test.ts +192 -0
  228. package/src/tests/migration-adapters.test.ts +480 -0
  229. package/src/tests/package-files.test.ts +54 -0
  230. package/src/tests/pinned-check.test.ts +194 -0
  231. package/src/tests/pinned-init.test.ts +126 -0
  232. package/src/tests/profile-schema.test.ts +194 -0
  233. package/src/tests/profile-validate.test.ts +120 -0
  234. package/src/tests/program-lease.test.ts +245 -0
  235. package/src/tests/program-paths-extended.test.ts +117 -0
  236. package/src/tests/program-paths.test.ts +98 -0
  237. package/src/tests/program-property.test.ts +139 -0
  238. package/src/tests/program-schemas.test.ts +445 -0
  239. package/src/tests/program-spec-node.test.ts +250 -0
  240. package/src/tests/promote.test.ts +481 -0
  241. package/src/tests/registry.test.ts +73 -0
  242. package/src/tests/scaffold-project.test.ts +150 -0
  243. package/src/tests/session-handlers.test.ts +503 -0
  244. package/src/tests/session-pbt.test.ts +190 -0
  245. package/src/tests/skill-schema.test.ts +146 -0
  246. package/src/tests/skill-validate-knowledge.test.ts +26 -0
  247. package/src/tests/skill-validate.test.ts +254 -0
  248. package/src/tests/stack-profile.test.ts +221 -0
  249. package/src/tests/string-utils.test.ts +42 -0
  250. package/src/tests/upgrade.test.ts +428 -0
  251. package/src/tests/werkstatt-lock.test.ts +343 -0
  252. package/src/tests/workspace-discovery-domain.test.ts +112 -0
  253. package/src/tests/workspace-discovery.test.ts +135 -0
  254. package/src/types.ts +221 -0
  255. package/src/utils/__tests__/fs-idempotent.test.ts +73 -0
  256. package/src/utils/__tests__/fs-trash.test.ts +45 -0
  257. package/src/utils/fs-atomic.ts +93 -0
  258. package/src/utils/fs-idempotent.ts +41 -0
  259. package/src/utils/fs-trash-sync.ts +37 -0
  260. package/src/utils/fs-trash.ts +24 -0
  261. package/src/utils/fs.ts +74 -0
  262. package/src/utils/generated-marker.ts +166 -0
  263. package/src/utils/hash.ts +19 -0
  264. package/src/utils/index.ts +29 -0
  265. package/src/utils/string-utils.ts +19 -0
  266. package/src/validators/__tests__/note-orphan-detect.test.ts +94 -0
  267. package/src/validators/note-frontmatter-validate.ts +142 -0
  268. package/src/validators/note-link-validate.ts +145 -0
  269. package/src/validators/note-orphan-detect.ts +146 -0
  270. package/src/validators/port-validate.ts +97 -0
  271. package/src/validators/skill-validate.ts +831 -0
@@ -0,0 +1,1297 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>forge.doctor — diagnoses forge state in an existing project.
4
+ Checks for forge.yaml, AGENTS.md, PREFERENCES.md, .agents/skills/, docs/rfcs/,
5
+ @warpgogol/* import autonomy guard, and bindings contract (RFC-0393).</purpose>
6
+ <non-goals>
7
+ <item>Do not modify files — doctor is read-only diagnostics.</item>
8
+ </non-goals>
9
+ </MODULE_CONTRACT>
10
+ <CHANGE_SUMMARY>
11
+ <item>Initial forge.doctor handler for autonomy refactor.</item>
12
+ <item>RFC-0391: added @warpgogol/* forbidden-imports autonomy guard.</item>
13
+ <item>RFC-0393: added bindings validation — resolved/absent/invalid reporting.</item>
14
+ <item>RFC-0524: added stale knowledge file detection — compares source and .agents/ copies.</item>
15
+ <item>RFC-0539: extended knowledge file check to iterate pack skills via discoverPackSkills. Added pack-skills check for stale/missing copies and skillPacks config validation.</item>
16
+ <item>RFC-0540: added defaultable-binding-null notices for forge-CLI-backed bindings.</item>
17
+ <item>RFC-0611: added nested AGENTS.md checks — missing, stale (dryRun comparison), hand-written improvement.</item>
18
+ <item>RFC-0640: added domain reporting, invariant listing (reported-only), terminology resolution, --strict flag, and software-specific check skipping for non-software domains.</item>
19
+ <item>RFC-0675: upgraded domain-invariants check from advisory to enforcement using invariant engine.</item>
20
+ <item>RFC-0660: added legacy-section count reporting for structured knowledge files.</item>
21
+ <item>RFC-0661: added knowledge-budgets check — validates override shape, computes per-skill budget reports, reports summary with headroom %.</item>
22
+ <item>RFC-0663: added knowledge-duplicates check (cross-skill L2 duplicate detection) and shared-knowledge-file check (schema/id uniqueness for the shared layer).</item>
23
+ <item>RFC-0664: added memory-layer health check (budget usage, gitignore coverage, daily-file leak risk).</item>
24
+ <item>RFC-0704: added independent-version-packages check — validates that paths in independentVersionPackages exist and contain package.json.</item>
25
+ </CHANGE_SUMMARY>
26
+ */
27
+
28
+ import { readFile, readdir, stat } from "node:fs/promises";
29
+ import { readFileSync } from "node:fs";
30
+ import { join, relative, dirname } from "node:path";
31
+ import { parse as parseYaml } from "yaml";
32
+ import type {
33
+ ForgeCommandInput,
34
+ ForgeCommandResult,
35
+ ForgeRuntimeContext,
36
+ } from "../types.ts";
37
+ import { resolveForgeRoot, loadForgeConfig, resolveBinding, resolveTerminology, FORGE_CLI_BINDING_DEFAULTS, resolvePmRunner } from "../config/forge-config.ts";
38
+ import { FORGE_SKILLS, discoverPackSkills } from "../registry.ts";
39
+ import { discoverWorkspaces } from "./workspace-discovery.ts";
40
+ import { buildNestedAgentsMd, selectNestedTemplate } from "./nested-agents-templates.ts";
41
+ import { readPackageInfo } from "./nested-agents-generate.ts";
42
+ import { listStackProfiles, type StackProfile } from "../profiles/stack-profile.ts";
43
+ import { resolveAllTerminology } from "../profiles/terminology-utils.ts";
44
+ import { TERMINOLOGY_DEFAULTS } from "../profiles/profile-schema.ts";
45
+ import type { ProfileWorkspaceType } from "../profiles/profile-schema.ts";
46
+ import { runProfileValidate } from "./profile-validate.ts";
47
+ import { parseKnowledgeFile } from "../knowledge/index.ts";
48
+ import type { ParsedKnowledgeFile } from "../knowledge/index.ts";
49
+ import { computeLayerBudgets, resolveKnowledgeBudgets, DEFAULT_KNOWLEDGE_BUDGETS } from "../knowledge/budgets.ts";
50
+ import { detectDuplicatePrinciples } from "../knowledge/index.ts";
51
+ import type { DuplicatePair } from "../knowledge/index.ts";
52
+ import { checkMemoryLayerHealth } from "./memory-scaffold.ts";
53
+ import { checkInvariants } from "./invariant-engine.ts";
54
+ import type { InvariantViolation } from "./invariant-engine.ts";
55
+ import { execSync } from "node:child_process";
56
+ import type { ProfilePrerequisite } from "../profiles/profile-schema.ts";
57
+
58
+ interface DoctorCheck {
59
+ name: string;
60
+ status: "pass" | "fail" | "warn";
61
+ message: string;
62
+ invariantViolations?: InvariantViolation[];
63
+ }
64
+
65
+ interface ForbiddenImport {
66
+ file: string;
67
+ specifier: string;
68
+ }
69
+
70
+ interface BindingValidation {
71
+ resolved: string[];
72
+ absent: string[];
73
+ invalid: string[];
74
+ notices: BindingNotice[];
75
+ }
76
+
77
+ interface BindingNotice {
78
+ key: string;
79
+ rule: string;
80
+ suggestion: string;
81
+ }
82
+
83
+ async function pathExists(target: string): Promise<boolean> {
84
+ try {
85
+ await stat(target);
86
+ return true;
87
+ } catch {
88
+ return false;
89
+ }
90
+ }
91
+
92
+ const FORBIDDEN_IMPORT_PATTERN =
93
+ /(?:^|\n)\s*(?:import\s+[^;]+?\s+from\s+|require\s*\(\s*)["'`](@warpgogol\/[^"'`]+)["'`]/g;
94
+
95
+ async function scanForForbiddenImports(
96
+ dir: string,
97
+ workspaceRoot: string,
98
+ ): Promise<ForbiddenImport[]> {
99
+ const violations: ForbiddenImport[] = [];
100
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
101
+
102
+ for (const entry of entries) {
103
+ const fullPath = join(dir, entry.name);
104
+
105
+ if (entry.isDirectory()) {
106
+ if (entry.name === "node_modules" || entry.name === "tests") continue;
107
+ const sub = await scanForForbiddenImports(fullPath, workspaceRoot);
108
+ violations.push(...sub);
109
+ } else if (entry.name.endsWith(".ts")) {
110
+ const content = await readFile(fullPath, "utf8").catch(() => "");
111
+ let match: RegExpExecArray | null;
112
+ const pattern = new RegExp(FORBIDDEN_IMPORT_PATTERN.source, "g");
113
+ while ((match = pattern.exec(content)) !== null) {
114
+ violations.push({
115
+ file: relative(workspaceRoot, fullPath),
116
+ specifier: match[1],
117
+ });
118
+ }
119
+ }
120
+ }
121
+
122
+ return violations;
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // Bindings validation (RFC-0393)
127
+ // ---------------------------------------------------------------------------
128
+
129
+ const BINDING_PATH_KEYS = [
130
+ "paths.invariantsFile",
131
+ "paths.reviewsDir",
132
+ "paths.handoffsDir",
133
+ "paths.sessionsDir",
134
+ ];
135
+
136
+ const BINDING_COMMAND_KEYS = [
137
+ "commands.validateRfc",
138
+ "commands.validateAdr",
139
+ "commands.implementStamp",
140
+ "commands.typecheck",
141
+ "commands.test",
142
+ "commands.scopedBuild",
143
+ "commands.specValidate",
144
+ "commands.sessionSave",
145
+ ];
146
+
147
+ async function validateBindings(workspaceRoot: string): Promise<BindingValidation> {
148
+ const result: BindingValidation = { resolved: [], absent: [], invalid: [], notices: [] };
149
+
150
+ let config;
151
+ try {
152
+ config = loadForgeConfig(workspaceRoot);
153
+ } catch {
154
+ return result;
155
+ }
156
+
157
+ if (!config.bindings) {
158
+ return result;
159
+ }
160
+
161
+ for (const key of BINDING_PATH_KEYS) {
162
+ const value = resolveBinding(config, key);
163
+ if (value === null) {
164
+ result.absent.push(key);
165
+ } else if (typeof value === "string") {
166
+ const exists = await pathExists(join(workspaceRoot, value));
167
+ if (exists) {
168
+ result.resolved.push(key);
169
+ } else {
170
+ result.invalid.push(`${key} (path not found: ${value})`);
171
+ }
172
+ }
173
+ }
174
+
175
+ const compassDocs = resolveBinding(config, "paths.compassDocs");
176
+ if (Array.isArray(compassDocs) && compassDocs.length > 0) {
177
+ for (const docPath of compassDocs) {
178
+ const exists = await pathExists(join(workspaceRoot, docPath));
179
+ if (exists) {
180
+ result.resolved.push(`paths.compassDocs[${docPath}]`);
181
+ } else {
182
+ result.invalid.push(`paths.compassDocs[${docPath}] (path not found)`);
183
+ }
184
+ }
185
+ } else {
186
+ result.absent.push("paths.compassDocs");
187
+ }
188
+
189
+ for (const key of BINDING_COMMAND_KEYS) {
190
+ const value = resolveBinding(config, key);
191
+ if (value === null) {
192
+ result.absent.push(key);
193
+ } else if (typeof value === "string") {
194
+ result.resolved.push(key);
195
+ }
196
+ }
197
+
198
+ // RFC-0540: Emit defaultable-binding-null notices for forge-CLI-backed bindings
199
+ const pm = config.project.packageManager;
200
+ const runner = resolvePmRunner(pm);
201
+ for (const entry of FORGE_CLI_BINDING_DEFAULTS) {
202
+ const value = resolveBinding(config, entry.key);
203
+ if (value === null) {
204
+ result.notices.push({
205
+ key: entry.key,
206
+ rule: "defaultable-binding-null",
207
+ suggestion: `${runner} ${entry.template}`,
208
+ });
209
+ }
210
+ }
211
+
212
+ return result;
213
+ }
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // Stale knowledge file detection (RFC-0524)
217
+ // ---------------------------------------------------------------------------
218
+
219
+ async function checkStaleKnowledgeFiles(
220
+ workspaceRoot: string,
221
+ forgeRoot: string,
222
+ ): Promise<DoctorCheck> {
223
+ const stale: string[] = [];
224
+
225
+ let config;
226
+ try {
227
+ config = loadForgeConfig(workspaceRoot);
228
+ } catch {
229
+ return { name: "knowledge-files", status: "pass", message: "No forge.yaml — knowledge file check skipped" };
230
+ }
231
+
232
+ const agentsSkillsDir = join(workspaceRoot, config.paths.skillsDir);
233
+
234
+ for (const skill of FORGE_SKILLS) {
235
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
236
+
237
+ const skillSrcDir = dirname(join(forgeRoot, skill.path));
238
+
239
+ for (const kf of skill.knowledge) {
240
+ const srcPath = join(skillSrcDir, kf);
241
+ const destPath = join(agentsSkillsDir, skill.name, kf);
242
+
243
+ const srcExists = await pathExists(srcPath);
244
+ const destExists = await pathExists(destPath);
245
+
246
+ if (srcExists && destExists) {
247
+ const srcContent = await readFile(srcPath, "utf8").catch(() => "");
248
+ const destContent = await readFile(destPath, "utf8").catch(() => "");
249
+ if (srcContent !== destContent) {
250
+ stale.push(`${skill.name}/${kf}`);
251
+ }
252
+ }
253
+ // If source exists but dest doesn't, skip — expected on first install
254
+ // If source doesn't exist, SKILL-13 in forge.skill.validate catches it
255
+ }
256
+ }
257
+
258
+ // RFC-0539: Check pack skill knowledge files
259
+ const packSkills = discoverPackSkills(workspaceRoot, config);
260
+ for (const skill of packSkills) {
261
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
262
+
263
+ const skillSrcDir = dirname(join(workspaceRoot, skill.dir, skill.path));
264
+
265
+ for (const kf of skill.knowledge) {
266
+ const srcPath = join(skillSrcDir, kf);
267
+ const destPath = join(agentsSkillsDir, skill.name, kf);
268
+
269
+ const srcExists = await pathExists(srcPath);
270
+ const destExists = await pathExists(destPath);
271
+
272
+ if (srcExists && destExists) {
273
+ const srcContent = await readFile(srcPath, "utf8").catch(() => "");
274
+ const destContent = await readFile(destPath, "utf8").catch(() => "");
275
+ if (srcContent !== destContent) {
276
+ stale.push(`${skill.name}/${kf}`);
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ return {
283
+ name: "knowledge-files",
284
+ status: stale.length === 0 ? "pass" : "warn",
285
+ message:
286
+ stale.length === 0
287
+ ? "All knowledge files in sync"
288
+ : `${stale.length} stale knowledge file(s): ${stale.join(", ")} — run 'forge create' to sync`,
289
+ };
290
+ }
291
+
292
+ // ---------------------------------------------------------------------------
293
+ // Legacy section detection (RFC-0660)
294
+ // ---------------------------------------------------------------------------
295
+
296
+ function checkLegacyKnowledgeSections(
297
+ workspaceRoot: string,
298
+ forgeRoot: string,
299
+ ): DoctorCheck {
300
+ let config;
301
+ try {
302
+ config = loadForgeConfig(workspaceRoot);
303
+ } catch {
304
+ return { name: "knowledge-legacy", status: "pass", message: "No forge.yaml — legacy section check skipped" };
305
+ }
306
+
307
+ let totalLegacy = 0;
308
+ let filesWithLegacy = 0;
309
+
310
+ // Check forge skills
311
+ for (const skill of FORGE_SKILLS) {
312
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
313
+ const skillDir = join(forgeRoot, dirname(skill.path));
314
+ for (const kf of skill.knowledge) {
315
+ const kfPath = join(skillDir, kf);
316
+ try {
317
+ const parsed = parseKnowledgeFile(kfPath);
318
+ if (parsed.isKnowledgeAdjacent) continue;
319
+ if (parsed.legacySections.length > 0) {
320
+ totalLegacy += parsed.legacySections.length;
321
+ filesWithLegacy++;
322
+ }
323
+ } catch {
324
+ // File read errors are handled by stale knowledge check
325
+ }
326
+ }
327
+ }
328
+
329
+ // Check pack skills
330
+ const packSkills = discoverPackSkills(workspaceRoot, config);
331
+ for (const skill of packSkills) {
332
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
333
+ const skillDir = join(workspaceRoot, skill.dir, dirname(skill.path));
334
+ for (const kf of skill.knowledge) {
335
+ const kfPath = join(skillDir, kf);
336
+ try {
337
+ const parsed = parseKnowledgeFile(kfPath);
338
+ if (parsed.isKnowledgeAdjacent) continue;
339
+ if (parsed.legacySections.length > 0) {
340
+ totalLegacy += parsed.legacySections.length;
341
+ filesWithLegacy++;
342
+ }
343
+ } catch {
344
+ // File read errors are handled by stale knowledge check
345
+ }
346
+ }
347
+ }
348
+
349
+ return {
350
+ name: "knowledge-legacy",
351
+ status: totalLegacy === 0 ? "pass" : "warn",
352
+ message:
353
+ totalLegacy === 0
354
+ ? "No legacy knowledge sections"
355
+ : `${totalLegacy} legacy section${totalLegacy === 1 ? "" : "s"} across ${filesWithLegacy} knowledge file${filesWithLegacy === 1 ? "" : "s"} — run the knowledge compaction command to migrate`,
356
+ };
357
+ }
358
+
359
+ // ---------------------------------------------------------------------------
360
+ // Knowledge budget check (RFC-0661)
361
+ // ---------------------------------------------------------------------------
362
+
363
+ function checkKnowledgeBudgets(
364
+ workspaceRoot: string,
365
+ forgeRoot: string,
366
+ ): DoctorCheck {
367
+ let config;
368
+ try {
369
+ config = loadForgeConfig(workspaceRoot);
370
+ } catch {
371
+ return { name: "knowledge-budgets", status: "pass", message: "No forge.yaml — budget check skipped" };
372
+ }
373
+
374
+ // Validate override shape if present
375
+ const overrideWarnings: string[] = [];
376
+ const effectiveBudgets = resolveKnowledgeBudgets(workspaceRoot);
377
+ let usingDefaults = true;
378
+
379
+ try {
380
+ const forgeYamlPath = join(workspaceRoot, "forge.yaml");
381
+ const content = readFileSync(forgeYamlPath, "utf8");
382
+ const parsed = parseYaml(content) as Record<string, unknown>;
383
+ const bindings = parsed?.bindings as Record<string, unknown> | undefined;
384
+ const knowledge = bindings?.knowledge as Record<string, unknown> | undefined;
385
+ const budgets = knowledge?.budgets as { hot?: unknown; warm?: unknown } | undefined;
386
+
387
+ if (budgets) {
388
+ usingDefaults = false;
389
+ if (typeof budgets.hot !== "number" || budgets.hot <= 0 || !Number.isInteger(budgets.hot)) {
390
+ overrideWarnings.push(`bindings.knowledge.budgets.hot invalid (got ${String(budgets.hot)}), using default ${DEFAULT_KNOWLEDGE_BUDGETS.hot}`);
391
+ }
392
+ if (typeof budgets.warm !== "number" || budgets.warm <= 0 || !Number.isInteger(budgets.warm)) {
393
+ overrideWarnings.push(`bindings.knowledge.budgets.warm invalid (got ${String(budgets.warm)}), using default ${DEFAULT_KNOWLEDGE_BUDGETS.warm}`);
394
+ }
395
+ }
396
+ } catch {
397
+ // forge.yaml not readable — defaults already applied
398
+ }
399
+
400
+ // Collect all parsed knowledge files from forge skills and pack skills
401
+ const parsedFiles: { file: ParsedKnowledgeFile; skillName: string; pack?: string }[] = [];
402
+
403
+ for (const skill of FORGE_SKILLS) {
404
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
405
+ const skillDir = join(forgeRoot, dirname(skill.path));
406
+ for (const kf of skill.knowledge) {
407
+ const kfPath = join(skillDir, kf);
408
+ try {
409
+ const parsed = parseKnowledgeFile(kfPath);
410
+ if (parsed.layer !== null && parsed.layer !== "L0" && !parsed.isKnowledgeAdjacent && parsed.parseIssues.length === 0) {
411
+ parsedFiles.push({ file: parsed, skillName: skill.name });
412
+ }
413
+ } catch {
414
+ // File read errors are handled by stale knowledge check
415
+ }
416
+ }
417
+ }
418
+
419
+ const packSkills = discoverPackSkills(workspaceRoot, config);
420
+ for (const skill of packSkills) {
421
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
422
+ const skillDir = join(workspaceRoot, skill.dir, dirname(skill.path));
423
+ for (const kf of skill.knowledge) {
424
+ const kfPath = join(skillDir, kf);
425
+ try {
426
+ const parsed = parseKnowledgeFile(kfPath);
427
+ if (parsed.layer !== null && parsed.layer !== "L0" && !parsed.isKnowledgeAdjacent && parsed.parseIssues.length === 0) {
428
+ parsedFiles.push({ file: parsed, skillName: skill.name, pack: skill.pack });
429
+ }
430
+ } catch {
431
+ // File read errors are handled by stale knowledge check
432
+ }
433
+ }
434
+ }
435
+
436
+ // Compute budget reports
437
+ const filesForBudget = parsedFiles.map((p) => p.file);
438
+ const skillNames = new Map<string, string>();
439
+ for (const p of parsedFiles) {
440
+ skillNames.set(p.file.path, p.skillName);
441
+ }
442
+
443
+ const reports = computeLayerBudgets(filesForBudget, effectiveBudgets, skillNames);
444
+
445
+ // Build summary
446
+ const budgetSource = usingDefaults ? "defaults" : "override";
447
+ const parts: string[] = [`budgets: hot=${effectiveBudgets.hot} warm=${effectiveBudgets.warm} (${budgetSource})`];
448
+
449
+ if (reports.length > 0) {
450
+ const summary = reports.map((r) => {
451
+ const pct = Math.round((r.activeChars / r.budget) * 100);
452
+ return `${r.skill}/${r.file}[${r.layer}]: ${r.activeChars}/${r.budget} (${pct}%)`;
453
+ });
454
+ parts.push(`${reports.length} file${reports.length === 1 ? "" : "s"}: ${summary.join(", ")}`);
455
+ } else {
456
+ parts.push("no hot/warm knowledge files to check");
457
+ }
458
+
459
+ if (overrideWarnings.length > 0) {
460
+ parts.push(overrideWarnings.join("; "));
461
+ }
462
+
463
+ const status: DoctorCheck["status"] = overrideWarnings.length > 0 ? "warn" : "pass";
464
+
465
+ return {
466
+ name: "knowledge-budgets",
467
+ status,
468
+ message: parts.join(" | "),
469
+ };
470
+ }
471
+
472
+ // ---------------------------------------------------------------------------
473
+ // Knowledge duplicate detection (RFC-0663)
474
+ // ---------------------------------------------------------------------------
475
+
476
+ function collectL2Files(
477
+ workspaceRoot: string,
478
+ forgeRoot: string,
479
+ ): Array<{ skill: string; parsed: ParsedKnowledgeFile }> {
480
+ let config;
481
+ try {
482
+ config = loadForgeConfig(workspaceRoot);
483
+ } catch {
484
+ return [];
485
+ }
486
+
487
+ const files: Array<{ skill: string; parsed: ParsedKnowledgeFile }> = [];
488
+
489
+ for (const skill of FORGE_SKILLS) {
490
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
491
+ const skillDir = join(forgeRoot, dirname(skill.path));
492
+ for (const kf of skill.knowledge) {
493
+ if (kf !== "learned-principles.md") continue;
494
+ const kfPath = join(skillDir, kf);
495
+ try {
496
+ const parsed = parseKnowledgeFile(kfPath);
497
+ if (parsed.isKnowledgeAdjacent) continue;
498
+ if (parsed.parseIssues.length > 0) continue;
499
+ files.push({ skill: skill.name, parsed });
500
+ } catch {
501
+ // File read errors are handled by stale knowledge check
502
+ }
503
+ }
504
+ }
505
+
506
+ const packSkills = discoverPackSkills(workspaceRoot, config);
507
+ for (const skill of packSkills) {
508
+ if (!skill.knowledge || skill.knowledge.length === 0) continue;
509
+ const skillDir = join(workspaceRoot, skill.dir, dirname(skill.path));
510
+ for (const kf of skill.knowledge) {
511
+ if (kf !== "learned-principles.md") continue;
512
+ const kfPath = join(skillDir, kf);
513
+ try {
514
+ const parsed = parseKnowledgeFile(kfPath);
515
+ if (parsed.isKnowledgeAdjacent) continue;
516
+ if (parsed.parseIssues.length > 0) continue;
517
+ files.push({ skill: skill.name, parsed });
518
+ } catch {
519
+ // File read errors are handled by stale knowledge check
520
+ }
521
+ }
522
+ }
523
+
524
+ const sharedPath = join(forgeRoot, "skills", "shared", "knowledge", "learned-principles.md");
525
+ try {
526
+ const parsed = parseKnowledgeFile(sharedPath);
527
+ if (!parsed.isKnowledgeAdjacent && parsed.parseIssues.length === 0 && parsed.entries.length > 0) {
528
+ files.push({ skill: "shared", parsed });
529
+ }
530
+ } catch {
531
+ // Shared layer not initialized — not an error
532
+ }
533
+
534
+ return files;
535
+ }
536
+
537
+ function checkKnowledgeDuplicates(
538
+ workspaceRoot: string,
539
+ forgeRoot: string,
540
+ ): DoctorCheck {
541
+ const l2Files = collectL2Files(workspaceRoot, forgeRoot);
542
+
543
+ if (l2Files.length === 0) {
544
+ return { name: "knowledge-duplicates", status: "pass", message: "No L2 knowledge files to check" };
545
+ }
546
+
547
+ const pairs: DuplicatePair[] = detectDuplicatePrinciples(l2Files);
548
+
549
+ if (pairs.length === 0) {
550
+ return { name: "knowledge-duplicates", status: "pass", message: "No cross-skill duplicate principles detected" };
551
+ }
552
+
553
+ const pairSummaries = pairs.map(
554
+ (p) => `${p.a.skill}/${p.a.entryId} ↔ ${p.b.skill}/${p.b.entryId} (${p.kind})`,
555
+ );
556
+
557
+ return {
558
+ name: "knowledge-duplicates",
559
+ status: "warn",
560
+ message: `${pairs.length} duplicate pair${pairs.length === 1 ? "" : "s"} detected — run fo-knowledge-distill to promote: ${pairSummaries.join("; ")}`,
561
+ };
562
+ }
563
+
564
+ // ---------------------------------------------------------------------------
565
+ // Shared knowledge file validation (RFC-0663)
566
+ // ---------------------------------------------------------------------------
567
+
568
+ function checkSharedKnowledgeFile(
569
+ workspaceRoot: string,
570
+ forgeRoot: string,
571
+ ): DoctorCheck {
572
+ const sharedPath = join(forgeRoot, "skills", "shared", "knowledge", "learned-principles.md");
573
+
574
+ let parsed: ParsedKnowledgeFile;
575
+ try {
576
+ parsed = parseKnowledgeFile(sharedPath);
577
+ } catch {
578
+ return { name: "shared-knowledge-file", status: "pass", message: "Shared knowledge layer not initialized — created on first promotion" };
579
+ }
580
+
581
+ if (parsed.isKnowledgeAdjacent) {
582
+ return { name: "shared-knowledge-file", status: "pass", message: "Shared knowledge layer is empty (no structured entries)" };
583
+ }
584
+
585
+ const issues: string[] = [];
586
+
587
+ for (const issue of parsed.parseIssues) {
588
+ issues.push(`line ${issue.line}: ${issue.message}`);
589
+ }
590
+
591
+ const seenIds = new Set<string>();
592
+ for (const entry of parsed.entries) {
593
+ if (seenIds.has(entry.meta.id)) {
594
+ issues.push(`duplicate entry id: ${entry.meta.id}`);
595
+ }
596
+ seenIds.add(entry.meta.id);
597
+ }
598
+
599
+ if (issues.length > 0) {
600
+ return {
601
+ name: "shared-knowledge-file",
602
+ status: "fail",
603
+ message: `${issues.length} issue${issues.length === 1 ? "" : "s"}: ${issues.join("; ")}`,
604
+ };
605
+ }
606
+
607
+ return {
608
+ name: "shared-knowledge-file",
609
+ status: "pass",
610
+ message: `Shared knowledge layer: ${parsed.entries.length} entr${parsed.entries.length === 1 ? "y" : "ies"}`,
611
+ };
612
+ }
613
+
614
+ // ---------------------------------------------------------------------------
615
+ // Independent version packages diagnostics (RFC-0704)
616
+ // ---------------------------------------------------------------------------
617
+
618
+ async function checkIndependentVersionPackages(workspaceRoot: string): Promise<DoctorCheck> {
619
+ let config;
620
+ try {
621
+ config = loadForgeConfig(workspaceRoot);
622
+ } catch {
623
+ return { name: "independent-version-packages", status: "pass", message: "No forge.yaml — independent version packages check skipped" };
624
+ }
625
+
626
+ if (!config.independentVersionPackages || config.independentVersionPackages.length === 0) {
627
+ return { name: "independent-version-packages", status: "pass", message: "No independent version packages declared" };
628
+ }
629
+
630
+ const issues: string[] = [];
631
+ let validCount = 0;
632
+
633
+ for (const pkgPath of config.independentVersionPackages) {
634
+ const dirExists = await pathExists(join(workspaceRoot, pkgPath));
635
+ const pkgJsonExists = await pathExists(join(workspaceRoot, pkgPath, "package.json"));
636
+ if (!dirExists) {
637
+ issues.push(`path '${pkgPath}' does not exist`);
638
+ } else if (!pkgJsonExists) {
639
+ issues.push(`path '${pkgPath}' has no package.json`);
640
+ } else {
641
+ validCount++;
642
+ }
643
+ }
644
+
645
+ if (issues.length === 0) {
646
+ return {
647
+ name: "independent-version-packages",
648
+ status: "pass",
649
+ message: `${validCount} independent version package${validCount === 1 ? "" : "s"} declared`,
650
+ };
651
+ }
652
+
653
+ return {
654
+ name: "independent-version-packages",
655
+ status: "warn",
656
+ message: `${issues.length} issue${issues.length === 1 ? "" : "s"}: ${issues.join(", ")}`,
657
+ };
658
+ }
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Pack skill diagnostics (RFC-0539)
662
+ // ---------------------------------------------------------------------------
663
+
664
+ async function checkPackSkills(workspaceRoot: string): Promise<DoctorCheck> {
665
+ let config;
666
+ try {
667
+ config = loadForgeConfig(workspaceRoot);
668
+ } catch {
669
+ return { name: "pack-skills", status: "pass", message: "No forge.yaml — pack skill check skipped" };
670
+ }
671
+
672
+ if (!config.skillPacks || config.skillPacks.length === 0) {
673
+ return { name: "pack-skills", status: "pass", message: "No skill packs declared" };
674
+ }
675
+
676
+ const issues: string[] = [];
677
+
678
+ // Validate skillPacks config: unique prefixes, unique dirs, no 'fo' prefix, dir exists
679
+ const prefixes = new Set<string>();
680
+ const dirs = new Set<string>();
681
+ for (const pack of config.skillPacks) {
682
+ if (prefixes.has(pack.prefix)) {
683
+ issues.push(`duplicate prefix '${pack.prefix}'`);
684
+ }
685
+ prefixes.add(pack.prefix);
686
+
687
+ if (pack.prefix === "fo") {
688
+ issues.push(`prefix 'fo' is reserved for forge`);
689
+ }
690
+
691
+ if (dirs.has(pack.dir)) {
692
+ issues.push(`duplicate dir '${pack.dir}'`);
693
+ }
694
+ dirs.add(pack.dir);
695
+
696
+ const packDirExists = await pathExists(join(workspaceRoot, pack.dir));
697
+ if (!packDirExists) {
698
+ issues.push(`pack dir '${pack.dir}' does not exist`);
699
+ }
700
+ }
701
+
702
+ // Check for stale/missing pack skill copies
703
+ const packSkills = discoverPackSkills(workspaceRoot, config);
704
+ const agentsSkillsDir = join(workspaceRoot, config.paths.skillsDir);
705
+
706
+ for (const skill of packSkills) {
707
+ const srcPath = join(workspaceRoot, skill.dir, skill.path);
708
+ const destPath = join(agentsSkillsDir, skill.name, "SKILL.md");
709
+
710
+ const srcExists = await pathExists(srcPath);
711
+ const destExists = await pathExists(destPath);
712
+
713
+ if (srcExists && destExists) {
714
+ const srcContent = await readFile(srcPath, "utf8").catch(() => "");
715
+ const destContent = await readFile(destPath, "utf8").catch(() => "");
716
+ if (srcContent !== destContent) {
717
+ issues.push(`stale copy of '${skill.name}'`);
718
+ }
719
+ } else if (srcExists && !destExists) {
720
+ issues.push(`missing copy of '${skill.name}'`);
721
+ }
722
+ }
723
+
724
+ return {
725
+ name: "pack-skills",
726
+ status: issues.length === 0 ? "pass" : "warn",
727
+ message:
728
+ issues.length === 0
729
+ ? `${packSkills.length} pack skill(s) in sync`
730
+ : `${issues.length} issue(s): ${issues.join(", ")} — run 'forge create' to sync`,
731
+ };
732
+ }
733
+
734
+ // ---------------------------------------------------------------------------
735
+ // Nested AGENTS.md diagnostics (RFC-0611)
736
+ // ---------------------------------------------------------------------------
737
+
738
+ async function checkNestedAgentsMd(
739
+ workspaceRoot: string,
740
+ workspaceTypes?: ProfileWorkspaceType[],
741
+ ): Promise<DoctorCheck> {
742
+ let config;
743
+ try {
744
+ config = loadForgeConfig(workspaceRoot);
745
+ } catch {
746
+ return {
747
+ name: "nested-AGENTS.md",
748
+ status: "pass",
749
+ message: "forge.yaml not loadable — nested AGENTS.md check skipped",
750
+ };
751
+ }
752
+
753
+ const workspaces = discoverWorkspaces(workspaceRoot, workspaceTypes);
754
+
755
+ if (workspaces.length === 0) {
756
+ return {
757
+ name: "nested-AGENTS.md",
758
+ status: "pass",
759
+ message: "no workspace directories found",
760
+ };
761
+ }
762
+
763
+ const issues: string[] = [];
764
+ let missing = 0;
765
+ let stale = 0;
766
+ let handwritten = 0;
767
+
768
+ for (const ws of workspaces) {
769
+ if (!ws.hasAgentsMd) {
770
+ missing++;
771
+ issues.push(`${ws.path}/AGENTS.md missing`);
772
+ continue;
773
+ }
774
+
775
+ if (!ws.isGenerated) {
776
+ handwritten++;
777
+ const suggestions: string[] = [];
778
+ try {
779
+ const content = await readFile(join(workspaceRoot, ws.path, "AGENTS.md"), "utf8");
780
+ if (!content.includes("AGENTS.md")) {
781
+ suggestions.push("reference root AGENTS.md");
782
+ }
783
+ } catch {
784
+ // unreadable — skip
785
+ }
786
+ if (suggestions.length > 0) {
787
+ issues.push(`${ws.path}/AGENTS.md hand-written — consider: ${suggestions.join(", ")}`);
788
+ }
789
+ continue;
790
+ }
791
+
792
+ // Stale check: compare in-memory render to committed file
793
+ // Must match the generate pipeline: readPackageInfo + buildNestedAgentsMd + selectNestedTemplate
794
+ try {
795
+ const packageInfo = readPackageInfo(workspaceRoot, ws.path);
796
+ const fallback = buildNestedAgentsMd(ws, config, packageInfo);
797
+ const profile = config.profile as StackProfile | undefined;
798
+ const terminology = resolveAllTerminology(config, profile);
799
+ const wsType = workspaceTypes?.find((wt) => wt.id === ws.type);
800
+ const expected = selectNestedTemplate(wsType, profile, terminology, fallback);
801
+ const actual = await readFile(join(workspaceRoot, ws.path, "AGENTS.md"), "utf8");
802
+ if (expected !== actual) {
803
+ stale++;
804
+ issues.push(`${ws.path}/AGENTS.md stale — run 'forge agents generate'`);
805
+ }
806
+ } catch {
807
+ // unreadable — skip
808
+ }
809
+ }
810
+
811
+ if (issues.length === 0) {
812
+ return {
813
+ name: "nested-AGENTS.md",
814
+ status: "pass",
815
+ message: `${workspaces.length} workspace(s) — all AGENTS.md in sync`,
816
+ };
817
+ }
818
+
819
+ const parts: string[] = [];
820
+ if (missing > 0) parts.push(`${missing} missing`);
821
+ if (stale > 0) parts.push(`${stale} stale`);
822
+ if (handwritten > 0) parts.push(`${handwritten} hand-written`);
823
+
824
+ return {
825
+ name: "nested-AGENTS.md",
826
+ status: stale > 0 ? "warn" : "pass",
827
+ message: `${parts.join(", ")} — ${issues.slice(0, 3).join("; ")}${issues.length > 3 ? ` (+${issues.length - 3} more)` : ""}`,
828
+ };
829
+ }
830
+
831
+ // ---------------------------------------------------------------------------
832
+ // Domain reporting (RFC-0640)
833
+ // ---------------------------------------------------------------------------
834
+
835
+ interface DomainReport {
836
+ domain: string;
837
+ register: "business" | "creative" | null;
838
+ terminology: Record<string, string>;
839
+ invariants: Array<{ id: string; rule: string; severity: string }>;
840
+ source: "forge.yaml" | "profile" | "default";
841
+ profileId?: string;
842
+ }
843
+
844
+ function buildTerminologyMap(
845
+ config: ReturnType<typeof loadForgeConfig>,
846
+ profileTerminology?: Record<string, string>,
847
+ ): Record<string, string> {
848
+ const result: Record<string, string> = {};
849
+ for (const key of Object.keys(TERMINOLOGY_DEFAULTS)) {
850
+ result[key] = resolveTerminology(config, profileTerminology, key);
851
+ }
852
+ // Also include any custom keys from bindings.terminology
853
+ if (config.bindings?.terminology) {
854
+ for (const key of Object.keys(config.bindings.terminology)) {
855
+ if (!(key in result)) {
856
+ result[key] = resolveTerminology(config, profileTerminology, key);
857
+ }
858
+ }
859
+ }
860
+ return result;
861
+ }
862
+
863
+ function resolveDomainReport(workspaceRoot: string, forgeRoot: string): DomainReport {
864
+ // 1. Try forge.yaml domain field
865
+ try {
866
+ const config = loadForgeConfig(workspaceRoot);
867
+ if (config.project.domain) {
868
+ const terminology = buildTerminologyMap(config);
869
+ const register = readRegisterFromPrefs(workspaceRoot);
870
+ return {
871
+ domain: config.project.domain,
872
+ register,
873
+ terminology,
874
+ invariants: [],
875
+ source: "forge.yaml",
876
+ };
877
+ }
878
+ } catch {
879
+ // forge.yaml not loadable
880
+ }
881
+
882
+ // 2. Try to find domain from stack profile matching config.project.stack
883
+ try {
884
+ const config = loadForgeConfig(workspaceRoot);
885
+ const profiles = listStackProfiles(forgeRoot);
886
+ for (const stackId of config.project.stack) {
887
+ const profile = profiles.find((p) => p.id === stackId);
888
+ if (profile?.domain) {
889
+ const terminology = buildTerminologyMap(config, profile.terminology);
890
+ const register = profile.register ?? readRegisterFromPrefs(workspaceRoot);
891
+ return {
892
+ domain: profile.domain,
893
+ register,
894
+ terminology,
895
+ invariants: profile.invariants ?? [],
896
+ source: "profile",
897
+ profileId: profile.id,
898
+ };
899
+ }
900
+ }
901
+ } catch {
902
+ // config or profiles not loadable
903
+ }
904
+
905
+ // 3. Default: software domain
906
+ return {
907
+ domain: "software",
908
+ register: null,
909
+ terminology: {},
910
+ invariants: [],
911
+ source: "default",
912
+ };
913
+ }
914
+
915
+ function readRegisterFromPrefs(workspaceRoot: string): "business" | "creative" | null {
916
+ try {
917
+ const prefsPath = join(workspaceRoot, "PREFERENCES.md");
918
+ const content = readFileSync(prefsPath, "utf8");
919
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
920
+ if (fmMatch) {
921
+ const fm = parseYaml(fmMatch[1]) as Record<string, unknown>;
922
+ if (fm["register"] === "creative") return "creative";
923
+ if (fm["register"] === "business") return "business";
924
+ }
925
+ } catch {
926
+ // PREFERENCES.md missing or unreadable
927
+ }
928
+ return null;
929
+ }
930
+
931
+ function checkDomainInfo(domainReport: DomainReport): DoctorCheck {
932
+ const parts: string[] = [`domain: ${domainReport.domain}`, `source: ${domainReport.source}`];
933
+ if (domainReport.register) {
934
+ parts.push(`register: ${domainReport.register}`);
935
+ }
936
+ if (Object.keys(domainReport.terminology).length > 0) {
937
+ const terms = Object.entries(domainReport.terminology)
938
+ .map(([k, v]) => `${k}=${v}`)
939
+ .join(", ");
940
+ parts.push(`terminology: ${terms}`);
941
+ }
942
+ if (domainReport.invariants.length > 0) {
943
+ parts.push(`invariants: ${domainReport.invariants.length} declared`);
944
+ }
945
+
946
+ return {
947
+ name: "domain-info",
948
+ status: "pass",
949
+ message: parts.join(", "),
950
+ };
951
+ }
952
+
953
+ // RFC-0664: Memory layer health check
954
+ function checkMemoryLayer(workspaceRoot: string): DoctorCheck {
955
+ const health = checkMemoryLayerHealth(workspaceRoot);
956
+
957
+ if (!health.memoryMdExists) {
958
+ return {
959
+ name: "memory-layer",
960
+ status: "pass",
961
+ message: "Memory layer not initialized — run 'forge create' or 'forge upgrade' to scaffold .agents/memory/",
962
+ };
963
+ }
964
+
965
+ const overBudget = health.memoryMdChars > health.budget;
966
+ const leakRisk = !health.gitignoreCoversDaily && health.dailyFileCount > 0;
967
+
968
+ if (overBudget && leakRisk) {
969
+ return {
970
+ name: "memory-layer",
971
+ status: "warn",
972
+ message: `MEMORY.md over budget (${health.memoryMdChars}/${health.budget} chars); ${health.dailyFileCount} daily file(s) untracked by .gitignore — add forge-agent-memory block`,
973
+ };
974
+ }
975
+
976
+ if (overBudget) {
977
+ return {
978
+ name: "memory-layer",
979
+ status: "warn",
980
+ message: `MEMORY.md over budget (${health.memoryMdChars}/${health.budget} chars) — compact or promote to skill knowledge`,
981
+ };
982
+ }
983
+
984
+ if (leakRisk) {
985
+ return {
986
+ name: "memory-layer",
987
+ status: "warn",
988
+ message: `${health.dailyFileCount} daily file(s) not covered by .gitignore — add forge-agent-memory block to prevent committing ephemeral logs`,
989
+ };
990
+ }
991
+
992
+ return {
993
+ name: "memory-layer",
994
+ status: "pass",
995
+ message: `MEMORY.md ${health.memoryMdChars}/${health.budget} chars; ${health.dailyFileCount} daily file(s); gitignore ${health.gitignoreCoversDaily ? "covers" : "absent (no daily files)"}`,
996
+ };
997
+ }
998
+
999
+ // ---------------------------------------------------------------------------
1000
+ // Prerequisite checks (profile-declared system dependencies)
1001
+ // ---------------------------------------------------------------------------
1002
+
1003
+ function checkPrerequisites(prerequisites: ProfilePrerequisite[]): DoctorCheck {
1004
+ if (prerequisites.length === 0) {
1005
+ return { name: "prerequisites", status: "pass", message: "No prerequisites declared" };
1006
+ }
1007
+
1008
+ const results: Array<{ id: string; name: string; status: "pass" | "fail"; message: string }> = [];
1009
+
1010
+ for (const prereq of prerequisites) {
1011
+ try {
1012
+ execSync(prereq.check, { stdio: "pipe", timeout: 10000 });
1013
+ results.push({ id: prereq.id, name: prereq.name, status: "pass", message: `${prereq.name} found` });
1014
+ } catch {
1015
+ const hint = prereq.installHint ? ` — install: ${prereq.installHint}` : "";
1016
+ results.push({ id: prereq.id, name: prereq.name, status: "fail", message: `${prereq.name} not found${hint}` });
1017
+ }
1018
+ }
1019
+
1020
+ const failed = results.filter((r) => r.status === "fail");
1021
+ const hasErrors = failed.some((r) => prerequisites.find((p) => p.id === r.id)?.severity === "error");
1022
+ const hasWarnings = failed.some((r) => prerequisites.find((p) => p.id === r.id)?.severity === "warning");
1023
+
1024
+ const status: DoctorCheck["status"] = hasErrors ? "fail" : hasWarnings ? "warn" : "pass";
1025
+
1026
+ const parts = results.map((r) => `${r.name}: ${r.status === "pass" ? "ok" : "missing"}`);
1027
+ return {
1028
+ name: "prerequisites",
1029
+ status,
1030
+ message: `${results.length} prerequisite(s): ${parts.join(", ")}`,
1031
+ };
1032
+ }
1033
+
1034
+ export async function runDoctor(
1035
+ input: ForgeCommandInput,
1036
+ context: ForgeRuntimeContext,
1037
+ ): Promise<ForgeCommandResult<{ command: string; checks: DoctorCheck[]; allPass: boolean; forbiddenImports: ForbiddenImport[]; bindings: BindingValidation; domain?: DomainReport }>> {
1038
+ const { workspaceRoot, logger, outputFormat } = context;
1039
+ const strict = input.flags["strict"] === true;
1040
+ const checks: DoctorCheck[] = [];
1041
+
1042
+ // Check forge.yaml
1043
+ const forgeYamlExists = await pathExists(join(workspaceRoot, "forge.yaml"));
1044
+ checks.push({
1045
+ name: "forge.yaml",
1046
+ status: forgeYamlExists ? "pass" : "warn",
1047
+ message: forgeYamlExists
1048
+ ? "forge.yaml found"
1049
+ : "forge.yaml not found — run 'forge create' to create project configuration",
1050
+ });
1051
+
1052
+ // Check AGENTS.md
1053
+ const agentsMdExists = await pathExists(join(workspaceRoot, "AGENTS.md"));
1054
+ checks.push({
1055
+ name: "AGENTS.md",
1056
+ status: agentsMdExists ? "pass" : "warn",
1057
+ message: agentsMdExists
1058
+ ? "AGENTS.md found"
1059
+ : "AGENTS.md not found — run 'forge create' to deploy agent instructions",
1060
+ });
1061
+
1062
+ // Check PREFERENCES.md
1063
+ const preferencesExists = await pathExists(join(workspaceRoot, "PREFERENCES.md"));
1064
+ checks.push({
1065
+ name: "PREFERENCES.md",
1066
+ status: preferencesExists ? "pass" : "warn",
1067
+ message: preferencesExists
1068
+ ? "PREFERENCES.md found"
1069
+ : "PREFERENCES.md not found — run 'forge create' to create preferences file",
1070
+ });
1071
+
1072
+ // Check .agents/skills/
1073
+ const skillsDirExists = await pathExists(join(workspaceRoot, ".agents", "skills"));
1074
+ checks.push({
1075
+ name: ".agents/skills/",
1076
+ status: skillsDirExists ? "pass" : "fail",
1077
+ message: skillsDirExists
1078
+ ? ".agents/skills/ directory found"
1079
+ : ".agents/skills/ directory not found — run 'forge create' to deploy skills",
1080
+ });
1081
+
1082
+ // Check docs/rfcs/
1083
+ const rfcsDirExists = await pathExists(join(workspaceRoot, "docs", "rfcs"));
1084
+ checks.push({
1085
+ name: "docs/rfcs/",
1086
+ status: rfcsDirExists ? "pass" : "warn",
1087
+ message: rfcsDirExists
1088
+ ? "docs/rfcs/ directory found"
1089
+ : "docs/rfcs/ directory not found — run 'forge create' to create RFC directory",
1090
+ });
1091
+
1092
+ // Check docs/adrs/
1093
+ const adrsDirExists = await pathExists(join(workspaceRoot, "docs", "adrs"));
1094
+ checks.push({
1095
+ name: "docs/adrs/",
1096
+ status: adrsDirExists ? "pass" : "warn",
1097
+ message: adrsDirExists
1098
+ ? "docs/adrs/ directory found"
1099
+ : "docs/adrs/ directory not found — run 'forge create' to create ADR directory",
1100
+ });
1101
+
1102
+ // Check @warpgogol/* forbidden imports (autonomy guard)
1103
+ let forgeRoot: string;
1104
+ try {
1105
+ forgeRoot = resolveForgeRoot(workspaceRoot);
1106
+ } catch {
1107
+ forgeRoot = join(workspaceRoot, "packages", "forge");
1108
+ }
1109
+
1110
+ // RFC-0640: Resolve domain report for domain-aware checks
1111
+ const domainReport = resolveDomainReport(workspaceRoot, forgeRoot);
1112
+
1113
+ // RFC-0640: Domain info check
1114
+ checks.push(checkDomainInfo(domainReport));
1115
+
1116
+ // RFC-0675: Enforce invariants using the invariant engine
1117
+ if (domainReport.invariants.length > 0) {
1118
+ const profiles = listStackProfiles(forgeRoot);
1119
+ const profile = domainReport.profileId
1120
+ ? profiles.find((p) => p.id === domainReport.profileId)
1121
+ : undefined;
1122
+
1123
+ const invariantResults = profile
1124
+ ? checkInvariants(profile, workspaceRoot)
1125
+ : [];
1126
+ const allViolations = invariantResults.flatMap((r) => r.violations);
1127
+ const errorViolations = allViolations.filter((v) => v.severity === "error");
1128
+ const warningViolations = allViolations.filter((v) => v.severity === "warning");
1129
+ const checkedCount = invariantResults.filter((r) => r.checked).length;
1130
+ const advisoryCount = invariantResults.filter((r) => !r.checked).length;
1131
+
1132
+ const status: DoctorCheck["status"] =
1133
+ errorViolations.length > 0 ? "fail" :
1134
+ warningViolations.length > 0 ? "warn" :
1135
+ "pass";
1136
+
1137
+ const parts: string[] = [];
1138
+ if (allViolations.length > 0) {
1139
+ parts.push(`${allViolations.length} violation(s)`);
1140
+ for (const v of allViolations.slice(0, 3)) {
1141
+ parts.push(`${v.invariantId}: ${v.file} — ${v.message}`);
1142
+ }
1143
+ if (allViolations.length > 3) parts.push(`(+${allViolations.length - 3} more)`);
1144
+ } else {
1145
+ parts.push(`${checkedCount} checked, ${advisoryCount} advisory`);
1146
+ }
1147
+
1148
+ checks.push({
1149
+ name: "domain-invariants",
1150
+ status,
1151
+ message: parts.join("; "),
1152
+ invariantViolations: allViolations.length > 0 ? allViolations : undefined,
1153
+ });
1154
+ }
1155
+
1156
+ // Prerequisite checks (profile-declared system dependencies)
1157
+ if (domainReport.profileId) {
1158
+ const profiles = listStackProfiles(forgeRoot);
1159
+ const profile = profiles.find((p) => p.id === domainReport.profileId);
1160
+ if (profile?.prerequisites && profile.prerequisites.length > 0) {
1161
+ checks.push(checkPrerequisites(profile.prerequisites));
1162
+ }
1163
+ }
1164
+
1165
+ // RFC-0640: Run forge.profile.validate as advisory check (warn on failure, not fail)
1166
+ const profileValidateResult = await runProfileValidate(
1167
+ { argv: [], flags: {} },
1168
+ { ...context, forgeRoot },
1169
+ );
1170
+ const invalidProfiles = profileValidateResult.data?.profiles.filter((p) => !p.valid) ?? [];
1171
+ checks.push({
1172
+ name: "profile-validate",
1173
+ status: invalidProfiles.length === 0 ? "pass" : "warn",
1174
+ message:
1175
+ invalidProfiles.length === 0
1176
+ ? `${profileValidateResult.data?.profiles.length ?? 0} profile(s) valid`
1177
+ : `${invalidProfiles.length} profile(s) invalid (advisory): ${invalidProfiles.map((p) => p.id).join(", ")}`,
1178
+ });
1179
+
1180
+ const forbiddenImports = await scanForForbiddenImports(forgeRoot, workspaceRoot);
1181
+ checks.push({
1182
+ name: "autonomy-guard",
1183
+ status: forbiddenImports.length === 0 ? "pass" : "fail",
1184
+ message:
1185
+ forbiddenImports.length === 0
1186
+ ? "No @warpgogol/* imports in forge source"
1187
+ : `${forbiddenImports.length} @warpgogol/* import(s) found in forge source — remove them`,
1188
+ });
1189
+
1190
+ // Check bindings contract (RFC-0393)
1191
+ const bindingsResult = await validateBindings(workspaceRoot);
1192
+ checks.push({
1193
+ name: "bindings",
1194
+ status: bindingsResult.invalid.length === 0 ? "pass" : "fail",
1195
+ message:
1196
+ bindingsResult.invalid.length === 0
1197
+ ? `Bindings: ${bindingsResult.resolved.length} resolved, ${bindingsResult.absent.length} absent`
1198
+ : `Bindings: ${bindingsResult.invalid.length} invalid — ${bindingsResult.invalid.join(", ")}`,
1199
+ });
1200
+
1201
+ // Check stale knowledge files (RFC-0524, RFC-0539)
1202
+ const staleCheck = await checkStaleKnowledgeFiles(workspaceRoot, forgeRoot);
1203
+ checks.push(staleCheck);
1204
+
1205
+ // RFC-0660: Check legacy sections in knowledge files
1206
+ const legacyCheck = checkLegacyKnowledgeSections(workspaceRoot, forgeRoot);
1207
+ checks.push(legacyCheck);
1208
+
1209
+ // RFC-0661: Check knowledge layer token budgets
1210
+ const budgetCheck = checkKnowledgeBudgets(workspaceRoot, forgeRoot);
1211
+ checks.push(budgetCheck);
1212
+
1213
+ // RFC-0663: Check cross-skill duplicate principles
1214
+ const duplicatesCheck = checkKnowledgeDuplicates(workspaceRoot, forgeRoot);
1215
+ checks.push(duplicatesCheck);
1216
+
1217
+ // RFC-0663: Validate shared knowledge layer file
1218
+ const sharedKnowledgeCheck = checkSharedKnowledgeFile(workspaceRoot, forgeRoot);
1219
+ checks.push(sharedKnowledgeCheck);
1220
+
1221
+ // RFC-0664: Check memory layer health (budget, gitignore coverage, leak risk)
1222
+ checks.push(checkMemoryLayer(workspaceRoot));
1223
+
1224
+ // RFC-0539: Check pack skills — stale/missing copies and config validation
1225
+ const packCheck = await checkPackSkills(workspaceRoot);
1226
+ checks.push(packCheck);
1227
+
1228
+ // RFC-0704: Check independent version packages — paths must exist and contain package.json
1229
+ const independentCheck = await checkIndependentVersionPackages(workspaceRoot);
1230
+ checks.push(independentCheck);
1231
+
1232
+ // RFC-0611: Check nested AGENTS.md — missing, stale, hand-written
1233
+ // RFC-0640: Use profile-driven workspace types when available (all domains)
1234
+ // RFC-0640 fix: previously gated by isSoftwareDomain, which skipped the check
1235
+ // entirely for non-software domains. Now runs for all domains — profile-driven
1236
+ // wsTypes replace hardcoded detection when present.
1237
+ {
1238
+ let wsTypes: ProfileWorkspaceType[] | undefined;
1239
+ try {
1240
+ const config = loadForgeConfig(workspaceRoot);
1241
+ // RFC-0643: prefer config.profile (loaded by loadForgeConfig)
1242
+ if (config.profile?.workspaceTypes && config.profile.workspaceTypes.length > 0) {
1243
+ wsTypes = config.profile.workspaceTypes;
1244
+ } else {
1245
+ const profiles = listStackProfiles(forgeRoot);
1246
+ for (const stackId of config.project.stack) {
1247
+ const profile = profiles.find((p) => p.id === stackId);
1248
+ if (profile?.workspaceTypes && profile.workspaceTypes.length > 0) {
1249
+ wsTypes = profile.workspaceTypes;
1250
+ break;
1251
+ }
1252
+ }
1253
+ }
1254
+ } catch {
1255
+ // profiles not loadable
1256
+ }
1257
+ const nestedCheck = await checkNestedAgentsMd(workspaceRoot, wsTypes);
1258
+ checks.push(nestedCheck);
1259
+ }
1260
+
1261
+ // RFC-0640: --strict flag elevates warn to fail for domain-related checks
1262
+ const finalChecks = strict
1263
+ ? checks.map((c) =>
1264
+ c.status === "warn" &&
1265
+ (c.name === "domain-invariants" || c.name === "profile-validate")
1266
+ ? { ...c, status: "fail" as const }
1267
+ : c,
1268
+ )
1269
+ : checks;
1270
+
1271
+ const allPass = finalChecks.every((c) => c.status === "pass");
1272
+ const hasFails = finalChecks.some((c) => c.status === "fail");
1273
+
1274
+ if (outputFormat === "pretty") {
1275
+ logger.section(`Forge Doctor — ${workspaceRoot}`);
1276
+ for (const check of finalChecks) {
1277
+ const icon = check.status === "pass" ? "✓" : check.status === "warn" ? "⚠" : "✖";
1278
+ const fn = check.status === "pass" ? logger.success : check.status === "warn" ? logger.warn : logger.error;
1279
+ fn(`${icon} ${check.name}: ${check.message}`);
1280
+ }
1281
+ if (allPass) {
1282
+ logger.success("All checks passed — forge is properly configured.");
1283
+ } else if (hasFails) {
1284
+ logger.error("Some checks failed — run 'forge create' to fix.");
1285
+ } else {
1286
+ logger.warn("Some checks warn — review above.");
1287
+ }
1288
+ }
1289
+
1290
+ return {
1291
+ data: { command: "forge.doctor", checks: finalChecks, allPass, forbiddenImports, bindings: bindingsResult, domain: domainReport },
1292
+ exitCode: hasFails ? 1 : 0,
1293
+ summary: allPass
1294
+ ? "forge.doctor: all checks passed"
1295
+ : `forge.doctor: ${finalChecks.filter((c) => c.status === "fail").length} fail(s), ${finalChecks.filter((c) => c.status === "warn").length} warn(s)`,
1296
+ };
1297
+ }