@mandujs/core 0.53.0 → 0.53.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/package.json +38 -2
  2. package/src/a11y/run-audit.ts +6 -6
  3. package/src/brain/adapters/oauth-flow.ts +1 -1
  4. package/src/brain/architecture/analyzer.ts +0 -2
  5. package/src/brain/credentials.ts +2 -2
  6. package/src/bundler/__tests__/build-runner.ts +13 -1
  7. package/src/bundler/__tests__/extended-watch.test.ts +3 -2
  8. package/src/bundler/__tests__/fast-refresh.test.ts +10 -12
  9. package/src/bundler/build.test.ts +30 -33
  10. package/src/bundler/build.ts +56 -27
  11. package/src/bundler/dev.ts +44 -39
  12. package/src/bundler/prerender.ts +63 -0
  13. package/src/bundler/safe-build.test.ts +2 -1
  14. package/src/bundler/types.ts +13 -6
  15. package/src/change/history.ts +1 -1
  16. package/src/change/snapshot.ts +18 -9
  17. package/src/client/Link.tsx +9 -9
  18. package/src/client/globals.ts +3 -2
  19. package/src/client/hooks.ts +0 -4
  20. package/src/client/hydrate.ts +1 -1
  21. package/src/client/router.ts +12 -12
  22. package/src/client/rpc.ts +1 -1
  23. package/src/client/use-fetch.ts +6 -6
  24. package/src/client/use-sse.ts +5 -5
  25. package/src/config/mcp-status.ts +0 -1
  26. package/src/config/validate.ts +4 -4
  27. package/src/config/watcher.ts +1 -1
  28. package/src/content/collection.ts +8 -12
  29. package/src/content/content-layer.ts +5 -5
  30. package/src/content/data-store.ts +2 -2
  31. package/src/content/loader-context.ts +0 -1
  32. package/src/content/loaders/file.ts +1 -1
  33. package/src/content/loaders/glob.ts +4 -4
  34. package/src/content/loaders/types.ts +1 -1
  35. package/src/content/meta-store.ts +1 -1
  36. package/src/content/types.ts +1 -1
  37. package/src/contract/define.ts +11 -12
  38. package/src/contract/index.ts +3 -3
  39. package/src/contract/protection.ts +2 -2
  40. package/src/contract/types.ts +1 -1
  41. package/src/contract/validator.ts +0 -1
  42. package/src/db/__tests__/db.test.ts +4 -7
  43. package/src/db/index.ts +138 -51
  44. package/src/db/migrations/index.ts +3 -0
  45. package/src/db/migrations/lock.ts +78 -23
  46. package/src/db/migrations/runner.ts +118 -101
  47. package/src/deploy/cache.ts +1 -0
  48. package/src/design/extract.ts +2 -1
  49. package/src/design/patch.ts +0 -1
  50. package/src/devtools/ai/mcp-connector.ts +24 -24
  51. package/src/devtools/client/components/kitchen-root.tsx +1 -1
  52. package/src/devtools/client/components/panel/errors-panel.tsx +1 -1
  53. package/src/devtools/client/state-manager.ts +1 -1
  54. package/src/devtools/init.ts +2 -3
  55. package/src/devtools/server/source-context.ts +1 -1
  56. package/src/devtools/worker/redaction-worker.ts +8 -4
  57. package/src/devtools/worker/worker-manager.ts +4 -3
  58. package/src/error/classifier.ts +1 -1
  59. package/src/error/domains.ts +1 -1
  60. package/src/filling/sse.ts +5 -5
  61. package/src/generator/generate.ts +2 -2
  62. package/src/guard/analyzer.ts +1 -1
  63. package/src/guard/ast-analyzer.ts +7 -7
  64. package/src/guard/auto-correct.ts +2 -2
  65. package/src/guard/config-guard.ts +0 -2
  66. package/src/guard/contract-guard.ts +1 -1
  67. package/src/guard/decision-memory.ts +2 -2
  68. package/src/guard/design-inline-class.ts +2 -1
  69. package/src/guard/graph.ts +1 -1
  70. package/src/guard/healing.ts +36 -41
  71. package/src/guard/negotiation.ts +3 -3
  72. package/src/guard/reporter.ts +1 -4
  73. package/src/guard/semantic-slots.ts +2 -2
  74. package/src/guard/suggestions.ts +2 -2
  75. package/src/guard/watcher.ts +5 -4
  76. package/src/index.ts +5 -5
  77. package/src/intent/index.ts +1 -1
  78. package/src/kitchen/api/agent-devtools-api.ts +544 -0
  79. package/src/kitchen/api/contract-api.ts +1 -1
  80. package/src/kitchen/api/file-api.ts +3 -3
  81. package/src/kitchen/kitchen-handler.ts +63 -38
  82. package/src/kitchen/kitchen-ui.ts +346 -62
  83. package/src/lockfile/validate.ts +0 -1
  84. package/src/openapi/generator.ts +2 -1
  85. package/src/openapi/openapi.test.ts +43 -14
  86. package/src/perf/user-marks.ts +1 -1
  87. package/src/plugins/registry.ts +1 -2
  88. package/src/plugins/types.ts +1 -1
  89. package/src/resource/__tests__/generator.test.ts +32 -15
  90. package/src/resource/ddl/__tests__/emit.test.ts +24 -0
  91. package/src/resource/ddl/diff.ts +0 -1
  92. package/src/resource/ddl/emit.ts +12 -1
  93. package/src/resource/generator-repo.ts +40 -20
  94. package/src/resource/generator.ts +1 -1
  95. package/src/resource/generators/contract.ts +1 -1
  96. package/src/resource/schema.ts +2 -1
  97. package/src/router/fs-routes.ts +6 -6
  98. package/src/router/fs-scanner.ts +1 -1
  99. package/src/runtime/env.ts +1 -1
  100. package/src/runtime/image-handler.ts +2 -1
  101. package/src/runtime/middleware.ts +2 -1
  102. package/src/runtime/server.ts +67 -60
  103. package/src/runtime/ssr.ts +3 -3
  104. package/src/runtime/streaming-ssr.ts +25 -27
  105. package/src/scheduler/validate.ts +1 -1
  106. package/src/seo/integration/ssr.ts +2 -3
  107. package/src/seo/render/opengraph.ts +1 -1
  108. package/src/seo/resolve/index.ts +0 -4
  109. package/src/slot/corrector.ts +1 -1
  110. package/src/slot/validator.ts +4 -4
  111. package/src/watcher/reporter.ts +1 -1
  112. package/src/watcher/watcher.ts +19 -19
