@mandujs/core 0.54.32 → 0.55.0-beta.1

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 (414) hide show
  1. package/README.md +654 -654
  2. package/package.json +106 -210
  3. package/scripts/postinstall-lock.ts +153 -153
  4. package/src/a11y/__tests__/run-audit.test.ts +333 -333
  5. package/src/a11y/fix-hints.ts +76 -76
  6. package/src/a11y/index.ts +18 -18
  7. package/src/a11y/run-audit.ts +15 -15
  8. package/src/a11y/types.ts +125 -125
  9. package/src/agent/__tests__/apply.test.ts +224 -0
  10. package/src/agent/__tests__/context.test.ts +97 -98
  11. package/src/agent/apply.ts +1031 -0
  12. package/src/agent/context.ts +552 -552
  13. package/src/agent/index.ts +4 -3
  14. package/src/agent/plan.ts +161 -243
  15. package/src/agent/repair.ts +239 -162
  16. package/src/agent/sync.ts +197 -198
  17. package/src/agent/types.ts +242 -94
  18. package/src/agent/verify.ts +55 -55
  19. package/src/auth/__tests__/login.test.ts +1 -1
  20. package/src/auth/__tests__/password.test.ts +15 -5
  21. package/src/auth/__tests__/reset.test.ts +2 -2
  22. package/src/auth/__tests__/tokens.test.ts +274 -274
  23. package/src/auth/__tests__/verification.test.ts +274 -274
  24. package/src/auth/index.ts +76 -76
  25. package/src/auth/login.ts +225 -225
  26. package/src/auth/password.ts +14 -2
  27. package/src/auth/reset.ts +243 -243
  28. package/src/auth/tokens.ts +612 -612
  29. package/src/auth/verification.ts +253 -253
  30. package/src/brain/__tests__/redactor.test.ts +94 -94
  31. package/src/brain/adapters/__tests__/_helpers.ts +83 -83
  32. package/src/brain/adapters/__tests__/anthropic-oauth.test.ts +196 -196
  33. package/src/brain/adapters/__tests__/chatgpt-auth.test.ts +193 -193
  34. package/src/brain/adapters/__tests__/openai-oauth.test.ts +209 -209
  35. package/src/brain/adapters/__tests__/resolver.test.ts +143 -143
  36. package/src/brain/adapters/anthropic-oauth.ts +1 -1
  37. package/src/brain/adapters/chatgpt-auth.ts +300 -300
  38. package/src/brain/adapters/index.ts +319 -319
  39. package/src/brain/adapters/oauth-flow.ts +439 -439
  40. package/src/brain/consent.ts +240 -240
  41. package/src/brain/credentials.ts +396 -396
  42. package/src/brain/doctor/analyzer.ts +7 -7
  43. package/src/bundler/__snapshots__/build.test.ts.snap +5 -5
  44. package/src/bundler/__tests__/build-runner.ts +166 -166
  45. package/src/bundler/__tests__/client-boundary-transform.test.ts +524 -524
  46. package/src/bundler/__tests__/cold-start.test.ts +60 -60
  47. package/src/bundler/__tests__/css.test.ts +49 -20
  48. package/src/bundler/__tests__/dev-reliability.test.ts +619 -619
  49. package/src/bundler/__tests__/extended-watch.test.ts +711 -711
  50. package/src/bundler/__tests__/fast-refresh.test.ts +24 -24
  51. package/src/bundler/__tests__/generation.test.ts +447 -0
  52. package/src/bundler/__tests__/hdr.test.ts +24 -18
  53. package/src/bundler/__tests__/hmr-client.test.ts +62 -24
  54. package/src/bundler/__tests__/jsx-runtime-shim.test.ts +179 -140
  55. package/src/bundler/__tests__/manifest-schema.test.ts +305 -266
  56. package/src/bundler/__tests__/prod-smoke.test.ts +138 -138
  57. package/src/bundler/__tests__/reverse-import-graph.test.ts +42 -42
  58. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -573
  59. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -286
  60. package/src/bundler/__tests__/vendor-cache.test.ts +455 -455
  61. package/src/bundler/analyzer.ts +15 -15
  62. package/src/bundler/budget.ts +404 -404
  63. package/src/bundler/build.test.ts +898 -915
  64. package/src/bundler/build.ts +113 -24
  65. package/src/bundler/client-boundary-transform.ts +977 -977
  66. package/src/bundler/css.ts +65 -44
  67. package/src/bundler/dev.ts +105 -73
  68. package/src/bundler/fast-refresh-preamble.ts +47 -47
  69. package/src/bundler/generation.ts +602 -0
  70. package/src/bundler/index.ts +3 -3
  71. package/src/bundler/manifest-schema.ts +55 -40
  72. package/src/bundler/plugins/__tests__/block-generated-imports.test.ts +13 -13
  73. package/src/bundler/plugins/__tests__/react-compiler-config.test.ts +83 -83
  74. package/src/bundler/plugins/__tests__/react-compiler-lint.test.ts +110 -110
  75. package/src/bundler/plugins/block-generated-imports.ts +16 -15
  76. package/src/bundler/plugins/index.ts +83 -83
  77. package/src/bundler/plugins/react-compiler-config.ts +108 -108
  78. package/src/bundler/plugins/react-compiler-lint.ts +253 -253
  79. package/src/bundler/plugins/react-compiler.ts +162 -162
  80. package/src/bundler/prerender.ts +29 -9
  81. package/src/bundler/reverse-import-graph.ts +339 -339
  82. package/src/bundler/safe-build.test.ts +1 -1
  83. package/src/bundler/safe-build.ts +103 -103
  84. package/src/bundler/scenario-matrix.ts +229 -229
  85. package/src/bundler/types.ts +58 -56
  86. package/src/bundler/vendor-cache-types.ts +130 -130
  87. package/src/bundler/vendor-cache.ts +526 -526
  88. package/src/change/snapshot.ts +18 -18
  89. package/src/client/Form.tsx +105 -105
  90. package/src/client/Link.tsx +9 -9
  91. package/src/client/__tests__/props-serialization.test.ts +37 -37
  92. package/src/client/__tests__/use-sse.test.ts +153 -153
  93. package/src/client/globals.ts +1 -1
  94. package/src/client/hooks.ts +362 -362
  95. package/src/client/hydrate.ts +2 -2
  96. package/src/client/index.ts +1 -1
  97. package/src/client/island.ts +79 -79
  98. package/src/client/prefetch-helper.ts +55 -55
  99. package/src/client/props-serialization.ts +233 -233
  100. package/src/client/runtime-entry.ts +598 -598
  101. package/src/client/runtime.ts +1 -1
  102. package/src/client/serialize.ts +50 -50
  103. package/src/client/use-fetch.ts +6 -6
  104. package/src/client/use-head.ts +197 -197
  105. package/src/client/use-sse.ts +378 -378
  106. package/src/client/window-state.ts +101 -101
  107. package/src/components/Image-compat.ts +3 -0
  108. package/src/components/Image.tsx +162 -162
  109. package/src/config/validate.ts +1 -1
  110. package/src/config/watcher.ts +311 -311
  111. package/src/constants.ts +40 -40
  112. package/src/content/collection.ts +9 -9
  113. package/src/content/content-layer.ts +7 -7
  114. package/src/content/data-store.ts +245 -245
  115. package/src/content/frontmatter.ts +189 -189
  116. package/src/content/generate-types.ts +1 -1
  117. package/src/content/index.ts +2 -2
  118. package/src/content/loader-context.ts +171 -171
  119. package/src/content/loaders/api.ts +216 -216
  120. package/src/content/loaders/file.ts +172 -172
  121. package/src/content/loaders/glob.ts +253 -253
  122. package/src/content/loaders/index.ts +34 -34
  123. package/src/content/loaders/types.ts +137 -137
  124. package/src/content/meta-store.ts +209 -209
  125. package/src/content/prebuild.test.ts +571 -571
  126. package/src/content/prebuild.ts +636 -636
  127. package/src/content/schema.ts +20 -20
  128. package/src/content/sidebar.ts +630 -630
  129. package/src/content/slug.ts +110 -110
  130. package/src/content/types.ts +282 -282
  131. package/src/content/watcher.ts +135 -135
  132. package/src/contract/client-safe.test.ts +42 -42
  133. package/src/contract/client-safe.ts +114 -114
  134. package/src/contract/define.ts +11 -11
  135. package/src/contract/index.ts +1 -1
  136. package/src/contract/normalize.test.ts +276 -276
  137. package/src/contract/normalize.ts +410 -410
  138. package/src/contract/registry.test.ts +206 -206
  139. package/src/contract/route-helpers.ts +1 -1
  140. package/src/contract/rpc.ts +443 -443
  141. package/src/contract/types.ts +58 -58
  142. package/src/db/__tests__/db.test.ts +9 -9
  143. package/src/db/index.ts +2 -2
  144. package/src/db/migrations/history-table.ts +345 -345
  145. package/src/db/migrations/index.ts +3 -3
  146. package/src/db/migrations/lock.ts +324 -324
  147. package/src/db/migrations/runner.ts +650 -650
  148. package/src/deploy/cache.ts +140 -140
  149. package/src/deploy/compile/vercel.ts +344 -344
  150. package/src/deploy/index.ts +87 -87
  151. package/src/deploy/inference/brain.ts +268 -268
  152. package/src/deploy/inference/context.ts +82 -82
  153. package/src/deploy/inference/filling-extract.ts +245 -245
  154. package/src/deploy/inference/heuristic.ts +182 -182
  155. package/src/deploy/intent.ts +173 -173
  156. package/src/deploy/plan.ts +178 -178
  157. package/src/design/__tests__/agents-link.test.ts +109 -109
  158. package/src/design/__tests__/extract-patch-diff.test.ts +265 -265
  159. package/src/design/__tests__/lint.test.ts +110 -110
  160. package/src/design/__tests__/parser.test.ts +195 -195
  161. package/src/design/__tests__/tailwind-theme.test.ts +229 -229
  162. package/src/design/agents-link.ts +165 -165
  163. package/src/design/diff.ts +138 -138
  164. package/src/design/extract.ts +285 -285
  165. package/src/design/index.ts +102 -102
  166. package/src/design/lint.ts +209 -209
  167. package/src/design/parser.ts +555 -555
  168. package/src/design/patch.ts +241 -241
  169. package/src/design/scaffold.ts +147 -147
  170. package/src/design/tailwind-theme.ts +441 -441
  171. package/src/design/types.ts +210 -210
  172. package/src/desktop/__tests__/smoke.test.ts +2 -2
  173. package/src/desktop/__tests__/webview-fallback.test.ts +12 -32
  174. package/src/desktop/__tests__/window.test.ts +20 -99
  175. package/src/desktop/__tests__/worker.test.ts +266 -266
  176. package/src/desktop/index.ts +43 -43
  177. package/src/desktop/types.ts +158 -158
  178. package/src/desktop/webview-fallback.ts +17 -4
  179. package/src/desktop/window.ts +17 -8
  180. package/src/desktop/worker.ts +180 -180
  181. package/src/dev-error-overlay/__tests__/overlay-injector.test.ts +241 -241
  182. package/src/dev-error-overlay/index.ts +30 -30
  183. package/src/dev-error-overlay/overlay-injector.ts +243 -243
  184. package/src/dev-error-overlay/overlay-styles.ts +52 -52
  185. package/src/dev-error-overlay/types.ts +66 -66
  186. package/src/devtools/ai/context-builder.ts +375 -375
  187. package/src/devtools/ai/index.ts +25 -25
  188. package/src/devtools/ai/mcp-connector.ts +25 -25
  189. package/src/devtools/client/catchers/error-catcher.ts +344 -344
  190. package/src/devtools/client/catchers/index.ts +18 -18
  191. package/src/devtools/client/components/index.ts +39 -39
  192. package/src/devtools/client/components/mandu-character.tsx +331 -331
  193. package/src/devtools/client/components/panel/errors-panel.tsx +259 -259
  194. package/src/devtools/client/components/panel/guard-panel.tsx +30 -30
  195. package/src/devtools/client/components/panel/islands-panel.tsx +16 -16
  196. package/src/devtools/client/components/panel/network-panel.tsx +291 -291
  197. package/src/devtools/client/components/panel/panel-container.tsx +1 -1
  198. package/src/devtools/client/components/panel/preview-panel.tsx +46 -46
  199. package/src/devtools/client/filters/context-filters.ts +282 -282
  200. package/src/devtools/client/filters/index.ts +16 -16
  201. package/src/devtools/client/index.ts +63 -63
  202. package/src/devtools/hook/create-hook.ts +207 -207
  203. package/src/devtools/hook/index.ts +13 -13
  204. package/src/devtools/index.ts +439 -439
  205. package/src/devtools/init.ts +265 -265
  206. package/src/devtools/protocol.ts +237 -237
  207. package/src/devtools/server/index.ts +17 -17
  208. package/src/devtools/types.ts +35 -35
  209. package/src/devtools/worker/index.ts +25 -25
  210. package/src/devtools/worker/redaction-worker.ts +233 -233
  211. package/src/diagnose/__tests__/checks.test.ts +136 -136
  212. package/src/diagnose/checks.ts +185 -185
  213. package/src/diagnose/index.ts +17 -17
  214. package/src/diagnose/run.ts +10 -10
  215. package/src/diagnose/types.ts +53 -53
  216. package/src/email/__tests__/email.test.ts +355 -355
  217. package/src/email/index.ts +282 -282
  218. package/src/email/smtp.ts +64 -64
  219. package/src/error/domains.ts +265 -265
  220. package/src/error/types.ts +6 -6
  221. package/src/errors/extractor.ts +409 -409
  222. package/src/errors/index.ts +19 -19
  223. package/src/filling/__tests__/session-sqlite.test.ts +5 -1
  224. package/src/filling/auth.ts +308 -308
  225. package/src/filling/body-parse.test.ts +60 -60
  226. package/src/filling/cookie-codec.ts +5 -3
  227. package/src/filling/deps.ts +265 -265
  228. package/src/filling/head-method.test.ts +154 -154
  229. package/src/filling/session-sqlite.ts +617 -617
  230. package/src/filling/sse.ts +5 -5
  231. package/src/filling/ws.ts +78 -78
  232. package/src/generator/generate.ts +30 -30
  233. package/src/generator/index.ts +3 -3
  234. package/src/generator/templates.test.ts +48 -48
  235. package/src/generator/templates.ts +219 -219
  236. package/src/guard/__tests__/design-inline-class.test.ts +219 -219
  237. package/src/guard/__tests__/tsgolint-bridge.test.ts +347 -347
  238. package/src/guard/analyzer.ts +360 -360
  239. package/src/guard/auto-correct.ts +1 -1
  240. package/src/guard/check.ts +39 -24
  241. package/src/guard/config-guard.ts +13 -13
  242. package/src/guard/contract-guard.ts +9 -9
  243. package/src/guard/define-rule.ts +243 -243
  244. package/src/guard/design-inline-class.ts +393 -393
  245. package/src/guard/file-type.test.ts +24 -24
  246. package/src/guard/fs-routes-policy.ts +51 -51
  247. package/src/guard/graph.ts +1 -1
  248. package/src/guard/healing.ts +36 -36
  249. package/src/guard/index.ts +11 -11
  250. package/src/guard/presets/atomic.ts +70 -70
  251. package/src/guard/presets/clean.ts +77 -77
  252. package/src/guard/presets/fsd.ts +79 -79
  253. package/src/guard/presets/hexagonal.ts +68 -68
  254. package/src/guard/reporter.ts +442 -442
  255. package/src/guard/rule-presets.ts +379 -379
  256. package/src/guard/semantic-slots.ts +1 -1
  257. package/src/guard/suggestions.ts +358 -358
  258. package/src/guard/tsgolint-bridge.ts +512 -512
  259. package/src/guard/types.ts +348 -348
  260. package/src/guard/watcher.ts +405 -405
  261. package/src/i18n/define.ts +126 -126
  262. package/src/i18n/index.ts +52 -52
  263. package/src/i18n/message-registry.ts +173 -173
  264. package/src/i18n/types.ts +112 -112
  265. package/src/id/__tests__/id.test.ts +3 -3
  266. package/src/id/index.ts +105 -105
  267. package/src/index.ts +9 -48
  268. package/src/internal/client-boundary.ts +266 -266
  269. package/src/internal/index.ts +2 -2
  270. package/src/kitchen/api/agent-devtools-api.ts +779 -779
  271. package/src/kitchen/api/bundle-inspector.ts +179 -0
  272. package/src/kitchen/api/errors-grouping.ts +126 -126
  273. package/src/kitchen/api/file-api.ts +11 -11
  274. package/src/kitchen/kitchen-handler.ts +36 -0
  275. package/src/kitchen/kitchen-ui.ts +456 -0
  276. package/src/logging/index.ts +22 -22
  277. package/src/logging/transports.ts +365 -365
  278. package/src/middleware/bridge.ts +147 -147
  279. package/src/middleware/compose.ts +134 -134
  280. package/src/middleware/compress.ts +62 -62
  281. package/src/middleware/cors.ts +47 -47
  282. package/src/middleware/csrf.ts +328 -328
  283. package/src/middleware/define.ts +132 -132
  284. package/src/middleware/jwt.ts +134 -134
  285. package/src/middleware/logger.ts +58 -58
  286. package/src/middleware/oauth/__tests__/oauth.test.ts +1 -1
  287. package/src/middleware/oauth/index.ts +505 -505
  288. package/src/middleware/oauth/providers.ts +115 -115
  289. package/src/middleware/rate-limit/index.ts +522 -522
  290. package/src/middleware/rate-limit/sqlite-store.ts +382 -382
  291. package/src/middleware/scheduler-cron.ts +96 -96
  292. package/src/middleware/secure/__tests__/secure.test.ts +360 -360
  293. package/src/middleware/secure/csp.ts +193 -193
  294. package/src/middleware/session.ts +174 -174
  295. package/src/middleware/timeout.ts +55 -55
  296. package/src/observability/logger-adapter.ts +36 -36
  297. package/src/observability/sqlite-store.ts +254 -254
  298. package/src/openapi/generator.ts +1 -1
  299. package/src/openapi/openapi.test.ts +43 -43
  300. package/src/perf/__tests__/user-marks.test.ts +354 -354
  301. package/src/perf/index.ts +133 -133
  302. package/src/perf/user-marks.ts +1 -1
  303. package/src/plugins/__tests__/lifecycle-integration.test.ts +272 -272
  304. package/src/plugins/__tests__/runner.test.ts +409 -409
  305. package/src/plugins/define.ts +124 -124
  306. package/src/plugins/examples/dep-check-plugin.ts +80 -80
  307. package/src/plugins/examples/prerender-cache-plugin.ts +111 -111
  308. package/src/plugins/examples/sitemap-plugin.ts +65 -65
  309. package/src/plugins/runner.ts +361 -361
  310. package/src/plugins/types.ts +368 -368
  311. package/src/report/index.ts +1 -1
  312. package/src/resource/__tests__/generator.test.ts +7 -7
  313. package/src/resource/__tests__/schema.test.ts +14 -14
  314. package/src/resource/ddl/__tests__/diff.test.ts +639 -639
  315. package/src/resource/ddl/__tests__/emit.test.ts +165 -165
  316. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -499
  317. package/src/resource/ddl/emit.ts +146 -146
  318. package/src/resource/ddl/persistence-types.ts +218 -218
  319. package/src/resource/ddl/type-map.ts +223 -223
  320. package/src/resource/ddl/types.ts +232 -232
  321. package/src/resource/generator-repo.ts +630 -630
  322. package/src/resource/generator-schema.ts +11 -11
  323. package/src/resource/generators/slot.ts +72 -72
  324. package/src/resource/schema.ts +21 -21
  325. package/src/router/client-entry.test.ts +227 -227
  326. package/src/router/client-entry.ts +218 -218
  327. package/src/router/fs-patterns.test.ts +96 -96
  328. package/src/router/fs-routes.test.ts +532 -532
  329. package/src/router/fs-routes.ts +53 -53
  330. package/src/router/fs-scanner.ts +216 -216
  331. package/src/router/fs-types.ts +19 -19
  332. package/src/router/route-source-analyzer.ts +521 -521
  333. package/src/routes/index.ts +74 -74
  334. package/src/routes/metadata-routes.ts +427 -427
  335. package/src/routes/types.ts +341 -341
  336. package/src/runtime/__tests__/devtools-adapter.test.ts +68 -68
  337. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -141
  338. package/src/runtime/__tests__/hdr-client.test.ts +223 -223
  339. package/src/runtime/__tests__/http-errors.test.ts +117 -117
  340. package/src/runtime/__tests__/inline-client-hydration.test.ts +237 -237
  341. package/src/runtime/__tests__/not-found.test.ts +152 -152
  342. package/src/runtime/__tests__/observability-lifecycle.test.ts +103 -103
  343. package/src/runtime/__tests__/page-render-response.test.ts +517 -517
  344. package/src/runtime/__tests__/request-middleware.test.ts +70 -70
  345. package/src/runtime/__tests__/searchparams-page-props.test.ts +81 -81
  346. package/src/runtime/adapter.ts +47 -47
  347. package/src/runtime/boundary.tsx +252 -252
  348. package/src/runtime/cache.ts +494 -494
  349. package/src/runtime/compose.ts +222 -222
  350. package/src/runtime/devtools-adapter.ts +68 -68
  351. package/src/runtime/escape.ts +34 -34
  352. package/src/runtime/fast-refresh-runtime.ts +322 -322
  353. package/src/runtime/fast-refresh-types.ts +1 -1
  354. package/src/runtime/handler.ts +65 -65
  355. package/src/runtime/handlers.ts +30 -11
  356. package/src/runtime/http-errors.ts +113 -113
  357. package/src/runtime/image-handler.ts +1 -1
  358. package/src/runtime/lifecycle.ts +381 -381
  359. package/src/runtime/logger.test.ts +345 -345
  360. package/src/runtime/middleware.ts +264 -264
  361. package/src/runtime/not-found.ts +93 -93
  362. package/src/runtime/observability-lifecycle.ts +290 -290
  363. package/src/runtime/openapi-endpoint.ts +236 -236
  364. package/src/runtime/page-render-response.ts +287 -274
  365. package/src/runtime/ppr.ts +74 -74
  366. package/src/runtime/rate-limit.ts +1 -1
  367. package/src/runtime/redirect.ts +1 -1
  368. package/src/runtime/registry.ts +171 -171
  369. package/src/runtime/request-middleware.ts +31 -31
  370. package/src/runtime/router.test.ts +4 -4
  371. package/src/runtime/router.ts +10 -10
  372. package/src/runtime/server.ts +127 -211
  373. package/src/runtime/shims.ts +48 -48
  374. package/src/runtime/ssr.ts +43 -17
  375. package/src/runtime/static-files.ts +369 -289
  376. package/src/runtime/streaming-ssr.ts +219 -180
  377. package/src/runtime/trace.ts +144 -144
  378. package/src/scheduler/__tests__/scheduler.test.ts +12 -11
  379. package/src/scheduler/index.ts +11 -5
  380. package/src/scheduler/validate.ts +169 -169
  381. package/src/seo/index.ts +219 -219
  382. package/src/seo/integration/ssr.ts +306 -306
  383. package/src/seo/render/basic.ts +435 -435
  384. package/src/seo/render/index.ts +143 -143
  385. package/src/seo/render/jsonld.ts +539 -539
  386. package/src/seo/render/opengraph.ts +197 -197
  387. package/src/seo/render/robots.ts +116 -116
  388. package/src/seo/render/sitemap.ts +137 -137
  389. package/src/seo/render/twitter.ts +127 -127
  390. package/src/seo/resolve/opengraph.ts +143 -143
  391. package/src/seo/resolve/robots.ts +73 -73
  392. package/src/seo/resolve/title.ts +94 -94
  393. package/src/seo/resolve/twitter.ts +73 -73
  394. package/src/seo/resolve/url.ts +104 -104
  395. package/src/seo/routes/index.ts +290 -290
  396. package/src/seo/types.ts +588 -588
  397. package/src/slot/validator.ts +39 -39
  398. package/src/spec/schema.ts +35 -35
  399. package/src/storage/s3/__tests__/s3.test.ts +479 -479
  400. package/src/storage/s3/index.ts +412 -412
  401. package/src/testing/__tests__/assertions.test.ts +632 -632
  402. package/src/testing/__tests__/reporter.test.ts +454 -454
  403. package/src/testing/assertions.ts +986 -986
  404. package/src/testing/db.ts +157 -157
  405. package/src/testing/index.ts +9 -3
  406. package/src/testing/lcov.ts +192 -0
  407. package/src/testing/mocks.ts +203 -203
  408. package/src/testing/session.ts +190 -190
  409. package/src/types/branded.ts +56 -56
  410. package/src/types/index.ts +1 -1
  411. package/src/utils/safe-io.ts +188 -188
  412. package/src/utils/string-safe.ts +298 -298
  413. package/src/watcher/__tests__/watcher.test.ts +59 -59
  414. package/src/watcher/watcher.ts +61 -61
