@mandujs/core 0.53.2 → 0.54.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 (338) hide show
  1. package/README.md +654 -654
  2. package/package.json +2 -2
  3. package/src/a11y/__tests__/run-audit.test.ts +333 -333
  4. package/src/a11y/fix-hints.ts +76 -76
  5. package/src/a11y/index.ts +18 -18
  6. package/src/a11y/run-audit.ts +394 -394
  7. package/src/a11y/types.ts +125 -125
  8. package/src/auth/__tests__/login.test.ts +1 -1
  9. package/src/auth/__tests__/password.test.ts +122 -122
  10. package/src/auth/__tests__/tokens.test.ts +274 -274
  11. package/src/auth/__tests__/verification.test.ts +274 -274
  12. package/src/auth/index.ts +76 -76
  13. package/src/auth/login.ts +225 -225
  14. package/src/auth/password.ts +120 -120
  15. package/src/auth/reset.ts +243 -243
  16. package/src/auth/tokens.ts +612 -612
  17. package/src/auth/verification.ts +253 -253
  18. package/src/brain/__tests__/redactor.test.ts +94 -94
  19. package/src/brain/adapters/__tests__/_helpers.ts +83 -83
  20. package/src/brain/adapters/__tests__/anthropic-oauth.test.ts +196 -196
  21. package/src/brain/adapters/__tests__/chatgpt-auth.test.ts +193 -193
  22. package/src/brain/adapters/__tests__/openai-oauth.test.ts +209 -209
  23. package/src/brain/adapters/__tests__/resolver.test.ts +143 -143
  24. package/src/brain/adapters/anthropic-oauth.ts +1 -1
  25. package/src/brain/adapters/chatgpt-auth.ts +300 -300
  26. package/src/brain/adapters/index.ts +319 -319
  27. package/src/brain/adapters/oauth-flow.ts +439 -439
  28. package/src/brain/consent.ts +240 -240
  29. package/src/brain/credentials.ts +396 -396
  30. package/src/bundler/__tests__/build-runner.ts +113 -113
  31. package/src/bundler/__tests__/dev-reliability.test.ts +619 -619
  32. package/src/bundler/__tests__/extended-watch.test.ts +711 -711
  33. package/src/bundler/__tests__/fast-refresh.test.ts +10 -10
  34. package/src/bundler/__tests__/hdr.test.ts +353 -353
  35. package/src/bundler/__tests__/hmr-client.test.ts +532 -532
  36. package/src/bundler/__tests__/manifest-schema.test.ts +266 -266
  37. package/src/bundler/__tests__/prod-smoke.test.ts +138 -138
  38. package/src/bundler/__tests__/reverse-import-graph.test.ts +519 -519
  39. package/src/bundler/__tests__/slot-dispatch.test.ts +573 -573
  40. package/src/bundler/__tests__/url-cap-and-slot-regex.test.ts +286 -286
  41. package/src/bundler/__tests__/vendor-cache.test.ts +455 -455
  42. package/src/bundler/budget.ts +404 -404
  43. package/src/bundler/build.test.ts +179 -179
  44. package/src/bundler/build.ts +55 -55
  45. package/src/bundler/dev.ts +42 -42
  46. package/src/bundler/manifest-schema.ts +301 -301
  47. package/src/bundler/plugins/__tests__/block-generated-imports.test.ts +263 -263
  48. package/src/bundler/plugins/__tests__/react-compiler-config.test.ts +83 -83
  49. package/src/bundler/plugins/__tests__/react-compiler-lint.test.ts +110 -110
  50. package/src/bundler/plugins/block-generated-imports.ts +155 -155
  51. package/src/bundler/plugins/index.ts +83 -83
  52. package/src/bundler/plugins/react-compiler-config.ts +108 -108
  53. package/src/bundler/plugins/react-compiler-lint.ts +253 -253
  54. package/src/bundler/plugins/react-compiler.ts +162 -162
  55. package/src/bundler/reverse-import-graph.ts +339 -339
  56. package/src/bundler/safe-build.test.ts +201 -201
  57. package/src/bundler/safe-build.ts +103 -103
  58. package/src/bundler/scenario-matrix.ts +229 -229
  59. package/src/bundler/types.ts +10 -10
  60. package/src/bundler/vendor-cache-types.ts +130 -130
  61. package/src/bundler/vendor-cache.ts +526 -526
  62. package/src/change/snapshot.ts +18 -18
  63. package/src/client/Form.tsx +105 -105
  64. package/src/client/Link.tsx +9 -9
  65. package/src/client/__tests__/use-sse.test.ts +153 -153
  66. package/src/client/globals.ts +1 -1
  67. package/src/client/hooks.ts +362 -362
  68. package/src/client/hydrate.ts +340 -340
  69. package/src/client/prefetch-helper.ts +55 -55
  70. package/src/client/router.ts +11 -11
  71. package/src/client/runtime.ts +47 -47
  72. package/src/client/serialize.ts +404 -404
  73. package/src/client/use-fetch.ts +6 -6
  74. package/src/client/use-head.ts +197 -197
  75. package/src/client/use-sse.ts +378 -378
  76. package/src/client/window-state.ts +101 -101
  77. package/src/components/Image.tsx +162 -162
  78. package/src/config/validate.ts +3 -3
  79. package/src/config/watcher.ts +311 -311
  80. package/src/constants.ts +40 -40
  81. package/src/content/collection.ts +8 -8
  82. package/src/content/content-layer.ts +7 -7
  83. package/src/content/data-store.ts +245 -245
  84. package/src/content/frontmatter.ts +189 -189
  85. package/src/content/loader-context.ts +171 -171
  86. package/src/content/loaders/api.ts +216 -216
  87. package/src/content/loaders/file.ts +172 -172
  88. package/src/content/loaders/glob.ts +253 -253
  89. package/src/content/loaders/index.ts +34 -34
  90. package/src/content/loaders/types.ts +137 -137
  91. package/src/content/meta-store.ts +209 -209
  92. package/src/content/prebuild.test.ts +571 -571
  93. package/src/content/prebuild.ts +636 -636
  94. package/src/content/schema.ts +20 -20
  95. package/src/content/sidebar.ts +630 -630
  96. package/src/content/slug.ts +110 -110
  97. package/src/content/types.ts +282 -282
  98. package/src/content/watcher.ts +135 -135
  99. package/src/contract/client-safe.test.ts +42 -42
  100. package/src/contract/client-safe.ts +114 -114
  101. package/src/contract/define.ts +11 -11
  102. package/src/contract/index.ts +1 -1
  103. package/src/contract/normalize.test.ts +276 -276
  104. package/src/contract/normalize.ts +410 -410
  105. package/src/contract/registry.test.ts +206 -206
  106. package/src/contract/route-helpers.ts +1 -1
  107. package/src/contract/rpc.ts +443 -443
  108. package/src/contract/schema.ts +48 -48
  109. package/src/contract/types.ts +58 -58
  110. package/src/db/__tests__/db.test.ts +482 -482
  111. package/src/db/index.ts +138 -138
  112. package/src/db/migrations/history-table.ts +345 -345
  113. package/src/db/migrations/index.ts +3 -3
  114. package/src/db/migrations/lock.ts +324 -324
  115. package/src/db/migrations/runner.ts +650 -650
  116. package/src/deploy/cache.ts +140 -140
  117. package/src/deploy/compile/vercel.ts +344 -344
  118. package/src/deploy/index.ts +87 -87
  119. package/src/deploy/inference/brain.ts +268 -268
  120. package/src/deploy/inference/context.ts +182 -182
  121. package/src/deploy/inference/filling-extract.ts +245 -245
  122. package/src/deploy/inference/heuristic.ts +182 -182
  123. package/src/deploy/intent.ts +173 -173
  124. package/src/deploy/plan.ts +178 -178
  125. package/src/design/__tests__/agents-link.test.ts +109 -109
  126. package/src/design/__tests__/extract-patch-diff.test.ts +265 -265
  127. package/src/design/__tests__/lint.test.ts +110 -110
  128. package/src/design/__tests__/parser.test.ts +195 -195
  129. package/src/design/__tests__/tailwind-theme.test.ts +229 -229
  130. package/src/design/agents-link.ts +165 -165
  131. package/src/design/diff.ts +138 -138
  132. package/src/design/extract.ts +285 -285
  133. package/src/design/index.ts +102 -102
  134. package/src/design/lint.ts +209 -209
  135. package/src/design/parser.ts +555 -555
  136. package/src/design/patch.ts +241 -241
  137. package/src/design/scaffold.ts +147 -147
  138. package/src/design/tailwind-theme.ts +441 -441
  139. package/src/design/types.ts +210 -210
  140. package/src/desktop/__tests__/webview-fallback.test.ts +254 -254
  141. package/src/desktop/__tests__/window.test.ts +248 -248
  142. package/src/desktop/__tests__/worker.test.ts +266 -266
  143. package/src/desktop/index.ts +43 -43
  144. package/src/desktop/types.ts +158 -158
  145. package/src/desktop/worker.ts +180 -180
  146. package/src/dev-error-overlay/__tests__/overlay-injector.test.ts +241 -241
  147. package/src/dev-error-overlay/index.ts +30 -30
  148. package/src/dev-error-overlay/overlay-injector.ts +243 -243
  149. package/src/dev-error-overlay/overlay-styles.ts +52 -52
  150. package/src/dev-error-overlay/types.ts +66 -66
  151. package/src/devtools/ai/context-builder.ts +375 -375
  152. package/src/devtools/ai/index.ts +25 -25
  153. package/src/devtools/ai/mcp-connector.ts +25 -25
  154. package/src/devtools/client/catchers/error-catcher.ts +344 -344
  155. package/src/devtools/client/catchers/index.ts +18 -18
  156. package/src/devtools/client/components/index.ts +39 -39
  157. package/src/devtools/client/components/mandu-character.tsx +331 -331
  158. package/src/devtools/client/components/overlay.tsx +368 -368
  159. package/src/devtools/client/components/panel/errors-panel.tsx +259 -259
  160. package/src/devtools/client/components/panel/guard-panel.tsx +30 -30
  161. package/src/devtools/client/components/panel/islands-panel.tsx +320 -320
  162. package/src/devtools/client/components/panel/network-panel.tsx +291 -291
  163. package/src/devtools/client/components/panel/panel-container.tsx +500 -500
  164. package/src/devtools/client/components/panel/preview-panel.tsx +46 -46
  165. package/src/devtools/client/filters/context-filters.ts +282 -282
  166. package/src/devtools/client/filters/index.ts +16 -16
  167. package/src/devtools/client/index.ts +63 -63
  168. package/src/devtools/client/persistence.ts +335 -335
  169. package/src/devtools/hook/create-hook.ts +207 -207
  170. package/src/devtools/hook/index.ts +13 -13
  171. package/src/devtools/index.ts +439 -439
  172. package/src/devtools/init.ts +265 -265
  173. package/src/devtools/protocol.ts +237 -237
  174. package/src/devtools/server/index.ts +17 -17
  175. package/src/devtools/server/source-context.ts +450 -450
  176. package/src/devtools/types.ts +35 -35
  177. package/src/devtools/worker/index.ts +25 -25
  178. package/src/devtools/worker/redaction-worker.ts +233 -233
  179. package/src/devtools/worker/worker-manager.ts +410 -410
  180. package/src/diagnose/__tests__/checks.test.ts +451 -380
  181. package/src/diagnose/checks.ts +832 -720
  182. package/src/diagnose/index.ts +17 -16
  183. package/src/diagnose/run.ts +93 -91
  184. package/src/diagnose/types.ts +53 -53
  185. package/src/email/__tests__/email.test.ts +355 -355
  186. package/src/email/index.ts +282 -282
  187. package/src/email/smtp.ts +64 -64
  188. package/src/error/domains.ts +265 -265
  189. package/src/error/result.ts +60 -60
  190. package/src/error/types.ts +6 -6
  191. package/src/errors/extractor.ts +409 -409
  192. package/src/errors/index.ts +19 -19
  193. package/src/filling/__tests__/session-sqlite.test.ts +454 -454
  194. package/src/filling/auth.ts +308 -308
  195. package/src/filling/cookie-codec.ts +299 -299
  196. package/src/filling/deps.ts +265 -265
  197. package/src/filling/session-sqlite.ts +617 -617
  198. package/src/filling/sse.ts +5 -5
  199. package/src/filling/ws.ts +78 -78
  200. package/src/generator/index.ts +3 -3
  201. package/src/guard/__tests__/design-inline-class.test.ts +219 -219
  202. package/src/guard/__tests__/tsgolint-bridge.test.ts +347 -347
  203. package/src/guard/analyzer.ts +360 -360
  204. package/src/guard/auto-correct.ts +1 -1
  205. package/src/guard/contract-guard.ts +9 -9
  206. package/src/guard/define-rule.ts +243 -243
  207. package/src/guard/design-inline-class.ts +393 -393
  208. package/src/guard/file-type.test.ts +24 -24
  209. package/src/guard/graph.ts +1 -1
  210. package/src/guard/healing.ts +36 -36
  211. package/src/guard/presets/atomic.ts +70 -70
  212. package/src/guard/presets/clean.ts +77 -77
  213. package/src/guard/presets/fsd.ts +79 -79
  214. package/src/guard/presets/hexagonal.ts +68 -68
  215. package/src/guard/reporter.ts +442 -442
  216. package/src/guard/rule-presets.ts +379 -379
  217. package/src/guard/semantic-slots.ts +1 -1
  218. package/src/guard/suggestions.ts +358 -358
  219. package/src/guard/tsgolint-bridge.ts +512 -512
  220. package/src/guard/types.ts +348 -348
  221. package/src/guard/watcher.ts +405 -405
  222. package/src/i18n/define.ts +126 -126
  223. package/src/i18n/index.ts +52 -52
  224. package/src/i18n/message-registry.ts +173 -173
  225. package/src/i18n/types.ts +112 -112
  226. package/src/id/index.ts +105 -105
  227. package/src/index.ts +2 -2
  228. package/src/kitchen/api/agent-devtools-api.ts +779 -544
  229. package/src/kitchen/api/errors-grouping.ts +126 -0
  230. package/src/kitchen/kitchen-handler.ts +192 -63
  231. package/src/kitchen/kitchen-ui.ts +842 -464
  232. package/src/logging/index.ts +22 -22
  233. package/src/logging/transports.ts +365 -365
  234. package/src/middleware/bridge.ts +147 -147
  235. package/src/middleware/compose.ts +134 -134
  236. package/src/middleware/compress.ts +62 -62
  237. package/src/middleware/cors.ts +47 -47
  238. package/src/middleware/csrf.ts +328 -328
  239. package/src/middleware/define.ts +132 -132
  240. package/src/middleware/jwt.ts +134 -134
  241. package/src/middleware/logger.ts +58 -58
  242. package/src/middleware/oauth/__tests__/oauth.test.ts +1 -1
  243. package/src/middleware/oauth/index.ts +505 -505
  244. package/src/middleware/oauth/providers.ts +115 -115
  245. package/src/middleware/rate-limit/index.ts +522 -522
  246. package/src/middleware/rate-limit/sqlite-store.ts +382 -382
  247. package/src/middleware/scheduler-cron.ts +96 -96
  248. package/src/middleware/secure/__tests__/secure.test.ts +360 -360
  249. package/src/middleware/secure/csp.ts +193 -193
  250. package/src/middleware/session.ts +174 -174
  251. package/src/middleware/timeout.ts +55 -55
  252. package/src/observability/logger-adapter.ts +36 -36
  253. package/src/observability/sqlite-store.ts +254 -254
  254. package/src/openapi/generator.ts +1 -1
  255. package/src/openapi/openapi.test.ts +43 -43
  256. package/src/perf/__tests__/user-marks.test.ts +354 -354
  257. package/src/perf/index.ts +133 -133
  258. package/src/plugins/__tests__/lifecycle-integration.test.ts +272 -272
  259. package/src/plugins/__tests__/runner.test.ts +409 -409
  260. package/src/plugins/define.ts +124 -124
  261. package/src/plugins/examples/dep-check-plugin.ts +80 -80
  262. package/src/plugins/examples/prerender-cache-plugin.ts +111 -111
  263. package/src/plugins/examples/sitemap-plugin.ts +65 -65
  264. package/src/plugins/runner.ts +361 -361
  265. package/src/plugins/types.ts +368 -368
  266. package/src/report/index.ts +1 -1
  267. package/src/resource/__tests__/generator.test.ts +32 -32
  268. package/src/resource/ddl/__tests__/diff.test.ts +639 -639
  269. package/src/resource/ddl/__tests__/emit.test.ts +823 -823
  270. package/src/resource/ddl/__tests__/snapshot.test.ts +499 -499
  271. package/src/resource/ddl/emit.ts +559 -559
  272. package/src/resource/ddl/persistence-types.ts +218 -218
  273. package/src/resource/ddl/type-map.ts +223 -223
  274. package/src/resource/ddl/types.ts +232 -232
  275. package/src/resource/generator-repo.ts +630 -630
  276. package/src/resource/schema.ts +1 -1
  277. package/src/router/fs-patterns.test.ts +96 -96
  278. package/src/router/fs-routes.ts +6 -6
  279. package/src/routes/index.ts +74 -74
  280. package/src/routes/metadata-routes.ts +427 -427
  281. package/src/routes/types.ts +341 -341
  282. package/src/runtime/__tests__/error-boundary-redaction.test.ts +141 -141
  283. package/src/runtime/__tests__/hdr-client.test.ts +223 -223
  284. package/src/runtime/__tests__/http-errors.test.ts +117 -117
  285. package/src/runtime/__tests__/not-found.test.ts +152 -152
  286. package/src/runtime/adapter.ts +47 -47
  287. package/src/runtime/boundary.tsx +252 -252
  288. package/src/runtime/cache.ts +494 -494
  289. package/src/runtime/compose.ts +222 -222
  290. package/src/runtime/fast-refresh-runtime.ts +322 -322
  291. package/src/runtime/handler.ts +65 -65
  292. package/src/runtime/handlers.ts +300 -300
  293. package/src/runtime/http-errors.ts +113 -113
  294. package/src/runtime/image-handler.ts +1 -1
  295. package/src/runtime/lifecycle.ts +381 -381
  296. package/src/runtime/logger.test.ts +345 -345
  297. package/src/runtime/middleware.ts +264 -264
  298. package/src/runtime/not-found.ts +93 -93
  299. package/src/runtime/openapi-endpoint.ts +236 -236
  300. package/src/runtime/ppr.ts +74 -74
  301. package/src/runtime/registry.ts +171 -171
  302. package/src/runtime/router.ts +105 -105
  303. package/src/runtime/server.ts +67 -67
  304. package/src/runtime/shims.ts +48 -48
  305. package/src/runtime/ssr.ts +24 -31
  306. package/src/runtime/streaming-ssr.ts +32 -37
  307. package/src/runtime/trace.ts +144 -144
  308. package/src/scheduler/validate.ts +169 -169
  309. package/src/seo/index.ts +219 -219
  310. package/src/seo/integration/ssr.ts +306 -306
  311. package/src/seo/render/basic.ts +435 -435
  312. package/src/seo/render/index.ts +143 -143
  313. package/src/seo/render/jsonld.ts +539 -539
  314. package/src/seo/render/opengraph.ts +197 -197
  315. package/src/seo/render/robots.ts +116 -116
  316. package/src/seo/render/sitemap.ts +137 -137
  317. package/src/seo/render/twitter.ts +127 -127
  318. package/src/seo/resolve/opengraph.ts +143 -143
  319. package/src/seo/resolve/robots.ts +73 -73
  320. package/src/seo/resolve/title.ts +94 -94
  321. package/src/seo/resolve/twitter.ts +73 -73
  322. package/src/seo/resolve/url.ts +104 -104
  323. package/src/seo/routes/index.ts +290 -290
  324. package/src/seo/types.ts +588 -588
  325. package/src/slot/validator.ts +39 -39
  326. package/src/storage/s3/__tests__/s3.test.ts +479 -479
  327. package/src/storage/s3/index.ts +412 -412
  328. package/src/testing/__tests__/assertions.test.ts +632 -632
  329. package/src/testing/__tests__/reporter.test.ts +454 -454
  330. package/src/testing/assertions.ts +986 -986
  331. package/src/testing/db.ts +157 -157
  332. package/src/testing/mocks.ts +203 -203
  333. package/src/testing/session.ts +190 -190
  334. package/src/types/branded.ts +56 -56
  335. package/src/types/index.ts +1 -1
  336. package/src/utils/safe-io.ts +188 -188
  337. package/src/utils/string-safe.ts +298 -298
  338. package/src/watcher/watcher.ts +18 -18
