/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @oncall memory_lab */ import {calledTools} from './perf-stats.js'; import {callText, type SpecialistRoute} from './specialist-routes.js'; /** * "Applicable tools not run this session": the closing line of a report. * * An investigation tends to stay on the tools it already knows, and a tool * built for exactly the growth in front of it goes unused because nothing in * the report it is reading names it at the point of decision. This line * names the applicable calls whose tool this server has not run yet, from * the session's call log, so the steering arrives inside the report rather * than through a separate `memlab_tools` call. */ export interface SteeringItem { /** The tool that, once called, retires the item. */ tool: string; /** The pasteable call (or chain), as markdown. */ text: string; /** Why it applies here. */ why: string; } /** The most items a report's closing line names. */ export const MAX_STEERING = 3; /** One item per specialist route, keyed by the route's first tool. */ export function steeringFromRoutes( routes: readonly SpecialistRoute[], ): SteeringItem[] { return routes.flatMap(route => { const main = route.calls.find(c => c.tool !== 'memlab_load_snapshot'); if (main == null) return []; const r = route.rows[0]; const growth = r == null ? '' : r.perCycle != null ? ` +${Math.round(r.perCycle * 100) / 100}/cycle` : r.netCount != null ? ` +${r.netCount}` : ''; const name = r == null ? '' : r.props != null ? 'Object shape' : r.name; return [ { tool: main.tool, text: route.calls.map(c => `\`${callText(c)}\``).join(' → '), why: `${route.label.toLowerCase()}${name !== '' ? `: ${name.length > 40 ? `${name.slice(0, 39)}…` : name}${growth}` : ''}`, }, ]; }); } /** The items whose tool this session has not called, deduplicated. */ export function notRunThisSession( items: readonly SteeringItem[], called: ReadonlySet = calledTools(), max = MAX_STEERING, ): SteeringItem[] { const seen = new Set(); const out: SteeringItem[] = []; for (const item of items) { if (called.has(item.tool) || seen.has(item.tool)) continue; seen.add(item.tool); out.push(item); if (out.length >= max) break; } return out; } /** The closing line, or null when every applicable tool has been run. */ export function steeringLine(items: readonly SteeringItem[]): string | null { if (items.length === 0) return null; return `**Applicable tools not run this session:** ${items .map(i => `${i.text} (${i.why})`) .join('; ')}.`; }