@@ -1,779 +1,779 @@
1
- import type { ObservabilityEvent } from "../../observability/event-bus";
2
- import type { RoutesManifest, RouteSpec } from "../../spec/schema";
3
- import type { BundleManifest } from "../../bundler/types";
4
- import type { DiagnoseReport, DiagnoseCheckResult } from "../../diagnose/types";
5
-
6
- export type AgentDevToolsCategory =
7
- | "hydration"
8
- | "guard"
9
- | "contract"
10
- | "runtime"
11
- | "release"
12
- | "agent-tools"
13
- | "build-broken"
14
- | "boot-breaking";
15
-
16
- export type AgentDevToolsMode = "observe" | "suggest" | "assist" | "approval_required";
17
-
18
- export interface AgentDevToolsError {
19
- id?: string;
20
- type?: string;
21
- severity?: string;
22
- message: string;
23
- stack?: string;
24
- url?: string;
25
- source?: string;
26
- line?: number;
27
- column?: number;
28
- timestamp?: number;
29
- }
30
-
31
- export interface AgentStatsInput {
32
- totalAgents: number;
33
- totalEvents: number;
34
- agents: Record<string, {
35
- toolCalls: number;
36
- failures: number;
37
- topTools: Array<{ tool: string; count: number }>;
38
- avgDuration: number;
39
- firstSeen: number;
40
- lastSeen: number;
41
- }>;
42
- }
43
-
44
- export interface AgentDevToolsRequestLike {
45
- method?: string;
46
- path?: string;
47
- status?: number;
48
- duration?: number;
49
- timestamp?: number;
50
- cacheStatus?: string;
51
- }
52
-
53
- export interface BuildAgentContextPackInput {
54
- rootDir: string;
55
- manifest: RoutesManifest;
56
- guardEnabled: boolean;
57
- errors: AgentDevToolsError[];
58
- requests: AgentDevToolsRequestLike[];
59
- httpEvents: ObservabilityEvent[];
60
- mcpEvents: ObservabilityEvent[];
61
- guardEvents: ObservabilityEvent[];
62
- agentStats: AgentStatsInput;
63
- /**
64
- * Plan 18 P0-2 — additional signals so `pickSituation` can distinguish
65
- * build-broken / boot-breaking from runtime errors. All three are
66
- * optional: the handler passes them when collection succeeds and
67
- * leaves them undefined on environments where the source is missing
68
- * (fixture roots, tests, fresh project before first build).
69
- */
70
- bundleManifest?: BundleManifest | null;
71
- diagnoseReport?: DiagnoseReport | null;
72
- changedFiles?: string[];
73
- }
74
-
75
- export interface AgentToolRecommendation {
76
- task: string;
77
- skill: string;
78
- mcpTools: string[];
79
- cliFallback: string;
80
- useWhen: string;
81
- }
82
-
83
- export interface KnowledgeCard {
84
- id: string;
85
- title: string;
86
- category: AgentDevToolsCategory;
87
- body: string;
88
- references: string[];
89
- }
90
-
91
- export interface PromptSuggestion {
92
- title: string;
93
- copyText: string;
94
- variables: Array<{ name: string; value: string }>;
95
- }
96
-
97
- export interface NextSafeAction {
98
- mode: AgentDevToolsMode;
99
- title: string;
100
- reason: string;
101
- tool?: string;
102
- command?: string;
103
- validation: string[];
104
- risk: "low" | "medium" | "high";
105
- }
106
-
107
- export interface AgentContextPack {
108
- generatedAt: string;
109
- project: {
110
- rootDir: string;
111
- framework: "mandu";
112
- };
113
- summary: {
114
- routes: {
115
- total: number;
116
- pages: number;
117
- apis: number;
118
- metadata: number;
119
- islands: number;
120
- contracts: number;
121
- };
122
- guardEnabled: boolean;
123
- storedErrors: number;
124
- recentRequests: number;
125
- recentHttpErrors: number;
126
- recentMcpEvents: number;
127
- /**
128
- * Plan 18 P0-2 — bundle / diagnose / diff summary. Each block is
129
- * absent when the corresponding signal was not provided.
130
- */
131
- bundle?: {
132
- env: "development" | "production";
133
- buildTime: string;
134
- bundleCount: number;
135
- islandCount: number;
136
- };
137
- diagnose?: {
138
- healthy: boolean;
139
- errorCount: number;
140
- warningCount: number;
141
- total: number;
142
- failedRules: string[];
143
- };
144
- changedFiles?: {
145
- count: number;
146
- sample: string[];
147
- };
148
- };
149
- agentStatus: {
150
- totalAgents: number;
151
- observedToolCalls: number;
152
- failures: number;
153
- topTools: Array<{ tool: string; count: number }>;
154
- brain: {
155
- oauth: "unknown";
156
- statusTool: "mandu.brain.status";
157
- note: string;
158
- };
159
- };
160
- situation: {
161
- category: AgentDevToolsCategory;
162
- severity: "info" | "warn" | "error";
163
- title: string;
164
- details: string[];
165
- };
166
- toolRecommendations: AgentToolRecommendation[];
167
- knowledgeCards: KnowledgeCard[];
168
- prompt: PromptSuggestion;
169
- nextSafeAction: NextSafeAction;
170
- }
171
-
172
- const TOOL_ROUTER: Record<AgentDevToolsCategory, AgentToolRecommendation> = {
173
- hydration: {
174
- task: "Hydration or client island work",
175
- skill: "mandu-hydration",
176
- mcpTools: ["mandu.island.list", "mandu.build.status", "mandu.hydration.set"],
177
- cliFallback: "bun run build",
178
- useWhen: "Hydration mismatch, island bundle, client slot, or browser runtime symptoms are present.",
179
- },
180
- guard: {
181
- task: "Architecture boundary work",
182
- skill: "mandu-guard-guide",
183
- mcpTools: ["mandu.guard.check", "mandu.guard.explain", "mandu.brain.checkImport"],
184
- cliFallback: "bun run typecheck",
185
- useWhen: "Imports, layer boundaries, file placement, or guard violations are relevant.",
186
- },
187
- contract: {
188
- task: "API contract and route schema work",
189
- skill: "mandu-create-api",
190
- mcpTools: ["mandu.contract.list", "mandu.contract.validate", "mandu.contract.create"],
191
- cliFallback: "bun test",
192
- useWhen: "API routes, request/response schema, generated handlers, or OpenAPI output are involved.",
193
- },
194
- runtime: {
195
- task: "Runtime diagnosis",
196
- skill: "mandu-debug",
197
- mcpTools: ["mandu.brain.doctor", "mandu.ai.brief", "mandu.test.smart"],
198
- cliFallback: "bun test",
199
- useWhen: "HTTP 4xx/5xx, request correlation, runtime exceptions, or failing tests are visible.",
200
- },
201
- release: {
202
- task: "Release confidence",
203
- skill: "mandu-release",
204
- mcpTools: ["mandu.build.status", "mandu.contract.validate", "mandu.test.precommit"],
205
- cliFallback: "bun run lint && bun run typecheck && bun test",
206
- useWhen: "The session is clean enough to validate and package changes.",
207
- },
208
- "agent-tools": {
209
- task: "Agent tool selection",
210
- skill: "mandu-agent-workflow",
211
- mcpTools: ["mandu.ai.brief", "mandu.brain.status", "mandu.watch.status"],
212
- cliFallback: "bun run lint",
213
- useWhen: "The next step is unclear, an agent skipped Mandu tools, or a supervised coding session is starting.",
214
- },
215
- "build-broken": {
216
- task: "Build artifact recovery",
217
- skill: "mandu-debug",
218
- mcpTools: ["mandu.build.status", "mandu.build", "mandu.diagnose"],
219
- cliFallback: "bun run build",
220
- useWhen: "Bundle manifest is missing, stale, or the diagnose pipeline reports a broken build artifact.",
221
- },
222
- "boot-breaking": {
223
- task: "Install or boot-time failure",
224
- skill: "mandu-debug",
225
- mcpTools: ["mandu.diagnose", "mandu.brain.doctor", "mandu.brain.checkImport"],
226
- cliFallback: "bun install",
227
- useWhen: "Diagnose surfaces nested_internal_core, package_export_gaps, or other install-time regressions (e.g. #260/#261).",
228
- },
229
- };
230
-
231
- function routeSummary(manifest: RoutesManifest): AgentContextPack["summary"]["routes"] {
232
- const routes = manifest.routes;
233
- return {
234
- total: routes.length,
235
- pages: routes.filter((route) => route.kind === "page").length,
236
- apis: routes.filter((route) => route.kind === "api").length,
237
- metadata: routes.filter((route) => route.kind === "metadata").length,
238
- islands: routes.filter((route) => !!route.clientModule).length,
239
- contracts: routes.filter((route) => !!route.contractModule).length,
240
- };
241
- }
242
-
243
- function readStatus(event: ObservabilityEvent | AgentDevToolsRequestLike): number {
244
- const fromData = "data" in event && typeof event.data?.status === "number"
245
- ? event.data.status
246
- : undefined;
247
- return fromData ?? ("status" in event && typeof event.status === "number" ? event.status : 0);
248
- }
249
-
250
- function readPath(event: ObservabilityEvent | AgentDevToolsRequestLike): string {
251
- if ("data" in event) {
252
- const path = event.data?.path ?? event.data?.url;
253
- if (typeof path === "string") return path;
254
- }
255
- return "path" in event && typeof event.path === "string" ? event.path : "";
256
- }
257
-
258
- function textContains(value: string | undefined, patterns: RegExp[]): boolean {
259
- if (!value) return false;
260
- return patterns.some((pattern) => pattern.test(value));
261
- }
262
-
263
- function isHydrationError(error: AgentDevToolsError): boolean {
264
- const patterns = [/hydration/i, /hydrate/i, /island/i, /client slot/i, /data-mandu/i];
265
- return textContains(error.message, patterns)
266
- || textContains(error.stack, patterns)
267
- || textContains(error.source, patterns)
268
- || textContains(error.type, patterns);
269
- }
270
-
271
- /**
272
- * Plan 18 P0-2 — install/boot-time regressions that make the next dev
273
- * step impossible. Surfaced ahead of every other category because the
274
- * symptom (`Cannot find module ...`, nested core shadowing) blocks the
275
- * tools the agent would otherwise use to investigate.
276
- */
277
- const BOOT_BREAKING_RULES = new Set([
278
- "nested_internal_core",
279
- "package_export_gaps",
280
- "manifest_validation",
281
- ]);
282
-
283
- function findBootBreakingCheck(report: DiagnoseReport | null | undefined): DiagnoseCheckResult | undefined {
284
- if (!report) return undefined;
285
- return report.checks.find(
286
- (check) => !check.ok && check.severity === "error" && BOOT_BREAKING_RULES.has(check.rule),
287
- );
288
- }
289
-
290
- function findBuildBrokenCheck(report: DiagnoseReport | null | undefined): DiagnoseCheckResult | undefined {
291
- if (!report) return undefined;
292
- return report.checks.find(
293
- (check) => !check.ok && check.severity === "error" && check.rule === "manifest_freshness",
294
- );
295
- }
296
-
297
- function isBundleManifestEmpty(manifest: BundleManifest | null | undefined): boolean {
298
- if (!manifest) return false; // null/undefined means "not collected", not "empty"
299
- const hasBundles = Object.keys(manifest.bundles ?? {}).length > 0;
300
- const hasIslands = Object.keys(manifest.islands ?? {}).length > 0;
301
- return !hasBundles && !hasIslands;
302
- }
303
-
304
- function pickSituation(input: BuildAgentContextPackInput): AgentContextPack["situation"] {
305
- // Boot-breaking has the highest priority: if the project can't load,
306
- // the agent's first move should be a recovery command, not a code edit.
307
- const bootBreaking = findBootBreakingCheck(input.diagnoseReport);
308
- if (bootBreaking) {
309
- return {
310
- category: "boot-breaking",
311
- severity: "error",
312
- title: "Install or boot regression detected",
313
- details: [
314
- `${bootBreaking.rule}: ${bootBreaking.message}`,
315
- bootBreaking.suggestion ?? "Run `mandu diagnose` for the copy-pastable fix.",
316
- ],
317
- };
318
- }
319
-
320
- // Build-broken comes next: missing or stale bundle manifest means
321
- // hydration / island / SSR diagnosis can't be trusted yet.
322
- const buildBroken = findBuildBrokenCheck(input.diagnoseReport);
323
- if (buildBroken) {
324
- return {
325
- category: "build-broken",
326
- severity: "error",
327
- title: "Build artifact is missing or stale",
328
- details: [
329
- buildBroken.message,
330
- buildBroken.suggestion ?? "Run `mandu build` and re-check.",
331
- ],
332
- };
333
- }
334
-
335
- // Bundle manifest absent on a hydrated project is the silent variant
336
- // of the above — diagnose may not have flagged it yet on a fresh
337
- // clone, but the supervisor should still hint at the missing build.
338
- const hydratedRoutes = input.manifest.routes.filter((route) => !!route.clientModule).length;
339
- if (
340
- input.bundleManifest !== undefined &&
341
- isBundleManifestEmpty(input.bundleManifest) &&
342
- hydratedRoutes > 0
343
- ) {
344
- return {
345
- category: "build-broken",
346
- severity: "warn",
347
- title: "Bundle manifest empty but hydration is declared",
348
- details: [
349
- `${hydratedRoutes} route(s) declare client hydration but no bundles are emitted.`,
350
- "Run `mandu build` before opening the page — DevTools will not see island bundles otherwise.",
351
- ],
352
- };
353
- }
354
-
355
- const hydrationError = input.errors.find(isHydrationError);
356
- if (hydrationError) {
357
- return {
358
- category: "hydration",
359
- severity: "error",
360
- title: "Hydration issue detected",
361
- details: [
362
- hydrationError.message,
363
- "Start from the island graph and build status before editing UI code.",
364
- ],
365
- };
366
- }
367
-
368
- const failingHttp = [...input.httpEvents, ...input.requests].find((event) => readStatus(event) >= 500);
369
- if (failingHttp) {
370
- return {
371
- category: "runtime",
372
- severity: "error",
373
- title: "Recent request failure detected",
374
- details: [
375
- `${readStatus(failingHttp)} ${readPath(failingHttp) || "unknown path"}`,
376
- "Trace the request correlation and reproduce with a targeted test or smoke request.",
377
- ],
378
- };
379
- }
380
-
381
- const guardFailure = input.guardEvents.find((event) => event.severity === "error" || event.severity === "warn");
382
- if (guardFailure) {
383
- return {
384
- category: "guard",
385
- severity: guardFailure.severity === "error" ? "error" : "warn",
386
- title: "Architecture guard signal detected",
387
- details: [
388
- guardFailure.message,
389
- "Use the guard toolchain before moving files or changing import paths.",
390
- ],
391
- };
392
- }
393
-
394
- const apiRoutes = input.manifest.routes.filter((route) => route.kind === "api");
395
- const apiRoutesWithoutContracts = apiRoutes.filter((route) => !route.contractModule);
396
- if (apiRoutes.length > 0 && apiRoutesWithoutContracts.length > 0) {
397
- return {
398
- category: "contract",
399
- severity: "warn",
400
- title: "API routes need contract attention",
401
- details: [
402
- `${apiRoutesWithoutContracts.length} of ${apiRoutes.length} API routes do not expose a contract module.`,
403
- "Prefer contract-aware changes so agents can validate request and response shape.",
404
- ],
405
- };
406
- }
407
-
408
- if (input.agentStats.totalEvents === 0) {
409
- return {
410
- category: "agent-tools",
411
- severity: "info",
412
- title: "No MCP tool usage observed yet",
413
- details: [
414
- "Start the session with an AI brief and brain status check.",
415
- "Record the selected skill, selected MCP tools, fallback reason, changed files, and validation in the agent report.",
416
- ],
417
- };
418
- }
419
-
420
- return {
421
- category: "release",
422
- severity: "info",
423
- title: "Session is ready for confidence checks",
424
- details: [
425
- "No high-priority runtime, guard, or hydration signal is currently visible.",
426
- "Run release confidence checks before shipping broader changes.",
427
- ],
428
- };
429
- }
430
-
431
- function buildKnowledgeCards(
432
- input: BuildAgentContextPackInput,
433
- situation: AgentContextPack["situation"],
434
- ): KnowledgeCard[] {
435
- const summary = routeSummary(input.manifest);
436
- const cards: KnowledgeCard[] = [
437
- {
438
- id: "mcp-first",
439
- title: "MCP first, CLI second",
440
- category: "agent-tools",
441
- body: "Agents should select the Mandu skill and MCP tool for the task domain before falling back to Bun or shell commands.",
442
- references: ["docs/guides/07_agent_workflow.md", "AGENTS.md"],
443
- },
444
- {
445
- id: "brain-status",
446
- title: "Brain status is explicit",
447
- category: "agent-tools",
448
- body: "Kitchen cannot infer cloud OAuth state from the browser. Ask the MCP layer for mandu.brain.status when LLM-assisted doctor or heal output matters.",
449
- references: ["packages/mcp/src/tools/brain.ts"],
450
- },
451
- ];
452
-
453
- if (summary.islands > 0 || situation.category === "hydration") {
454
- cards.push({
455
- id: "hydration-map",
456
- title: "Inspect islands before editing UI",
457
- category: "hydration",
458
- body: "Hydration changes should start from route island inventory and current build status, then narrow to the affected client slot.",
459
- references: ["packages/mcp/src/tools/hydration.ts", "docs/guides/07_agent_workflow.md"],
460
- });
461
- }
462
-
463
- if (input.guardEnabled || situation.category === "guard") {
464
- cards.push({
465
- id: "guard-boundaries",
466
- title: "Guard preserves architecture",
467
- category: "guard",
468
- body: "Boundary fixes should explain the violated rule and verify imports with guard tools before typecheck.",
469
- references: ["packages/mcp/src/tools/guard.ts", "packages/core/src/guard"],
470
- });
471
- }
472
-
473
- if (summary.apis > 0 || situation.category === "contract") {
474
- cards.push({
475
- id: "contract-confidence",
476
- title: "Contracts make API edits agent-safe",
477
- category: "contract",
478
- body: "API edits should keep route contracts synchronized and use contract validation before broad tests.",
479
- references: ["packages/mcp/src/tools/contract.ts", "packages/core/src/kitchen/api/contract-api.ts"],
480
- });
481
- }
482
-
483
- if (situation.category === "build-broken") {
484
- cards.push({
485
- id: "build-first",
486
- title: "Bundle manifest is the source of truth",
487
- category: "build-broken",
488
- body: "Hydration / island / DevTools all read .mandu/manifest.json. When it is missing or stale, every downstream signal is unreliable — rebuild first, diagnose second.",
489
- references: ["packages/core/src/bundler/types.ts", "packages/core/src/diagnose/checks.ts"],
490
- });
491
- }
492
-
493
- if (situation.category === "boot-breaking") {
494
- cards.push({
495
- id: "boot-recovery",
496
- title: "Install regressions need install-time recovery",
497
- category: "boot-breaking",
498
- body: "nested_internal_core and package_export_gaps shadow module resolution. Code edits won't help until node_modules is reconciled — let mandu diagnose print the exact rm/install command.",
499
- references: ["packages/core/src/diagnose/checks.ts", "docs/issues (#260, #261)"],
500
- });
501
- }
502
-
503
- return cards.slice(0, 6);
504
- }
505
-
506
- function buildPrompt(
507
- situation: AgentContextPack["situation"],
508
- recommendation: AgentToolRecommendation,
509
- input: BuildAgentContextPackInput,
510
- ): PromptSuggestion {
511
- const summary = routeSummary(input.manifest);
512
- const routeHint = pickRouteHint(input.manifest.routes, situation.category);
513
-
514
- const lines: string[] = [
515
- "You are working inside a Mandu agent-native project.",
516
- `Task domain: ${situation.category}`,
517
- `Selected skill: ${recommendation.skill}`,
518
- `MCP tools to try first: ${recommendation.mcpTools.join(", ")}`,
519
- `Fallback command only if MCP is unavailable: ${recommendation.cliFallback}`,
520
- `Current signal: ${situation.title}`,
521
- `Details: ${situation.details.join(" | ")}`,
522
- `Route hint: ${routeHint}`,
523
- `Project shape: ${summary.pages} pages, ${summary.apis} APIs, ${summary.islands} islands, ${summary.contracts} contracts.`,
524
- ];
525
-
526
- // Plan 18 P0-2 — surface build / diagnose / diff signals into the
527
- // prompt so the agent does not need a second tool call to learn the
528
- // environment shape.
529
- const bundle = summarizeBundleManifest(input.bundleManifest);
530
- if (bundle) {
531
- lines.push(
532
- `Build state: env=${bundle.env}, bundles=${bundle.bundleCount}, islands=${bundle.islandCount}, builtAt=${bundle.buildTime}.`,
533
- );
534
- }
535
- const diag = summarizeDiagnose(input.diagnoseReport);
536
- if (diag) {
537
- lines.push(
538
- diag.healthy
539
- ? `Diagnose: healthy (${diag.total} checks).`
540
- : `Diagnose: ${diag.errorCount} error / ${diag.warningCount} warning — failed rules: ${diag.failedRules.join(", ") || "(none listed)"}.`,
541
- );
542
- }
543
- const changed = summarizeChangedFiles(input.changedFiles);
544
- if (changed && changed.count > 0) {
545
- lines.push(
546
- `Changed files (${changed.count}, first ${changed.sample.length}): ${changed.sample.join(", ")}.`,
547
- );
548
- }
549
-
550
- lines.push(
551
- "Before editing: inspect affected files and state the exact tool/skill choice.",
552
- "After editing: report changed files, validation commands, and any fallback reason.",
553
- );
554
-
555
- return {
556
- title: `Prompt for ${situation.category} work`,
557
- copyText: lines.join("\n"),
558
- variables: [
559
- { name: "task_domain", value: situation.category },
560
- { name: "selected_skill", value: recommendation.skill },
561
- { name: "route_hint", value: routeHint },
562
- ],
563
- };
564
- }
565
-
566
- function pickRouteHint(routes: RouteSpec[], category: AgentDevToolsCategory): string {
567
- if (category === "hydration") {
568
- return routes.find((route) => route.clientModule)?.pattern ?? "No client island route detected.";
569
- }
570
- if (category === "contract") {
571
- return routes.find((route) => route.kind === "api" && !route.contractModule)?.pattern
572
- ?? routes.find((route) => route.kind === "api")?.pattern
573
- ?? "No API route detected.";
574
- }
575
- return routes[0]?.pattern ?? "No route detected.";
576
- }
577
-
578
- function buildNextSafeAction(
579
- situation: AgentContextPack["situation"],
580
- recommendation: AgentToolRecommendation,
581
- ): NextSafeAction {
582
- switch (situation.category) {
583
- case "hydration":
584
- return {
585
- mode: "observe",
586
- title: "Inspect island inventory",
587
- reason: "Hydration fixes should begin by locating the exact island and build artifact.",
588
- tool: "mandu.island.list",
589
- command: "bun run build",
590
- validation: ["mandu.build.status", "targeted browser smoke if UI changed"],
591
- risk: "low",
592
- };
593
- case "guard":
594
- return {
595
- mode: "suggest",
596
- title: "Run guard check before moving code",
597
- reason: "Architecture fixes need rule-level evidence before imports are rewritten.",
598
- tool: "mandu.guard.check",
599
- command: "bun run typecheck",
600
- validation: ["mandu.guard.explain for any violation", "bun run typecheck"],
601
- risk: "low",
602
- };
603
- case "contract":
604
- return {
605
- mode: "assist",
606
- title: "Validate route contracts",
607
- reason: "API edits are safer when request and response shape are checked first.",
608
- tool: "mandu.contract.validate",
609
- command: "bun test",
610
- validation: ["mandu.contract.list", "mandu.contract.validate", "targeted API tests"],
611
- risk: "medium",
612
- };
613
- case "runtime":
614
- return {
615
- mode: "suggest",
616
- title: "Trace failing request",
617
- reason: "Runtime failures need the exact request path and correlated events before patching.",
618
- tool: "mandu.brain.doctor",
619
- command: "bun test",
620
- validation: ["targeted repro", "related unit or integration test"],
621
- risk: "medium",
622
- };
623
- case "release":
624
- return {
625
- mode: "assist",
626
- title: "Run confidence gate",
627
- reason: "No blocking signal is visible, so the next useful step is validation.",
628
- tool: recommendation.mcpTools[0],
629
- command: recommendation.cliFallback,
630
- validation: ["lint", "typecheck", "tests"],
631
- risk: "low",
632
- };
633
- case "agent-tools":
634
- return {
635
- mode: "observe",
636
- title: "Check brain and AI brief",
637
- reason: "The session has not shown MCP usage yet, so establish context before editing.",
638
- tool: "mandu.ai.brief",
639
- command: "bun run lint",
640
- validation: ["mandu.brain.status", "mandu.ai.brief"],
641
- risk: "low",
642
- };
643
- case "build-broken":
644
- return {
645
- mode: "assist",
646
- title: "Rebuild before any other change",
647
- reason: "Bundle manifest is missing or stale — DevTools, hydration, and island inventory all read it.",
648
- tool: "mandu.build",
649
- command: "bun run build",
650
- validation: ["mandu.build.status", "mandu.diagnose"],
651
- risk: "low",
652
- };
653
- case "boot-breaking":
654
- return {
655
- mode: "observe",
656
- title: "Run mandu diagnose for the recovery command",
657
- reason: "An install regression is shadowing module resolution; let diagnose print the exact rm/install fix.",
658
- tool: "mandu.diagnose",
659
- command: "bun install",
660
- validation: ["mandu.diagnose", "bunx @mandujs/mcp --help"],
661
- risk: "low",
662
- };
663
- }
664
- }
665
-
666
- function flattenTopTools(agentStats: AgentStatsInput): Array<{ tool: string; count: number }> {
667
- const counts = new Map<string, number>();
668
- for (const agent of Object.values(agentStats.agents)) {
669
- for (const item of agent.topTools) {
670
- counts.set(item.tool, (counts.get(item.tool) ?? 0) + item.count);
671
- }
672
- }
673
- return Array.from(counts.entries())
674
- .map(([tool, count]) => ({ tool, count }))
675
- .sort((a, b) => b.count - a.count)
676
- .slice(0, 5);
677
- }
678
-
679
- function uniqueRecommendations(primary: AgentDevToolsCategory): AgentToolRecommendation[] {
680
- const order: AgentDevToolsCategory[] = [
681
- primary,
682
- "boot-breaking",
683
- "build-broken",
684
- "agent-tools",
685
- "guard",
686
- "contract",
687
- "hydration",
688
- "runtime",
689
- "release",
690
- ];
691
- const seen = new Set<AgentDevToolsCategory>();
692
- const result: AgentToolRecommendation[] = [];
693
- for (const category of order) {
694
- if (seen.has(category)) continue;
695
- seen.add(category);
696
- result.push(TOOL_ROUTER[category]);
697
- }
698
- return result.slice(0, 4);
699
- }
700
-
701
- function summarizeBundleManifest(manifest: BundleManifest | null | undefined): AgentContextPack["summary"]["bundle"] {
702
- if (!manifest) return undefined;
703
- return {
704
- env: manifest.env,
705
- buildTime: manifest.buildTime,
706
- bundleCount: Object.keys(manifest.bundles ?? {}).length,
707
- islandCount: Object.keys(manifest.islands ?? {}).length,
708
- };
709
- }
710
-
711
- function summarizeDiagnose(report: DiagnoseReport | null | undefined): AgentContextPack["summary"]["diagnose"] {
712
- if (!report) return undefined;
713
- const failedRules = report.checks.filter((c) => !c.ok).map((c) => c.rule);
714
- return {
715
- healthy: report.healthy,
716
- errorCount: report.errorCount,
717
- warningCount: report.warningCount,
718
- total: report.summary.total,
719
- failedRules,
720
- };
721
- }
722
-
723
- function summarizeChangedFiles(files: string[] | undefined): AgentContextPack["summary"]["changedFiles"] {
724
- if (!files) return undefined;
725
- return {
726
- count: files.length,
727
- sample: files.slice(0, 8),
728
- };
729
- }
730
-
731
- export function buildAgentContextPack(input: BuildAgentContextPackInput): AgentContextPack {
732
- const routes = routeSummary(input.manifest);
733
- const recentHttpErrors = [...input.httpEvents, ...input.requests]
734
- .filter((event) => readStatus(event) >= 400).length;
735
- const situation = pickSituation(input);
736
- const recommendations = uniqueRecommendations(situation.category);
737
- const primaryRecommendation = recommendations[0] ?? TOOL_ROUTER["agent-tools"];
738
- const failures = Object.values(input.agentStats.agents)
739
- .reduce((sum, agent) => sum + agent.failures, 0);
740
-
741
- return {
742
- generatedAt: new Date().toISOString(),
743
- project: {
744
- rootDir: input.rootDir,
745
- framework: "mandu",
746
- },
747
- summary: {
748
- routes,
749
- guardEnabled: input.guardEnabled,
750
- storedErrors: input.errors.length,
751
- recentRequests: input.requests.length + input.httpEvents.length,
752
- recentHttpErrors,
753
- recentMcpEvents: input.mcpEvents.length,
754
- bundle: summarizeBundleManifest(input.bundleManifest),
755
- diagnose: summarizeDiagnose(input.diagnoseReport),
756
- changedFiles: summarizeChangedFiles(input.changedFiles),
757
- },
758
- agentStatus: {
759
- totalAgents: input.agentStats.totalAgents,
760
- observedToolCalls: input.agentStats.totalEvents,
761
- failures,
762
- topTools: flattenTopTools(input.agentStats),
763
- brain: {
764
- oauth: "unknown",
765
- statusTool: "mandu.brain.status",
766
- note: "OAuth state is owned by the MCP brain layer; call mandu.brain.status for current provider/tier.",
767
- },
768
- },
769
- situation,
770
- toolRecommendations: recommendations,
771
- knowledgeCards: buildKnowledgeCards(input, situation),
772
- prompt: buildPrompt(situation, primaryRecommendation, input),
773
- nextSafeAction: buildNextSafeAction(situation, primaryRecommendation),
774
- };
775
- }
776
-
777
- export function handleAgentContextRequest(input: BuildAgentContextPackInput): Response {
778
- return Response.json(buildAgentContextPack(input));
779
- }
1
+ import type { ObservabilityEvent } from "../../observability/event-bus";
2
+ import type { RoutesManifest, RouteSpec } from "../../spec/schema";
3
+ import type { BundleManifest } from "../../bundler/types";
4
+ import type { DiagnoseReport, DiagnoseCheckResult } from "../../diagnose/types";
5
+
6
+ export type AgentDevToolsCategory =
7
+ | "hydration"
8
+ | "guard"
9
+ | "contract"
10
+ | "runtime"
11
+ | "release"
12
+ | "agent-tools"
13
+ | "build-broken"
14
+ | "boot-breaking";
15
+
16
+ export type AgentDevToolsMode = "observe" | "suggest" | "assist" | "approval_required";
17
+
18
+ export interface AgentDevToolsError {
19
+ id?: string;
20
+ type?: string;
21
+ severity?: string;
22
+ message: string;
23
+ stack?: string;
24
+ url?: string;
25
+ source?: string;
26
+ line?: number;
27
+ column?: number;
28
+ timestamp?: number;
29
+ }
30
+
31
+ export interface AgentStatsInput {
32
+ totalAgents: number;
33
+ totalEvents: number;
34
+ agents: Record<string, {
35
+ toolCalls: number;
36
+ failures: number;
37
+ topTools: Array<{ tool: string; count: number }>;
38
+ avgDuration: number;
39
+ firstSeen: number;
40
+ lastSeen: number;
41
+ }>;
42
+ }
43
+
44
+ export interface AgentDevToolsRequestLike {
45
+ method?: string;
46
+ path?: string;
47
+ status?: number;
48
+ duration?: number;
49
+ timestamp?: number;
50
+ cacheStatus?: string;
51
+ }
52
+
53
+ export interface BuildAgentContextPackInput {
54
+ rootDir: string;
55
+ manifest: RoutesManifest;
56
+ guardEnabled: boolean;
57
+ errors: AgentDevToolsError[];
58
+ requests: AgentDevToolsRequestLike[];
59
+ httpEvents: ObservabilityEvent[];
60
+ mcpEvents: ObservabilityEvent[];
61
+ guardEvents: ObservabilityEvent[];
62
+ agentStats: AgentStatsInput;
63
+ /**
64
+ * Plan 18 P0-2 — additional signals so `pickSituation` can distinguish
65
+ * build-broken / boot-breaking from runtime errors. All three are
66
+ * optional: the handler passes them when collection succeeds and
67
+ * leaves them undefined on environments where the source is missing
68
+ * (fixture roots, tests, fresh project before first build).
69
+ */
70
+ bundleManifest?: BundleManifest | null;
71
+ diagnoseReport?: DiagnoseReport | null;
72
+ changedFiles?: string[];
73
+ }
74
+
75
+ export interface AgentToolRecommendation {
76
+ task: string;
77
+ skill: string;
78
+ mcpTools: string[];
79
+ cliFallback: string;
80
+ useWhen: string;
81
+ }
82
+
83
+ export interface KnowledgeCard {
84
+ id: string;
85
+ title: string;
86
+ category: AgentDevToolsCategory;
87
+ body: string;
88
+ references: string[];
89
+ }
90
+
91
+ export interface PromptSuggestion {
92
+ title: string;
93
+ copyText: string;
94
+ variables: Array<{ name: string; value: string }>;
95
+ }
96
+
97
+ export interface NextSafeAction {
98
+ mode: AgentDevToolsMode;
99
+ title: string;
100
+ reason: string;
101
+ tool?: string;
102
+ command?: string;
103
+ validation: string[];
104
+ risk: "low" | "medium" | "high";
105
+ }
106
+
107
+ export interface AgentContextPack {
108
+ generatedAt: string;
109
+ project: {
110
+ rootDir: string;
111
+ framework: "mandu";
112
+ };
113
+ summary: {
114
+ routes: {
115
+ total: number;
116
+ pages: number;
117
+ apis: number;
118
+ metadata: number;
119
+ islands: number;
120
+ contracts: number;
121
+ };
122
+ guardEnabled: boolean;
123
+ storedErrors: number;
124
+ recentRequests: number;
125
+ recentHttpErrors: number;
126
+ recentMcpEvents: number;
127
+ /**
128
+ * Plan 18 P0-2 — bundle / diagnose / diff summary. Each block is
129
+ * absent when the corresponding signal was not provided.
130
+ */
131
+ bundle?: {
132
+ env: "development" | "production";
133
+ buildTime: string;
134
+ bundleCount: number;
135
+ islandCount: number;
136
+ };
137
+ diagnose?: {
138
+ healthy: boolean;
139
+ errorCount: number;
140
+ warningCount: number;
141
+ total: number;
142
+ failedRules: string[];
143
+ };
144
+ changedFiles?: {
145
+ count: number;
146
+ sample: string[];
147
+ };
148
+ };
149
+ agentStatus: {
150
+ totalAgents: number;
151
+ observedToolCalls: number;
152
+ failures: number;
153
+ topTools: Array<{ tool: string; count: number }>;
154
+ brain: {
155
+ oauth: "unknown";
156
+ statusTool: "mandu.brain.status";
157
+ note: string;
158
+ };
159
+ };
160
+ situation: {
161
+ category: AgentDevToolsCategory;
162
+ severity: "info" | "warn" | "error";
163
+ title: string;
164
+ details: string[];
165
+ };
166
+ toolRecommendations: AgentToolRecommendation[];
167
+ knowledgeCards: KnowledgeCard[];
168
+ prompt: PromptSuggestion;
169
+ nextSafeAction: NextSafeAction;
170
+ }
171
+
172
+ const TOOL_ROUTER: Record<AgentDevToolsCategory, AgentToolRecommendation> = {
173
+ hydration: {
174
+ task: "Hydration or client island work",
175
+ skill: "mandu-hydration",
176
+ mcpTools: ["mandu.island.list", "mandu.build.status", "mandu.hydration.set"],
177
+ cliFallback: "bun run build",
178
+ useWhen: "Hydration mismatch, island bundle, client slot, or browser runtime symptoms are present.",
179
+ },
180
+ guard: {
181
+ task: "Architecture boundary work",
182
+ skill: "mandu-guard-guide",
183
+ mcpTools: ["mandu.guard.check", "mandu.guard.explain", "mandu.brain.checkImport"],
184
+ cliFallback: "bun run typecheck",
185
+ useWhen: "Imports, layer boundaries, file placement, or guard violations are relevant.",
186
+ },
187
+ contract: {
188
+ task: "API contract and route schema work",
189
+ skill: "mandu-create-api",
190
+ mcpTools: ["mandu.contract.list", "mandu.contract.validate", "mandu.contract.create"],
191
+ cliFallback: "bun test",
192
+ useWhen: "API routes, request/response schema, generated handlers, or OpenAPI output are involved.",
193
+ },
194
+ runtime: {
195
+ task: "Runtime diagnosis",
196
+ skill: "mandu-debug",
197
+ mcpTools: ["mandu.brain.doctor", "mandu.ai.brief", "mandu.test.smart"],
198
+ cliFallback: "bun test",
199
+ useWhen: "HTTP 4xx/5xx, request correlation, runtime exceptions, or failing tests are visible.",
200
+ },
201
+ release: {
202
+ task: "Release confidence",
203
+ skill: "mandu-release",
204
+ mcpTools: ["mandu.build.status", "mandu.contract.validate", "mandu.test.precommit"],
205
+ cliFallback: "bun run lint && bun run typecheck && bun test",
206
+ useWhen: "The session is clean enough to validate and package changes.",
207
+ },
208
+ "agent-tools": {
209
+ task: "Agent tool selection",
210
+ skill: "mandu-agent-workflow",
211
+ mcpTools: ["mandu.ai.brief", "mandu.brain.status", "mandu.watch.status"],
212
+ cliFallback: "bun run lint",
213
+ useWhen: "The next step is unclear, an agent skipped Mandu tools, or a supervised coding session is starting.",
214
+ },
215
+ "build-broken": {
216
+ task: "Build artifact recovery",
217
+ skill: "mandu-debug",
218
+ mcpTools: ["mandu.build.status", "mandu.build", "mandu.diagnose"],
219
+ cliFallback: "bun run build",
220
+ useWhen: "Bundle manifest is missing, stale, or the diagnose pipeline reports a broken build artifact.",
221
+ },
222
+ "boot-breaking": {
223
+ task: "Install or boot-time failure",
224
+ skill: "mandu-debug",
225
+ mcpTools: ["mandu.diagnose", "mandu.brain.doctor", "mandu.brain.checkImport"],
226
+ cliFallback: "bun install",
227
+ useWhen: "Diagnose surfaces nested_internal_core, package_export_gaps, or other install-time regressions (e.g. #260/#261).",
228
+ },
229
+ };
230
+
231
+ function routeSummary(manifest: RoutesManifest): AgentContextPack["summary"]["routes"] {
232
+ const routes = manifest.routes;
233
+ return {
234
+ total: routes.length,
235
+ pages: routes.filter((route) => route.kind === "page").length,
236
+ apis: routes.filter((route) => route.kind === "api").length,
237
+ metadata: routes.filter((route) => route.kind === "metadata").length,
238
+ islands: routes.filter((route) => !!route.clientModule).length,
239
+ contracts: routes.filter((route) => !!route.contractModule).length,
240
+ };
241
+ }
242
+
243
+ function readStatus(event: ObservabilityEvent | AgentDevToolsRequestLike): number {
244
+ const fromData = "data" in event && typeof event.data?.status === "number"
245
+ ? event.data.status
246
+ : undefined;
247
+ return fromData ?? ("status" in event && typeof event.status === "number" ? event.status : 0);
248
+ }
249
+
250
+ function readPath(event: ObservabilityEvent | AgentDevToolsRequestLike): string {
251
+ if ("data" in event) {
252
+ const path = event.data?.path ?? event.data?.url;
253
+ if (typeof path === "string") return path;
254
+ }
255
+ return "path" in event && typeof event.path === "string" ? event.path : "";
256
+ }
257
+
258
+ function textContains(value: string | undefined, patterns: RegExp[]): boolean {
259
+ if (!value) return false;
260
+ return patterns.some((pattern) => pattern.test(value));
261
+ }
262
+
263
+ function isHydrationError(error: AgentDevToolsError): boolean {
264
+ const patterns = [/hydration/i, /hydrate/i, /island/i, /client slot/i, /data-mandu/i];
265
+ return textContains(error.message, patterns)
266
+ || textContains(error.stack, patterns)
267
+ || textContains(error.source, patterns)
268
+ || textContains(error.type, patterns);
269
+ }
270
+
271
+ /**
272
+ * Plan 18 P0-2 — install/boot-time regressions that make the next dev
273
+ * step impossible. Surfaced ahead of every other category because the
274
+ * symptom (`Cannot find module ...`, nested core shadowing) blocks the
275
+ * tools the agent would otherwise use to investigate.
276
+ */
277
+ const BOOT_BREAKING_RULES = new Set([
278
+ "nested_internal_core",
279
+ "package_export_gaps",
280
+ "manifest_validation",
281
+ ]);
282
+
283
+ function findBootBreakingCheck(report: DiagnoseReport | null | undefined): DiagnoseCheckResult | undefined {
284
+ if (!report) return undefined;
285
+ return report.checks.find(
286
+ (check) => !check.ok && check.severity === "error" && BOOT_BREAKING_RULES.has(check.rule),
287
+ );
288
+ }
289
+
290
+ function findBuildBrokenCheck(report: DiagnoseReport | null | undefined): DiagnoseCheckResult | undefined {
291
+ if (!report) return undefined;
292
+ return report.checks.find(
293
+ (check) => !check.ok && check.severity === "error" && check.rule === "manifest_freshness",
294
+ );
295
+ }
296
+
297
+ function isBundleManifestEmpty(manifest: BundleManifest | null | undefined): boolean {
298
+ if (!manifest) return false; // null/undefined means "not collected", not "empty"
299
+ const hasBundles = Object.keys(manifest.bundles ?? {}).length > 0;
300
+ const hasIslands = Object.keys(manifest.islands ?? {}).length > 0;
301
+ return !hasBundles && !hasIslands;
302
+ }
303
+
304
+ function pickSituation(input: BuildAgentContextPackInput): AgentContextPack["situation"] {
305
+ // Boot-breaking has the highest priority: if the project can't load,
306
+ // the agent's first move should be a recovery command, not a code edit.
307
+ const bootBreaking = findBootBreakingCheck(input.diagnoseReport);
308
+ if (bootBreaking) {
309
+ return {
310
+ category: "boot-breaking",
311
+ severity: "error",
312
+ title: "Install or boot regression detected",
313
+ details: [
314
+ `${bootBreaking.rule}: ${bootBreaking.message}`,
315
+ bootBreaking.suggestion ?? "Run `mandu diagnose` for the copy-pastable fix.",
316
+ ],
317
+ };
318
+ }
319
+
320
+ // Build-broken comes next: missing or stale bundle manifest means
321
+ // hydration / island / SSR diagnosis can't be trusted yet.
322
+ const buildBroken = findBuildBrokenCheck(input.diagnoseReport);
323
+ if (buildBroken) {
324
+ return {
325
+ category: "build-broken",
326
+ severity: "error",
327
+ title: "Build artifact is missing or stale",
328
+ details: [
329
+ buildBroken.message,
330
+ buildBroken.suggestion ?? "Run `mandu build` and re-check.",
331
+ ],
332
+ };
333
+ }
334
+
335
+ // Bundle manifest absent on a hydrated project is the silent variant
336
+ // of the above — diagnose may not have flagged it yet on a fresh
337
+ // clone, but the supervisor should still hint at the missing build.
338
+ const hydratedRoutes = input.manifest.routes.filter((route) => !!route.clientModule).length;
339
+ if (
340
+ input.bundleManifest !== undefined &&
341
+ isBundleManifestEmpty(input.bundleManifest) &&
342
+ hydratedRoutes > 0
343
+ ) {
344
+ return {
345
+ category: "build-broken",
346
+ severity: "warn",
347
+ title: "Bundle manifest empty but hydration is declared",
348
+ details: [
349
+ `${hydratedRoutes} route(s) declare client hydration but no bundles are emitted.`,
350
+ "Run `mandu build` before opening the page — DevTools will not see island bundles otherwise.",
351
+ ],
352
+ };
353
+ }
354
+
355
+ const hydrationError = input.errors.find(isHydrationError);
356
+ if (hydrationError) {
357
+ return {
358
+ category: "hydration",
359
+ severity: "error",
360
+ title: "Hydration issue detected",
361
+ details: [
362
+ hydrationError.message,
363
+ "Start from the island graph and build status before editing UI code.",
364
+ ],
365
+ };
366
+ }
367
+
368
+ const failingHttp = [...input.httpEvents, ...input.requests].find((event) => readStatus(event) >= 500);
369
+ if (failingHttp) {
370
+ return {
371
+ category: "runtime",
372
+ severity: "error",
373
+ title: "Recent request failure detected",
374
+ details: [
375
+ `${readStatus(failingHttp)} ${readPath(failingHttp) || "unknown path"}`,
376
+ "Trace the request correlation and reproduce with a targeted test or smoke request.",
377
+ ],
378
+ };
379
+ }
380
+
381
+ const guardFailure = input.guardEvents.find((event) => event.severity === "error" || event.severity === "warn");
382
+ if (guardFailure) {
383
+ return {
384
+ category: "guard",
385
+ severity: guardFailure.severity === "error" ? "error" : "warn",
386
+ title: "Architecture guard signal detected",
387
+ details: [
388
+ guardFailure.message,
389
+ "Use the guard toolchain before moving files or changing import paths.",
390
+ ],
391
+ };
392
+ }
393
+
394
+ const apiRoutes = input.manifest.routes.filter((route) => route.kind === "api");
395
+ const apiRoutesWithoutContracts = apiRoutes.filter((route) => !route.contractModule);
396
+ if (apiRoutes.length > 0 && apiRoutesWithoutContracts.length > 0) {
397
+ return {
398
+ category: "contract",
399
+ severity: "warn",
400
+ title: "API routes need contract attention",
401
+ details: [
402
+ `${apiRoutesWithoutContracts.length} of ${apiRoutes.length} API routes do not expose a contract module.`,
403
+ "Prefer contract-aware changes so agents can validate request and response shape.",
404
+ ],
405
+ };
406
+ }
407
+
408
+ if (input.agentStats.totalEvents === 0) {
409
+ return {
410
+ category: "agent-tools",
411
+ severity: "info",
412
+ title: "No MCP tool usage observed yet",
413
+ details: [
414
+ "Start the session with an AI brief and brain status check.",
415
+ "Record the selected skill, selected MCP tools, fallback reason, changed files, and validation in the agent report.",
416
+ ],
417
+ };
418
+ }
419
+
420
+ return {
421
+ category: "release",
422
+ severity: "info",
423
+ title: "Session is ready for confidence checks",
424
+ details: [
425
+ "No high-priority runtime, guard, or hydration signal is currently visible.",
426
+ "Run release confidence checks before shipping broader changes.",
427
+ ],
428
+ };
429
+ }
430
+
431
+ function buildKnowledgeCards(
432
+ input: BuildAgentContextPackInput,
433
+ situation: AgentContextPack["situation"],
434
+ ): KnowledgeCard[] {
435
+ const summary = routeSummary(input.manifest);
436
+ const cards: KnowledgeCard[] = [
437
+ {
438
+ id: "mcp-first",
439
+ title: "MCP first, CLI second",
440
+ category: "agent-tools",
441
+ body: "Agents should select the Mandu skill and MCP tool for the task domain before falling back to Bun or shell commands.",
442
+ references: ["docs/guides/07_agent_workflow.md", "AGENTS.md"],
443
+ },
444
+ {
445
+ id: "brain-status",
446
+ title: "Brain status is explicit",
447
+ category: "agent-tools",
448
+ body: "Kitchen cannot infer cloud OAuth state from the browser. Ask the MCP layer for mandu.brain.status when LLM-assisted doctor or heal output matters.",
449
+ references: ["packages/mcp/src/tools/brain.ts"],
450
+ },
451
+ ];
452
+
453
+ if (summary.islands > 0 || situation.category === "hydration") {
454
+ cards.push({
455
+ id: "hydration-map",
456
+ title: "Inspect islands before editing UI",
457
+ category: "hydration",
458
+ body: "Hydration changes should start from route island inventory and current build status, then narrow to the affected client slot.",
459
+ references: ["packages/mcp/src/tools/hydration.ts", "docs/guides/07_agent_workflow.md"],
460
+ });
461
+ }
462
+
463
+ if (input.guardEnabled || situation.category === "guard") {
464
+ cards.push({
465
+ id: "guard-boundaries",
466
+ title: "Guard preserves architecture",
467
+ category: "guard",
468
+ body: "Boundary fixes should explain the violated rule and verify imports with guard tools before typecheck.",
469
+ references: ["packages/mcp/src/tools/guard.ts", "packages/core/src/guard"],
470
+ });
471
+ }
472
+
473
+ if (summary.apis > 0 || situation.category === "contract") {
474
+ cards.push({
475
+ id: "contract-confidence",
476
+ title: "Contracts make API edits agent-safe",
477
+ category: "contract",
478
+ body: "API edits should keep route contracts synchronized and use contract validation before broad tests.",
479
+ references: ["packages/mcp/src/tools/contract.ts", "packages/core/src/kitchen/api/contract-api.ts"],
480
+ });
481
+ }
482
+
483
+ if (situation.category === "build-broken") {
484
+ cards.push({
485
+ id: "build-first",
486
+ title: "Bundle manifest is the source of truth",
487
+ category: "build-broken",
488
+ body: "Hydration / island / DevTools all read .mandu/manifest.json. When it is missing or stale, every downstream signal is unreliable — rebuild first, diagnose second.",
489
+ references: ["packages/core/src/bundler/types.ts", "packages/core/src/diagnose/checks.ts"],
490
+ });
491
+ }
492
+
493
+ if (situation.category === "boot-breaking") {
494
+ cards.push({
495
+ id: "boot-recovery",
496
+ title: "Install regressions need install-time recovery",
497
+ category: "boot-breaking",
498
+ body: "nested_internal_core and package_export_gaps shadow module resolution. Code edits won't help until node_modules is reconciled — let mandu diagnose print the exact rm/install command.",
499
+ references: ["packages/core/src/diagnose/checks.ts", "docs/issues (#260, #261)"],
500
+ });
501
+ }
502
+
503
+ return cards.slice(0, 6);
504
+ }
505
+
506
+ function buildPrompt(
507
+ situation: AgentContextPack["situation"],
508
+ recommendation: AgentToolRecommendation,
509
+ input: BuildAgentContextPackInput,
510
+ ): PromptSuggestion {
511
+ const summary = routeSummary(input.manifest);
512
+ const routeHint = pickRouteHint(input.manifest.routes, situation.category);
513
+
514
+ const lines: string[] = [
515
+ "You are working inside a Mandu agent-native project.",
516
+ `Task domain: ${situation.category}`,
517
+ `Selected skill: ${recommendation.skill}`,
518
+ `MCP tools to try first: ${recommendation.mcpTools.join(", ")}`,
519
+ `Fallback command only if MCP is unavailable: ${recommendation.cliFallback}`,
520
+ `Current signal: ${situation.title}`,
521
+ `Details: ${situation.details.join(" | ")}`,
522
+ `Route hint: ${routeHint}`,
523
+ `Project shape: ${summary.pages} pages, ${summary.apis} APIs, ${summary.islands} islands, ${summary.contracts} contracts.`,
524
+ ];
525
+
526
+ // Plan 18 P0-2 — surface build / diagnose / diff signals into the
527
+ // prompt so the agent does not need a second tool call to learn the
528
+ // environment shape.
529
+ const bundle = summarizeBundleManifest(input.bundleManifest);
530
+ if (bundle) {
531
+ lines.push(
532
+ `Build state: env=${bundle.env}, bundles=${bundle.bundleCount}, islands=${bundle.islandCount}, builtAt=${bundle.buildTime}.`,
533
+ );
534
+ }
535
+ const diag = summarizeDiagnose(input.diagnoseReport);
536
+ if (diag) {
537
+ lines.push(
538
+ diag.healthy
539
+ ? `Diagnose: healthy (${diag.total} checks).`
540
+ : `Diagnose: ${diag.errorCount} error / ${diag.warningCount} warning — failed rules: ${diag.failedRules.join(", ") || "(none listed)"}.`,
541
+ );
542
+ }
543
+ const changed = summarizeChangedFiles(input.changedFiles);
544
+ if (changed && changed.count > 0) {
545
+ lines.push(
546
+ `Changed files (${changed.count}, first ${changed.sample.length}): ${changed.sample.join(", ")}.`,
547
+ );
548
+ }
549
+
550
+ lines.push(
551
+ "Before editing: inspect affected files and state the exact tool/skill choice.",
552
+ "After editing: report changed files, validation commands, and any fallback reason.",
553
+ );
554
+
555
+ return {
556
+ title: `Prompt for ${situation.category} work`,
557
+ copyText: lines.join("\n"),
558
+ variables: [
559
+ { name: "task_domain", value: situation.category },
560
+ { name: "selected_skill", value: recommendation.skill },
561
+ { name: "route_hint", value: routeHint },
562
+ ],
563
+ };
564
+ }
565
+
566
+ function pickRouteHint(routes: RouteSpec[], category: AgentDevToolsCategory): string {
567
+ if (category === "hydration") {
568
+ return routes.find((route) => route.clientModule)?.pattern ?? "No client island route detected.";
569
+ }
570
+ if (category === "contract") {
571
+ return routes.find((route) => route.kind === "api" && !route.contractModule)?.pattern
572
+ ?? routes.find((route) => route.kind === "api")?.pattern
573
+ ?? "No API route detected.";
574
+ }
575
+ return routes[0]?.pattern ?? "No route detected.";
576
+ }
577
+
578
+ function buildNextSafeAction(
579
+ situation: AgentContextPack["situation"],
580
+ recommendation: AgentToolRecommendation,
581
+ ): NextSafeAction {
582
+ switch (situation.category) {
583
+ case "hydration":
584
+ return {
585
+ mode: "observe",
586
+ title: "Inspect island inventory",
587
+ reason: "Hydration fixes should begin by locating the exact island and build artifact.",
588
+ tool: "mandu.island.list",
589
+ command: "bun run build",
590
+ validation: ["mandu.build.status", "targeted browser smoke if UI changed"],
591
+ risk: "low",
592
+ };
593
+ case "guard":
594
+ return {
595
+ mode: "suggest",
596
+ title: "Run guard check before moving code",
597
+ reason: "Architecture fixes need rule-level evidence before imports are rewritten.",
598
+ tool: "mandu.guard.check",
599
+ command: "bun run typecheck",
600
+ validation: ["mandu.guard.explain for any violation", "bun run typecheck"],
601
+ risk: "low",
602
+ };
603
+ case "contract":
604
+ return {
605
+ mode: "assist",
606
+ title: "Validate route contracts",
607
+ reason: "API edits are safer when request and response shape are checked first.",
608
+ tool: "mandu.contract.validate",
609
+ command: "bun test",
610
+ validation: ["mandu.contract.list", "mandu.contract.validate", "targeted API tests"],
611
+ risk: "medium",
612
+ };
613
+ case "runtime":
614
+ return {
615
+ mode: "suggest",
616
+ title: "Trace failing request",
617
+ reason: "Runtime failures need the exact request path and correlated events before patching.",
618
+ tool: "mandu.brain.doctor",
619
+ command: "bun test",
620
+ validation: ["targeted repro", "related unit or integration test"],
621
+ risk: "medium",
622
+ };
623
+ case "release":
624
+ return {
625
+ mode: "assist",
626
+ title: "Run confidence gate",
627
+ reason: "No blocking signal is visible, so the next useful step is validation.",
628
+ tool: recommendation.mcpTools[0],
629
+ command: recommendation.cliFallback,
630
+ validation: ["lint", "typecheck", "tests"],
631
+ risk: "low",
632
+ };
633
+ case "agent-tools":
634
+ return {
635
+ mode: "observe",
636
+ title: "Check brain and AI brief",
637
+ reason: "The session has not shown MCP usage yet, so establish context before editing.",
638
+ tool: "mandu.ai.brief",
639
+ command: "bun run lint",
640
+ validation: ["mandu.brain.status", "mandu.ai.brief"],
641
+ risk: "low",
642
+ };
643
+ case "build-broken":
644
+ return {
645
+ mode: "assist",
646
+ title: "Rebuild before any other change",
647
+ reason: "Bundle manifest is missing or stale — DevTools, hydration, and island inventory all read it.",
648
+ tool: "mandu.build",
649
+ command: "bun run build",
650
+ validation: ["mandu.build.status", "mandu.diagnose"],
651
+ risk: "low",
652
+ };
653
+ case "boot-breaking":
654
+ return {
655
+ mode: "observe",
656
+ title: "Run mandu diagnose for the recovery command",
657
+ reason: "An install regression is shadowing module resolution; let diagnose print the exact rm/install fix.",
658
+ tool: "mandu.diagnose",
659
+ command: "bun install",
660
+ validation: ["mandu.diagnose", "bunx @mandujs/mcp --help"],
661
+ risk: "low",
662
+ };
663
+ }
664
+ }
665
+
666
+ function flattenTopTools(agentStats: AgentStatsInput): Array<{ tool: string; count: number }> {
667
+ const counts = new Map<string, number>();
668
+ for (const agent of Object.values(agentStats.agents)) {
669
+ for (const item of agent.topTools) {
670
+ counts.set(item.tool, (counts.get(item.tool) ?? 0) + item.count);
671
+ }
672
+ }
673
+ return Array.from(counts.entries())
674
+ .map(([tool, count]) => ({ tool, count }))
675
+ .sort((a, b) => b.count - a.count)
676
+ .slice(0, 5);
677
+ }
678
+
679
+ function uniqueRecommendations(primary: AgentDevToolsCategory): AgentToolRecommendation[] {
680
+ const order: AgentDevToolsCategory[] = [
681
+ primary,
682
+ "boot-breaking",
683
+ "build-broken",
684
+ "agent-tools",
685
+ "guard",
686
+ "contract",
687
+ "hydration",
688
+ "runtime",
689
+ "release",
690
+ ];
691
+ const seen = new Set<AgentDevToolsCategory>();
692
+ const result: AgentToolRecommendation[] = [];
693
+ for (const category of order) {
694
+ if (seen.has(category)) continue;
695
+ seen.add(category);
696
+ result.push(TOOL_ROUTER[category]);
697
+ }
698
+ return result.slice(0, 4);
699
+ }
700
+
701
+ function summarizeBundleManifest(manifest: BundleManifest | null | undefined): AgentContextPack["summary"]["bundle"] {
702
+ if (!manifest) return undefined;
703
+ return {
704
+ env: manifest.env,
705
+ buildTime: manifest.buildTime,
706
+ bundleCount: Object.keys(manifest.bundles ?? {}).length,
707
+ islandCount: Object.keys(manifest.islands ?? {}).length,
708
+ };
709
+ }
710
+
711
+ function summarizeDiagnose(report: DiagnoseReport | null | undefined): AgentContextPack["summary"]["diagnose"] {
712
+ if (!report) return undefined;
713
+ const failedRules = report.checks.filter((c) => !c.ok).map((c) => c.rule);
714
+ return {
715
+ healthy: report.healthy,
716
+ errorCount: report.errorCount,
717
+ warningCount: report.warningCount,
718
+ total: report.summary.total,
719
+ failedRules,
720
+ };
721
+ }
722
+
723
+ function summarizeChangedFiles(files: string[] | undefined): AgentContextPack["summary"]["changedFiles"] {
724
+ if (!files) return undefined;
725
+ return {
726
+ count: files.length,
727
+ sample: files.slice(0, 8),
728
+ };
729
+ }
730
+
731
+ export function buildAgentContextPack(input: BuildAgentContextPackInput): AgentContextPack {
732
+ const routes = routeSummary(input.manifest);
733
+ const recentHttpErrors = [...input.httpEvents, ...input.requests]
734
+ .filter((event) => readStatus(event) >= 400).length;
735
+ const situation = pickSituation(input);
736
+ const recommendations = uniqueRecommendations(situation.category);
737
+ const primaryRecommendation = recommendations[0] ?? TOOL_ROUTER["agent-tools"];
738
+ const failures = Object.values(input.agentStats.agents)
739
+ .reduce((sum, agent) => sum + agent.failures, 0);
740
+
741
+ return {
742
+ generatedAt: new Date().toISOString(),
743
+ project: {
744
+ rootDir: input.rootDir,
745
+ framework: "mandu",
746
+ },
747
+ summary: {
748
+ routes,
749
+ guardEnabled: input.guardEnabled,
750
+ storedErrors: input.errors.length,
751
+ recentRequests: input.requests.length + input.httpEvents.length,
752
+ recentHttpErrors,
753
+ recentMcpEvents: input.mcpEvents.length,
754
+ bundle: summarizeBundleManifest(input.bundleManifest),
755
+ diagnose: summarizeDiagnose(input.diagnoseReport),
756
+ changedFiles: summarizeChangedFiles(input.changedFiles),
757
+ },
758
+ agentStatus: {
759
+ totalAgents: input.agentStats.totalAgents,
760
+ observedToolCalls: input.agentStats.totalEvents,
761
+ failures,
762
+ topTools: flattenTopTools(input.agentStats),
763
+ brain: {
764
+ oauth: "unknown",
765
+ statusTool: "mandu.brain.status",
766
+ note: "OAuth state is owned by the MCP brain layer; call mandu.brain.status for current provider/tier.",
767
+ },
768
+ },
769
+ situation,
770
+ toolRecommendations: recommendations,
771
+ knowledgeCards: buildKnowledgeCards(input, situation),
772
+ prompt: buildPrompt(situation, primaryRecommendation, input),
773
+ nextSafeAction: buildNextSafeAction(situation, primaryRecommendation),
774
+ };
775
+ }
776
+
777
+ export function handleAgentContextRequest(input: BuildAgentContextPackInput): Response {
778
+ return Response.json(buildAgentContextPack(input));
779
+ }