@blackbelt-technology/pi-dashboard-extension 0.5.4 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/.pi/skills/browser/LICENSE +201 -0
  2. package/.pi/skills/browser/SKILL.md +105 -0
  3. package/.pi/skills/browser/UPSTREAM.md +46 -0
  4. package/.pi/skills/browser/references/electron.md +351 -0
  5. package/.pi/skills/browser/references/web.md +2789 -0
  6. package/.pi/skills/browser/scripts/detect-dashboard.sh +55 -0
  7. package/.pi/skills/doctor/AGENTS.md +27 -0
  8. package/.pi/skills/doctor/SKILL.md +89 -0
  9. package/.pi/skills/doctor/_lib/checks.ts +177 -0
  10. package/.pi/skills/doctor/_lib/derive-tokens.ts +43 -0
  11. package/.pi/skills/doctor/_lib/front-matter.ts +122 -0
  12. package/.pi/skills/doctor/_lib/index.ts +14 -0
  13. package/.pi/skills/doctor/_lib/knowledge-hash.ts +74 -0
  14. package/.pi/skills/doctor/_lib/provenance.ts +50 -0
  15. package/.pi/skills/doctor/_lib/regenerate.ts +100 -0
  16. package/.pi/skills/doctor/_lib/router.ts +155 -0
  17. package/.pi/skills/doctor/_lib/server-tier.ts +62 -0
  18. package/.pi/skills/doctor/modules/build-reload.knowledge.hash +1 -0
  19. package/.pi/skills/doctor/modules/build-reload.md +51 -0
  20. package/.pi/skills/doctor/modules/env-node.knowledge.hash +1 -0
  21. package/.pi/skills/doctor/modules/env-node.md +49 -0
  22. package/.pi/skills/doctor/modules/install-topology.knowledge.hash +1 -0
  23. package/.pi/skills/doctor/modules/install-topology.md +53 -0
  24. package/.pi/skills/doctor/modules/model-resolution.knowledge.hash +1 -0
  25. package/.pi/skills/doctor/modules/model-resolution.md +53 -0
  26. package/.pi/skills/doctor/modules/peers.knowledge.hash +1 -0
  27. package/.pi/skills/doctor/modules/peers.md +57 -0
  28. package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -0
  29. package/.pi/skills/doctor/modules/pi-resolution.md +60 -0
  30. package/.pi/skills/doctor/modules/plugins-bridges.knowledge.hash +1 -0
  31. package/.pi/skills/doctor/modules/plugins-bridges.md +56 -0
  32. package/.pi/skills/pi-dashboard/SKILL.md +68 -0
  33. package/.pi/skills/pi-dashboard/commands/README.md +45 -0
  34. package/.pi/skills/pi-dashboard/commands/dashboard-flow-abort.md +10 -0
  35. package/.pi/skills/pi-dashboard/commands/dashboard-flow-auto.md +10 -0
  36. package/.pi/skills/pi-dashboard/commands/dashboard-git-branches.md +6 -0
  37. package/.pi/skills/pi-dashboard/commands/dashboard-git-init.md +8 -0
  38. package/.pi/skills/pi-dashboard/commands/dashboard-git-stash-pop.md +8 -0
  39. package/.pi/skills/pi-dashboard/commands/dashboard-list-models.md +10 -0
  40. package/.pi/skills/pi-dashboard/commands/dashboard-peer-list.md +6 -0
  41. package/.pi/skills/pi-dashboard/commands/dashboard-peer-scan.md +6 -0
  42. package/.pi/skills/pi-dashboard/commands/dashboard-pin-list.md +5 -0
  43. package/.pi/skills/pi-dashboard/commands/dashboard-proposal-archive.md +6 -0
  44. package/.pi/skills/pi-dashboard/commands/dashboard-proposal-attach.md +10 -0
  45. package/.pi/skills/pi-dashboard/commands/dashboard-proposal-detach.md +10 -0
  46. package/.pi/skills/pi-dashboard/commands/dashboard-server-config.md +5 -0
  47. package/.pi/skills/pi-dashboard/commands/dashboard-server-health.md +6 -0
  48. package/.pi/skills/pi-dashboard/commands/dashboard-server-tunnel-off.md +6 -0
  49. package/.pi/skills/pi-dashboard/commands/dashboard-server-tunnel-on.md +6 -0
  50. package/.pi/skills/pi-dashboard/commands/dashboard-server-tunnel-status.md +6 -0
  51. package/.pi/skills/pi-dashboard/commands/dashboard-session-abort-all.md +14 -0
  52. package/.pi/skills/pi-dashboard/commands/dashboard-session-abort.md +10 -0
  53. package/.pi/skills/pi-dashboard/commands/dashboard-session-diff.md +11 -0
  54. package/.pi/skills/pi-dashboard/commands/dashboard-session-fork.md +10 -0
  55. package/.pi/skills/pi-dashboard/commands/dashboard-session-hide.md +10 -0
  56. package/.pi/skills/pi-dashboard/commands/dashboard-session-info.md +11 -0
  57. package/.pi/skills/pi-dashboard/commands/dashboard-session-kill.md +10 -0
  58. package/.pi/skills/pi-dashboard/commands/dashboard-session-list-active.md +8 -0
  59. package/.pi/skills/pi-dashboard/commands/dashboard-session-list-here.md +8 -0
  60. package/.pi/skills/pi-dashboard/commands/dashboard-session-list.md +6 -0
  61. package/.pi/skills/pi-dashboard/commands/dashboard-session-model.md +10 -0
  62. package/.pi/skills/pi-dashboard/commands/dashboard-session-rename.md +10 -0
  63. package/.pi/skills/pi-dashboard/commands/dashboard-session-resume.md +10 -0
  64. package/.pi/skills/pi-dashboard/commands/dashboard-session-spawn.md +10 -0
  65. package/.pi/skills/pi-dashboard/commands/dashboard-session-tell.md +10 -0
  66. package/.pi/skills/pi-dashboard/commands/dashboard-session-thinking.md +10 -0
  67. package/.pi/skills/pi-dashboard/commands/dashboard-session-unhide.md +10 -0
  68. package/.pi/skills/pi-dashboard/references/api-reference.md +30 -0
  69. package/.pi/skills/pi-dashboard/references/recipes.md +38 -0
  70. package/.pi/skills/pi-dashboard/references/slash-commands.md +71 -0
  71. package/.pi/skills/pi-dashboard/scripts/dashboard-api.sh +6 -0
  72. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +217 -0
  73. package/.pi/skills/project-init/SKILL.md +279 -0
  74. package/.pi/skills/project-init/dox-doctrine.md +104 -0
  75. package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +111 -0
  76. package/.pi/skills/project-init/profiles/coding/profile.json +5 -0
  77. package/.pi/skills/project-init/profiles/coding/prompts/plan-change.md +5 -0
  78. package/.pi/skills/project-init/profiles/coding/prompts/tdd-loop.md +6 -0
  79. package/.pi/skills/project-init/profiles/coding/settings.json.tmpl +9 -0
  80. package/.pi/skills/project-init/profiles/docs/AGENTS.md.tmpl +37 -0
  81. package/.pi/skills/project-init/profiles/docs/profile.json +4 -0
  82. package/.pi/skills/project-init/profiles/docs/prompts/draft-page.md +5 -0
  83. package/.pi/skills/project-init/profiles/docs/settings.json.tmpl +9 -0
  84. package/package.json +12 -4
  85. package/src/AGENTS.md +56 -0
  86. package/src/__tests__/abort-latch.test.ts +97 -0
  87. package/src/__tests__/agent-settled.test.ts +82 -0
  88. package/src/__tests__/artifact-roots.test.ts +83 -0
  89. package/src/__tests__/ask-user-attachments.test.ts +106 -0
  90. package/src/__tests__/ask-user-tool.test.ts +90 -27
  91. package/src/__tests__/auto-session-namer.test.ts +339 -0
  92. package/src/__tests__/bridge-default-model-apply.test.ts +242 -0
  93. package/src/__tests__/bridge-default-model-gate.test.ts +6 -3
  94. package/src/__tests__/bridge-followup-mutation.test.ts +217 -0
  95. package/src/__tests__/bridge-followup-queue-drain.test.ts +266 -0
  96. package/src/__tests__/bridge-hasui-flip.test.ts +109 -0
  97. package/src/__tests__/bridge-no-queue-mutation.test.ts +112 -0
  98. package/src/__tests__/bridge-plugin-emit-event.test.ts +44 -0
  99. package/src/__tests__/bridge-shutdown-reset.test.ts +57 -136
  100. package/src/__tests__/bridge-slash-command-routing.test.ts +7 -7
  101. package/src/__tests__/bridge-stop-after-turn.test.ts +72 -0
  102. package/src/__tests__/bridge-system-followup.test.ts +163 -0
  103. package/src/__tests__/bridge-thinking-level-select.test.ts +68 -0
  104. package/src/__tests__/browser-skill-registered.test.ts +84 -0
  105. package/src/__tests__/build-provider-catalogue.test.ts +35 -1
  106. package/src/__tests__/command-handler.test.ts +331 -35
  107. package/src/__tests__/commit-draft.test.ts +100 -0
  108. package/src/__tests__/connection-dropped-frames.test.ts +78 -0
  109. package/src/__tests__/custom-provider-apikey-roundtrip.test.ts +128 -0
  110. package/src/__tests__/cwd-missing-probe.test.ts +82 -0
  111. package/src/__tests__/dashboard-commands-shipped.test.ts +53 -0
  112. package/src/__tests__/dashboard-context-injector.test.ts +190 -0
  113. package/src/__tests__/doctor/checks.test.ts +121 -0
  114. package/src/__tests__/doctor/modules.test.ts +64 -0
  115. package/src/__tests__/doctor/provenance-hash.test.ts +94 -0
  116. package/src/__tests__/doctor/router.test.ts +143 -0
  117. package/src/__tests__/empty-actionable-guard-config.test.ts +32 -0
  118. package/src/__tests__/empty-actionable-guard.test.ts +73 -0
  119. package/src/__tests__/enrich-model-metadata.test.ts +21 -0
  120. package/src/__tests__/extension-slash-command-detection.test.ts +37 -1
  121. package/src/__tests__/filter-enabled-models.test.ts +151 -0
  122. package/src/__tests__/fixtures/turn-actionability-fixtures.ts +69 -0
  123. package/src/__tests__/git-info-status.test.ts +73 -0
  124. package/src/__tests__/git-poll.test.ts +69 -0
  125. package/src/__tests__/markdown-image-inliner.test.ts +37 -0
  126. package/src/__tests__/model-resolve.test.ts +379 -0
  127. package/src/__tests__/pi-version-tracker.test.ts +109 -0
  128. package/src/__tests__/process-scanner.test.ts +112 -22
  129. package/src/__tests__/project-init-detect-stack.test.ts +61 -0
  130. package/src/__tests__/project-init-dox-kb-config.test.ts +53 -0
  131. package/src/__tests__/project-init-profiles.test.ts +84 -0
  132. package/src/__tests__/project-init-scaffold.test.ts +139 -0
  133. package/src/__tests__/project-init-seed-doctrine.test.ts +100 -0
  134. package/src/__tests__/project-trust.test.ts +92 -0
  135. package/src/__tests__/prompt-expander.test.ts +191 -1
  136. package/src/__tests__/provider-register-reload.test.ts +36 -6
  137. package/src/__tests__/provider-register-thinking-levels.test.ts +51 -0
  138. package/src/__tests__/retry-tracker.test.ts +75 -70
  139. package/src/__tests__/role-manager.test.ts +585 -0
  140. package/src/__tests__/role-model-tools-registry-readiness.test.ts +114 -0
  141. package/src/__tests__/role-model-tools.test.ts +229 -0
  142. package/src/__tests__/search-files-completeness.test.ts +111 -0
  143. package/src/__tests__/search-files-ranking.test.ts +168 -0
  144. package/src/__tests__/server-auto-start.test.ts +121 -4
  145. package/src/__tests__/server-launcher-launch.test.ts +24 -6
  146. package/src/__tests__/server-launcher.test.ts +19 -2
  147. package/src/__tests__/session-sync.test.ts +36 -0
  148. package/src/__tests__/subagent-frame-buffer.test.ts +239 -0
  149. package/src/__tests__/tool-result-image-inliner.test.ts +206 -0
  150. package/src/__tests__/tui-prompt-adapter.test.ts +70 -64
  151. package/src/__tests__/turn-actionability.test.ts +86 -0
  152. package/src/__tests__/vcs-info.test.ts +145 -4
  153. package/src/__tests__/visibility-intent.test.ts +43 -0
  154. package/src/abort-latch.ts +55 -0
  155. package/src/abort-latch.ts.AGENTS.md +3 -0
  156. package/src/agent-settled.ts +72 -0
  157. package/src/agent-settled.ts.AGENTS.md +3 -0
  158. package/src/artifact-roots.ts +73 -0
  159. package/src/artifact-roots.ts.AGENTS.md +3 -0
  160. package/src/ask-user-attachments.ts +121 -0
  161. package/src/ask-user-attachments.ts.AGENTS.md +3 -0
  162. package/src/ask-user-tool.ts +56 -58
  163. package/src/ask-user-tool.ts.AGENTS.md +3 -0
  164. package/src/auto-session-namer.ts +334 -0
  165. package/src/auto-session-namer.ts.AGENTS.md +3 -0
  166. package/src/bridge-context.ts +86 -8
  167. package/src/bridge-context.ts.AGENTS.md +3 -0
  168. package/src/bridge-default-model-gate.ts +22 -6
  169. package/src/bridge-default-model-gate.ts.AGENTS.md +3 -0
  170. package/src/bridge.ts +1241 -360
  171. package/src/bridge.ts.AGENTS.md +3 -0
  172. package/src/canvas-tool.ts +107 -0
  173. package/src/command-handler.ts +490 -51
  174. package/src/command-handler.ts.AGENTS.md +3 -0
  175. package/src/commit-draft-agent.ts +114 -0
  176. package/src/commit-draft-agent.ts.AGENTS.md +3 -0
  177. package/src/commit-draft.ts +136 -0
  178. package/src/commit-draft.ts.AGENTS.md +3 -0
  179. package/src/connection.ts +32 -1
  180. package/src/connection.ts.AGENTS.md +3 -0
  181. package/src/dashboard-context-injector.ts +124 -0
  182. package/src/dashboard-context-injector.ts.AGENTS.md +3 -0
  183. package/src/dashboard-default-adapter.ts.AGENTS.md +3 -0
  184. package/src/dev-build.ts.AGENTS.md +3 -0
  185. package/src/empty-actionable-guard-config.ts +32 -0
  186. package/src/empty-actionable-guard-config.ts.AGENTS.md +3 -0
  187. package/src/empty-actionable-guard.ts +90 -0
  188. package/src/empty-actionable-guard.ts.AGENTS.md +3 -0
  189. package/src/event-forwarder.ts.AGENTS.md +3 -0
  190. package/src/flow-event-wiring.ts +4 -14
  191. package/src/flow-event-wiring.ts.AGENTS.md +3 -0
  192. package/src/git-link-builder.ts.AGENTS.md +3 -0
  193. package/src/git-poll.ts +38 -0
  194. package/src/git-poll.ts.AGENTS.md +3 -0
  195. package/src/hasui-flip.ts +56 -0
  196. package/src/hasui-flip.ts.AGENTS.md +3 -0
  197. package/src/markdown-image-inliner.ts +45 -2
  198. package/src/markdown-image-inliner.ts.AGENTS.md +3 -0
  199. package/src/model-tracker.ts +145 -19
  200. package/src/model-tracker.ts.AGENTS.md +3 -0
  201. package/src/multiselect-decode.ts.AGENTS.md +3 -0
  202. package/src/multiselect-list.ts.AGENTS.md +3 -0
  203. package/src/multiselect-polyfill.ts.AGENTS.md +3 -0
  204. package/src/process-metrics.ts.AGENTS.md +3 -0
  205. package/src/process-scanner.ts +114 -103
  206. package/src/process-scanner.ts.AGENTS.md +3 -0
  207. package/src/project-init/AGENTS.md +12 -0
  208. package/src/project-init/detect-stack.ts +146 -0
  209. package/src/project-init/dox-kb-config.ts +47 -0
  210. package/src/project-init/profiles.ts +135 -0
  211. package/src/project-init/scaffold.ts +192 -0
  212. package/src/project-init/seed-doctrine.ts +95 -0
  213. package/src/project-trust.ts +63 -0
  214. package/src/project-trust.ts.AGENTS.md +3 -0
  215. package/src/prompt-bus.ts +10 -1
  216. package/src/prompt-bus.ts.AGENTS.md +3 -0
  217. package/src/prompt-expander.ts +238 -37
  218. package/src/prompt-expander.ts.AGENTS.md +3 -0
  219. package/src/provider-register.ts +323 -54
  220. package/src/provider-register.ts.AGENTS.md +3 -0
  221. package/src/retry-tracker.ts +64 -39
  222. package/src/retry-tracker.ts.AGENTS.md +3 -0
  223. package/src/role-manager.ts +436 -0
  224. package/src/role-manager.ts.AGENTS.md +3 -0
  225. package/src/role-model-tools.ts +301 -0
  226. package/src/role-model-tools.ts.AGENTS.md +3 -0
  227. package/src/server-auto-start.ts +59 -23
  228. package/src/server-auto-start.ts.AGENTS.md +3 -0
  229. package/src/server-launcher.ts +56 -16
  230. package/src/server-launcher.ts.AGENTS.md +3 -0
  231. package/src/session-sync.ts +111 -15
  232. package/src/session-sync.ts.AGENTS.md +3 -0
  233. package/src/slash-dispatch.ts +13 -11
  234. package/src/slash-dispatch.ts.AGENTS.md +3 -0
  235. package/src/source-detector.ts.AGENTS.md +3 -0
  236. package/src/subagent-frame-buffer.ts +220 -0
  237. package/src/subagent-frame-buffer.ts.AGENTS.md +3 -0
  238. package/src/tool-result-image-inliner.ts +204 -0
  239. package/src/tool-result-image-inliner.ts.AGENTS.md +3 -0
  240. package/src/tui-prompt-adapter.ts +123 -0
  241. package/src/tui-prompt-adapter.ts.AGENTS.md +3 -0
  242. package/src/turn-actionability.ts +117 -0
  243. package/src/turn-actionability.ts.AGENTS.md +3 -0
  244. package/src/ui-modules.ts.AGENTS.md +3 -0
  245. package/src/vcs-info.ts +91 -129
  246. package/src/vcs-info.ts.AGENTS.md +3 -0
  247. package/src/visibility-intent.ts +34 -0
  248. package/src/visibility-intent.ts.AGENTS.md +3 -0
  249. package/src/__tests__/bridge-retry-ordering.test.ts +0 -148
  250. package/src/__tests__/bridge-shadow-queue-drain.test.ts +0 -221
  251. package/src/__tests__/fixtures/usage-limit-error-strings.ts +0 -127
  252. package/src/__tests__/usage-limit-orderer.test.ts +0 -117
  253. package/src/__tests__/vcs-info-jj.test.ts +0 -145
  254. package/src/usage-limit-orderer.ts +0 -93