@@ -0,0 +1,544 @@
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
+ }
@@ -193,7 +193,7 @@ export class ContractPlaygroundAPI {
193
193
  }
194
194
 
195
195
  return Response.json({ valid: true });
196
- } catch (e) {
196
+ } catch {
197
197
  return Response.json(
198
198
  { error: "Invalid request body" },
199
199
  { status: 400 },
@@ -52,7 +52,7 @@ export class FileAPI {
52
52
  const language = detectLanguage(filePath);
53
53
 
54
54
  return Response.json({ filePath, content, language });
55
- } catch (error) {
55
+ } catch {
56
56
  return Response.json(
57
57
  { error: "Failed to read file" },
58
58
  { status: 500 },
@@ -84,7 +84,7 @@ export class FileAPI {
84
84
  try {
85
85
  const diff = await this.getFileDiff(filePath, resolved);
86
86
  return Response.json(diff);
87
- } catch (error) {
87
+ } catch {
88
88
  return Response.json(
89
89
  { error: "Failed to get diff" },
90
90
  { status: 500 },
@@ -100,7 +100,7 @@ export class FileAPI {
100
100
  try {
101
101
  const changes = await this.getGitStatus();
102
102
  return Response.json({ changes });
103
- } catch (error) {
103
+ } catch {
104
104
  return Response.json(
105
105
  { error: "Failed to get changes" },
106
106
  { status: 500 },