@@ -1,544 +1,779 @@
1
- import type { ObservabilityEvent } from "../../observability/event-bus";
2
- import type { RoutesManifest, RouteSpec } from "../../spec/schema";
3
-
4
- export type AgentDevToolsCategory =
5
- | "hydration"
6
- | "guard"
7
- | "contract"
8
- | "runtime"
9
- | "release"
10
- | "agent-tools";
11
-
12
- export type AgentDevToolsMode = "observe" | "suggest" | "assist" | "approval_required";
13
-
14
- export interface AgentDevToolsError {
15
- id?: string;
16
- type?: string;
17
- severity?: string;
18
- message: string;
19
- stack?: string;
20
- url?: string;
21
- source?: string;
22
- line?: number;
23
- column?: number;
24
- timestamp?: number;
25
- }
26
-
27
- export interface AgentStatsInput {
28
- totalAgents: number;
29
- totalEvents: number;
30
- agents: Record<string, {
31
- toolCalls: number;
32
- failures: number;
33
- topTools: Array<{ tool: string; count: number }>;
34
- avgDuration: number;
35
- firstSeen: number;
36
- lastSeen: number;
37
- }>;
38
- }
39
-
40
- export interface AgentDevToolsRequestLike {
41
- method?: string;
42
- path?: string;
43
- status?: number;
44
- duration?: number;
45
- timestamp?: number;
46
- cacheStatus?: string;
47
- }
48
-
49
- export interface BuildAgentContextPackInput {
50
- rootDir: string;
51
- manifest: RoutesManifest;
52
- guardEnabled: boolean;
53
- errors: AgentDevToolsError[];
54
- requests: AgentDevToolsRequestLike[];
55
- httpEvents: ObservabilityEvent[];
56
- mcpEvents: ObservabilityEvent[];
57
- guardEvents: ObservabilityEvent[];
58
- agentStats: AgentStatsInput;
59
- }
60
-
61
- export interface AgentToolRecommendation {
62
- task: string;
63
- skill: string;
64
- mcpTools: string[];
65
- cliFallback: string;
66
- useWhen: string;
67
- }
68
-
69
- export interface KnowledgeCard {
70
- id: string;
71
- title: string;
72
- category: AgentDevToolsCategory;
73
- body: string;
74
- references: string[];
75
- }
76
-
77
- export interface PromptSuggestion {
78
- title: string;
79
- copyText: string;
80
- variables: Array<{ name: string; value: string }>;
81
- }
82
-
83
- export interface NextSafeAction {
84
- mode: AgentDevToolsMode;
85
- title: string;
86
- reason: string;
87
- tool?: string;
88
- command?: string;
89
- validation: string[];
90
- risk: "low" | "medium" | "high";
91
- }
92
-
93
- export interface AgentContextPack {
94
- generatedAt: string;
95
- project: {
96
- rootDir: string;
97
- framework: "mandu";
98
- };
99
- summary: {
100
- routes: {
101
- total: number;
102
- pages: number;
103
- apis: number;
104
- metadata: number;
105
- islands: number;
106
- contracts: number;
107
- };
108
- guardEnabled: boolean;
109
- storedErrors: number;
110
- recentRequests: number;
111
- recentHttpErrors: number;
112
- recentMcpEvents: number;
113
- };
114
- agentStatus: {
115
- totalAgents: number;
116
- observedToolCalls: number;
117
- failures: number;
118
- topTools: Array<{ tool: string; count: number }>;
119
- brain: {
120
- oauth: "unknown";
121
- statusTool: "mandu.brain.status";
122
- note: string;
123
- };
124
- };
125
- situation: {
126
- category: AgentDevToolsCategory;
127
- severity: "info" | "warn" | "error";
128
- title: string;
129
- details: string[];
130
- };
131
- toolRecommendations: AgentToolRecommendation[];
132
- knowledgeCards: KnowledgeCard[];
133
- prompt: PromptSuggestion;
134
- nextSafeAction: NextSafeAction;
135
- }
136
-
137
- const TOOL_ROUTER: Record<AgentDevToolsCategory, AgentToolRecommendation> = {
138
- hydration: {
139
- task: "Hydration or client island work",
140
- skill: "mandu-hydration",
141
- mcpTools: ["mandu.island.list", "mandu.build.status", "mandu.hydration.set"],
142
- cliFallback: "bun run build",
143
- useWhen: "Hydration mismatch, island bundle, client slot, or browser runtime symptoms are present.",
144
- },
145
- guard: {
146
- task: "Architecture boundary work",
147
- skill: "mandu-guard-guide",
148
- mcpTools: ["mandu.guard.check", "mandu.guard.explain", "mandu.brain.checkImport"],
149
- cliFallback: "bun run typecheck",
150
- useWhen: "Imports, layer boundaries, file placement, or guard violations are relevant.",
151
- },
152
- contract: {
153
- task: "API contract and route schema work",
154
- skill: "mandu-create-api",
155
- mcpTools: ["mandu.contract.list", "mandu.contract.validate", "mandu.contract.create"],
156
- cliFallback: "bun test",
157
- useWhen: "API routes, request/response schema, generated handlers, or OpenAPI output are involved.",
158
- },
159
- runtime: {
160
- task: "Runtime diagnosis",
161
- skill: "mandu-debug",
162
- mcpTools: ["mandu.brain.doctor", "mandu.ai.brief", "mandu.test.smart"],
163
- cliFallback: "bun test",
164
- useWhen: "HTTP 4xx/5xx, request correlation, runtime exceptions, or failing tests are visible.",
165
- },
166
- release: {
167
- task: "Release confidence",
168
- skill: "mandu-release",
169
- mcpTools: ["mandu.build.status", "mandu.contract.validate", "mandu.test.precommit"],
170
- cliFallback: "bun run lint && bun run typecheck && bun test",
171
- useWhen: "The session is clean enough to validate and package changes.",
172
- },
173
- "agent-tools": {
174
- task: "Agent tool selection",
175
- skill: "mandu-agent-workflow",
176
- mcpTools: ["mandu.ai.brief", "mandu.brain.status", "mandu.watch.status"],
177
- cliFallback: "bun run lint",
178
- useWhen: "The next step is unclear, an agent skipped Mandu tools, or a supervised coding session is starting.",
179
- },
180
- };
181
-
182
- function routeSummary(manifest: RoutesManifest): AgentContextPack["summary"]["routes"] {
183
- const routes = manifest.routes;
184
- return {
185
- total: routes.length,
186
- pages: routes.filter((route) => route.kind === "page").length,
187
- apis: routes.filter((route) => route.kind === "api").length,
188
- metadata: routes.filter((route) => route.kind === "metadata").length,
189
- islands: routes.filter((route) => !!route.clientModule).length,
190
- contracts: routes.filter((route) => !!route.contractModule).length,
191
- };
192
- }
193
-
194
- function readStatus(event: ObservabilityEvent | AgentDevToolsRequestLike): number {
195
- const fromData = "data" in event && typeof event.data?.status === "number"
196
- ? event.data.status
197
- : undefined;
198
- return fromData ?? ("status" in event && typeof event.status === "number" ? event.status : 0);
199
- }
200
-
201
- function readPath(event: ObservabilityEvent | AgentDevToolsRequestLike): string {
202
- if ("data" in event) {
203
- const path = event.data?.path ?? event.data?.url;
204
- if (typeof path === "string") return path;
205
- }
206
- return "path" in event && typeof event.path === "string" ? event.path : "";
207
- }
208
-
209
- function textContains(value: string | undefined, patterns: RegExp[]): boolean {
210
- if (!value) return false;
211
- return patterns.some((pattern) => pattern.test(value));
212
- }
213
-
214
- function isHydrationError(error: AgentDevToolsError): boolean {
215
- const patterns = [/hydration/i, /hydrate/i, /island/i, /client slot/i, /data-mandu/i];
216
- return textContains(error.message, patterns)
217
- || textContains(error.stack, patterns)
218
- || textContains(error.source, patterns)
219
- || textContains(error.type, patterns);
220
- }
221
-
222
- function pickSituation(input: BuildAgentContextPackInput): AgentContextPack["situation"] {
223
- const hydrationError = input.errors.find(isHydrationError);
224
- if (hydrationError) {
225
- return {
226
- category: "hydration",
227
- severity: "error",
228
- title: "Hydration issue detected",
229
- details: [
230
- hydrationError.message,
231
- "Start from the island graph and build status before editing UI code.",
232
- ],
233
- };
234
- }
235
-
236
- const failingHttp = [...input.httpEvents, ...input.requests].find((event) => readStatus(event) >= 500);
237
- if (failingHttp) {
238
- return {
239
- category: "runtime",
240
- severity: "error",
241
- title: "Recent request failure detected",
242
- details: [
243
- `${readStatus(failingHttp)} ${readPath(failingHttp) || "unknown path"}`,
244
- "Trace the request correlation and reproduce with a targeted test or smoke request.",
245
- ],
246
- };
247
- }
248
-
249
- const guardFailure = input.guardEvents.find((event) => event.severity === "error" || event.severity === "warn");
250
- if (guardFailure) {
251
- return {
252
- category: "guard",
253
- severity: guardFailure.severity === "error" ? "error" : "warn",
254
- title: "Architecture guard signal detected",
255
- details: [
256
- guardFailure.message,
257
- "Use the guard toolchain before moving files or changing import paths.",
258
- ],
259
- };
260
- }
261
-
262
- const apiRoutes = input.manifest.routes.filter((route) => route.kind === "api");
263
- const apiRoutesWithoutContracts = apiRoutes.filter((route) => !route.contractModule);
264
- if (apiRoutes.length > 0 && apiRoutesWithoutContracts.length > 0) {
265
- return {
266
- category: "contract",
267
- severity: "warn",
268
- title: "API routes need contract attention",
269
- details: [
270
- `${apiRoutesWithoutContracts.length} of ${apiRoutes.length} API routes do not expose a contract module.`,
271
- "Prefer contract-aware changes so agents can validate request and response shape.",
272
- ],
273
- };
274
- }
275
-
276
- if (input.agentStats.totalEvents === 0) {
277
- return {
278
- category: "agent-tools",
279
- severity: "info",
280
- title: "No MCP tool usage observed yet",
281
- details: [
282
- "Start the session with an AI brief and brain status check.",
283
- "Record the selected skill, selected MCP tools, fallback reason, changed files, and validation in the agent report.",
284
- ],
285
- };
286
- }
287
-
288
- return {
289
- category: "release",
290
- severity: "info",
291
- title: "Session is ready for confidence checks",
292
- details: [
293
- "No high-priority runtime, guard, or hydration signal is currently visible.",
294
- "Run release confidence checks before shipping broader changes.",
295
- ],
296
- };
297
- }
298
-
299
- function buildKnowledgeCards(
300
- input: BuildAgentContextPackInput,
301
- situation: AgentContextPack["situation"],
302
- ): KnowledgeCard[] {
303
- const summary = routeSummary(input.manifest);
304
- const cards: KnowledgeCard[] = [
305
- {
306
- id: "mcp-first",
307
- title: "MCP first, CLI second",
308
- category: "agent-tools",
309
- body: "Agents should select the Mandu skill and MCP tool for the task domain before falling back to Bun or shell commands.",
310
- references: ["docs/guides/07_agent_workflow.md", "AGENTS.md"],
311
- },
312
- {
313
- id: "brain-status",
314
- title: "Brain status is explicit",
315
- category: "agent-tools",
316
- 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.",
317
- references: ["packages/mcp/src/tools/brain.ts"],
318
- },
319
- ];
320
-
321
- if (summary.islands > 0 || situation.category === "hydration") {
322
- cards.push({
323
- id: "hydration-map",
324
- title: "Inspect islands before editing UI",
325
- category: "hydration",
326
- body: "Hydration changes should start from route island inventory and current build status, then narrow to the affected client slot.",
327
- references: ["packages/mcp/src/tools/hydration.ts", "docs/guides/07_agent_workflow.md"],
328
- });
329
- }
330
-
331
- if (input.guardEnabled || situation.category === "guard") {
332
- cards.push({
333
- id: "guard-boundaries",
334
- title: "Guard preserves architecture",
335
- category: "guard",
336
- body: "Boundary fixes should explain the violated rule and verify imports with guard tools before typecheck.",
337
- references: ["packages/mcp/src/tools/guard.ts", "packages/core/src/guard"],
338
- });
339
- }
340
-
341
- if (summary.apis > 0 || situation.category === "contract") {
342
- cards.push({
343
- id: "contract-confidence",
344
- title: "Contracts make API edits agent-safe",
345
- category: "contract",
346
- body: "API edits should keep route contracts synchronized and use contract validation before broad tests.",
347
- references: ["packages/mcp/src/tools/contract.ts", "packages/core/src/kitchen/api/contract-api.ts"],
348
- });
349
- }
350
-
351
- return cards.slice(0, 6);
352
- }
353
-
354
- function buildPrompt(
355
- situation: AgentContextPack["situation"],
356
- recommendation: AgentToolRecommendation,
357
- input: BuildAgentContextPackInput,
358
- ): PromptSuggestion {
359
- const summary = routeSummary(input.manifest);
360
- const routeHint = pickRouteHint(input.manifest.routes, situation.category);
361
- const copyText = [
362
- "You are working inside a Mandu agent-native project.",
363
- `Task domain: ${situation.category}`,
364
- `Selected skill: ${recommendation.skill}`,
365
- `MCP tools to try first: ${recommendation.mcpTools.join(", ")}`,
366
- `Fallback command only if MCP is unavailable: ${recommendation.cliFallback}`,
367
- `Current signal: ${situation.title}`,
368
- `Details: ${situation.details.join(" | ")}`,
369
- `Route hint: ${routeHint}`,
370
- `Project shape: ${summary.pages} pages, ${summary.apis} APIs, ${summary.islands} islands, ${summary.contracts} contracts.`,
371
- "Before editing: inspect affected files and state the exact tool/skill choice.",
372
- "After editing: report changed files, validation commands, and any fallback reason.",
373
- ].join("\n");
374
-
375
- return {
376
- title: `Prompt for ${situation.category} work`,
377
- copyText,
378
- variables: [
379
- { name: "task_domain", value: situation.category },
380
- { name: "selected_skill", value: recommendation.skill },
381
- { name: "route_hint", value: routeHint },
382
- ],
383
- };
384
- }
385
-
386
- function pickRouteHint(routes: RouteSpec[], category: AgentDevToolsCategory): string {
387
- if (category === "hydration") {
388
- return routes.find((route) => route.clientModule)?.pattern ?? "No client island route detected.";
389
- }
390
- if (category === "contract") {
391
- return routes.find((route) => route.kind === "api" && !route.contractModule)?.pattern
392
- ?? routes.find((route) => route.kind === "api")?.pattern
393
- ?? "No API route detected.";
394
- }
395
- return routes[0]?.pattern ?? "No route detected.";
396
- }
397
-
398
- function buildNextSafeAction(
399
- situation: AgentContextPack["situation"],
400
- recommendation: AgentToolRecommendation,
401
- ): NextSafeAction {
402
- switch (situation.category) {
403
- case "hydration":
404
- return {
405
- mode: "observe",
406
- title: "Inspect island inventory",
407
- reason: "Hydration fixes should begin by locating the exact island and build artifact.",
408
- tool: "mandu.island.list",
409
- command: "bun run build",
410
- validation: ["mandu.build.status", "targeted browser smoke if UI changed"],
411
- risk: "low",
412
- };
413
- case "guard":
414
- return {
415
- mode: "suggest",
416
- title: "Run guard check before moving code",
417
- reason: "Architecture fixes need rule-level evidence before imports are rewritten.",
418
- tool: "mandu.guard.check",
419
- command: "bun run typecheck",
420
- validation: ["mandu.guard.explain for any violation", "bun run typecheck"],
421
- risk: "low",
422
- };
423
- case "contract":
424
- return {
425
- mode: "assist",
426
- title: "Validate route contracts",
427
- reason: "API edits are safer when request and response shape are checked first.",
428
- tool: "mandu.contract.validate",
429
- command: "bun test",
430
- validation: ["mandu.contract.list", "mandu.contract.validate", "targeted API tests"],
431
- risk: "medium",
432
- };
433
- case "runtime":
434
- return {
435
- mode: "suggest",
436
- title: "Trace failing request",
437
- reason: "Runtime failures need the exact request path and correlated events before patching.",
438
- tool: "mandu.brain.doctor",
439
- command: "bun test",
440
- validation: ["targeted repro", "related unit or integration test"],
441
- risk: "medium",
442
- };
443
- case "release":
444
- return {
445
- mode: "assist",
446
- title: "Run confidence gate",
447
- reason: "No blocking signal is visible, so the next useful step is validation.",
448
- tool: recommendation.mcpTools[0],
449
- command: recommendation.cliFallback,
450
- validation: ["lint", "typecheck", "tests"],
451
- risk: "low",
452
- };
453
- case "agent-tools":
454
- return {
455
- mode: "observe",
456
- title: "Check brain and AI brief",
457
- reason: "The session has not shown MCP usage yet, so establish context before editing.",
458
- tool: "mandu.ai.brief",
459
- command: "bun run lint",
460
- validation: ["mandu.brain.status", "mandu.ai.brief"],
461
- risk: "low",
462
- };
463
- }
464
- }
465
-
466
- function flattenTopTools(agentStats: AgentStatsInput): Array<{ tool: string; count: number }> {
467
- const counts = new Map<string, number>();
468
- for (const agent of Object.values(agentStats.agents)) {
469
- for (const item of agent.topTools) {
470
- counts.set(item.tool, (counts.get(item.tool) ?? 0) + item.count);
471
- }
472
- }
473
- return Array.from(counts.entries())
474
- .map(([tool, count]) => ({ tool, count }))
475
- .sort((a, b) => b.count - a.count)
476
- .slice(0, 5);
477
- }
478
-
479
- function uniqueRecommendations(primary: AgentDevToolsCategory): AgentToolRecommendation[] {
480
- const order: AgentDevToolsCategory[] = [
481
- primary,
482
- "agent-tools",
483
- "guard",
484
- "contract",
485
- "hydration",
486
- "runtime",
487
- "release",
488
- ];
489
- const seen = new Set<AgentDevToolsCategory>();
490
- const result: AgentToolRecommendation[] = [];
491
- for (const category of order) {
492
- if (seen.has(category)) continue;
493
- seen.add(category);
494
- result.push(TOOL_ROUTER[category]);
495
- }
496
- return result.slice(0, 4);
497
- }
498
-
499
- export function buildAgentContextPack(input: BuildAgentContextPackInput): AgentContextPack {
500
- const routes = routeSummary(input.manifest);
501
- const recentHttpErrors = [...input.httpEvents, ...input.requests]
502
- .filter((event) => readStatus(event) >= 400).length;
503
- const situation = pickSituation(input);
504
- const recommendations = uniqueRecommendations(situation.category);
505
- const primaryRecommendation = recommendations[0] ?? TOOL_ROUTER["agent-tools"];
506
- const failures = Object.values(input.agentStats.agents)
507
- .reduce((sum, agent) => sum + agent.failures, 0);
508
-
509
- return {
510
- generatedAt: new Date().toISOString(),
511
- project: {
512
- rootDir: input.rootDir,
513
- framework: "mandu",
514
- },
515
- summary: {
516
- routes,
517
- guardEnabled: input.guardEnabled,
518
- storedErrors: input.errors.length,
519
- recentRequests: input.requests.length + input.httpEvents.length,
520
- recentHttpErrors,
521
- recentMcpEvents: input.mcpEvents.length,
522
- },
523
- agentStatus: {
524
- totalAgents: input.agentStats.totalAgents,
525
- observedToolCalls: input.agentStats.totalEvents,
526
- failures,
527
- topTools: flattenTopTools(input.agentStats),
528
- brain: {
529
- oauth: "unknown",
530
- statusTool: "mandu.brain.status",
531
- note: "OAuth state is owned by the MCP brain layer; call mandu.brain.status for current provider/tier.",
532
- },
533
- },
534
- situation,
535
- toolRecommendations: recommendations,
536
- knowledgeCards: buildKnowledgeCards(input, situation),
537
- prompt: buildPrompt(situation, primaryRecommendation, input),
538
- nextSafeAction: buildNextSafeAction(situation, primaryRecommendation),
539
- };
540
- }
541
-
542
- export function handleAgentContextRequest(input: BuildAgentContextPackInput): Response {
543
- return Response.json(buildAgentContextPack(input));
544
- }
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
+ }