@@ -0,0 +1,55 @@
1
+ #!/usr/bin/env bash
2
+ # Detect dashboard server URL, mode, and Vite dev server status.
3
+ #
4
+ # Usage:
5
+ # bash detect-dashboard.sh
6
+ #
7
+ # Output (key=value):
8
+ # DASHBOARD_URL=http://localhost:8000
9
+ # MODE=dev
10
+ # VITE_URL=http://localhost:5173
11
+ #
12
+ # Or if not running:
13
+ # DASHBOARD=not-running
14
+
15
+ set -euo pipefail
16
+
17
+ # ── Read port from config ──────────────────────────────────────────
18
+
19
+ CONFIG_FILE="$HOME/.pi/dashboard/config.json"
20
+
21
+ if [ -f "$CONFIG_FILE" ]; then
22
+ PORT=$(grep '"port"' "$CONFIG_FILE" 2>/dev/null | grep -o '[0-9]*' || echo 8000)
23
+ else
24
+ PORT=8000
25
+ fi
26
+
27
+ BASE="http://localhost:$PORT"
28
+
29
+ # ── Probe dashboard health ─────────────────────────────────────────
30
+
31
+ HEALTH=$(curl -s --connect-timeout 2 --max-time 3 "$BASE/api/health" 2>/dev/null || echo "")
32
+
33
+ if [ -z "$HEALTH" ]; then
34
+ echo "DASHBOARD=not-running"
35
+ echo "PORT=$PORT"
36
+ exit 0
37
+ fi
38
+
39
+ echo "DASHBOARD_URL=$BASE"
40
+
41
+ # ── Extract mode ───────────────────────────────────────────────────
42
+
43
+ MODE=$(echo "$HEALTH" | grep -o '"mode":"[^"]*"' | head -1 | cut -d'"' -f4 || echo "unknown")
44
+ echo "MODE=$MODE"
45
+
46
+ # ── Probe Vite dev server ─────────────────────────────────────────
47
+
48
+ VITE_PORT=5173
49
+ VITE_PROBE=$(curl -s --connect-timeout 1 --max-time 2 "http://localhost:$VITE_PORT" 2>/dev/null || echo "")
50
+
51
+ if [ -n "$VITE_PROBE" ]; then
52
+ echo "VITE_URL=http://localhost:$VITE_PORT"
53
+ else
54
+ echo "VITE=not-running"
55
+ fi
@@ -0,0 +1,27 @@
1
+ # DOX — packages/extension/.pi/skills/doctor
2
+
3
+ Modular doctor skill. Thin router `SKILL.md` + N self-contained capability MDs
4
+ read on demand + shared `_lib` check primitives. Router derives symptom map +
5
+ sweep DAG from module front-matter; adding a module MD auto-registers it.
6
+ See change: add-modular-doctor-skill.
7
+
8
+ | File | Purpose |
9
+ |------|---------|
10
+ | `SKILL.md` | Thin router. NO capability knowledge. Routes symptom→module, runs named module, or full sweep (env→pi→peers→plugins→build→runtime) with lower-layer short-circuit. Documents two-tier self-update + `--regenerate`. |
11
+ | `_lib/index.ts` | Barrel re-exporting all `_lib` primitives. |
12
+ | `_lib/front-matter.ts` | Parses module front-matter (`name`/`scope`/`symptoms`/`depends-on`/`derives-from`). `parseFrontMatter`, `extractFrontMatterBlock`. Scalar + block/inline list subset. |
13
+ | `_lib/router.ts` | `loadModules`, `buildSymptomMap`, `routeSymptom` (punctuation-insensitive), `buildSweepOrder` (topo-sort by depends-on), `planSweep` (short-circuit: dep failure suppresses dependents). |
14
+ | `_lib/checks.ts` | Wraps shared resolver primitives (NO reimpl). `probePeer` (tier-1 createRequire / tier-2 pi packages[]), `detectNameSkew`, `enumeratePiInstalls`, `piVersionDivergence`, `readPiFloor`. |
15
+ | `_lib/server-tier.ts` | Additive `/api/*` tier. `fetchHealth`, `fetchPiCoreVersions` — degrade to `{ok:false,reason}` when server down, never throw. |
16
+ | `_lib/provenance.ts` | Fact labeller. `fileFact`/`serverFact`/`summariseProvenance` — `serverUnavailable` true when no server-enriched fact. |
17
+ | `_lib/knowledge-hash.ts` | Per-module semantic hash. `extractSemanticTokens` (package names + semver, no prose), `computeKnowledgeHash`, `checkDrift`, read/write sidecar. Whitespace-stable; peer rename / floor bump drifts. |
18
+ | `_lib/derive-tokens.ts` | `MODULE_TOKEN_SOURCES` maps module→repo-relative derives-from files; `deriveLiveTokens(repoRoot,id)` reads them for the hash. |
19
+ | `_lib/regenerate.ts` | CLI: `--check` reports drift, `--write [module]` rewrites sidecars from live sources. Never edits authored prose. `findRepoRoot`, `reportDrift`, `writeHashes`. |
20
+ | `modules/env-node.md` | Node version/OS/platform baseline. depends-on: none (root layer). |
21
+ | `modules/pi-resolution.md` | Enumerate every pi install (CLI/repo/managed/nvm/cwd), flag divergence + floor violation. depends-on: env-node. |
22
+ | `modules/peers.md` | pi-flows + anthropic peer via tier-1/tier-2; detect published-name skew. depends-on: pi-resolution. |
23
+ | `modules/plugins-bridges.md` | Bridge `bridgeLoadedFrom`; flag dashboardPluginBridges-only (invisible to pi packages[]); activation status. depends-on: peers. |
24
+ | `modules/build-reload.md` | Three-component rebuild/reload gaps (client build / server restart / bridge reload). depends-on: install-topology. |
25
+ | `modules/install-topology.md` | Detect npm-global / Electron (immutable) / Docker / dev; topology-specific fix routing. depends-on: env-node. |
26
+ | `modules/model-resolution.md` | `model:resolve` handler, roles/preset, `@role` resolvability, pi-flows model-resolve-aware. depends-on: pi-resolution, plugins-bridges. |
27
+ | `modules/*.knowledge.hash` | Per-module stored knowledge-hash sidecar (7). Regenerate via `_lib/regenerate.ts --write`. |
@@ -0,0 +1,89 @@
1
+ ---
2
+ name: doctor
3
+ description: >-
4
+ Diagnose why pi-flows, the Anthropic-messages bridge, model resolution, a pi
5
+ install, a peer, a plugin/bridge, or a build/reload is broken in the
6
+ pi-agent-dashboard. Derives every fact live (works with the server down),
7
+ reports pi across ALL install locations, detects peer name-skew, and routes
8
+ each failure to the topology-correct fix. Use on "flow won't show",
9
+ "bridge waiting_peers", "pi version mismatch", "I built it but it's still
10
+ broken", "which pi is this using", "agent model fails at spawn", "diagnose the
11
+ dashboard", "doctor".
12
+ license: MIT
13
+ ---
14
+
15
+ # doctor — modular diagnostic skill
16
+
17
+ This SKILL.md is a **thin router**. It owns NO capability knowledge. Every
18
+ diagnostic fact lives in a self-contained capability module under `modules/`,
19
+ read on demand. The router derives its symptom map and sweep order from each
20
+ module's front-matter (`symptoms:`, `depends-on:`) — so **adding a module MD
21
+ auto-registers it with no edit here**.
22
+
23
+ ## Modules
24
+
25
+ Each `modules/<id>.md` follows a uniform 5-part contract: **SCOPE · KNOWLEDGE ·
26
+ CHECKS · FIX ROUTING · DERIVES-FROM** (+ a `<id>.knowledge.hash` sidecar).
27
+
28
+ | id | scope |
29
+ |---|---|
30
+ | `env-node` | Node runtime + OS/platform baseline |
31
+ | `pi-resolution` | every pi install location, divergence + floor |
32
+ | `peers` | pi-flows + anthropic peer, tier-1/tier-2, name-skew |
33
+ | `plugins-bridges` | bridge registration (packages[] vs dashboardPluginBridges) + activation |
34
+ | `build-reload` | three-component rebuild/reload gaps |
35
+ | `install-topology` | npm-global / Electron / Docker / dev + topology fixes |
36
+ | `model-resolution` | model:resolve handler, roles/preset, @role resolvability |
37
+
38
+ ## How to route
39
+
40
+ The router logic lives in `_lib/router.ts` (load modules, build the symptom
41
+ map, topo-sort the sweep DAG, plan short-circuit). Use it — do not hand-keep a
42
+ catalog.
43
+
44
+ 1. **Symptom phrase** (e.g. "flow won't show") → `routeSymptom(modules, phrase)`
45
+ returns exactly one module id. Read that module MD and run its CHECKS.
46
+ 2. **Named capability** (e.g. "check peers") → read `modules/peers.md` directly.
47
+ 3. **Full sweep** (no hint, or "full") → `buildSweepOrder(modules)` orders
48
+ modules env → pi → peers → plugins → build → runtime. Run in order; when a
49
+ module fails, `planSweep(modules, failed)` marks every dependent module
50
+ `suppressed` so a lower-layer failure (missing pi) is reported as the ROOT
51
+ CAUSE and NOT re-reported as a broken bridge.
52
+
53
+ ## Fact provenance (server up or down)
54
+
55
+ Checks are **shell-first**: they read files + `createRequire` and work with the
56
+ dashboard server DOWN. When the server is reachable, `_lib/server-tier.ts`
57
+ (`fetchHealth`, `fetchPiCoreVersions`) enriches the report as an ADDITIVE tier.
58
+ Every reported fact is labelled `file-derived` or `server-enriched`
59
+ (`_lib/provenance.ts`) so a partial (server-down) run is never mistaken for a
60
+ clean bill.
61
+
62
+ ## Two-tier self-update
63
+
64
+ - **Tier 1 (derive-on-run)** — versions, peer names, resolved paths, the
65
+ recommended set are read from live sources every run; they can never rot.
66
+ - **Tier 2 (knowledge-hash)** — each module stores `<id>.knowledge.hash` over
67
+ the semantic tokens of its `derives-from` sources (`_lib/knowledge-hash.ts`).
68
+ On run, `checkDrift(id, liveTokens, hashPath)` compares live vs stored; a
69
+ mismatch flags that module's authored prose as possibly stale.
70
+
71
+ ### `--regenerate <module>`
72
+
73
+ When a module's hash drifts:
74
+ 1. Re-derive the module's tables from its live `derives-from` sources.
75
+ 2. Propose edits to the module's authored prose **for confirmation** — never
76
+ overwrite silently.
77
+ 3. After confirmation, `writeStoredHash(hashPath, liveHash)` to clear the drift.
78
+
79
+ Regeneration is always confirmed. The AGENTS.md Documentation Update Protocol
80
+ maps each source-of-truth change to the single module to regenerate (peer
81
+ rename → `peers`; pi floor bump → `pi-resolution`; new install platform →
82
+ `install-topology`; new bridge slot → `plugins-bridges`).
83
+
84
+ ## Report format
85
+
86
+ For each module report: `PASS / FAIL`, the resolved path(s) + version(s) per
87
+ tier, the provenance of each fact, and — on FAIL — the matching FIX ROUTING
88
+ remediation for the detected install topology. Never report a version without
89
+ the resolved path it came from.
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Doctor check library — thin wrappers over the existing `shared/` resolution
3
+ * primitives. The doctor NEVER reimplements resolution; it composes
4
+ * `resolvePiPackage`, `resolvePiPackageEntry`, `listPiPackages`,
5
+ * `sourcesMatch`, and `parseSourceKey`. Shell-first: every helper reads files
6
+ * + `createRequire` and works with the dashboard server down.
7
+ *
8
+ * See change: add-modular-doctor-skill (design.md D4/D8, spec: Derive-on-run).
9
+ */
10
+
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { createRequire } from "node:module";
13
+ import {
14
+ listPiPackages,
15
+ type ResolvePiPackageOptions,
16
+ resolvePiPackage,
17
+ resolvePiPackageEntry,
18
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-package-resolver.js";
19
+ import {
20
+ parseSourceKey,
21
+ type SourceKey,
22
+ sourcesMatch,
23
+ } from "@blackbelt-technology/pi-dashboard-shared/source-matching.js";
24
+
25
+ export type { ResolvePiPackageOptions, SourceKey };
26
+ // Re-export the primitives so modules import them from one place (DRY: the
27
+ // wrappers below are the ONLY doctor-specific additions).
28
+ export {
29
+ listPiPackages,
30
+ parseSourceKey,
31
+ resolvePiPackage,
32
+ resolvePiPackageEntry,
33
+ sourcesMatch,
34
+ };
35
+
36
+ export type PeerTier = "tier-1" | "tier-2" | null;
37
+
38
+ export interface PeerProbeResult {
39
+ spec: string;
40
+ /** Which tier resolved the peer, or null when unresolved. */
41
+ tier: PeerTier;
42
+ /** Absolute resolved entry path, or null. */
43
+ resolvedPath: string | null;
44
+ present: boolean;
45
+ }
46
+
47
+ /**
48
+ * Probe a peer via tier-1 then tier-2 resolution, mirroring how the bridge
49
+ * actually resolves peers (`peer-probe.ts`):
50
+ * - tier-1: `createRequire(cwd + "/_").resolve(spec)` (anchored at session cwd)
51
+ * - tier-2: `resolvePiPackageEntry(spec)` (walks pi `packages[]`)
52
+ * A peer is PRESENT if either tier resolves it.
53
+ */
54
+ export function probePeer(
55
+ spec: string,
56
+ opts: ResolvePiPackageOptions = {},
57
+ ): PeerProbeResult {
58
+ // Tier 1 — cwd-anchored createRequire.
59
+ if (opts.cwd) {
60
+ try {
61
+ const req = createRequire(`${opts.cwd}/_`);
62
+ const resolved = req.resolve(spec);
63
+ return { spec, tier: "tier-1", resolvedPath: resolved, present: true };
64
+ } catch {
65
+ // fall through to tier 2
66
+ }
67
+ }
68
+ // Tier 2 — pi packages[].
69
+ const entry = resolvePiPackageEntry(spec, opts);
70
+ if (entry) {
71
+ return { spec, tier: "tier-2", resolvedPath: entry, present: true };
72
+ }
73
+ return { spec, tier: null, resolvedPath: null, present: false };
74
+ }
75
+
76
+ export interface NameSkewResult {
77
+ /** The name that actually resolved (the current package), or null. */
78
+ resolvedName: string | null;
79
+ /** Names probed but unresolved (stale / rescoped). */
80
+ staleNames: string[];
81
+ tier: PeerTier;
82
+ resolvedPath: string | null;
83
+ }
84
+
85
+ /**
86
+ * Probe a set of candidate names for one logical peer (e.g. the current
87
+ * `@scope/pi-anthropic-messages` and its legacy `@pi/anthropic-messages`
88
+ * alias). Reports which name currently resolves and which probed names are
89
+ * dead — the signal for published-bridge name skew after a rescope.
90
+ */
91
+ export function detectNameSkew(
92
+ candidates: string[],
93
+ opts: ResolvePiPackageOptions = {},
94
+ ): NameSkewResult {
95
+ const stale: string[] = [];
96
+ for (const name of candidates) {
97
+ const res = probePeer(name, opts);
98
+ if (res.present) {
99
+ // Names probed before the hit (still in `stale`) are the dead aliases.
100
+ return {
101
+ resolvedName: name,
102
+ staleNames: stale,
103
+ tier: res.tier,
104
+ resolvedPath: res.resolvedPath,
105
+ };
106
+ }
107
+ stale.push(name);
108
+ }
109
+ return { resolvedName: null, staleNames: stale, tier: null, resolvedPath: null };
110
+ }
111
+
112
+ export interface PiInstall {
113
+ /** Human label for the consumer/location. */
114
+ location: string;
115
+ /** Absolute path the install resolves from, or null when not found. */
116
+ resolvedPath: string | null;
117
+ /** Parsed package.json version, or null. */
118
+ version: string | null;
119
+ }
120
+
121
+ function readPkgVersion(pkgJsonPath: string): string | null {
122
+ try {
123
+ const raw = JSON.parse(readFileSync(pkgJsonPath, "utf8")) as { version?: string };
124
+ return typeof raw.version === "string" ? raw.version : null;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Enumerate pi installs across candidate locations and read each version from
132
+ * its package.json. `locations` maps a human label to a candidate package
133
+ * directory (repo node_modules, managed dir, nvm-global, …). The caller
134
+ * supplies the candidate dirs; this helper only resolves + reads versions so
135
+ * it stays platform-agnostic and testable with fixtures.
136
+ */
137
+ export function enumeratePiInstalls(
138
+ locations: Record<string, string>,
139
+ ): PiInstall[] {
140
+ const out: PiInstall[] = [];
141
+ for (const [location, dir] of Object.entries(locations)) {
142
+ const pkgJson = `${dir}/package.json`;
143
+ if (existsSync(pkgJson)) {
144
+ out.push({ location, resolvedPath: dir, version: readPkgVersion(pkgJson) });
145
+ } else {
146
+ out.push({ location, resolvedPath: null, version: null });
147
+ }
148
+ }
149
+ return out;
150
+ }
151
+
152
+ /**
153
+ * Given the enumerated installs, return the set of distinct non-null versions.
154
+ * More than one distinct version means the consumers diverge.
155
+ */
156
+ export function piVersionDivergence(installs: PiInstall[]): {
157
+ diverged: boolean;
158
+ versions: string[];
159
+ } {
160
+ const versions = [...new Set(installs.map((i) => i.version).filter((v): v is string => !!v))];
161
+ return { diverged: versions.length > 1, versions };
162
+ }
163
+
164
+ /**
165
+ * Read the pi compatibility floor from a server package.json on disk
166
+ * (`piCompatibility.minimum`). Shell-first: no server call needed.
167
+ */
168
+ export function readPiFloor(serverPkgJsonPath: string): string | null {
169
+ try {
170
+ const raw = JSON.parse(readFileSync(serverPkgJsonPath, "utf8")) as {
171
+ piCompatibility?: { minimum?: string };
172
+ };
173
+ return raw.piCompatibility?.minimum ?? null;
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Maps each capability module to the concrete `derives-from` source files that
3
+ * carry its semantic tokens (peer names, version floor, manifest ids), and
4
+ * derives the live token set the knowledge-hash is computed over. Reading the
5
+ * SOURCES (not the module prose) is what makes a source-of-truth change drift
6
+ * the module's stored hash and flag its authored prose as stale.
7
+ *
8
+ * Paths are repo-root-relative so the same map works in a dev checkout and a
9
+ * resolved workspace. Missing files contribute no tokens (a partial repo view
10
+ * degrades, it does not throw).
11
+ *
12
+ * See change: add-modular-doctor-skill (design.md D6, spec: prose-drift).
13
+ */
14
+
15
+ import { existsSync, readFileSync } from "node:fs";
16
+ import path from "node:path";
17
+ import { extractSemanticTokens } from "./knowledge-hash.js";
18
+
19
+ /** Module id → repo-root-relative source files carrying its semantic tokens. */
20
+ export const MODULE_TOKEN_SOURCES: Record<string, string[]> = {
21
+ "env-node": ["packages/shared/src/node-version.ts"],
22
+ "pi-resolution": ["packages/server/package.json"],
23
+ peers: ["packages/flows-anthropic-bridge-plugin/src/peer-probe.ts"],
24
+ "plugins-bridges": ["packages/shared/src/plugin-bridge-register.ts"],
25
+ "build-reload": ["packages/extension/package.json"],
26
+ "install-topology": ["packages/shared/src/dashboard-paths.ts"],
27
+ "model-resolution": ["packages/extension/src/provider-register.ts"],
28
+ };
29
+
30
+ /**
31
+ * Read a module's live `derives-from` source files under `repoRoot` and return
32
+ * the extracted semantic tokens (deduped by `computeKnowledgeHash` downstream).
33
+ */
34
+ export function deriveLiveTokens(repoRoot: string, moduleId: string): string[] {
35
+ const sources = MODULE_TOKEN_SOURCES[moduleId] ?? [];
36
+ const tokens: string[] = [];
37
+ for (const rel of sources) {
38
+ const abs = path.join(repoRoot, rel);
39
+ if (!existsSync(abs)) continue;
40
+ tokens.push(...extractSemanticTokens(readFileSync(abs, "utf8")));
41
+ }
42
+ return tokens;
43
+ }
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Minimal front-matter parser for doctor capability modules.
3
+ *
4
+ * Each capability MD opens with a `---`-delimited block declaring the router
5
+ * contract keys: `name`, `scope`, `symptoms:` (phrases), `depends-on:` (module
6
+ * ids), and `derives-from:` (live sources of truth). The router derives its
7
+ * symptom map and sweep DAG from these keys alone, so the parser only supports
8
+ * the subset actually used: string scalars and single-level string lists
9
+ * (block `- item` or inline `[a, b]`).
10
+ *
11
+ * See change: add-modular-doctor-skill (design.md D1/D2).
12
+ */
13
+
14
+ export interface ModuleFrontMatter {
15
+ /** Module id (defaults to the MD basename when `name` is absent). */
16
+ name: string;
17
+ /** One-sentence scope declaration. */
18
+ scope: string;
19
+ /** Symptom phrases routed to this module. */
20
+ symptoms: string[];
21
+ /** Module ids this module depends on (defines the sweep DAG). */
22
+ dependsOn: string[];
23
+ /** Live sources of truth this module derives from. */
24
+ derivesFrom: string[];
25
+ }
26
+
27
+ function stripQuotes(raw: string): string {
28
+ const t = raw.trim();
29
+ if (
30
+ (t.startsWith('"') && t.endsWith('"')) ||
31
+ (t.startsWith("'") && t.endsWith("'"))
32
+ ) {
33
+ return t.slice(1, -1);
34
+ }
35
+ return t;
36
+ }
37
+
38
+ function parseInlineList(raw: string): string[] {
39
+ const inner = raw.trim().replace(/^\[/, "").replace(/\]$/, "");
40
+ if (!inner.trim()) return [];
41
+ return inner
42
+ .split(",")
43
+ .map((s) => stripQuotes(s))
44
+ .filter((s) => s.length > 0);
45
+ }
46
+
47
+ /**
48
+ * Extract the raw front-matter block (between the first two `---` fences).
49
+ * Returns null when the document has no front-matter.
50
+ */
51
+ export function extractFrontMatterBlock(md: string): string | null {
52
+ const m = md.match(/^---\r?\n([\s\S]*?)\r?\n---/);
53
+ return m ? m[1] : null;
54
+ }
55
+
56
+ type ListKey = "symptoms" | "dependsOn" | "derivesFrom";
57
+
58
+ const LIST_KEYS: Record<string, ListKey> = {
59
+ symptoms: "symptoms",
60
+ "depends-on": "dependsOn",
61
+ "derives-from": "derivesFrom",
62
+ };
63
+
64
+ /** Append a block-list continuation (` - item`) to the active list, if any. */
65
+ function handleListItem(fm: ModuleFrontMatter, line: string, active: ListKey | null): boolean {
66
+ const m = line.match(/^\s+-\s+(.*)$/);
67
+ if (!m || !active) return false;
68
+ const val = stripQuotes(m[1]);
69
+ if (val) fm[active].push(val);
70
+ return true;
71
+ }
72
+
73
+ /**
74
+ * Apply a `key: rest` line to the accumulator and return the next active list
75
+ * key (non-null when a block list was opened, so following `- item` lines
76
+ * append to it).
77
+ */
78
+ function applyKeyLine(
79
+ fm: ModuleFrontMatter,
80
+ key: string,
81
+ rest: string,
82
+ fallbackName: string,
83
+ ): ListKey | null {
84
+ const listKey = LIST_KEYS[key];
85
+ if (listKey) {
86
+ if (rest.trim().startsWith("[")) {
87
+ fm[listKey] = parseInlineList(rest);
88
+ return null;
89
+ }
90
+ return listKey;
91
+ }
92
+ if (key === "name") fm.name = stripQuotes(rest) || fallbackName;
93
+ else if (key === "scope") fm.scope = stripQuotes(rest);
94
+ return null;
95
+ }
96
+
97
+ /**
98
+ * Parse a capability module's front-matter into the router contract shape.
99
+ * `fallbackName` (the file basename) is used when `name:` is absent.
100
+ */
101
+ export function parseFrontMatter(md: string, fallbackName: string): ModuleFrontMatter {
102
+ const fm: ModuleFrontMatter = {
103
+ name: fallbackName,
104
+ scope: "",
105
+ symptoms: [],
106
+ dependsOn: [],
107
+ derivesFrom: [],
108
+ };
109
+ const block = extractFrontMatterBlock(md);
110
+ if (!block) return fm;
111
+
112
+ let active: ListKey | null = null;
113
+ for (const line of block.split(/\r?\n/)) {
114
+ if (!line.trim()) continue;
115
+ if (handleListItem(fm, line, active)) continue;
116
+ const kv = line.match(/^([a-zA-Z][\w-]*):\s*(.*)$/);
117
+ if (!kv) continue;
118
+ active = applyKeyLine(fm, kv[1].toLowerCase(), kv[2], fallbackName);
119
+ }
120
+
121
+ return fm;
122
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Doctor `_lib` barrel — the mechanical check helpers shared across capability
3
+ * modules. Modules keep all KNOWLEDGE/FIX prose to themselves; only these
4
+ * resolution/probe/label/hash primitives are shared (design.md D8, DRY rule).
5
+ *
6
+ * See change: add-modular-doctor-skill.
7
+ */
8
+
9
+ export * from "./checks.js";
10
+ export * from "./front-matter.js";
11
+ export * from "./knowledge-hash.js";
12
+ export * from "./provenance.js";
13
+ export * from "./router.js";
14
+ export * from "./server-tier.js";
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Two-tier self-update, tier-2: per-module knowledge-hash. Mirrors the
3
+ * `PLUGIN_REGISTRY_HASH` pattern. The hash is computed over *semantic tokens*
4
+ * extracted from a module's `derives-from` sources (peer names, the version
5
+ * floor, manifest ids) — NOT raw file bytes — so a whitespace/refactor change
6
+ * does not drift the hash but a peer rename does. A drift between the live
7
+ * hash and the stored `<module>.knowledge.hash` flags the module's authored
8
+ * prose as possibly stale and drives a confirmed `--regenerate <module>`.
9
+ *
10
+ * See change: add-modular-doctor-skill (design.md D6, spec: prose-drift).
11
+ */
12
+
13
+ import { createHash } from "node:crypto";
14
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
15
+
16
+ /**
17
+ * Compute a stable hash over a set of semantic tokens. Tokens are trimmed,
18
+ * lower-cased, de-duplicated and sorted so ordering / casing / whitespace
19
+ * differences in the source do not drift the hash — only the *set* of
20
+ * meaningful tokens does.
21
+ */
22
+ export function computeKnowledgeHash(tokens: string[]): string {
23
+ const norm = [...new Set(tokens.map((t) => t.trim().toLowerCase()).filter(Boolean))].sort();
24
+ return createHash("sha256").update(norm.join("\n")).digest("hex").slice(0, 16);
25
+ }
26
+
27
+ /**
28
+ * Extract semantic tokens from a `derives-from` source's raw text: scoped and
29
+ * unscoped package names, and semver strings (the version floor / carried
30
+ * versions). Prose, whitespace, and comments contribute no tokens, so a
31
+ * reformat leaves the hash stable while a peer rename or floor bump changes it.
32
+ */
33
+ export function extractSemanticTokens(text: string): string[] {
34
+ const tokens: string[] = [];
35
+ // Scoped + unscoped npm package names (e.g. @scope/name, pi-flows).
36
+ for (const m of text.matchAll(/@[a-z0-9-]+\/[a-z0-9-]+|\b[a-z][a-z0-9-]*-[a-z0-9-]+\b/gi)) {
37
+ tokens.push(m[0]);
38
+ }
39
+ // Semver strings (floor, carried versions).
40
+ for (const m of text.matchAll(/\b\d+\.\d+\.\d+\b/g)) {
41
+ tokens.push(m[0]);
42
+ }
43
+ return tokens;
44
+ }
45
+
46
+ /** Read a stored `<module>.knowledge.hash` sidecar, or null when absent. */
47
+ export function readStoredHash(hashPath: string): string | null {
48
+ if (!existsSync(hashPath)) return null;
49
+ return readFileSync(hashPath, "utf8").trim() || null;
50
+ }
51
+
52
+ /** Write a `<module>.knowledge.hash` sidecar. */
53
+ export function writeStoredHash(hashPath: string, hash: string): void {
54
+ writeFileSync(hashPath, `${hash}\n`);
55
+ }
56
+
57
+ export interface DriftResult {
58
+ module: string;
59
+ stored: string | null;
60
+ live: string;
61
+ /** True when authored prose may be stale (hash mismatch or no sidecar). */
62
+ drifted: boolean;
63
+ }
64
+
65
+ /**
66
+ * Compare a module's live semantic hash against its stored sidecar.
67
+ * `drifted` is true when they differ OR the sidecar is missing — either way
68
+ * the authored prose has not been reconciled with the current sources.
69
+ */
70
+ export function checkDrift(module: string, liveTokens: string[], hashPath: string): DriftResult {
71
+ const live = computeKnowledgeHash(liveTokens);
72
+ const stored = readStoredHash(hashPath);
73
+ return { module, stored, live, drifted: stored !== live };
74
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Fact-provenance labeller. Every fact a module reports is tagged
3
+ * `file-derived` (read from files + `createRequire`, always available) or
4
+ * `server-enriched` (came from a live `/api/*` endpoint). A partial run with
5
+ * the server down is then never mistaken for a clean bill of health.
6
+ *
7
+ * See change: add-modular-doctor-skill (design.md D4, spec: server-down label).
8
+ */
9
+
10
+ export type Provenance = "file-derived" | "server-enriched";
11
+
12
+ export interface Fact<T = unknown> {
13
+ label: string;
14
+ value: T;
15
+ provenance: Provenance;
16
+ }
17
+
18
+ /** Tag a file-derived fact (works with the server down). */
19
+ export function fileFact<T>(label: string, value: T): Fact<T> {
20
+ return { label, value, provenance: "file-derived" };
21
+ }
22
+
23
+ /** Tag a server-enriched fact (only present when `/api/*` was reachable). */
24
+ export function serverFact<T>(label: string, value: T): Fact<T> {
25
+ return { label, value, provenance: "server-enriched" };
26
+ }
27
+
28
+ export interface ProvenanceSummary {
29
+ total: number;
30
+ fileDerived: number;
31
+ serverEnriched: number;
32
+ /** True when NO server-enriched fact is present (server was down). */
33
+ serverUnavailable: boolean;
34
+ }
35
+
36
+ /** Summarise a fact list so a report can render the provenance banner. */
37
+ export function summariseProvenance(facts: Fact[]): ProvenanceSummary {
38
+ let fileDerived = 0;
39
+ let serverEnriched = 0;
40
+ for (const f of facts) {
41
+ if (f.provenance === "server-enriched") serverEnriched++;
42
+ else fileDerived++;
43
+ }
44
+ return {
45
+ total: facts.length,
46
+ fileDerived,
47
+ serverEnriched,
48
+ serverUnavailable: serverEnriched === 0,
49
+ };
50
+ }