@sightmap/mcp 0.9.0 → 0.10.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts","../src/tools/match.ts","../src/tools/snapshot.ts","../src/tools/network.ts","../src/tools/curate/list.ts","../src/tools/curate/get.ts","../src/curate/locator.ts","../src/tools/curate/check.ts","../src/tools/curate/update.ts","../src/tools/curate/add.ts","../src/tools/curate/remove.ts","../src/tools/curate/init.ts","../src/curate/scaffolder.ts","../src/tools/runtime/snapshot.ts","../src/runtime/inject-script.ts","../src/tools/propose/store.ts","../src/tools/propose/view.ts","../src/tools/propose/component.ts","../src/tools/propose/review.ts","../src/tools/propose/commit.ts","../src/prompts/sepTrack.ts","../src/prompts/index.ts","../src/upstream.ts","../src/mcpServer.ts"],"sourcesContent":["import {\n match as sightmapMatch,\n resolveSightmapAct,\n buildInPageEvalFunction,\n type Sightmap,\n} from \"@sightmap/sightmap\";\nimport { handleSightmapMatch } from \"./tools/match.js\";\nimport {\n buildSightmapSnapshotResponse,\n type InPageSightmapMatch,\n} from \"./tools/snapshot.js\";\nimport {\n parseNetworkRequestsText,\n annotateNetworkRequests,\n} from \"./tools/network.js\";\nimport {\n handleListViews,\n type ListViewsInput,\n} from \"./tools/curate/list.js\";\nimport { handleGetView } from \"./tools/curate/get.js\";\nimport { handleCheck, type CheckInput } from \"./tools/curate/check.js\";\nimport {\n handleUpdateView,\n type ViewPatch,\n} from \"./tools/curate/update.js\";\nimport { handleAddView } from \"./tools/curate/add.js\";\nimport { handleDeleteView } from \"./tools/curate/remove.js\";\nimport type { View } from \"@sightmap/sightmap\";\nimport {\n handleInitProject,\n type InitProjectInput,\n} from \"./tools/curate/init.js\";\nimport {\n handleRuntimeSnapshot,\n type RuntimeSnapshotInput,\n} from \"./tools/runtime/snapshot.js\";\nimport { getInjectScript } from \"./runtime/inject-script.js\";\nimport {\n handleProposeView,\n type ProposeViewInput,\n} from \"./tools/propose/view.js\";\nimport {\n handleProposeComponent,\n type ProposeComponentInput,\n} from \"./tools/propose/component.js\";\nimport { handleReviewProposals } from \"./tools/propose/review.js\";\nimport {\n handleCommitProposals,\n type CommitProposalsInput,\n} from \"./tools/propose/commit.js\";\nimport type { PromptDefinition, PromptEntry, PromptResult } from \"./prompts/index.js\";\nimport { PROMPT_REGISTRY } from \"./prompts/index.js\";\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n}\n\nexport interface ToolResult {\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n}\n\n/**\n * Abstraction over the upstream MCP server (typically `@playwright/mcp`).\n *\n * Implementations: a real MCP-SDK Client connected via stdio in production,\n * a fake in unit tests.\n */\nexport interface UpstreamClient {\n listTools(): Promise<ToolDefinition[]>;\n callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;\n}\n\nexport interface SightmapMcpServerOptions {\n sightmap: Sightmap;\n /** Optional upstream MCP server to proxy non-sightmap_* tool calls through. */\n upstream?: UpstreamClient;\n /**\n * Writable `.sightmap/` directory for curation tools that read/write files\n * (e.g. `sightmap_get_view`, `sightmap_update_view`). The CLI populates this\n * from `--curate-root` (or, by default, the first `--sightmap-dir`).\n */\n curateRoot?: string;\n}\n\nconst SIGHTMAP_MATCH: ToolDefinition = {\n name: \"sightmap_match\",\n description:\n \"Pure-query lookup against the loaded sightmap. Returns the matched view, applicable components, applicable requests, and aggregated memory for a given URL. Useful for agent planning before navigation. Does not touch the browser.\",\n inputSchema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\",\n description: \"The URL to resolve against the sightmap's view routes.\",\n },\n method: {\n type: \"string\",\n description: \"Optional HTTP method to filter matched requests (e.g., 'GET', 'POST').\",\n },\n },\n required: [\"url\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_SNAPSHOT: ToolDefinition = {\n name: \"sightmap_snapshot\",\n description:\n \"Returns the upstream ARIA snapshot enriched with sightmap awareness: matched view name, applicable component names with their selectors and live matchCount on the page, view-level memory, and page-aggregated memory. Use this instead of browser_snapshot when you want sightmap-aware semantics in one round-trip.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_NETWORK_REQUESTS: ToolDefinition = {\n name: \"sightmap_network_requests\",\n description:\n \"Returns recent network requests captured by the upstream, annotated with sightmap names and memory where the request URL+method matches a sightmap `requests:` entry. Use this in place of browser_network_requests when you want sightmap-aware semantics for network calls.\",\n inputSchema: {\n type: \"object\",\n properties: {\n static: {\n type: \"boolean\",\n description:\n \"Include successful static resources (images, fonts, scripts). Default false.\",\n },\n filter: {\n type: \"string\",\n description: \"Only return requests whose URL matches this regexp.\",\n },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_INIT_PROJECT: ToolDefinition = {\n name: \"sightmap_init_project\",\n description:\n \"Scaffold an empty .sightmap/ directory in the target project. Pass `dir` to override the location (default: server cwd). Refuses to overwrite an existing .sightmap/ unless `force=true`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dir: { type: \"string\", description: \"Project root. Default: server cwd.\" },\n force: { type: \"boolean\", description: \"Default false.\" },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_UPDATE_VIEW: ToolDefinition = {\n name: \"sightmap_update_view\",\n description:\n \"Apply a patch to a view's fields. Accepts both semantic edits (description, intent, memory_append/memory_replace) and structural edits (name, route, components). Memory edits use either `memory_append` (default) or `memory_replace` — pass exactly one. Components is a full array replacement; use sightmap_add_view/sightmap_delete_view for whole-view lifecycle.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n patch: {\n type: \"object\",\n properties: {\n description: { type: \"string\" },\n intent: { type: \"string\" },\n memory_append: { type: \"array\", items: { type: \"string\" } },\n memory_replace: { type: \"array\", items: { type: \"string\" } },\n name: { type: \"string\" },\n route: { type: \"string\" },\n components: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n selector: { type: \"string\" },\n memory: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"name\", \"selector\"],\n additionalProperties: true,\n },\n },\n },\n additionalProperties: false,\n },\n },\n required: [\"name\", \"patch\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_ADD_VIEW: ToolDefinition = {\n name: \"sightmap_add_view\",\n description:\n \"Create a new view in a new .yaml file. Filename defaults to kebab(view.name) + '.yaml' unless overridden via `file`. Rejects names that collide with an existing view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n view: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n route: { type: \"string\" },\n description: { type: \"string\" },\n memory: { type: \"array\", items: { type: \"string\" } },\n components: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n selector: { type: \"string\" },\n memory: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"name\", \"selector\"],\n additionalProperties: true,\n },\n },\n },\n required: [\"name\", \"route\"],\n additionalProperties: true,\n },\n file: {\n type: \"string\",\n description:\n \"Optional filename hint (relative to the curate root). Defaults to kebab(view.name) + '.yaml'.\",\n },\n },\n required: [\"view\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_RUNTIME_SNAPSHOT: ToolDefinition = {\n name: \"sightmap_runtime_snapshot\",\n description:\n \"Fetch a SightmapSnapshot (fiber-tree introspection from bippy). Three sources:\\n\" +\n \" - { kind: 'endpoint', url } — HTTP GET against the @sightmap/react Vite plugin endpoint (zero-config for Vite users).\\n\" +\n \" - { kind: 'browser', url, routes?, inject? } — drive the live browser via @playwright/mcp; works on any React app (Webpack, RR 5.x, etc.) and, with `inject: true`, on apps that haven't installed @sightmap/react.\\n\" +\n \" - { kind: 'literal', snapshot } — accept a pre-captured snapshot from any source (subtext live-eval-script, devtools console paste, custom Playwright scripts, CI capture). Validates the shape; returns it.\",\n inputSchema: {\n type: \"object\",\n properties: {\n source: {\n type: \"object\",\n oneOf: [\n {\n type: \"object\",\n properties: {\n kind: { type: \"string\", const: \"endpoint\" },\n url: { type: \"string\", description: \"Plugin endpoint URL, e.g. http://localhost:5173/__sightmap__/snapshot.json.\" },\n },\n required: [\"kind\", \"url\"],\n additionalProperties: false,\n },\n {\n type: \"object\",\n properties: {\n kind: { type: \"string\", const: \"browser\" },\n url: { type: \"string\", description: \"Target URL to navigate to.\" },\n routes: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional list of routes (absolute or relative to `url`) to capture in sequence.\",\n },\n inject: {\n type: \"boolean\",\n description:\n \"When true, inject bippy + the snapshot bootstrap before navigation so non-@sightmap/react apps work. \" +\n \"Omit to auto-inject only when the page lacks window.__sightmap__.\",\n },\n },\n required: [\"kind\", \"url\"],\n additionalProperties: false,\n },\n {\n type: \"object\",\n properties: {\n kind: { type: \"string\", const: \"literal\" },\n snapshot: {\n description:\n \"A pre-captured SightmapSnapshot object. Must include capturedAt, route, components, markers, unmarkedCandidates.\",\n },\n },\n required: [\"kind\", \"snapshot\"],\n additionalProperties: false,\n },\n ],\n },\n },\n required: [\"source\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_PROPOSE_VIEW: ToolDefinition = {\n name: \"sightmap_propose_view\",\n description:\n \"Stage a proposed view from runtime observation. Does NOT write disk. Use sightmap_commit_proposals to persist.\",\n inputSchema: {\n type: \"object\",\n properties: {\n route: { type: \"string\", description: \"URL path for the observed view (e.g., '/dashboard').\" },\n name: { type: \"string\", description: \"Optional display name. If omitted, derived from route at commit time.\" },\n intent: { type: \"string\", description: \"Optional one-liner describing the view's purpose.\" },\n observed: { type: \"string\", description: \"Free-form note about what was observed on this view.\" },\n observed_components: { type: \"array\", items: { type: \"string\" } },\n memory_notes: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"route\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_PROPOSE_COMPONENT: ToolDefinition = {\n name: \"sightmap_propose_component\",\n description:\n \"Stage a proposed component observation. Does NOT write disk.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Component name (e.g., 'KpiCard').\" },\n selector_candidate: { type: \"string\", description: \"Best-guess CSS selector for the component.\" },\n observed_routes: { type: \"array\", items: { type: \"string\" } },\n notes: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_REVIEW_PROPOSALS: ToolDefinition = {\n name: \"sightmap_review_proposals\",\n description:\n \"Return the current staged proposals (views + components).\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_COMMIT_PROPOSALS: ToolDefinition = {\n name: \"sightmap_commit_proposals\",\n description:\n \"Promote staged proposals to disk via add_view. Pass dry_run:true to preview without consuming the queue. Pass ids:[...] to commit a selection only.\",\n inputSchema: {\n type: \"object\",\n properties: {\n ids: { type: \"array\", items: { type: \"string\" }, description: \"Optional subset of proposal ids to commit. Omit to commit everything.\" },\n dry_run: { type: \"boolean\", description: \"If true, preview without consuming the queue and without writing.\" },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_DELETE_VIEW: ToolDefinition = {\n name: \"sightmap_delete_view\",\n description:\n \"Delete a view by name. If the containing .yaml file has only this view, the file is removed; otherwise the view is spliced out and the file rewritten.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_CHECK: ToolDefinition = {\n name: \"sightmap_check\",\n description:\n \"Validate the loaded sightmap. level='schema' returns only schema-level diagnostics (parse errors, schema failures, merge collisions). level='quality' (default) also runs lint rules: duplicate routes, route shadowing, selector syntax, unknown source attributions. Returns an array of diagnostics; an empty array means clean.\",\n inputSchema: {\n type: \"object\",\n properties: {\n level: {\n type: \"string\",\n enum: [\"schema\", \"quality\"],\n description: \"Default 'quality'.\",\n },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_GET_VIEW: ToolDefinition = {\n name: \"sightmap_get_view\",\n description:\n \"Fetch a single view by name, including all memory, components, and requests. Returns the file path the view was read from for subsequent edits. Use sightmap_list_views first to discover view names.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"View name (case-sensitive).\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_LIST_VIEWS: ToolDefinition = {\n name: \"sightmap_list_views\",\n description:\n \"List all views in the loaded sightmap. Returns compact summaries (name, route, description) by default; pass detail='full' for the complete view objects including memory and components. Token-efficient: prefer the default for any agent that hasn't yet narrowed to a specific view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n detail: {\n type: \"string\",\n enum: [\"summary\", \"full\"],\n description: \"Default 'summary'.\",\n },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_ACT: ToolDefinition = {\n name: \"sightmap_act\",\n description:\n \"Performs an action on a UI element. Prefer `componentName` so the agent operates in sightmap semantics; fall back to a raw `selector` for one-off targets the sightmap doesn't define (e.g., a stray link or a third-party widget). Supported actions: 'click' (browser_click), 'type' (browser_type, requires `text`), 'hover' (browser_hover). Pass exactly one of `componentName` or `selector`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n componentName: {\n type: \"string\",\n description: \"Sightmap component name to act on (case-sensitive). Mutually exclusive with `selector`.\",\n },\n selector: {\n type: \"string\",\n description:\n \"Escape hatch: a raw CSS selector for a target the sightmap doesn't name. Same tagging + dispatch path as componentName. Use this only when no sightmap component fits — most actions should use `componentName` so the agent's reasoning stays in sightmap semantics. Mutually exclusive with `componentName`.\",\n },\n action: {\n type: \"string\",\n enum: [\"click\", \"type\", \"hover\"],\n description: \"The action to perform on the component.\",\n },\n text: {\n type: \"string\",\n description: \"Required for action='type'. Text to enter into the matched element.\",\n },\n submit: {\n type: \"boolean\",\n description: \"For action='type' only. Press Enter after typing.\",\n },\n instance: {\n type: \"integer\",\n minimum: 0,\n description:\n \"Zero-based index of the matching element when the component selector resolves to multiple elements (default 0). Use sightmap_snapshot.matchCount to discover how many instances exist. Mutually exclusive with `containingText`.\",\n },\n containingText: {\n type: \"string\",\n description:\n \"Disambiguator for multi-match components: pick the first element whose visible text contains this substring (case-insensitive). Use this instead of `instance` when you can identify the element by its visible label rather than position. Mutually exclusive with `instance`.\",\n },\n },\n required: [\"componentName\", \"action\"],\n additionalProperties: false,\n },\n};\n\n/**\n * Upstream tools whose sightmap-aware equivalents should appear instead in\n * the listed-tools surface. The agent only sees one of each pair, biasing\n * its tool choices toward sightmap semantics. Direct invocation by name\n * still works for callers that need the raw passthrough.\n */\nconst SHADOWED_UPSTREAM_TOOLS: ReadonlySet<string> = new Set([\n \"browser_snapshot\",\n \"browser_click\",\n \"browser_type\",\n \"browser_hover\",\n \"browser_network_requests\",\n]);\n\n/**\n * Core dispatcher for the sightmap-mcp wrapper.\n *\n * Holds the loaded sightmap, exposes the surface of sightmap-aware tools, and\n * dispatches `callTool` requests. Transport-agnostic — wired up to stdio in\n * the CLI entry, and unit-testable directly without spinning up MCP plumbing.\n *\n * Phase 1 surface: `sightmap_match` only. Subsequent phases add\n * `sightmap_snapshot` and `sightmap_act`, plus a passthrough proxy for the\n * upstream @playwright/mcp tools.\n */\nexport class SightmapMcpServer {\n private readonly sightmap: Sightmap;\n private readonly upstream: UpstreamClient | undefined;\n private readonly curateRoot: string | undefined;\n\n constructor(opts: SightmapMcpServerOptions) {\n this.sightmap = opts.sightmap;\n this.upstream = opts.upstream;\n this.curateRoot = opts.curateRoot;\n }\n\n /** Synchronous list of sightmap-aware tools that don't need an upstream. */\n listTools(): ToolDefinition[] {\n return [\n SIGHTMAP_MATCH,\n SIGHTMAP_LIST_VIEWS,\n SIGHTMAP_GET_VIEW,\n SIGHTMAP_CHECK,\n SIGHTMAP_ADD_VIEW,\n SIGHTMAP_UPDATE_VIEW,\n SIGHTMAP_DELETE_VIEW,\n SIGHTMAP_INIT_PROJECT,\n SIGHTMAP_RUNTIME_SNAPSHOT,\n SIGHTMAP_PROPOSE_VIEW,\n SIGHTMAP_PROPOSE_COMPONENT,\n SIGHTMAP_REVIEW_PROPOSALS,\n SIGHTMAP_COMMIT_PROPOSALS,\n ];\n }\n\n /** Full async list including upstream-proxied tools, if configured. */\n async listToolsAsync(): Promise<ToolDefinition[]> {\n const own: ToolDefinition[] = [\n SIGHTMAP_MATCH,\n SIGHTMAP_LIST_VIEWS,\n SIGHTMAP_GET_VIEW,\n SIGHTMAP_CHECK,\n SIGHTMAP_ADD_VIEW,\n SIGHTMAP_UPDATE_VIEW,\n SIGHTMAP_DELETE_VIEW,\n SIGHTMAP_INIT_PROJECT,\n SIGHTMAP_RUNTIME_SNAPSHOT,\n SIGHTMAP_PROPOSE_VIEW,\n SIGHTMAP_PROPOSE_COMPONENT,\n SIGHTMAP_REVIEW_PROPOSALS,\n SIGHTMAP_COMMIT_PROPOSALS,\n ];\n if (this.upstream !== undefined) {\n own.push(SIGHTMAP_SNAPSHOT, SIGHTMAP_ACT, SIGHTMAP_NETWORK_REQUESTS);\n }\n if (this.upstream === undefined) return own;\n const upstreamTools = await this.upstream.listTools();\n // Hide upstream tools that have a sightmap_* equivalent. Goal: nudge the\n // agent toward the sightmap-aware surface instead of letting it fall\n // back to the generic browser_* duplicates by habit. Calls to these\n // hidden tools still pass through if the agent invokes them by name —\n // hiding only affects the discovery surface.\n const shadowed = SHADOWED_UPSTREAM_TOOLS;\n const filtered = upstreamTools.filter((t) => !shadowed.has(t.name));\n return [...own, ...filtered];\n }\n\n /** All prompts the server advertises. Static; no upstream involvement. */\n listPrompts(): PromptDefinition[] {\n return PROMPT_REGISTRY.map((p) => p.definition);\n }\n\n /**\n * Resolve a prompt by name, validate args, and produce the prompt result\n * (the messages the agent will inject). Throws on unknown names or on a\n * handler that itself throws (e.g., bad phase value).\n */\n getPrompt(name: string, args: Record<string, string>): PromptResult {\n const entry: PromptEntry | undefined = PROMPT_REGISTRY.find(\n (p) => p.definition.name === name,\n );\n if (entry === undefined) throw new Error(`unknown prompt: ${name}`);\n return entry.handler(args);\n }\n\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n if (isSightmapTool(name)) {\n switch (name) {\n case \"sightmap_match\":\n return this.callSightmapMatch(args);\n case \"sightmap_list_views\":\n return this.callSightmapListViews(args);\n case \"sightmap_get_view\":\n return this.callSightmapGetView(args);\n case \"sightmap_check\":\n return this.callSightmapCheck(args);\n case \"sightmap_add_view\":\n return this.callSightmapAddView(args);\n case \"sightmap_update_view\":\n return this.callSightmapUpdateView(args);\n case \"sightmap_delete_view\":\n return this.callSightmapDeleteView(args);\n case \"sightmap_init_project\":\n return this.callSightmapInitProject(args);\n case \"sightmap_runtime_snapshot\":\n return this.callSightmapRuntimeSnapshot(args);\n case \"sightmap_propose_view\":\n return this.callSightmapProposeView(args);\n case \"sightmap_propose_component\":\n return this.callSightmapProposeComponent(args);\n case \"sightmap_review_proposals\":\n return this.callSightmapReviewProposals();\n case \"sightmap_commit_proposals\":\n return this.callSightmapCommitProposals(args);\n case \"sightmap_snapshot\":\n return this.callSightmapSnapshot();\n case \"sightmap_act\":\n return this.callSightmapAct(args);\n case \"sightmap_network_requests\":\n return this.callSightmapNetworkRequests(args);\n default:\n return errorResult(`Unknown sightmap tool: ${name}`);\n }\n }\n if (this.upstream !== undefined) {\n return this.upstream.callTool(name, args);\n }\n return errorResult(`Unknown tool: ${name}`);\n }\n\n /**\n * Tag a single element matching `selector` with a unique\n * `data-sm-act-target` attribute and return a CSS selector that resolves\n * to exactly that element. The selection mode picks WHICH match to tag:\n * - `{ kind: \"index\", index }` — pick the Nth match (default).\n * - `{ kind: \"containingText\", text }` — pick the first match whose\n * `textContent` contains `text` (case-insensitive).\n *\n * Returns null if no candidate is selected (index out of range, or no\n * element's text contains the needle).\n */\n private async tagSingleMatch(\n selector: string,\n selection:\n | { kind: \"index\"; index: number }\n | { kind: \"containingText\"; text: string },\n ): Promise<string | null> {\n if (this.upstream === undefined) return null;\n const marker = `sm-${Math.random().toString(36).slice(2, 10)}-${Date.now().toString(36)}`;\n const pickExpr =\n selection.kind === \"index\"\n ? `els[${selection.index}]`\n : `els.find((el) => (el.textContent || \"\").toLowerCase().includes(${JSON.stringify(selection.text.toLowerCase())}))`;\n const fnBody = `() => {\n const els = Array.from(document.querySelectorAll(${JSON.stringify(selector)}));\n const target = ${pickExpr};\n if (!target) return null;\n target.setAttribute(\"data-sm-act-target\", ${JSON.stringify(marker)});\n return \"[data-sm-act-target=\\\\\"\" + ${JSON.stringify(marker)} + \"\\\\\"]\";\n }`;\n const r = await this.upstream.callTool(\"browser_evaluate\", { function: fnBody });\n if (r.isError === true) return null;\n const text = r.content.map((b) => b.text).join(\"\\n\");\n const decoded = decodeMcpEvalResult(text);\n if (typeof decoded !== \"string\") return null;\n if (!decoded.includes(`data-sm-act-target=\"${marker}\"`)) return null;\n return decoded;\n }\n\n private async callSightmapNetworkRequests(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (this.upstream === undefined) {\n return errorResult(\n \"sightmap_network_requests: requires an upstream (e.g., @playwright/mcp).\",\n );\n }\n const upstreamArgs: Record<string, unknown> = {};\n if (typeof args[\"static\"] === \"boolean\") upstreamArgs[\"static\"] = args[\"static\"];\n if (typeof args[\"filter\"] === \"string\") upstreamArgs[\"filter\"] = args[\"filter\"];\n\n const r = await this.upstream.callTool(\"browser_network_requests\", upstreamArgs);\n if (r.isError === true) {\n return r;\n }\n const text = r.content.map((b) => b.text).join(\"\\n\");\n const parsed = parseNetworkRequestsText(text);\n const annotated = annotateNetworkRequests(this.sightmap, parsed);\n return {\n content: [{ type: \"text\", text: JSON.stringify({ requests: annotated }, null, 2) }],\n };\n }\n\n private async callSightmapAct(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.upstream === undefined) {\n return errorResult(\n \"sightmap_act: requires an upstream (e.g., @playwright/mcp) to be configured.\",\n );\n }\n const hasComponent =\n typeof args[\"componentName\"] === \"string\" && args[\"componentName\"].length > 0;\n const hasSelector =\n typeof args[\"selector\"] === \"string\" && args[\"selector\"].length > 0;\n if (hasComponent && hasSelector) {\n return errorResult(\n \"sightmap_act: `componentName` and `selector` are mutually exclusive — pass one, not both.\",\n );\n }\n if (!hasComponent && !hasSelector) {\n return errorResult(\n \"sightmap_act: pass either `componentName` (preferred) or `selector` (escape hatch for off-sightmap targets).\",\n );\n }\n if (typeof args[\"action\"] !== \"string\") {\n return errorResult(\"sightmap_act: required argument `action` (string) is missing.\");\n }\n\n const action = args[\"action\"];\n const validActions = new Set([\"click\", \"type\", \"hover\"]);\n if (!validActions.has(action)) {\n return errorResult(\n `sightmap_act: unsupported action \"${action}\". Supported: click, type, hover.`,\n );\n }\n if (action === \"type\" && typeof args[\"text\"] !== \"string\") {\n return errorResult(\"sightmap_act: action='type' requires `text` (string).\");\n }\n\n const hasInstance = typeof args[\"instance\"] === \"number\";\n const hasContainingText =\n typeof args[\"containingText\"] === \"string\" && args[\"containingText\"].length > 0;\n if (hasInstance && hasContainingText) {\n return errorResult(\n \"sightmap_act: `instance` and `containingText` are mutually exclusive — pass one, not both.\",\n );\n }\n\n // Resolve the target: either via sightmap lookup or directly from `selector`.\n let targetSelector: string;\n let targetLabel: string;\n if (hasComponent) {\n const resolved = resolveSightmapAct(this.sightmap, {\n componentName: args[\"componentName\"] as string,\n });\n if (resolved.kind === \"error\") {\n return errorResult(\"sightmap_act: \" + resolved.message);\n }\n targetSelector = resolved.selector;\n targetLabel = resolved.componentName;\n } else {\n targetSelector = args[\"selector\"] as string;\n targetLabel = `selector:${targetSelector}`;\n }\n const resolved = { kind: \"ok\" as const, componentName: targetLabel, selector: targetSelector };\n\n // Tag a single matching element with a unique data-sm-act-target marker\n // via browser_evaluate, then act on that uniquely-tagged element. This\n // sidesteps Playwright's strict-mode multi-match violation regardless of\n // whether the sightmap selector resolves to one element or many. Costs\n // one extra round-trip per action; buys universal correctness.\n const selection: { kind: \"index\"; index: number } | { kind: \"containingText\"; text: string } =\n hasContainingText\n ? { kind: \"containingText\", text: args[\"containingText\"] as string }\n : { kind: \"index\", index: hasInstance ? Math.floor(args[\"instance\"] as number) : 0 };\n const taggedSelector = await this.tagSingleMatch(resolved.selector, selection);\n if (taggedSelector === null) {\n const reason =\n selection.kind === \"containingText\"\n ? `no instance of \"${resolved.componentName}\" contains text ${JSON.stringify(selection.text)}`\n : `could not tag the element at instance=${selection.index} for component \"${resolved.componentName}\"`;\n return errorResult(\n `sightmap_act: ${reason}. The selector ${JSON.stringify(resolved.selector)} ` +\n `may not resolve any matching elements on the current page.`,\n );\n }\n\n const baseArgs: Record<string, unknown> = {\n target: taggedSelector,\n element: resolved.componentName,\n };\n\n let upstreamName: string;\n let upstreamArgs: Record<string, unknown>;\n switch (action) {\n case \"click\":\n upstreamName = \"browser_click\";\n upstreamArgs = baseArgs;\n break;\n case \"hover\":\n upstreamName = \"browser_hover\";\n upstreamArgs = baseArgs;\n break;\n case \"type\":\n upstreamName = \"browser_type\";\n upstreamArgs = {\n ...baseArgs,\n text: args[\"text\"],\n ...(args[\"submit\"] === true ? { submit: true } : {}),\n };\n break;\n default:\n return errorResult(`sightmap_act: unsupported action \"${action}\".`);\n }\n\n return this.upstream.callTool(upstreamName, upstreamArgs);\n }\n\n private async callSightmapSnapshot(): Promise<ToolResult> {\n if (this.upstream === undefined) {\n return errorResult(\n \"sightmap_snapshot: requires an upstream (e.g., @playwright/mcp) to be configured.\",\n );\n }\n\n // 1. Pull the ARIA snapshot from upstream.\n const snapResult = await this.upstream.callTool(\"browser_snapshot\", {});\n if (snapResult.isError === true) {\n return errorResult(\n \"sightmap_snapshot: upstream browser_snapshot failed: \" +\n (snapResult.content[0]?.text ?? \"unknown error\"),\n );\n }\n const ariaSnapshotText = snapResult.content.map((b) => b.text).join(\"\\n\");\n\n // 2. Determine the URL and find sightmap-applicable components for it.\n // We do this server-side via match(), so the in-page eval only needs\n // to look up `document.querySelectorAll(selector)` for each.\n const currentUrl = parsePageUrl(ariaSnapshotText) ?? \"\";\n const matchResult = sightmapMatch(this.sightmap, { url: currentUrl });\n const componentSelectors = matchResult.components.map((c) => ({\n name: c.name,\n selector: c.selector,\n }));\n\n // 3. In-page evaluate: query each component's selectors, return matchCount\n // and first match's bounding rect.\n const evalResult = await this.upstream.callTool(\"browser_evaluate\", {\n function: buildInPageEvalFunction(componentSelectors),\n });\n if (evalResult.isError === true) {\n return errorResult(\n \"sightmap_snapshot: upstream browser_evaluate failed: \" +\n (evalResult.content[0]?.text ?? \"unknown error\"),\n );\n }\n const inPageMatches = parseInPageEvalResult(\n evalResult.content.map((b) => b.text).join(\"\\n\"),\n );\n\n // 4. Synthesize the response.\n const response = buildSightmapSnapshotResponse({\n sightmap: this.sightmap,\n currentUrl,\n ariaSnapshotText,\n inPageMatches,\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(response, null, 2) }],\n };\n }\n\n private callSightmapMatch(args: Record<string, unknown>): ToolResult {\n if (typeof args[\"url\"] !== \"string\" || args[\"url\"].length === 0) {\n return errorResult(\"sightmap_match: required argument `url` (string) is missing or empty.\");\n }\n const input: { url: string; method?: string } = { url: args[\"url\"] };\n if (typeof args[\"method\"] === \"string\") {\n input.method = args[\"method\"];\n }\n const output = handleSightmapMatch(this.sightmap, input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(output, null, 2) }],\n };\n }\n\n private async callSightmapGetView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_get_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\"sightmap_get_view: required argument `name` (string) is missing or empty.\");\n }\n try {\n const result = await handleGetView({\n sightmapDir: this.curateRoot,\n name: args[\"name\"],\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapInitProject(args: Record<string, unknown>): Promise<ToolResult> {\n const input: InitProjectInput = {};\n if (typeof args[\"dir\"] === \"string\") input.dir = args[\"dir\"];\n if (args[\"force\"] === true) input.force = true;\n try {\n const result = await handleInitProject(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapRuntimeSnapshot(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n const source = args[\"source\"];\n if (source === null || typeof source !== \"object\" || Array.isArray(source)) {\n return errorResult(\n \"sightmap_runtime_snapshot: required argument `source` (object) is missing.\",\n );\n }\n const s = source as Record<string, unknown>;\n const kind = s[\"kind\"];\n if (kind !== \"endpoint\" && kind !== \"browser\" && kind !== \"literal\") {\n return errorResult(\n \"sightmap_runtime_snapshot: `source.kind` must be 'endpoint', 'browser', or 'literal'.\",\n );\n }\n let input: RuntimeSnapshotInput;\n if (kind === \"endpoint\") {\n if (typeof s[\"url\"] !== \"string\" || s[\"url\"].length === 0) {\n return errorResult(\n \"sightmap_runtime_snapshot: endpoint mode requires `source.url` (string).\",\n );\n }\n input = { source: { kind: \"endpoint\", url: s[\"url\"] } };\n } else if (kind === \"browser\") {\n if (typeof s[\"url\"] !== \"string\" || s[\"url\"].length === 0) {\n return errorResult(\n \"sightmap_runtime_snapshot: browser mode requires `source.url` (string).\",\n );\n }\n const browserSrc: { kind: \"browser\"; url: string; routes?: string[]; inject?: boolean } = {\n kind: \"browser\",\n url: s[\"url\"],\n };\n if (Array.isArray(s[\"routes\"])) {\n browserSrc.routes = (s[\"routes\"] as unknown[]).filter(\n (r): r is string => typeof r === \"string\",\n );\n }\n if (typeof s[\"inject\"] === \"boolean\") {\n browserSrc.inject = s[\"inject\"];\n }\n input = { source: browserSrc };\n } else {\n // literal\n if (!(\"snapshot\" in s)) {\n return errorResult(\n \"sightmap_runtime_snapshot: literal mode requires `source.snapshot`.\",\n );\n }\n input = { source: { kind: \"literal\", snapshot: s[\"snapshot\"] } };\n }\n try {\n const deps: import(\"./tools/runtime/snapshot.js\").RuntimeSnapshotDeps = {\n getInjectScript,\n };\n if (this.upstream !== undefined) deps.upstream = this.upstream;\n const result = await handleRuntimeSnapshot(input, deps);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapProposeView(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (typeof args[\"route\"] !== \"string\" || args[\"route\"].length === 0) {\n return errorResult(\n \"sightmap_propose_view: required argument `route` (string) is missing or empty.\",\n );\n }\n const input: ProposeViewInput = { route: args[\"route\"] };\n if (typeof args[\"name\"] === \"string\") input.name = args[\"name\"];\n if (typeof args[\"intent\"] === \"string\") input.intent = args[\"intent\"];\n if (typeof args[\"observed\"] === \"string\") input.observed = args[\"observed\"];\n if (Array.isArray(args[\"observed_components\"])) {\n input.observed_components = (args[\"observed_components\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n if (Array.isArray(args[\"memory_notes\"])) {\n input.memory_notes = (args[\"memory_notes\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n try {\n const result = await handleProposeView(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapProposeComponent(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_propose_component: required argument `name` (string) is missing or empty.\",\n );\n }\n const input: ProposeComponentInput = { name: args[\"name\"] };\n if (typeof args[\"selector_candidate\"] === \"string\") {\n input.selector_candidate = args[\"selector_candidate\"];\n }\n if (Array.isArray(args[\"observed_routes\"])) {\n input.observed_routes = (args[\"observed_routes\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n if (Array.isArray(args[\"notes\"])) {\n input.notes = (args[\"notes\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n try {\n const result = await handleProposeComponent(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapReviewProposals(): Promise<ToolResult> {\n try {\n const result = await handleReviewProposals();\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapCommitProposals(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_commit_proposals: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n const input: CommitProposalsInput = { sightmapDir: this.curateRoot };\n if (Array.isArray(args[\"ids\"])) {\n input.ids = (args[\"ids\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n if (args[\"dry_run\"] === true) input.dry_run = true;\n try {\n const result = await handleCommitProposals(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapAddView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_add_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (\n args[\"view\"] === null ||\n typeof args[\"view\"] !== \"object\" ||\n Array.isArray(args[\"view\"])\n ) {\n return errorResult(\n \"sightmap_add_view: required argument `view` (object) is missing.\",\n );\n }\n const view = args[\"view\"] as Record<string, unknown>;\n if (typeof view[\"name\"] !== \"string\" || view[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_add_view: `view.name` (string) is required.\",\n );\n }\n if (typeof view[\"route\"] !== \"string\" || view[\"route\"].length === 0) {\n return errorResult(\n \"sightmap_add_view: `view.route` (string) is required.\",\n );\n }\n const input: { sightmapDir: string; view: View; file?: string } = {\n sightmapDir: this.curateRoot,\n view: view as unknown as View,\n };\n if (typeof args[\"file\"] === \"string\" && args[\"file\"].length > 0) {\n input.file = args[\"file\"];\n }\n try {\n const result = await handleAddView(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapUpdateView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_update_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_update_view: required argument `name` (string) is missing or empty.\",\n );\n }\n if (\n args[\"patch\"] === null ||\n typeof args[\"patch\"] !== \"object\" ||\n Array.isArray(args[\"patch\"])\n ) {\n return errorResult(\n \"sightmap_update_view: required argument `patch` (object) is missing.\",\n );\n }\n try {\n const result = await handleUpdateView({\n sightmapDir: this.curateRoot,\n name: args[\"name\"],\n patch: args[\"patch\"] as ViewPatch,\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapDeleteView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_delete_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_delete_view: required argument `name` (string) is missing or empty.\",\n );\n }\n try {\n const result = await handleDeleteView({\n sightmapDir: this.curateRoot,\n name: args[\"name\"],\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapCheck(args: Record<string, unknown>): Promise<ToolResult> {\n const input: CheckInput = {};\n if (args[\"level\"] === \"schema\" || args[\"level\"] === \"quality\") {\n input.level = args[\"level\"];\n } else if (args[\"level\"] !== undefined) {\n return errorResult(\n `sightmap_check: level must be \"schema\" or \"quality\".`,\n );\n }\n const result = await handleCheck(this.sightmap, input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n }\n\n private callSightmapListViews(args: Record<string, unknown>): ToolResult {\n const input: ListViewsInput = {};\n if (args[\"detail\"] === \"summary\" || args[\"detail\"] === \"full\") {\n input.detail = args[\"detail\"];\n } else if (args[\"detail\"] !== undefined) {\n return errorResult(\n `sightmap_list_views: detail must be \"summary\" or \"full\".`,\n );\n }\n const output = handleListViews(this.sightmap, input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(output, null, 2) }],\n };\n }\n}\n\nfunction errorResult(text: string): ToolResult {\n return {\n content: [{ type: \"text\", text }],\n isError: true,\n };\n}\n\nfunction isSightmapTool(name: string): boolean {\n return name.startsWith(\"sightmap_\");\n}\n\n/** Extract the \"Page URL: ...\" line from an upstream browser_snapshot response. */\nfunction parsePageUrl(text: string): string | null {\n const m = /Page URL:\\s*(\\S+)/.exec(text);\n return m?.[1] ?? null;\n}\n\n/**\n * Parse the upstream `browser_evaluate` response text into a JSON payload.\n *\n * @playwright/mcp wraps the result like:\n * ### Result\n * {\"url\": \"...\", \"matches\": [...]}\n * ### Ran Playwright code\n * ...\n *\n * We extract the first JSON object after `### Result`. If the format changes,\n * fall back to a generic { from first '{' } scan.\n */\nfunction parseInPageEvalResult(text: string): InPageSightmapMatch[] {\n const afterResult = text.split(/^###\\s*Result/im)[1] ?? text;\n const start = afterResult.indexOf(\"{\");\n if (start < 0) return [];\n for (let end = afterResult.length; end > start; end--) {\n try {\n const parsed = JSON.parse(afterResult.slice(start, end)) as {\n url?: string;\n matches?: unknown[];\n };\n if (Array.isArray(parsed.matches)) {\n return parsed.matches.filter(isInPageMatch);\n }\n } catch {\n // try shorter window\n }\n }\n return [];\n}\n\n/**\n * Decode the value an upstream `browser_evaluate` returned to us.\n * Format is text after `### Result`, JSON-encoded: a number is `42`, a\n * string is `\"foo\"`, an object/array is the JSON literal.\n */\nfunction decodeMcpEvalResult(text: string): unknown {\n const afterResult = text.split(/^###\\s*Result/im)[1] ?? \"\";\n const trimmed = afterResult.trim();\n if (trimmed.length === 0) return undefined;\n // Find the first JSON-y token at the start of trimmed.\n for (let end = trimmed.length; end > 0; end--) {\n try {\n return JSON.parse(trimmed.slice(0, end));\n } catch {\n // try shorter\n }\n }\n return undefined;\n}\n\nfunction isInPageMatch(value: unknown): value is InPageSightmapMatch {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return typeof v[\"name\"] === \"string\" && typeof v[\"matchCount\"] === \"number\";\n}\n","import { match as sightmapMatch, type Sightmap, type MatchResult } from \"@sightmap/sightmap\";\n\nexport interface SightmapMatchInput {\n url: string;\n method?: string;\n}\n\nexport interface SightmapMatchOutput {\n view: { name: string; route: string; description?: string } | null;\n components: Array<{\n name: string;\n selector: string[];\n memory: string[];\n scope: \"global\" | \"view-scoped\";\n }>;\n requests: Array<{\n name: string;\n route: string;\n method?: string;\n memory: string[];\n }>;\n /** Page-level aggregated memory from sightmap-js. */\n memory: string[];\n /** Memory attached to the matched view itself, if any. */\n viewMemory: string[];\n}\n\n/**\n * Pure handler for the `sightmap_match` MCP tool.\n *\n * Wraps sightmap-js's `match()` and shapes the response for agent consumption.\n * No browser involvement — this is the planning-side query: \"what should I\n * expect at this URL?\"\n */\nexport function handleSightmapMatch(\n sightmap: Sightmap,\n input: SightmapMatchInput,\n): SightmapMatchOutput {\n const result: MatchResult = sightmapMatch(sightmap, {\n url: input.url,\n ...(input.method !== undefined ? { method: input.method } : {}),\n });\n\n return {\n view: result.view\n ? {\n name: result.view.name,\n route: result.view.route,\n ...(result.view.description !== undefined\n ? { description: result.view.description }\n : {}),\n }\n : null,\n components: result.components.map((c) => ({\n name: c.name,\n selector: c.selector,\n memory: c.memory ?? [],\n scope: c.scope,\n })),\n requests: result.requests.map((r) => ({\n name: r.name,\n route: r.route,\n ...(r.method !== undefined ? { method: r.method } : {}),\n memory: r.memory ?? [],\n })),\n memory: result.memory ?? [],\n viewMemory: result.view?.memory ?? [],\n };\n}\n","import {\n enrichSnapshot,\n type EnrichedSnapshot,\n type InPageSightmapMatch,\n type BoundingRect,\n type SightmapSnapshotComponent,\n type Sightmap,\n} from \"@sightmap/sightmap\";\n\n// Re-export kernel types so existing MCP callers keep working unchanged.\nexport type { InPageSightmapMatch, BoundingRect, SightmapSnapshotComponent };\n\nexport interface BuildSnapshotOptions {\n sightmap: Sightmap;\n currentUrl: string;\n ariaSnapshotText: string;\n inPageMatches: InPageSightmapMatch[];\n}\n\nexport type SightmapSnapshotResponse = EnrichedSnapshot & {\n /** Raw ARIA tree text passthrough from browser_snapshot. */\n ariaSnapshot: string;\n};\n\n/**\n * Wraps the kernel's enrichSnapshot with the Playwright-MCP-specific\n * ariaSnapshot passthrough. The agent gets both the structured enrichment\n * (view, components, memory) and the raw a11y text for context.\n */\nexport function buildSightmapSnapshotResponse(\n opts: BuildSnapshotOptions,\n): SightmapSnapshotResponse {\n const enriched = enrichSnapshot({\n sightmap: opts.sightmap,\n currentUrl: opts.currentUrl,\n inPageMatches: opts.inPageMatches,\n });\n return { ...enriched, ariaSnapshot: opts.ariaSnapshotText };\n}\n","import type { ParsedNetworkRequest } from \"@sightmap/sightmap\";\n\n// Re-export so existing MCP callers continue to work.\nexport type {\n ParsedNetworkRequest,\n AnnotatedNetworkRequest,\n} from \"@sightmap/sightmap\";\nexport { annotateNetworkRequests } from \"@sightmap/sightmap\";\n\n/**\n * Parse the text output of `@playwright/mcp` `browser_network_requests`.\n *\n * Expected line format (one request per line, in the body after `### Result`):\n *\n * N. [METHOD] URL => [STATUS] STATUS_TEXT\n *\n * Lines that don't match are silently dropped — `browser_network_requests`\n * also emits notes about static resources, page-level metadata, etc.\n *\n * This parser is Playwright-MCP-specific and stays here; other engine\n * adapters write their own parser against their own engine's output.\n */\nexport function parseNetworkRequestsText(text: string): ParsedNetworkRequest[] {\n const lines = text.split(/\\r?\\n/);\n const requests: ParsedNetworkRequest[] = [];\n const re = /^\\s*\\d+\\.\\s*\\[([A-Z]+)\\]\\s+(\\S+)\\s+=>\\s+\\[(\\d+)\\]\\s+(.*?)\\s*$/;\n for (const line of lines) {\n const m = re.exec(line);\n if (m === null) continue;\n requests.push({\n method: m[1] ?? \"\",\n url: m[2] ?? \"\",\n status: Number.parseInt(m[3] ?? \"0\", 10),\n statusText: m[4] ?? \"\",\n });\n }\n return requests;\n}\n","// `sightmap_list_views` handler.\n//\n// Read-only; defaults to compact summaries (name + route + optional\n// description) so a single-call discovery in an agent's first turn fits in a\n// small token budget. `detail: \"full\"` returns the entire View object\n// including memory, components, and requests.\n\nimport type { Sightmap, View } from \"@sightmap/sightmap\";\n\nexport interface ListViewsInput {\n detail?: \"summary\" | \"full\";\n}\n\nexport interface ViewSummary {\n name: string;\n route: string;\n description?: string;\n}\n\nexport interface ListViewsOutput {\n views: Array<ViewSummary | View>;\n}\n\nexport function handleListViews(\n sightmap: Sightmap,\n input: ListViewsInput,\n): ListViewsOutput {\n const detail = input.detail ?? \"summary\";\n const sorted = [...sightmap.views].sort((a, b) =>\n a.name.localeCompare(b.name),\n );\n\n if (detail === \"full\") {\n return { views: sorted };\n }\n\n return {\n views: sorted.map((v) => {\n const summary: ViewSummary = { name: v.name, route: v.route };\n if (v.description !== undefined) summary.description = v.description;\n return summary;\n }),\n };\n}\n","// `sightmap_get_view` handler.\n//\n// Read-only single-view fetch. Returns the parsed view object plus the file\n// path it was read from, so callers can chain `update_view` against the same\n// file without an extra lookup.\n\nimport { readFile } from \"node:fs/promises\";\nimport { parse, type View } from \"@sightmap/sightmap\";\nimport { findFileForView } from \"../../curate/locator.js\";\n\nexport interface GetViewInput {\n sightmapDir: string;\n name: string;\n}\n\nexport interface GetViewOutput {\n view: View;\n file: string;\n}\n\nexport async function handleGetView(input: GetViewInput): Promise<GetViewOutput> {\n const file = await findFileForView(input.sightmapDir, input.name);\n if (file === null) {\n throw new Error(\n `View \"${input.name}\" not found in ${input.sightmapDir}`,\n );\n }\n const text = await readFile(file, \"utf8\");\n const parsed = parse(text, { sourceFile: file });\n const view = parsed.views?.find((v) => v.name === input.name);\n if (view === undefined) {\n throw new Error(\n `View \"${input.name}\" not found in ${file} (locator drift?)`,\n );\n }\n return { view, file };\n}\n","// Locate the YAML file in a `.sightmap/` directory that contains a given view.\n//\n// Used by curation tools (`get_view`, `update_view`) so callers can pass a view\n// name without also tracking which file declared it.\n\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { parse } from \"@sightmap/sightmap\";\n\nexport type FindViewOptions = {\n onWarning?: (msg: string) => void;\n};\n\nexport async function findFileForView(\n sightmapDir: string,\n viewName: string,\n options: FindViewOptions = {},\n): Promise<string | null> {\n const entries = await readdir(sightmapDir);\n const yamlFiles = entries\n .filter((e) => e.endsWith(\".yaml\") || e.endsWith(\".yml\"))\n .sort();\n\n let firstMatch: string | null = null;\n let matchCount = 0;\n\n for (const file of yamlFiles) {\n const path = join(sightmapDir, file);\n let parsed;\n try {\n const text = await readFile(path, \"utf8\");\n parsed = parse(text, { sourceFile: path });\n } catch {\n // Skip unparseable files; `sightmap_check` is the right tool for those.\n continue;\n }\n if (parsed.views?.some((v) => v.name === viewName)) {\n matchCount++;\n if (firstMatch === null) firstMatch = path;\n }\n }\n\n if (matchCount > 1 && options.onWarning) {\n options.onWarning(\n `duplicate view name \"${viewName}\" found in ${matchCount} files; using ${firstMatch}`,\n );\n }\n\n return firstMatch;\n}\n","// `sightmap_check` handler.\n//\n// Wraps `@sightmap/sightmap`'s `lint` plus the merge/load diagnostics already\n// attached to the loaded `Sightmap` (parse errors, schema failures, merge\n// collisions). Two levels:\n//\n// schema - return only the schema-level diagnostics already on the sightmap.\n// quality - schema diagnostics plus lint output (duplicate routes, route\n// shadowing, selector syntax, etc.).\n\nimport { lint, type Sightmap, type Diagnostic } from \"@sightmap/sightmap\";\n\nexport interface CheckInput {\n level?: \"schema\" | \"quality\";\n}\n\nexport interface CheckOutput {\n diagnostics: Diagnostic[];\n}\n\nexport async function handleCheck(\n sightmap: Sightmap,\n input: CheckInput,\n): Promise<CheckOutput> {\n const level = input.level ?? \"quality\";\n const schemaDiag = [...sightmap.diagnostics];\n if (level === \"schema\") return { diagnostics: schemaDiag };\n const lintDiag = await lint(sightmap);\n return { diagnostics: [...schemaDiag, ...lintDiag] };\n}\n","// `sightmap_update_view` handler.\n//\n// Reads the YAML file containing the named view, applies a patch to the\n// view's fields, then re-writes the file via the canonical writer. The\n// emitted bytes are piped through `canonicalize()` so the result passes\n// `sightmap fmt --check` (per sightmap spec adapter-behavior guidance).\n//\n// Accepts both semantic edits (description, intent, memory_append/replace)\n// and structural edits (name, route, components). Memory edits use either\n// `memory_append` (the default operation) or `memory_replace` — never both\n// in the same patch. Components is a full array replacement; use\n// sightmap_add_view / sightmap_delete_view for whole-view lifecycle.\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport {\n parse,\n format,\n canonicalize,\n type FormatInput,\n type View,\n} from \"@sightmap/sightmap\";\nimport { findFileForView } from \"../../curate/locator.js\";\n\nexport interface ViewPatch {\n // Semantic fields (unchanged — backward-compatible)\n description?: string;\n intent?: string;\n memory_append?: string[];\n memory_replace?: string[];\n // Structural fields (new in 1.0-rc — replaces what codegen used to own)\n name?: string;\n route?: string;\n components?: { name: string; selector: string; memory?: string[] }[];\n}\n\nexport interface UpdateViewInput {\n sightmapDir: string;\n name: string;\n patch: ViewPatch;\n}\n\nexport interface UpdateViewOutput {\n ok: true;\n file: string;\n written: View;\n}\n\nexport async function handleUpdateView(\n input: UpdateViewInput,\n): Promise<UpdateViewOutput> {\n if (input.patch.memory_append && input.patch.memory_replace) {\n throw new Error(\n \"cannot use both memory_append and memory_replace in the same patch\",\n );\n }\n\n const file = await findFileForView(input.sightmapDir, input.name);\n if (file === null) {\n throw new Error(\n `View \"${input.name}\" not found in ${input.sightmapDir}`,\n );\n }\n\n const text = await readFile(file, \"utf8\");\n const parsed = parse(text, { sourceFile: file });\n const views = parsed.views ?? [];\n const idx = views.findIndex((v) => v.name === input.name);\n if (idx < 0) {\n throw new Error(\n `View \"${input.name}\" not found in ${file} (locator drift?)`,\n );\n }\n\n const before = views[idx]!;\n const after: View & { intent?: string } = { ...before };\n if (input.patch.description !== undefined) {\n after.description = input.patch.description;\n }\n if (input.patch.intent !== undefined) {\n after.intent = input.patch.intent;\n }\n if (input.patch.memory_append) {\n after.memory = [...(before.memory ?? []), ...input.patch.memory_append];\n }\n if (input.patch.memory_replace) {\n after.memory = [...input.patch.memory_replace];\n }\n if (input.patch.name !== undefined) {\n after.name = input.patch.name;\n }\n if (input.patch.route !== undefined) {\n after.route = input.patch.route;\n }\n if (input.patch.components !== undefined) {\n // Validate uniqueness of component names within this view.\n const seen = new Set<string>();\n for (const c of input.patch.components) {\n if (seen.has(c.name)) {\n throw new Error(`duplicate component name in patch: ${c.name}`);\n }\n seen.add(c.name);\n }\n after.components = input.patch.components;\n }\n\n const nextViews: View[] = [...views];\n nextViews[idx] = after;\n const nextDoc = stripFragmentBrand(parsed as unknown as Record<string, unknown>);\n nextDoc.views = nextViews;\n const out = format(nextDoc);\n // Pipe through `canonicalize()` so the rewritten file matches what\n // `sightmap fmt --check` expects (per-entry-type key order, top-level seq\n // sort, blank-line separators, etc.). The value object came from the parsed\n // file plus a narrow patch, so canonicalize won't return schema-invalid in\n // practice; fall back to the format() bytes if it does.\n const c = canonicalize(out, { file });\n const finalText = c.kind === \"canonical\" ? c.text : out;\n await writeFile(file, finalText, \"utf8\");\n\n return { ok: true, file, written: after };\n}\n\nfunction stripFragmentBrand(input: Record<string, unknown>): FormatInput {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(input)) {\n if (k === \"__brand\" || k === \"__sourceFile\") continue;\n out[k] = input[k];\n }\n return out as FormatInput;\n}\n","// `sightmap_add_view` handler.\n//\n// Creates a new view by writing a fresh .yaml file under the .sightmap/ dir.\n// The filename defaults to `kebab(view.name) + \".yaml\"` unless overridden via\n// the `file` hint. The emitted bytes are piped through `canonicalize()` so the\n// result passes `sightmap fmt --check` (per sightmap spec adapter-behavior\n// guidance).\n//\n// Refuses to write if a view with the same name already exists anywhere in\n// the corpus — duplicate names would collide at parse-time. Use\n// sightmap_update_view to edit existing views.\n\nimport { writeFile, readFile, readdir } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport {\n format,\n canonicalize,\n type FormatInput,\n type View,\n} from \"@sightmap/sightmap\";\n\nexport interface AddViewInput {\n sightmapDir: string;\n view: View;\n /** Optional filename hint. Defaults to kebab(view.name) + \".yaml\". */\n file?: string;\n}\n\nexport interface AddViewOutput {\n ok: true;\n file: string;\n written: View;\n}\n\nexport async function handleAddView(input: AddViewInput): Promise<AddViewOutput> {\n await ensureNotExists(input.sightmapDir, input.view.name);\n const filename = input.file ?? kebab(input.view.name) + \".yaml\";\n const path = join(input.sightmapDir, filename);\n const doc: FormatInput = {\n version: 1,\n views: [input.view],\n };\n const out = format(doc);\n // Pipe through canonicalize() so the new file matches what `sightmap fmt\n // --check` expects (per-entry-type key order, blank-line separators, etc.).\n // Fall back to the raw format() bytes if canonicalize can't normalize.\n const c = canonicalize(out, { file: path });\n const text = c.kind === \"canonical\" ? c.text : out;\n await writeFile(path, text, \"utf8\");\n return { ok: true, file: path, written: input.view };\n}\n\nasync function ensureNotExists(dir: string, name: string): Promise<void> {\n let files: string[];\n try {\n files = await readdir(dir);\n } catch {\n return; // empty/missing dir, nothing to check\n }\n for (const f of files) {\n if (!f.endsWith(\".yaml\")) continue;\n const text = await readFile(resolve(dir, f), \"utf8\");\n if (new RegExp(`(^|\\\\n)\\\\s*-\\\\s+name:\\\\s+${escapeRe(name)}(\\\\s|$)`).test(text)) {\n throw new Error(`view \"${name}\" already exists in ${f}`);\n }\n }\n}\n\nfunction kebab(s: string): string {\n return s\n .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n .replace(/[\\s_]+/g, \"-\")\n .toLowerCase();\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","// `sightmap_delete_view` handler.\n//\n// Removes a view by name. Scans every .yaml file under the curate root for an\n// entry with the matching name. If the containing file has only the deleted\n// view, the file itself is unlinked; otherwise the view is spliced out and\n// the file rewritten via the canonical writer (so it still passes\n// `sightmap fmt --check`).\n//\n// Symmetric counterpart to sightmap_add_view: together they let an agent\n// fully manage view lifecycle without invoking codegen.\n\nimport { readFile, writeFile, unlink, readdir } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport {\n parse,\n format,\n canonicalize,\n type FormatInput,\n type View,\n} from \"@sightmap/sightmap\";\n\nexport interface DeleteViewInput {\n sightmapDir: string;\n name: string;\n}\n\nexport interface DeleteViewOutput {\n ok: true;\n file: string;\n fileDeleted: boolean;\n}\n\nexport async function handleDeleteView(\n input: DeleteViewInput,\n): Promise<DeleteViewOutput> {\n const entries = await readdir(input.sightmapDir);\n for (const entry of entries) {\n if (!entry.endsWith(\".yaml\")) continue;\n const path = resolve(input.sightmapDir, entry);\n const text = await readFile(path, \"utf8\");\n const parsed = parse(text, { sourceFile: path });\n const views = parsed.views ?? [];\n const idx = views.findIndex((v) => v.name === input.name);\n if (idx < 0) continue;\n const remaining = views.filter((_, i) => i !== idx);\n if (remaining.length === 0) {\n await unlink(path);\n return { ok: true, file: path, fileDeleted: true };\n }\n const nextDoc = stripFragmentBrand(parsed as unknown as Record<string, unknown>);\n nextDoc.views = remaining as View[];\n const out = format(nextDoc);\n // Pipe through `canonicalize()` so the rewritten file matches what\n // `sightmap fmt --check` expects (per-entry-type key order, top-level seq\n // sort, blank-line separators, etc.). Fall back to format() bytes if it\n // can't normalize.\n const c = canonicalize(out, { file: path });\n const finalText = c.kind === \"canonical\" ? c.text : out;\n await writeFile(path, finalText, \"utf8\");\n return { ok: true, file: path, fileDeleted: false };\n }\n throw new Error(`view \"${input.name}\" not found in ${input.sightmapDir}`);\n}\n\nfunction stripFragmentBrand(input: Record<string, unknown>): FormatInput {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(input)) {\n if (k === \"__brand\" || k === \"__sourceFile\") continue;\n out[k] = input[k];\n }\n return out as FormatInput;\n}\n","// `sightmap_init_project` handler.\n//\n// Scaffolds an empty `.sightmap/app.yaml` in a target project directory.\n// Refuses to overwrite an existing `.sightmap/` unless `force: true`.\n\nimport { mkdir, writeFile, access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { makeStarterSightmap } from \"../../curate/scaffolder.js\";\n\nexport interface InitProjectInput {\n dir?: string;\n force?: boolean;\n}\n\nexport interface InitProjectOutput {\n ok: true;\n files: string[];\n}\n\nexport async function handleInitProject(\n input: InitProjectInput,\n): Promise<InitProjectOutput> {\n const root = input.dir ?? process.cwd();\n const sightmapDir = join(root, \".sightmap\");\n const appFile = join(sightmapDir, \"app.yaml\");\n\n if (input.force !== true) {\n let exists = false;\n try {\n await access(sightmapDir);\n exists = true;\n } catch {\n /* dir does not exist; continue */\n }\n if (exists) {\n throw new Error(\n `.sightmap/ already exists at ${sightmapDir} — pass force=true to overwrite`,\n );\n }\n }\n\n await mkdir(sightmapDir, { recursive: true });\n await writeFile(appFile, makeStarterSightmap(), \"utf8\");\n\n return { ok: true, files: [appFile] };\n}\n","// Starter `.sightmap/` scaffolding.\n//\n// `makeStarterSightmap` returns a minimal canonical YAML document — just a\n// `version: 1` line with no views/components/requests. Real content lands when\n// the user (or `sightmap-react gen`) adds files to the directory.\n//\n// Output is piped through `canonicalize()` so the emitted bytes match what\n// `sightmap fmt --check` expects. See sightmap/spec\n// docs/authoring-conventions.md#adapter-behavior.\n\nimport { format, canonicalize } from \"@sightmap/sightmap\";\n\nexport function makeStarterSightmap(): string {\n const text = format({ version: 1 });\n const c = canonicalize(text, { file: \"app.yaml\" });\n return c.kind === \"canonical\" ? c.text : text;\n}\n","// sightmap_runtime_snapshot: fetch a live SightmapSnapshot from a running app.\n//\n// Three capture modes:\n//\n// - `endpoint` — HTTP GET against the @sightmap/react Vite plugin endpoint.\n// Zero-config for Vite users; the plugin already serves the cached\n// snapshot at /__sightmap__/snapshot.json.\n//\n// - `browser` — drive the live browser via the @playwright/mcp passthrough.\n// Navigate to `url` (or each entry in `routes`), evaluate\n// `window.__sightmap__.snapshot()`, return the result. The bippy IIFE +\n// bootstrap are pre-navigate addInitScript'd at sightmap-mcp startup\n// (via @playwright/mcp's PLAYWRIGHT_MCP_INIT_SCRIPT env var) so the hook\n// is installed BEFORE React's first commit — works on any React app,\n// including static first-paint apps that previously yielded commits: 0.\n// A post-navigate browser_evaluate inject remains as a fallback for\n// environments where the pre-nav init script couldn't be wired.\n//\n// - `literal` — accept a pre-captured snapshot from any source (subtext's\n// live-eval-script, devtools console paste, custom Playwright scripts,\n// CI capture). Validates the shape; returns it. The universal escape\n// valve for cases where MCP can't reach the browser itself.\n\nimport type { UpstreamClient } from \"../../server.js\";\n\nexport interface RuntimeSnapshotInput {\n source:\n | { kind: \"endpoint\"; url: string }\n | {\n kind: \"browser\";\n url: string;\n routes?: string[];\n /**\n * If true (default when `window.__sightmap__` is missing), addInitScript\n * the bippy IIFE + snapshot bootstrap before navigation. Set to false\n * to require the app to already have @sightmap/react installed.\n */\n inject?: boolean;\n }\n | { kind: \"literal\"; snapshot: unknown };\n}\n\nexport type RuntimeSnapshotOutput =\n | { ok: true; snapshot: unknown; source: RuntimeSnapshotInput[\"source\"] }\n | {\n ok: true;\n snapshots: { url: string; snapshot: unknown }[];\n source: RuntimeSnapshotInput[\"source\"];\n };\n\nexport interface RuntimeSnapshotDeps {\n /** Upstream MCP client (typically @playwright/mcp). Required for browser mode. */\n upstream?: UpstreamClient;\n /** Provides the inject script (bippy IIFE + bootstrap) lazily. */\n getInjectScript?: () => Promise<string>;\n}\n\nexport async function handleRuntimeSnapshot(\n input: RuntimeSnapshotInput,\n deps: RuntimeSnapshotDeps = {},\n): Promise<RuntimeSnapshotOutput> {\n if (input.source.kind === \"endpoint\") {\n return runEndpoint(input.source);\n }\n if (input.source.kind === \"literal\") {\n return runLiteral(input.source);\n }\n return runBrowser(input.source, deps);\n}\n\nasync function runEndpoint(\n source: Extract<RuntimeSnapshotInput[\"source\"], { kind: \"endpoint\" }>,\n): Promise<RuntimeSnapshotOutput> {\n const res = await fetch(source.url);\n if (res.status === 404) {\n // The plugin returns 404 with a JSON body when no snapshot has been\n // cached yet (the user hasn't loaded a page that mounts a Provider).\n // Surface the body's `error` field so the agent's error includes the\n // root cause, not just the HTTP code.\n let detail = \"\";\n try {\n const body = (await res.json()) as { error?: string };\n detail = body.error ?? \"\";\n } catch {\n // body wasn't JSON; ignore\n }\n throw new Error(\n `no snapshot cached yet at ${source.url}${detail ? `: ${detail}` : \"\"}`,\n );\n }\n if (!res.ok) {\n throw new Error(`snapshot fetch failed: HTTP ${res.status}`);\n }\n const snapshot = (await res.json()) as unknown;\n return { ok: true, snapshot, source };\n}\n\nconst REQUIRED_SNAPSHOT_FIELDS = [\n \"capturedAt\",\n \"route\",\n \"components\",\n \"markers\",\n \"unmarkedCandidates\",\n] as const;\n\nfunction runLiteral(\n source: Extract<RuntimeSnapshotInput[\"source\"], { kind: \"literal\" }>,\n): RuntimeSnapshotOutput {\n validateSnapshotShape(source.snapshot, \"literal\");\n return { ok: true, snapshot: source.snapshot, source };\n}\n\n/**\n * Validate that `value` looks like a SightmapSnapshot. Throws a clear error\n * on the first missing field. Intentionally lenient: only checks for the\n * required top-level keys; nested shapes are trusted to the upstream\n * producer (the plugin, the user's eval, or our injected bootstrap).\n */\nfunction validateSnapshotShape(value: unknown, label: string): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `${label} snapshot: expected an object with fields ` +\n `{ capturedAt, route, components, markers, unmarkedCandidates }; ` +\n `got ${value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value}`,\n );\n }\n const s = value as Record<string, unknown>;\n for (const field of REQUIRED_SNAPSHOT_FIELDS) {\n if (!(field in s)) {\n throw new Error(`${label} snapshot: missing required field \\`${field}\\``);\n }\n }\n if (!Array.isArray(s[\"components\"])) {\n throw new Error(`${label} snapshot: \\`components\\` must be an array`);\n }\n if (!Array.isArray(s[\"markers\"])) {\n throw new Error(`${label} snapshot: \\`markers\\` must be an array`);\n }\n if (!Array.isArray(s[\"unmarkedCandidates\"])) {\n throw new Error(`${label} snapshot: \\`unmarkedCandidates\\` must be an array`);\n }\n}\n\nasync function runBrowser(\n source: Extract<RuntimeSnapshotInput[\"source\"], { kind: \"browser\" }>,\n deps: RuntimeSnapshotDeps,\n): Promise<RuntimeSnapshotOutput> {\n if (deps.upstream === undefined) {\n throw new Error(\n \"browser-mode snapshot requires an upstream MCP server (e.g., @playwright/mcp). \" +\n \"Run sightmap-mcp without `--curate-only` so the @playwright/mcp passthrough is wired up.\",\n );\n }\n const upstream = deps.upstream;\n\n // Decide whether to inject. Defaults: when `inject` is explicit, honor it;\n // when omitted, auto-detect by probing window.__sightmap__ after navigation\n // — if absent, evaluate the inject script post-navigate as a fallback.\n const wantInject = source.inject === true;\n const allowAutoInject = source.inject === undefined;\n\n // Injection is normally wired pre-navigate via the upstream\n // (@playwright/mcp >= 0.0.75) `PLAYWRIGHT_MCP_INIT_SCRIPT` / `--init-script`,\n // configured at sightmap-mcp startup in cli.ts. That path installs bippy +\n // bootstrap BEFORE any page script runs, so window.__sightmap__.snapshot\n // is present before React's first commit. The post-navigate\n // browser_evaluate inject below is the belt-and-suspenders fallback for:\n // - servers where the pre-nav init script couldn't be written (rare),\n // - hosts that filter env vars and strip PLAYWRIGHT_MCP_INIT_SCRIPT,\n // - users running an older @playwright/mcp pinned via `--`,\n // and so on. When pre-nav inject works (the common case) the probe below\n // returns \"function\" and the post-nav inject is skipped.\n\n const urls = source.routes !== undefined && source.routes.length > 0\n ? source.routes.map((r) => absolutize(r, source.url))\n : [source.url];\n\n const captures: { url: string; snapshot: unknown }[] = [];\n for (const targetUrl of urls) {\n const captureOpts: CaptureOpts = {\n forceInject: wantInject,\n autoInject: allowAutoInject,\n };\n if (deps.getInjectScript !== undefined) {\n captureOpts.getInjectScript = deps.getInjectScript;\n }\n const cap = await captureOneUrl(upstream, targetUrl, captureOpts);\n validateSnapshotShape(cap, \"browser\");\n captures.push({ url: targetUrl, snapshot: cap });\n }\n\n if (source.routes === undefined || source.routes.length === 0) {\n return { ok: true, snapshot: captures[0]!.snapshot, source };\n }\n return { ok: true, snapshots: captures, source };\n}\n\nfunction absolutize(routeOrUrl: string, baseUrl: string): string {\n // If the entry parses as an absolute URL, return as-is. Otherwise treat it\n // as a path on the same origin as `baseUrl`.\n try {\n return new URL(routeOrUrl).toString();\n } catch {\n const base = new URL(baseUrl);\n return new URL(routeOrUrl, base).toString();\n }\n}\n\ninterface CaptureOpts {\n forceInject: boolean;\n autoInject: boolean;\n getInjectScript?: () => Promise<string>;\n}\n\nasync function captureOneUrl(\n upstream: UpstreamClient,\n url: string,\n opts: CaptureOpts,\n): Promise<unknown> {\n // Navigate first.\n const navResult = await upstream.callTool(\"browser_navigate\", { url });\n if (navResult.isError === true) {\n throw new Error(\n `browser_navigate to ${url} failed: ${navResult.content[0]?.text ?? \"unknown error\"}`,\n );\n }\n\n // Probe for window.__sightmap__. Decoded JSON value: \"function\" | \"object\" | \"undefined\".\n const probe = await evalAndDecode(\n upstream,\n `() => typeof (window.__sightmap__ && window.__sightmap__.snapshot)`,\n );\n const hasHook = probe === \"function\";\n\n if (!hasHook && (opts.forceInject || opts.autoInject)) {\n if (opts.getInjectScript === undefined) {\n throw new Error(\n \"browser-mode snapshot: page has no window.__sightmap__ and no inject script provider was configured. \" +\n \"Install @sightmap/react in the target app, or wire `getInjectScript` into the MCP server.\",\n );\n }\n const script = await opts.getInjectScript();\n // The script is a self-installing IIFE. Wrap it as a fn body for\n // browser_evaluate: it expects `() => { ... }` and the script's own\n // outermost IIFE runs as part of `value` evaluation.\n const wrapped = `() => { ${script}\\n; return typeof (window.__sightmap__ && window.__sightmap__.snapshot); }`;\n const injectResult = await evalAndDecode(upstream, wrapped);\n if (injectResult !== \"function\") {\n throw new Error(\n `browser-mode snapshot: inject script did not install window.__sightmap__.snapshot ` +\n `(typeof after inject: ${String(injectResult)}). The target page may not be a React app.`,\n );\n }\n } else if (!hasHook && opts.forceInject === false && opts.autoInject === false) {\n throw new Error(\n \"browser-mode snapshot: page has no window.__sightmap__.snapshot and `inject: false` was set. \" +\n \"Either install @sightmap/react in the app or pass `inject: true`.\",\n );\n }\n\n // Evaluate the snapshot. We wrap with JSON.parse(JSON.stringify(...)) to\n // force a plain serializable value (defends against Sets / Maps / Dates\n // that the upstream's stringify path might mangle).\n const snap = await evalAndDecode(\n upstream,\n `() => JSON.parse(JSON.stringify(window.__sightmap__.snapshot()))`,\n );\n return snap;\n}\n\nasync function evalAndDecode(\n upstream: UpstreamClient,\n fnSource: string,\n): Promise<unknown> {\n const r = await upstream.callTool(\"browser_evaluate\", { function: fnSource });\n if (r.isError === true) {\n throw new Error(\n `browser_evaluate failed: ${r.content[0]?.text ?? \"unknown error\"}`,\n );\n }\n const text = r.content.map((b) => b.text).join(\"\\n\");\n return decodeEvalText(text);\n}\n\n/**\n * Decode a @playwright/mcp `browser_evaluate` response into the raw JS value.\n *\n * The upstream wraps the result as a text block containing a `### Result`\n * header followed by the JSON-encoded value. We scan for the first complete\n * JSON token after the header.\n */\nfunction decodeEvalText(text: string): unknown {\n const afterResult = text.split(/^###\\s*Result/im)[1] ?? text;\n const trimmed = afterResult.trim();\n if (trimmed.length === 0) return undefined;\n // Try whole-string parse first (handles the simple case where the result\n // payload IS the trimmed text).\n for (let end = trimmed.length; end > 0; end--) {\n try {\n return JSON.parse(trimmed.slice(0, end));\n } catch {\n // try shorter\n }\n }\n return undefined;\n}\n","// Build the browser-side inject script for `sightmap_runtime_snapshot`'s\n// `kind: \"browser\"` mode.\n//\n// The script has two parts, concatenated:\n//\n// 1. bippy's IIFE bundle (read once from node_modules/bippy/dist/index.iife.js).\n// Exposes `window.Bippy` with `instrument`, `traverseFiber`, `getDisplayName`,\n// `isCompositeFiber`.\n//\n// 2. A small bootstrap (BOOTSTRAP_SRC below) that:\n// - calls `Bippy.instrument({ onCommitFiberRoot })` to capture FiberRoots\n// - defines `window.__sightmap__.snapshot()` that serializes the fiber\n// tree into the same SightmapSnapshot shape the @sightmap/react\n// runtime produces, so the rest of the pipeline (audit, propose,\n// match) treats inject-mode output identically to plugin-endpoint\n// output.\n//\n// This script is `addInitScript`-injected before navigation when the caller\n// requests `inject: true` (or when auto-detection finds `window.__sightmap__`\n// absent on the target page). One file, no build-time bundling — easier to\n// debug and keeps `@sightmap/mcp`'s tsup config unchanged.\n\nimport { createRequire } from \"node:module\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nlet cachedScript: string | undefined;\n\n/**\n * Returns the full inject script (bippy IIFE + bootstrap), cached after the\n * first call. Reads bippy's IIFE lazily so test environments that never\n * exercise browser mode don't pay for it.\n */\nexport async function getInjectScript(): Promise<string> {\n if (cachedScript !== undefined) return cachedScript;\n const bippyIife = await loadBippyIife();\n cachedScript = `${bippyIife}\\n${BOOTSTRAP_SRC}`;\n return cachedScript;\n}\n\nasync function loadBippyIife(): Promise<string> {\n // Resolve bippy from this module's location. Works under both pnpm's\n // .pnpm/ layout and a flat hoisted node_modules.\n const require = createRequire(import.meta.url);\n const bippyPkgJson = require.resolve(\"bippy/package.json\");\n const iifePath = resolve(dirname(bippyPkgJson), \"dist/index.iife.js\");\n return readFile(iifePath, \"utf8\");\n}\n\n// Bootstrap script: pure JS string. Mirrors packages/react/src/runtime\n// (bippy-install + serialize + rank-selectors + portal-aware-walker), pared\n// down to the minimum needed by `sightmap_runtime_snapshot { kind: \"browser\" }`.\n//\n// Kept in sync with serialize.ts by convention; if the snapshot schema\n// evolves, update both call sites.\nconst BOOTSTRAP_SRC = String.raw`\n(function () {\n if (typeof window === \"undefined\") return;\n if (!window.Bippy || typeof window.Bippy.instrument !== \"function\") return;\n if (window.__sightmap__ && typeof window.__sightmap__.snapshot === \"function\") {\n // Already installed (e.g. @sightmap/react is present). Don't double-wire.\n return;\n }\n\n var trackedRoots = new Set();\n window.Bippy.instrument({\n onCommitFiberRoot: function (_id, root) {\n trackedRoots.add(root);\n },\n });\n\n var FRAMEWORK_NOISE = new Set([\n \"Routes\", \"Route\", \"RenderedRoute\", \"Outlet\", \"BrowserRouter\",\n \"Router\", \"RouterProvider\", \"DataRouterProvider\", \"RouterProviderImpl\",\n \"LinkWithRef\", \"StrictMode\", \"SightmapProvider\", \"Fragment\", \"Anonymous\",\n \"Suspense\", \"ErrorBoundary\", \"Provider\", \"Consumer\",\n \"ThemeProvider\", \"Hydration\", \"HydrateFallback\",\n \"RemixErrorBoundary\", \"HydratedRouter\", \"DataRoutes\",\n \"WithHydrateFallbackProps2\", \"RenderErrorBoundary\", \"Layout\",\n ]);\n\n var HOST_PORTAL_TAG = 4;\n\n function cssEsc(v) { return String(v).replace(/\"/g, '\\\\\"'); }\n function isHumanShapedId(id) {\n if (/[0-9]{6,}/.test(id)) return false;\n if (/^[a-z]+-[a-f0-9]{8,}/i.test(id)) return false;\n if (/:r[0-9a-z]+:/i.test(id)) return false;\n return true;\n }\n function rankSelectors(el) {\n var out = [];\n var dsm = el.getAttribute(\"data-sightmap\");\n if (dsm !== null) {\n out.push({ selector: '[data-sightmap=\"' + cssEsc(dsm) + '\"]', stability: \"high\", source: \"data-sightmap\" });\n }\n [\"data-testid\", \"data-cy\", \"data-test\"].forEach(function (attr) {\n var v = el.getAttribute(attr);\n if (v !== null) {\n out.push({ selector: \"[\" + attr + '=\"' + cssEsc(v) + '\"]', stability: \"high\", source: attr });\n }\n });\n var role = el.getAttribute(\"role\");\n var aria = el.getAttribute(\"aria-label\");\n if (role && aria) {\n out.push({ selector: '[role=\"' + cssEsc(role) + '\"][aria-label=\"' + cssEsc(aria) + '\"]', stability: \"medium\", source: \"aria\" });\n } else if (aria) {\n out.push({ selector: '[aria-label=\"' + cssEsc(aria) + '\"]', stability: \"medium\", source: \"aria-label\" });\n }\n var name = el.getAttribute(\"name\");\n if (name !== null && /^(form|input|button|select|textarea|nav)$/i.test(el.tagName)) {\n out.push({ selector: el.tagName.toLowerCase() + '[name=\"' + cssEsc(name) + '\"]', stability: \"medium\", source: \"semantic-name\" });\n }\n if (el.id && isHumanShapedId(el.id)) {\n out.push({ selector: \"#\" + cssEsc(el.id), stability: \"high\", source: \"id\" });\n }\n return out;\n }\n\n function findHostElementForFiber(fiber) {\n if (!fiber.child) return null;\n var stack = [fiber.child];\n var walks = 0;\n while (stack.length > 0 && walks < 5000) {\n walks++;\n var f = stack.pop();\n if (!f) continue;\n if (f.sibling) stack.push(f.sibling);\n if (f.tag === HOST_PORTAL_TAG) continue;\n var sn = f.stateNode;\n if (sn && typeof sn === \"object\" && \"tagName\" in sn && document.contains(sn)) {\n return sn;\n }\n if (f.child) stack.push(f.child);\n }\n return null;\n }\n\n function bridgeDomToFiber(el) {\n for (var i = 0, keys = Object.keys(el); i < keys.length; i++) {\n if (keys[i].indexOf(\"__reactFiber$\") === 0) return el[keys[i]] || null;\n }\n return null;\n }\n\n function nearestCompositeName(fiber) {\n var f = fiber, walks = 0;\n while (f && walks < 50) {\n if (window.Bippy.isCompositeFiber(f)) {\n var n = window.Bippy.getDisplayName(f);\n if (n) return n;\n }\n f = f.return;\n walks++;\n }\n return undefined;\n }\n\n function domDepth(el) {\n var d = 0, cur = el.parentElement;\n while (cur && cur !== document.body) { d++; cur = cur.parentElement; }\n return d;\n }\n\n function collectComponents(rootFiber) {\n var out = [];\n var depthByFiber = new Map();\n depthByFiber.set(rootFiber, 0);\n window.Bippy.traverseFiber(rootFiber, function (f) {\n var depth = depthByFiber.get(f) || 0;\n var c = f.child;\n while (c) { depthByFiber.set(c, depth + 1); c = c.sibling; }\n if (!window.Bippy.isCompositeFiber(f)) return false;\n var name = window.Bippy.getDisplayName(f);\n if (!name) return false;\n var childNames = [];\n var cc = f.child;\n while (cc) {\n if (window.Bippy.isCompositeFiber(cc)) {\n var n = window.Bippy.getDisplayName(cc);\n if (n) childNames.push(n);\n }\n cc = cc.sibling;\n }\n out.push({ displayName: name, depth: depth, children: childNames });\n return false;\n });\n return out;\n }\n\n function collectMarkers() {\n var out = [];\n if (typeof document === \"undefined\") return out;\n var els = document.querySelectorAll(\"[data-sightmap]\");\n for (var i = 0; i < els.length; i++) {\n var el = els[i];\n var name = el.getAttribute(\"data-sightmap\") || \"\";\n var fiber = bridgeDomToFiber(el);\n var nc = nearestCompositeName(fiber);\n var marker = {\n name: name,\n hostTag: el.tagName.toLowerCase(),\n domDepth: domDepth(el),\n candidateSelectors: rankSelectors(el),\n };\n if (nc !== undefined) marker.nearestComponent = nc;\n out.push(marker);\n }\n return out;\n }\n\n function collectUnmarkedCandidates(rootFiber) {\n var out = [];\n var seen = new Set();\n window.Bippy.traverseFiber(rootFiber, function (f) {\n if (!window.Bippy.isCompositeFiber(f)) return false;\n var name = window.Bippy.getDisplayName(f);\n if (!name || seen.has(name) || FRAMEWORK_NOISE.has(name)) return false;\n seen.add(name);\n var hostEl = findHostElementForFiber(f);\n if (!hostEl) return false;\n var selectors = rankSelectors(hostEl);\n if (selectors.length === 0) return false;\n out.push({\n displayName: name,\n hostTag: hostEl.tagName.toLowerCase(),\n selectors: selectors,\n domDepth: domDepth(hostEl),\n });\n return false;\n });\n return out;\n }\n\n function snapshot() {\n var roots = Array.from(trackedRoots);\n var now = new Date().toISOString();\n var loc = (typeof window !== \"undefined\" && window.location)\n ? (window.location.pathname + (window.location.search || \"\"))\n : \"?\";\n if (roots.length === 0) {\n return { capturedAt: now, route: loc === \"?\" ? \"?\" : loc, commits: 0, components: [], markers: [], unmarkedCandidates: [] };\n }\n var root = roots.find(function (r) { return r.current && r.current.child !== null; }) || roots[0];\n if (!root) {\n return { capturedAt: now, route: loc === \"?\" ? \"?\" : loc, commits: 0, components: [], markers: [], unmarkedCandidates: [] };\n }\n var rootFiber = root.current;\n return {\n capturedAt: now,\n route: loc,\n commits: roots.length,\n components: collectComponents(rootFiber),\n markers: collectMarkers(),\n unmarkedCandidates: collectUnmarkedCandidates(rootFiber),\n };\n }\n\n window.__sightmap__ = { snapshot: snapshot };\n})();\n`;\n","import type {\n ProposedView,\n ProposedComponent,\n ReviewResult,\n CommitInput,\n} from \"./types.js\";\n\nexport class ProposalStore {\n private views: ProposedView[] = [];\n private components: ProposedComponent[] = [];\n private nextId = 1;\n\n private mintId(prefix: string): string {\n return `${prefix}_${this.nextId++}`;\n }\n\n appendView(p: Omit<ProposedView, \"id\">): ProposedView {\n const v: ProposedView = { id: this.mintId(\"v\"), ...p };\n this.views.push(v);\n return v;\n }\n\n appendComponent(p: Omit<ProposedComponent, \"id\">): ProposedComponent {\n const c: ProposedComponent = { id: this.mintId(\"c\"), ...p };\n this.components.push(c);\n return c;\n }\n\n review(): ReviewResult {\n return { views: [...this.views], components: [...this.components] };\n }\n\n commit(input: CommitInput = {}): ReviewResult {\n if (!input.ids) {\n const out = this.review();\n this.views = [];\n this.components = [];\n return out;\n }\n const selected = new Set(input.ids);\n const consumedViews = this.views.filter((v) => selected.has(v.id));\n const consumedComponents = this.components.filter((c) => selected.has(c.id));\n this.views = this.views.filter((v) => !selected.has(v.id));\n this.components = this.components.filter((c) => !selected.has(c.id));\n return { views: consumedViews, components: consumedComponents };\n }\n}\n\n/**\n * Process-wide singleton. The MCP server is a single process per session, so\n * one global queue is correct. If we ever multi-tenant, replace with a per-\n * session map keyed off the JSON-RPC client id.\n */\nexport const proposalStore = new ProposalStore();\n","// `sightmap_propose_view` handler.\n//\n// Stages a proposed view observation in the in-memory proposal store. Does NOT\n// write to disk. Use `sightmap_commit_proposals` to persist staged proposals\n// via `sightmap_add_view`.\n//\n// Part of the agent-curation loop: agents call propose_view as they observe\n// noteworthy views during runtime exploration; the staging area is reviewed\n// and committed in a separate step.\n\nimport { proposalStore } from \"./store.js\";\nimport type { ProposedView } from \"./types.js\";\n\nexport type ProposeViewInput = Omit<ProposedView, \"id\">;\nexport interface ProposeViewOutput {\n ok: true;\n id: string;\n}\n\nexport async function handleProposeView(\n input: ProposeViewInput,\n): Promise<ProposeViewOutput> {\n const v = proposalStore.appendView(input);\n return { ok: true, id: v.id };\n}\n","// `sightmap_propose_component` handler.\n//\n// Stages a proposed component observation in the in-memory proposal store.\n// Does NOT write to disk. Components are usually attached to a view at commit\n// time (Phase 3); for now they accumulate alongside view proposals and surface\n// through `sightmap_review_proposals`.\n\nimport { proposalStore } from \"./store.js\";\nimport type { ProposedComponent } from \"./types.js\";\n\nexport type ProposeComponentInput = Omit<ProposedComponent, \"id\">;\nexport interface ProposeComponentOutput {\n ok: true;\n id: string;\n}\n\nexport async function handleProposeComponent(\n input: ProposeComponentInput,\n): Promise<ProposeComponentOutput> {\n const c = proposalStore.appendComponent(input);\n return { ok: true, id: c.id };\n}\n","// `sightmap_review_proposals` handler.\n//\n// Returns the current staged proposals (views + components) without consuming\n// the queue. Read-only — purely a peek into the proposal store so the agent\n// can sanity-check the batch before committing.\n\nimport { proposalStore } from \"./store.js\";\nimport type { ReviewResult } from \"./types.js\";\n\nexport async function handleReviewProposals(): Promise<ReviewResult> {\n return proposalStore.review();\n}\n","// `sightmap_commit_proposals` handler.\n//\n// Promotes staged proposals to disk by delegating to `sightmap_add_view` for\n// each consumed view. Two modes:\n// - dry_run: peek at what *would* be committed without consuming the queue\n// and without writing anything. Used by the plugin's skill to preview\n// before final write.\n// - real run: consume matching proposals from the store and write yaml files.\n//\n// `ids` (optional) restricts the operation to a selected subset; if omitted,\n// every staged proposal is consumed/peeked.\n//\n// Components in the queue are currently surfaced in the `committed` payload\n// but not written to their own files (Phase 3 will attach them to views).\n\nimport { proposalStore } from \"./store.js\";\nimport { handleAddView } from \"../curate/add.js\";\nimport type { ReviewResult } from \"./types.js\";\n\nexport interface CommitProposalsInput {\n sightmapDir: string;\n ids?: string[];\n dry_run?: boolean;\n}\n\nexport interface CommitProposalsOutput {\n ok: true;\n committed: ReviewResult;\n writes: { kind: \"view\"; file: string }[];\n}\n\nexport async function handleCommitProposals(\n input: CommitProposalsInput,\n): Promise<CommitProposalsOutput> {\n if (input.dry_run === true) {\n const peek = proposalStore.review();\n const selectedIds = input.ids ? new Set(input.ids) : null;\n const filtered: ReviewResult = {\n views: selectedIds\n ? peek.views.filter((v) => selectedIds.has(v.id))\n : peek.views,\n components: selectedIds\n ? peek.components.filter((c) => selectedIds.has(c.id))\n : peek.components,\n };\n return { ok: true, committed: filtered, writes: [] };\n }\n\n const consumed = proposalStore.commit(\n input.ids ? { ids: input.ids } : {},\n );\n const writes: { kind: \"view\"; file: string }[] = [];\n for (const v of consumed.views) {\n const r = await handleAddView({\n sightmapDir: input.sightmapDir,\n view: {\n name: v.name ?? deriveName(v.route),\n route: v.route,\n components: [],\n ...(v.intent !== undefined ? { intent: v.intent } : {}),\n ...(v.memory_notes && v.memory_notes.length > 0\n ? { memory: v.memory_notes }\n : {}),\n },\n });\n writes.push({ kind: \"view\", file: r.file });\n }\n return { ok: true, committed: consumed, writes };\n}\n\nfunction deriveName(route: string): string {\n const parts = route\n .replace(/^\\/+|\\/+$/g, \"\")\n .split(\"/\")\n .filter((p) => p.length > 0);\n const last = parts[parts.length - 1] ?? \"Index\";\n return last\n .replace(/[-_]/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n .replace(/\\s+/g, \"\");\n}\n","import type { PromptEntry, PromptResult } from \"./index.js\";\n\n/**\n * sightmap_sep_track — multi-phase prompt that walks an author through\n * writing a Sightmap Enhancement Proposal, the matching spec/ change,\n * and the matching conformance/ fixture.\n *\n * Phase model:\n * draft → write seps/NNNN-{slug}.md, then STOP for user confirmation\n * spec → propose a diff against spec/, then STOP for user confirmation\n * fixture → create conformance/NNN-{slug}/, then STOP for user confirmation\n * verify → terminal summary message, no further phases\n *\n * Confirmation gates are encoded as text directives in each non-final phase\n * because MCP prompts have no native \"wait for user\" primitive. The agent\n * is expected to honor them.\n *\n * Inspired by Archcore's architecture_track (Archcore audit §1.6).\n */\n\nconst VALID_PHASES = [\"draft\", \"spec\", \"fixture\", \"verify\"] as const;\ntype Phase = (typeof VALID_PHASES)[number];\n\nfunction buildDraftPhase(args: { slug?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n return [\n `# SEP track — phase 1 of 4: Draft the SEP`,\n ``,\n `You are helping the user author a Sightmap Enhancement Proposal (SEP).`,\n `An SEP is required for any change to the spec's schema, semantics, or`,\n `discovery rules. See \\`seps/README.md\\` for the full list.`,\n ``,\n `## Steps for this phase`,\n ``,\n `1. **Pick a number.** Look at \\`seps/\\` and find the lowest unused 4-digit`,\n ` integer (skip \\`0000-template.md\\`). Call this NNNN.`,\n `2. **Copy the template.** \\`cp seps/0000-template.md seps/NNNN-${slug}.md\\`.`,\n `3. **Fill in the front-matter.** Title, author, today's date, status: Draft.`,\n `4. **Write the body.** Sections from the template:`,\n ` - Summary (one paragraph; treat as the abstract)`,\n ` - Motivation (concrete user-facing problem; name a real app or pattern)`,\n ` - Proposal (Shape, Semantics, Conformance — show YAML, show JSON Schema diff)`,\n ` - Alternatives considered (at least two, including \"do nothing\")`,\n ` - Migration (what changes for existing users)`,\n ` - Open questions`,\n `5. **Read it back.** Does it pass the acceptance checklist in \\`seps/README.md\\`?`,\n ``,\n `## STOP HERE`,\n ``,\n `Show the draft to the user. Ask for explicit \"go\" before continuing.`,\n `Do **not** open the spec edit until the user confirms the SEP draft.`,\n ``,\n `When the user is ready, call this prompt again with`,\n `\\`phase: \"spec\"\\` and pass \\`sep_number: \"NNNN\"\\` and \\`slug: \"${slug}\"\\`.`,\n ].join(\"\\n\");\n}\n\nfunction buildSpecPhase(args: { slug?: string; sep_number?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n const sep = args.sep_number ?? \"NNNN\";\n return [\n `# SEP track — phase 2 of 4: Propose the spec change`,\n ``,\n `Building on \\`seps/${sep}-${slug}.md\\`.`,\n ``,\n `## Steps for this phase`,\n ``,\n `1. **Identify the spec files affected.** Most changes touch:`,\n ` - \\`spec/v1/sightmap.schema.json\\` (the JSON Schema)`,\n ` - \\`spec/v1/sightmap.spec.md\\` (the prose spec)`,\n ` - Possibly \\`spec/v1/examples/\\` if the change adds a shape worth showing`,\n `2. **Make the edits.** Keep the diff small. The SEP is the design doc;`,\n ` the spec edit is the precise textual change.`,\n `3. **Run \\`pnpm -F @sightmap/sightmap test\\`.** Existing examples must still`,\n ` parse and validate, unless the SEP is explicitly breaking — in which`,\n ` case the SEP's Migration section must say so.`,\n `4. **Cross-reference.** Add a \"Spec changes:\" line near the top of the SEP`,\n ` listing the touched files. Add a comment in the schema file pointing`,\n ` back to \\`seps/${sep}-${slug}.md\\` if the rationale isn't obvious from`,\n ` the diff alone.`,\n ``,\n `## STOP HERE`,\n ``,\n `Show the spec diff to the user. Ask for explicit \"go\" before continuing.`,\n `Do **not** start the conformance fixture until the user confirms the spec edit.`,\n ``,\n `When the user is ready, call this prompt again with`,\n `\\`phase: \"fixture\"\\`, \\`sep_number: \"${sep}\"\\`, \\`slug: \"${slug}\"\\`.`,\n ].join(\"\\n\");\n}\n\nfunction buildFixturePhase(args: { slug?: string; sep_number?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n const sep = args.sep_number ?? \"NNNN\";\n // Conformance fixture numbers in this repo are 3-digit; SEP numbers are 4-digit.\n // Drop the leading zero of the SEP number to suggest a fixture number, but\n // tell the agent to verify against existing fixtures.\n const fixtureGuess = sep.startsWith(\"0\") ? sep.slice(1) : sep;\n return [\n `# SEP track — phase 3 of 4: Write the conformance fixture`,\n ``,\n `Building on \\`seps/${sep}-${slug}.md\\` and the spec edit from phase 2.`,\n ``,\n `## Steps for this phase`,\n ``,\n `1. **Pick a fixture number.** Conformance fixtures use 3-digit numbers`,\n ` (\\`001-minimal\\`, \\`002-multi-file-merge\\`, …). Pick the lowest unused`,\n ` number — likely \\`${fixtureGuess}\\` if the SEP and fixture numberings`,\n ` line up, but verify against \\`conformance/\\`.`,\n `2. **Create the directory.** \\`mkdir conformance/${fixtureGuess}-${slug}\\`.`,\n `3. **Write the input.** \\`conformance/${fixtureGuess}-${slug}/sightmap/\\``,\n ` contains one or more \\`.yaml\\` files demonstrating the new behavior.`,\n ` Keep it minimal — one fixture, one behavior under test.`,\n `4. **Write the expected output.** \\`conformance/${fixtureGuess}-${slug}/expected.json\\``,\n ` is the canonical merged + resolved sightmap that any spec-conformant`,\n ` parser must produce. Use the existing \\`@sightmap/sightmap\\` parser`,\n ` to generate the baseline, then hand-audit it against the SEP.`,\n `5. **Run the conformance suite.** \\`pnpm -F @sightmap/sightmap test\\` should`,\n ` pick up the new fixture and validate it.`,\n ``,\n `## STOP HERE`,\n ``,\n `Show the fixture (input + expected.json) to the user. Ask for explicit`,\n `\"go\" before continuing. Do **not** declare the SEP ready for review until`,\n `the user confirms all three artefacts.`,\n ``,\n `When the user is ready, call this prompt again with`,\n `\\`phase: \"verify\"\\`, \\`sep_number: \"${sep}\"\\`, \\`slug: \"${slug}\"\\`.`,\n ].join(\"\\n\");\n}\n\nfunction buildVerifyPhase(args: { slug?: string; sep_number?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n const sep = args.sep_number ?? \"NNNN\";\n return [\n `# SEP track — phase 4 of 4: Verify and hand off`,\n ``,\n `## Summary`,\n ``,\n `SEP ${sep} ← spec edit ← conformance fixture, ready for review.`,\n ``,\n `Three artefacts should now exist on this branch:`,\n ``,\n `- \\`seps/${sep}-${slug}.md\\` (Draft → flip to Review when filing the PR)`,\n `- spec/ edits (listed in the SEP's \"Spec changes:\" line)`,\n `- \\`conformance/<fixture-number>-${slug}/\\` with \\`sightmap/\\` input and`,\n ` \\`expected.json\\` output`,\n ``,\n `## Next steps for the user`,\n ``,\n `1. Open a draft PR titled \"SEP ${sep}: <short title>\".`,\n `2. PR description: link the SEP, the spec diff, and the fixture; link any`,\n ` prior Discussion or Issue.`,\n `3. Flip the SEP front-matter \\`status\\` from \\`Draft\\` to \\`Review\\` when`,\n ` ready for substantive feedback.`,\n `4. Per \\`seps/README.md\\`: minimum review window is 7 days for minor`,\n ` changes, 14 days for anything affecting the JSON Schema.`,\n ``,\n `Track is complete. No further phases.`,\n ].join(\"\\n\");\n}\n\nfunction buildPhase(args: Record<string, string>): string {\n if (typeof args[\"phase\"] !== \"string\" || args[\"phase\"].length === 0) {\n throw new Error(`sightmap_sep_track: argument \"phase\" is required`);\n }\n if (!(VALID_PHASES as readonly string[]).includes(args[\"phase\"])) {\n throw new Error(\n `sightmap_sep_track: unknown phase \"${args[\"phase\"]}\" — expected one of ${VALID_PHASES.join(\", \")}`,\n );\n }\n const phase = args[\"phase\"] as Phase;\n // Build the per-phase argument bag conditionally so undefined values are\n // omitted (required by `exactOptionalPropertyTypes: true`).\n const phaseArgs: { slug?: string; sep_number?: string } = {};\n if (typeof args[\"slug\"] === \"string\") phaseArgs.slug = args[\"slug\"];\n if (typeof args[\"sep_number\"] === \"string\") phaseArgs.sep_number = args[\"sep_number\"];\n switch (phase) {\n case \"draft\":\n return buildDraftPhase(phaseArgs);\n case \"spec\":\n return buildSpecPhase(phaseArgs);\n case \"fixture\":\n return buildFixturePhase(phaseArgs);\n case \"verify\":\n return buildVerifyPhase(phaseArgs);\n }\n}\n\nexport const sepTrackPrompt: PromptEntry = {\n definition: {\n name: \"sightmap_sep_track\",\n description:\n \"Walks an author through writing a Sightmap Enhancement Proposal (SEP), the matching spec/ change, and the matching conformance/ fixture in four phases (draft → spec → fixture → verify). Each non-final phase ends with a confirmation gate — call this prompt again with the next phase only after the user confirms. Inspired by Archcore's architecture_track pattern.\",\n arguments: [\n {\n name: \"phase\",\n description: 'One of \"draft\", \"spec\", \"fixture\", \"verify\". Required.',\n required: true,\n },\n {\n name: \"slug\",\n description: \"Short kebab-case slug for the SEP (e.g. 'extend-memory').\",\n required: false,\n },\n {\n name: \"sep_number\",\n description: 'Four-digit SEP number assigned in phase \"draft\" (e.g. \"0001\").',\n required: false,\n },\n ],\n },\n handler: (args): PromptResult => {\n const text = buildPhase(args);\n return {\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\n };\n },\n};\n","import type { GetPromptResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { sepTrackPrompt } from \"./sepTrack.js\";\n\n/** MCP prompt argument descriptor (mirrors the SDK's PromptArgumentSchema). */\nexport interface PromptArgumentDef {\n name: string;\n description?: string;\n required?: boolean;\n}\n\n/** A prompt the server advertises in `prompts/list`. */\nexport interface PromptDefinition {\n name: string;\n description: string;\n arguments?: PromptArgumentDef[];\n}\n\n/** Result of `prompts/get` — what the agent gets. */\nexport type PromptResult = GetPromptResult;\n\n/** Handler signature: takes user-supplied string args, returns the result. */\nexport type PromptHandler = (args: Record<string, string>) => PromptResult;\n\n/**\n * Promise-tolerant variant for handlers that need IO. None today; reserved.\n */\nexport type AsyncPromptHandler = (args: Record<string, string>) => Promise<PromptResult>;\n\n/** Registry entry pairing a definition with its handler. */\nexport interface PromptEntry {\n definition: PromptDefinition;\n handler: PromptHandler;\n}\n\n/** All prompts the server exposes via `prompts/list` and `prompts/get`. */\nexport const PROMPT_REGISTRY: PromptEntry[] = [sepTrackPrompt];\n","import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { ToolDefinition, ToolResult, UpstreamClient } from \"./server.js\";\n\ninterface SdkTool {\n name: string;\n description?: string;\n inputSchema: ToolDefinition[\"inputSchema\"];\n}\n\ninterface SdkToolsResponse {\n tools: SdkTool[];\n}\n\ninterface SdkContentBlock {\n type: string;\n text?: string;\n data?: string;\n mimeType?: string;\n}\n\ninterface SdkCallResponse {\n content?: SdkContentBlock[];\n isError?: boolean;\n}\n\n/**\n * Wraps a connected `@modelcontextprotocol/sdk` Client and exposes it as\n * the `UpstreamClient` interface that `SightmapMcpServer` consumes.\n *\n * The constructor takes an *already-connected* Client so testing can\n * substitute any duck-typed implementation. The CLI builds the real one.\n */\nexport class McpClientUpstream implements UpstreamClient {\n constructor(private readonly client: Client) {}\n\n async listTools(): Promise<ToolDefinition[]> {\n const r = (await this.client.listTools()) as unknown as SdkToolsResponse;\n return r.tools.map((t) => ({\n name: t.name,\n description: t.description ?? \"\",\n inputSchema: t.inputSchema,\n }));\n }\n\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n const raw = (await this.client.callTool({\n name,\n arguments: args,\n })) as unknown as SdkCallResponse;\n\n const content = (raw.content ?? []).map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { type: \"text\" as const, text: block.text };\n }\n // Non-text content (image, audio, embedded resource): serialize to text\n // so nothing is silently dropped. Agent can decide what to do with the\n // string description.\n return {\n type: \"text\" as const,\n text: stringifyNonTextBlock(block),\n };\n });\n\n return {\n content: content.length > 0 ? content : [{ type: \"text\", text: \"\" }],\n ...(raw.isError === true ? { isError: true } : {}),\n };\n }\n}\n\nfunction stringifyNonTextBlock(block: SdkContentBlock): string {\n const parts: string[] = [`[${block.type}]`];\n if (block.mimeType) parts.push(`mimeType=${block.mimeType}`);\n if (typeof block.data === \"string\") {\n const preview = block.data.length > 64 ? block.data.slice(0, 64) + \"…\" : block.data;\n parts.push(`data=${preview}`);\n }\n return parts.join(\" \");\n}\n","import { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SightmapMcpServer } from \"./server.js\";\n\n/**\n * Wraps a `SightmapMcpServer` (the dispatcher) in an MCP SDK `Server`,\n * registering tools/list, tools/call, prompts/list, and prompts/get handlers\n * that delegate to it.\n *\n * Returns the Server unconnected — caller chooses transport (stdio,\n * InMemoryTransport for tests, etc.) and calls `.connect(transport)`.\n */\nexport function buildMcpServer(dispatcher: SightmapMcpServer): Server {\n const server = new Server(\n { name: \"sightmap-mcp\", version: \"0.0.0\" },\n { capabilities: { tools: {}, prompts: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const tools = await dispatcher.listToolsAsync();\n return { tools };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n const name = req.params.name;\n const args = (req.params.arguments ?? {}) as Record<string, unknown>;\n const result = await dispatcher.callTool(name, args);\n // The SDK's CallToolResult is a discriminated union (regular result vs.\n // long-running task indicator). We always return a regular result.\n return result as unknown as { content: Array<{ type: \"text\"; text: string }>; isError?: boolean };\n });\n\n server.setRequestHandler(ListPromptsRequestSchema, async () => {\n return { prompts: dispatcher.listPrompts() };\n });\n\n server.setRequestHandler(GetPromptRequestSchema, async (req) => {\n const name = req.params.name;\n const args = (req.params.arguments ?? {}) as Record<string, string>;\n return dispatcher.getPrompt(name, args);\n });\n\n return server;\n}\n"],"mappings":";AAAA;AAAA,EACE,SAASA;AAAA,EACT;AAAA,EACA;AAAA,OAEK;;;ACLP,SAAS,SAAS,qBAAsD;AAkCjE,SAAS,oBACd,UACA,OACqB;AACrB,QAAM,SAAsB,cAAc,UAAU;AAAA,IAClD,KAAK,MAAM;AAAA,IACX,GAAI,MAAM,WAAW,SAAY,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;AAAA,EAC/D,CAAC;AAED,SAAO;AAAA,IACL,MAAM,OAAO,OACT;AAAA,MACE,MAAM,OAAO,KAAK;AAAA,MAClB,OAAO,OAAO,KAAK;AAAA,MACnB,GAAI,OAAO,KAAK,gBAAgB,SAC5B,EAAE,aAAa,OAAO,KAAK,YAAY,IACvC,CAAC;AAAA,IACP,IACA;AAAA,IACJ,YAAY,OAAO,WAAW,IAAI,CAAC,OAAO;AAAA,MACxC,MAAM,EAAE;AAAA,MACR,UAAU,EAAE;AAAA,MACZ,QAAQ,EAAE,UAAU,CAAC;AAAA,MACrB,OAAO,EAAE;AAAA,IACX,EAAE;AAAA,IACF,UAAU,OAAO,SAAS,IAAI,CAAC,OAAO;AAAA,MACpC,MAAM,EAAE;AAAA,MACR,OAAO,EAAE;A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AAAA,EAC7C;AAEA,SAAO,kBAAkB,wBAAwB,YAAY;AAC3D,UAAM,QAAQ,MAAM,WAAW,eAAe;AAC9C,WAAO,EAAE,MAAM;AAAA,EACjB,CAAC;AAED,SAAO,kBAAkB,uBAAuB,OAAO,QAAQ;AAC7D,UAAM,OAAO,IAAI,OAAO;AACxB,UAAM,OAAQ,IAAI,OAAO,aAAa,CAAC;AACvC,UAAM,SAAS,MAAM,WAAW,SAAS,MAAM,IAAI;AAGnD,WAAO;AAAA,EACT,CAAC;AAED,SAAO,kBAAkB,0BAA0B,YAAY;AAC7D,WAAO,EAAE,SAAS,WAAW,YAAY,EAAE;AAAA,EAC7C,CAAC;AAED,SAAO,kBAAkB,wBAAwB,OAAO,QAAQ;AAC9D,UAAM,OAAO,IAAI,OAAO;AACxB,UAAM,OAAQ,IAAI,OAAO,aAAa,CAAC;AACvC,WAAO,WAAW,UAAU,MAAM,IAAI;AAAA,EACxC,CAAC;AAED,SAAO;AACT;","names":["sightmapMatch","readFile","parse","readFile","parse","readFile","parse","readFile","parse","c","writeFile","readFile","readdir","join","format","canonicalize","readFile","writeFile","readdir","resolve","parse","format","canonicalize","stripFragmentBrand","writeFile","join","format","canonicalize","join","writeFile","readFile","resolve","require","resolved","sightmapMatch"]}
1
+ {"version":3,"sources":["../src/server.ts","../src/tools/match.ts","../src/tools/snapshot.ts","../src/tools/network.ts","../src/tools/curate/list.ts","../src/tools/curate/get.ts","../src/curate/locator.ts","../src/tools/curate/check.ts","../src/tools/curate/update.ts","../src/tools/curate/add.ts","../src/tools/curate/remove.ts","../src/tools/curate/init.ts","../src/curate/scaffolder.ts","../src/tools/runtime/snapshot.ts","../src/runtime/inject-script.ts","../src/tools/propose/store.ts","../src/tools/propose/view.ts","../src/tools/propose/component.ts","../src/tools/propose/review.ts","../src/tools/propose/commit.ts","../src/prompts/sepTrack.ts","../src/prompts/index.ts","../src/upstream.ts","../src/mcpServer.ts"],"sourcesContent":["import {\n match as sightmapMatch,\n resolveSightmapAct,\n buildInPageEvalFunction,\n type Sightmap,\n} from \"@sightmap/sightmap\";\nimport { handleSightmapMatch } from \"./tools/match.js\";\nimport {\n buildSightmapSnapshotResponse,\n type InPageSightmapMatch,\n} from \"./tools/snapshot.js\";\nimport {\n parseNetworkRequestsText,\n annotateNetworkRequests,\n} from \"./tools/network.js\";\nimport {\n handleListViews,\n type ListViewsInput,\n} from \"./tools/curate/list.js\";\nimport { handleGetView } from \"./tools/curate/get.js\";\nimport { handleCheck, type CheckInput } from \"./tools/curate/check.js\";\nimport {\n handleUpdateView,\n type ViewPatch,\n} from \"./tools/curate/update.js\";\nimport { handleAddView } from \"./tools/curate/add.js\";\nimport { handleDeleteView } from \"./tools/curate/remove.js\";\nimport type { View } from \"@sightmap/sightmap\";\nimport {\n handleInitProject,\n type InitProjectInput,\n} from \"./tools/curate/init.js\";\nimport {\n handleRuntimeSnapshot,\n type RuntimeSnapshotInput,\n} from \"./tools/runtime/snapshot.js\";\nimport { getInjectScript } from \"./runtime/inject-script.js\";\nimport {\n handleProposeView,\n type ProposeViewInput,\n} from \"./tools/propose/view.js\";\nimport {\n handleProposeComponent,\n type ProposeComponentInput,\n} from \"./tools/propose/component.js\";\nimport { handleReviewProposals } from \"./tools/propose/review.js\";\nimport {\n handleCommitProposals,\n type CommitProposalsInput,\n} from \"./tools/propose/commit.js\";\nimport type { PromptDefinition, PromptEntry, PromptResult } from \"./prompts/index.js\";\nimport { PROMPT_REGISTRY } from \"./prompts/index.js\";\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: {\n type: \"object\";\n properties?: Record<string, unknown>;\n required?: string[];\n additionalProperties?: boolean;\n };\n}\n\nexport interface ToolResult {\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n}\n\n/**\n * Abstraction over the upstream MCP server (typically `@playwright/mcp`).\n *\n * Implementations: a real MCP-SDK Client connected via stdio in production,\n * a fake in unit tests.\n */\nexport interface UpstreamClient {\n listTools(): Promise<ToolDefinition[]>;\n callTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;\n}\n\nexport interface SightmapMcpServerOptions {\n sightmap: Sightmap;\n /** Optional upstream MCP server to proxy non-sightmap_* tool calls through. */\n upstream?: UpstreamClient;\n /**\n * Writable `.sightmap/` directory for curation tools that read/write files\n * (e.g. `sightmap_get_view`, `sightmap_update_view`). The CLI populates this\n * from `--curate-root` (or, by default, the first `--sightmap-dir`).\n */\n curateRoot?: string;\n}\n\nconst SIGHTMAP_MATCH: ToolDefinition = {\n name: \"sightmap_match\",\n description:\n \"Pure-query lookup against the loaded sightmap. Returns the matched view, applicable components, applicable requests, and aggregated memory for a given URL. Useful for agent planning before navigation. Does not touch the browser.\",\n inputSchema: {\n type: \"object\",\n properties: {\n url: {\n type: \"string\",\n description: \"The URL to resolve against the sightmap's view routes.\",\n },\n method: {\n type: \"string\",\n description: \"Optional HTTP method to filter matched requests (e.g., 'GET', 'POST').\",\n },\n },\n required: [\"url\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_SNAPSHOT: ToolDefinition = {\n name: \"sightmap_snapshot\",\n description:\n \"Returns the upstream ARIA snapshot enriched with sightmap awareness: matched view name, applicable component names with their selectors and live matchCount on the page, view-level memory, and page-aggregated memory. Use this instead of browser_snapshot when you want sightmap-aware semantics in one round-trip.\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_NETWORK_REQUESTS: ToolDefinition = {\n name: \"sightmap_network_requests\",\n description:\n \"Returns recent network requests captured by the upstream, annotated with sightmap names and memory where the request URL+method matches a sightmap `requests:` entry. Use this in place of browser_network_requests when you want sightmap-aware semantics for network calls.\",\n inputSchema: {\n type: \"object\",\n properties: {\n static: {\n type: \"boolean\",\n description:\n \"Include successful static resources (images, fonts, scripts). Default false.\",\n },\n filter: {\n type: \"string\",\n description: \"Only return requests whose URL matches this regexp.\",\n },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_INIT_PROJECT: ToolDefinition = {\n name: \"sightmap_init_project\",\n description:\n \"Scaffold an empty .sightmap/ directory in the target project. Pass `dir` to override the location (default: server cwd). Refuses to overwrite an existing .sightmap/ unless `force=true`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n dir: { type: \"string\", description: \"Project root. Default: server cwd.\" },\n force: { type: \"boolean\", description: \"Default false.\" },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_UPDATE_VIEW: ToolDefinition = {\n name: \"sightmap_update_view\",\n description:\n \"Apply a patch to a view's fields. Accepts both semantic edits (description, intent, memory_append/memory_replace) and structural edits (name, route, components). Memory edits use either `memory_append` (default) or `memory_replace` — pass exactly one. Components is a full array replacement; use sightmap_add_view/sightmap_delete_view for whole-view lifecycle.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n patch: {\n type: \"object\",\n properties: {\n description: { type: \"string\" },\n intent: { type: \"string\" },\n memory_append: { type: \"array\", items: { type: \"string\" } },\n memory_replace: { type: \"array\", items: { type: \"string\" } },\n name: { type: \"string\" },\n route: { type: \"string\" },\n components: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n selector: { type: \"string\" },\n memory: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"name\", \"selector\"],\n additionalProperties: true,\n },\n },\n },\n additionalProperties: false,\n },\n },\n required: [\"name\", \"patch\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_ADD_VIEW: ToolDefinition = {\n name: \"sightmap_add_view\",\n description:\n \"Create a new view in a new .yaml file. Filename defaults to kebab(view.name) + '.yaml' unless overridden via `file`. Rejects names that collide with an existing view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n view: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n route: { type: \"string\" },\n description: { type: \"string\" },\n memory: { type: \"array\", items: { type: \"string\" } },\n components: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n selector: { type: \"string\" },\n memory: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"name\", \"selector\"],\n additionalProperties: true,\n },\n },\n },\n required: [\"name\", \"route\"],\n additionalProperties: true,\n },\n file: {\n type: \"string\",\n description:\n \"Optional filename hint (relative to the curate root). Defaults to kebab(view.name) + '.yaml'.\",\n },\n },\n required: [\"view\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_RUNTIME_SNAPSHOT: ToolDefinition = {\n name: \"sightmap_runtime_snapshot\",\n description:\n \"Fetch a SightmapSnapshot (fiber-tree introspection from bippy). Three sources:\\n\" +\n \" - { kind: 'endpoint', url } — HTTP GET against the @sightmap/react Vite plugin endpoint (zero-config for Vite users).\\n\" +\n \" - { kind: 'browser', url, routes?, inject? } — drive the live browser via @playwright/mcp; works on any React app (Webpack, RR 5.x, etc.) and, with `inject: true`, on apps that haven't installed @sightmap/react.\\n\" +\n \" - { kind: 'literal', snapshot } — accept a pre-captured snapshot from any source (subtext live-eval-script, devtools console paste, custom Playwright scripts, CI capture). Validates the shape; returns it.\",\n inputSchema: {\n type: \"object\",\n properties: {\n source: {\n type: \"object\",\n oneOf: [\n {\n type: \"object\",\n properties: {\n kind: { type: \"string\", const: \"endpoint\" },\n url: { type: \"string\", description: \"Plugin endpoint URL, e.g. http://localhost:5173/__sightmap__/snapshot.json.\" },\n },\n required: [\"kind\", \"url\"],\n additionalProperties: false,\n },\n {\n type: \"object\",\n properties: {\n kind: { type: \"string\", const: \"browser\" },\n url: { type: \"string\", description: \"Target URL to navigate to.\" },\n routes: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Optional list of routes (absolute or relative to `url`) to capture in sequence.\",\n },\n inject: {\n type: \"boolean\",\n description:\n \"When true, inject bippy + the snapshot bootstrap before navigation so non-@sightmap/react apps work. \" +\n \"Omit to auto-inject only when the page lacks window.__sightmap__.\",\n },\n },\n required: [\"kind\", \"url\"],\n additionalProperties: false,\n },\n {\n type: \"object\",\n properties: {\n kind: { type: \"string\", const: \"literal\" },\n snapshot: {\n description:\n \"A pre-captured SightmapSnapshot object. Must include capturedAt, route, components, markers, unmarkedCandidates.\",\n },\n },\n required: [\"kind\", \"snapshot\"],\n additionalProperties: false,\n },\n ],\n },\n },\n required: [\"source\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_PROPOSE_VIEW: ToolDefinition = {\n name: \"sightmap_propose_view\",\n description:\n \"Stage a proposed view from runtime observation. Does NOT write disk. Use sightmap_commit_proposals to persist.\",\n inputSchema: {\n type: \"object\",\n properties: {\n route: { type: \"string\", description: \"URL path for the observed view (e.g., '/dashboard').\" },\n name: { type: \"string\", description: \"Optional display name. If omitted, derived from route at commit time.\" },\n intent: { type: \"string\", description: \"Optional one-liner describing the view's purpose.\" },\n observed: { type: \"string\", description: \"Free-form note about what was observed on this view.\" },\n observed_components: { type: \"array\", items: { type: \"string\" } },\n memory_notes: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"route\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_PROPOSE_COMPONENT: ToolDefinition = {\n name: \"sightmap_propose_component\",\n description:\n \"Stage a proposed component observation. Does NOT write disk.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"Component name (e.g., 'KpiCard').\" },\n selector_candidate: { type: \"string\", description: \"Best-guess CSS selector for the component.\" },\n observed_routes: { type: \"array\", items: { type: \"string\" } },\n notes: { type: \"array\", items: { type: \"string\" } },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_REVIEW_PROPOSALS: ToolDefinition = {\n name: \"sightmap_review_proposals\",\n description:\n \"Return the current staged proposals (views + components).\",\n inputSchema: {\n type: \"object\",\n properties: {},\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_COMMIT_PROPOSALS: ToolDefinition = {\n name: \"sightmap_commit_proposals\",\n description:\n \"Promote staged proposals to disk via add_view. Pass dry_run:true to preview without consuming the queue. Pass ids:[...] to commit a selection only.\",\n inputSchema: {\n type: \"object\",\n properties: {\n ids: { type: \"array\", items: { type: \"string\" }, description: \"Optional subset of proposal ids to commit. Omit to commit everything.\" },\n dry_run: { type: \"boolean\", description: \"If true, preview without consuming the queue and without writing.\" },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_DELETE_VIEW: ToolDefinition = {\n name: \"sightmap_delete_view\",\n description:\n \"Delete a view by name. If the containing .yaml file has only this view, the file is removed; otherwise the view is spliced out and the file rewritten.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_CHECK: ToolDefinition = {\n name: \"sightmap_check\",\n description:\n \"Validate the loaded sightmap. level='schema' returns only schema-level diagnostics (parse errors, schema failures, merge collisions). level='quality' (default) also runs lint rules: duplicate routes, route shadowing, selector syntax, unknown source attributions. Returns an array of diagnostics; an empty array means clean.\",\n inputSchema: {\n type: \"object\",\n properties: {\n level: {\n type: \"string\",\n enum: [\"schema\", \"quality\"],\n description: \"Default 'quality'.\",\n },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_GET_VIEW: ToolDefinition = {\n name: \"sightmap_get_view\",\n description:\n \"Fetch a single view by name, including all memory, components, and requests. Returns the file path the view was read from for subsequent edits. Use sightmap_list_views first to discover view names.\",\n inputSchema: {\n type: \"object\",\n properties: {\n name: { type: \"string\", description: \"View name (case-sensitive).\" },\n },\n required: [\"name\"],\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_LIST_VIEWS: ToolDefinition = {\n name: \"sightmap_list_views\",\n description:\n \"List all views in the loaded sightmap. Returns compact summaries (name, route, description) by default; pass detail='full' for the complete view objects including memory and components. Token-efficient: prefer the default for any agent that hasn't yet narrowed to a specific view.\",\n inputSchema: {\n type: \"object\",\n properties: {\n detail: {\n type: \"string\",\n enum: [\"summary\", \"full\"],\n description: \"Default 'summary'.\",\n },\n },\n additionalProperties: false,\n },\n};\n\nconst SIGHTMAP_ACT: ToolDefinition = {\n name: \"sightmap_act\",\n description:\n \"Performs an action on a UI element. Prefer `componentName` so the agent operates in sightmap semantics; fall back to a raw `selector` for one-off targets the sightmap doesn't define (e.g., a stray link or a third-party widget). Supported actions: 'click' (browser_click), 'type' (browser_type, requires `text`), 'hover' (browser_hover). Pass exactly one of `componentName` or `selector`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n componentName: {\n type: \"string\",\n description: \"Sightmap component name to act on (case-sensitive). Mutually exclusive with `selector`.\",\n },\n selector: {\n type: \"string\",\n description:\n \"Escape hatch: a raw CSS selector for a target the sightmap doesn't name. Same tagging + dispatch path as componentName. Use this only when no sightmap component fits — most actions should use `componentName` so the agent's reasoning stays in sightmap semantics. Mutually exclusive with `componentName`.\",\n },\n action: {\n type: \"string\",\n enum: [\"click\", \"type\", \"hover\"],\n description: \"The action to perform on the component.\",\n },\n text: {\n type: \"string\",\n description: \"Required for action='type'. Text to enter into the matched element.\",\n },\n submit: {\n type: \"boolean\",\n description: \"For action='type' only. Press Enter after typing.\",\n },\n instance: {\n type: \"integer\",\n minimum: 0,\n description:\n \"Zero-based index of the matching element when the component selector resolves to multiple elements (default 0). Use sightmap_snapshot.matchCount to discover how many instances exist. Mutually exclusive with `containingText`.\",\n },\n containingText: {\n type: \"string\",\n description:\n \"Disambiguator for multi-match components: pick the first element whose visible text contains this substring (case-insensitive). Use this instead of `instance` when you can identify the element by its visible label rather than position. Mutually exclusive with `instance`.\",\n },\n },\n required: [\"componentName\", \"action\"],\n additionalProperties: false,\n },\n};\n\n/**\n * Upstream tools whose sightmap-aware equivalents should appear instead in\n * the listed-tools surface. The agent only sees one of each pair, biasing\n * its tool choices toward sightmap semantics. Direct invocation by name\n * still works for callers that need the raw passthrough.\n */\nconst SHADOWED_UPSTREAM_TOOLS: ReadonlySet<string> = new Set([\n \"browser_snapshot\",\n \"browser_click\",\n \"browser_type\",\n \"browser_hover\",\n \"browser_network_requests\",\n]);\n\n/**\n * Core dispatcher for the sightmap-mcp wrapper.\n *\n * Holds the loaded sightmap, exposes the surface of sightmap-aware tools, and\n * dispatches `callTool` requests. Transport-agnostic — wired up to stdio in\n * the CLI entry, and unit-testable directly without spinning up MCP plumbing.\n *\n * Phase 1 surface: `sightmap_match` only. Subsequent phases add\n * `sightmap_snapshot` and `sightmap_act`, plus a passthrough proxy for the\n * upstream @playwright/mcp tools.\n */\nexport class SightmapMcpServer {\n private readonly sightmap: Sightmap;\n private readonly upstream: UpstreamClient | undefined;\n private readonly curateRoot: string | undefined;\n\n constructor(opts: SightmapMcpServerOptions) {\n this.sightmap = opts.sightmap;\n this.upstream = opts.upstream;\n this.curateRoot = opts.curateRoot;\n }\n\n /** Synchronous list of sightmap-aware tools that don't need an upstream. */\n listTools(): ToolDefinition[] {\n return [\n SIGHTMAP_MATCH,\n SIGHTMAP_LIST_VIEWS,\n SIGHTMAP_GET_VIEW,\n SIGHTMAP_CHECK,\n SIGHTMAP_ADD_VIEW,\n SIGHTMAP_UPDATE_VIEW,\n SIGHTMAP_DELETE_VIEW,\n SIGHTMAP_INIT_PROJECT,\n SIGHTMAP_RUNTIME_SNAPSHOT,\n SIGHTMAP_PROPOSE_VIEW,\n SIGHTMAP_PROPOSE_COMPONENT,\n SIGHTMAP_REVIEW_PROPOSALS,\n SIGHTMAP_COMMIT_PROPOSALS,\n ];\n }\n\n /** Full async list including upstream-proxied tools, if configured. */\n async listToolsAsync(): Promise<ToolDefinition[]> {\n const own: ToolDefinition[] = [\n SIGHTMAP_MATCH,\n SIGHTMAP_LIST_VIEWS,\n SIGHTMAP_GET_VIEW,\n SIGHTMAP_CHECK,\n SIGHTMAP_ADD_VIEW,\n SIGHTMAP_UPDATE_VIEW,\n SIGHTMAP_DELETE_VIEW,\n SIGHTMAP_INIT_PROJECT,\n SIGHTMAP_RUNTIME_SNAPSHOT,\n SIGHTMAP_PROPOSE_VIEW,\n SIGHTMAP_PROPOSE_COMPONENT,\n SIGHTMAP_REVIEW_PROPOSALS,\n SIGHTMAP_COMMIT_PROPOSALS,\n ];\n if (this.upstream !== undefined) {\n own.push(SIGHTMAP_SNAPSHOT, SIGHTMAP_ACT, SIGHTMAP_NETWORK_REQUESTS);\n }\n if (this.upstream === undefined) return own;\n const upstreamTools = await this.upstream.listTools();\n // Hide upstream tools that have a sightmap_* equivalent. Goal: nudge the\n // agent toward the sightmap-aware surface instead of letting it fall\n // back to the generic browser_* duplicates by habit. Calls to these\n // hidden tools still pass through if the agent invokes them by name —\n // hiding only affects the discovery surface.\n const shadowed = SHADOWED_UPSTREAM_TOOLS;\n const filtered = upstreamTools.filter((t) => !shadowed.has(t.name));\n return [...own, ...filtered];\n }\n\n /** All prompts the server advertises. Static; no upstream involvement. */\n listPrompts(): PromptDefinition[] {\n return PROMPT_REGISTRY.map((p) => p.definition);\n }\n\n /**\n * Resolve a prompt by name, validate args, and produce the prompt result\n * (the messages the agent will inject). Throws on unknown names or on a\n * handler that itself throws (e.g., bad phase value).\n */\n getPrompt(name: string, args: Record<string, string>): PromptResult {\n const entry: PromptEntry | undefined = PROMPT_REGISTRY.find(\n (p) => p.definition.name === name,\n );\n if (entry === undefined) throw new Error(`unknown prompt: ${name}`);\n return entry.handler(args);\n }\n\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n if (isSightmapTool(name)) {\n switch (name) {\n case \"sightmap_match\":\n return this.callSightmapMatch(args);\n case \"sightmap_list_views\":\n return this.callSightmapListViews(args);\n case \"sightmap_get_view\":\n return this.callSightmapGetView(args);\n case \"sightmap_check\":\n return this.callSightmapCheck(args);\n case \"sightmap_add_view\":\n return this.callSightmapAddView(args);\n case \"sightmap_update_view\":\n return this.callSightmapUpdateView(args);\n case \"sightmap_delete_view\":\n return this.callSightmapDeleteView(args);\n case \"sightmap_init_project\":\n return this.callSightmapInitProject(args);\n case \"sightmap_runtime_snapshot\":\n return this.callSightmapRuntimeSnapshot(args);\n case \"sightmap_propose_view\":\n return this.callSightmapProposeView(args);\n case \"sightmap_propose_component\":\n return this.callSightmapProposeComponent(args);\n case \"sightmap_review_proposals\":\n return this.callSightmapReviewProposals();\n case \"sightmap_commit_proposals\":\n return this.callSightmapCommitProposals(args);\n case \"sightmap_snapshot\":\n return this.callSightmapSnapshot();\n case \"sightmap_act\":\n return this.callSightmapAct(args);\n case \"sightmap_network_requests\":\n return this.callSightmapNetworkRequests(args);\n default:\n return errorResult(`Unknown sightmap tool: ${name}`);\n }\n }\n if (this.upstream !== undefined) {\n return this.upstream.callTool(name, args);\n }\n return errorResult(`Unknown tool: ${name}`);\n }\n\n /**\n * Tag a single element matching `selector` with a unique\n * `data-sm-act-target` attribute and return a CSS selector that resolves\n * to exactly that element. The selection mode picks WHICH match to tag:\n * - `{ kind: \"index\", index }` — pick the Nth match (default).\n * - `{ kind: \"containingText\", text }` — pick the first match whose\n * `textContent` contains `text` (case-insensitive).\n *\n * Returns null if no candidate is selected (index out of range, or no\n * element's text contains the needle).\n */\n private async tagSingleMatch(\n selector: string,\n selection:\n | { kind: \"index\"; index: number }\n | { kind: \"containingText\"; text: string },\n ): Promise<string | null> {\n if (this.upstream === undefined) return null;\n const marker = `sm-${Math.random().toString(36).slice(2, 10)}-${Date.now().toString(36)}`;\n const pickExpr =\n selection.kind === \"index\"\n ? `els[${selection.index}]`\n : `els.find((el) => (el.textContent || \"\").toLowerCase().includes(${JSON.stringify(selection.text.toLowerCase())}))`;\n const fnBody = `() => {\n const els = Array.from(document.querySelectorAll(${JSON.stringify(selector)}));\n const target = ${pickExpr};\n if (!target) return null;\n target.setAttribute(\"data-sm-act-target\", ${JSON.stringify(marker)});\n return \"[data-sm-act-target=\\\\\"\" + ${JSON.stringify(marker)} + \"\\\\\"]\";\n }`;\n const r = await this.upstream.callTool(\"browser_evaluate\", { function: fnBody });\n if (r.isError === true) return null;\n const text = r.content.map((b) => b.text).join(\"\\n\");\n const decoded = decodeMcpEvalResult(text);\n if (typeof decoded !== \"string\") return null;\n if (!decoded.includes(`data-sm-act-target=\"${marker}\"`)) return null;\n return decoded;\n }\n\n private async callSightmapNetworkRequests(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (this.upstream === undefined) {\n return errorResult(\n \"sightmap_network_requests: requires an upstream (e.g., @playwright/mcp).\",\n );\n }\n const upstreamArgs: Record<string, unknown> = {};\n if (typeof args[\"static\"] === \"boolean\") upstreamArgs[\"static\"] = args[\"static\"];\n if (typeof args[\"filter\"] === \"string\") upstreamArgs[\"filter\"] = args[\"filter\"];\n\n const r = await this.upstream.callTool(\"browser_network_requests\", upstreamArgs);\n if (r.isError === true) {\n return r;\n }\n const text = r.content.map((b) => b.text).join(\"\\n\");\n const parsed = parseNetworkRequestsText(text);\n const annotated = annotateNetworkRequests(this.sightmap, parsed);\n return {\n content: [{ type: \"text\", text: JSON.stringify({ requests: annotated }, null, 2) }],\n };\n }\n\n private async callSightmapAct(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.upstream === undefined) {\n return errorResult(\n \"sightmap_act: requires an upstream (e.g., @playwright/mcp) to be configured.\",\n );\n }\n const hasComponent =\n typeof args[\"componentName\"] === \"string\" && args[\"componentName\"].length > 0;\n const hasSelector =\n typeof args[\"selector\"] === \"string\" && args[\"selector\"].length > 0;\n if (hasComponent && hasSelector) {\n return errorResult(\n \"sightmap_act: `componentName` and `selector` are mutually exclusive — pass one, not both.\",\n );\n }\n if (!hasComponent && !hasSelector) {\n return errorResult(\n \"sightmap_act: pass either `componentName` (preferred) or `selector` (escape hatch for off-sightmap targets).\",\n );\n }\n if (typeof args[\"action\"] !== \"string\") {\n return errorResult(\"sightmap_act: required argument `action` (string) is missing.\");\n }\n\n const action = args[\"action\"];\n const validActions = new Set([\"click\", \"type\", \"hover\"]);\n if (!validActions.has(action)) {\n return errorResult(\n `sightmap_act: unsupported action \"${action}\". Supported: click, type, hover.`,\n );\n }\n if (action === \"type\" && typeof args[\"text\"] !== \"string\") {\n return errorResult(\"sightmap_act: action='type' requires `text` (string).\");\n }\n\n const hasInstance = typeof args[\"instance\"] === \"number\";\n const hasContainingText =\n typeof args[\"containingText\"] === \"string\" && args[\"containingText\"].length > 0;\n if (hasInstance && hasContainingText) {\n return errorResult(\n \"sightmap_act: `instance` and `containingText` are mutually exclusive — pass one, not both.\",\n );\n }\n\n // Resolve the target: either via sightmap lookup or directly from `selector`.\n let targetSelector: string;\n let targetLabel: string;\n if (hasComponent) {\n const resolved = resolveSightmapAct(this.sightmap, {\n componentName: args[\"componentName\"] as string,\n });\n if (resolved.kind === \"error\") {\n return errorResult(\"sightmap_act: \" + resolved.message);\n }\n targetSelector = resolved.selector;\n targetLabel = resolved.componentName;\n } else {\n targetSelector = args[\"selector\"] as string;\n targetLabel = `selector:${targetSelector}`;\n }\n const resolved = { kind: \"ok\" as const, componentName: targetLabel, selector: targetSelector };\n\n // Tag a single matching element with a unique data-sm-act-target marker\n // via browser_evaluate, then act on that uniquely-tagged element. This\n // sidesteps Playwright's strict-mode multi-match violation regardless of\n // whether the sightmap selector resolves to one element or many. Costs\n // one extra round-trip per action; buys universal correctness.\n const selection: { kind: \"index\"; index: number } | { kind: \"containingText\"; text: string } =\n hasContainingText\n ? { kind: \"containingText\", text: args[\"containingText\"] as string }\n : { kind: \"index\", index: hasInstance ? Math.floor(args[\"instance\"] as number) : 0 };\n const taggedSelector = await this.tagSingleMatch(resolved.selector, selection);\n if (taggedSelector === null) {\n const reason =\n selection.kind === \"containingText\"\n ? `no instance of \"${resolved.componentName}\" contains text ${JSON.stringify(selection.text)}`\n : `could not tag the element at instance=${selection.index} for component \"${resolved.componentName}\"`;\n return errorResult(\n `sightmap_act: ${reason}. The selector ${JSON.stringify(resolved.selector)} ` +\n `may not resolve any matching elements on the current page.`,\n );\n }\n\n const baseArgs: Record<string, unknown> = {\n target: taggedSelector,\n element: resolved.componentName,\n };\n\n let upstreamName: string;\n let upstreamArgs: Record<string, unknown>;\n switch (action) {\n case \"click\":\n upstreamName = \"browser_click\";\n upstreamArgs = baseArgs;\n break;\n case \"hover\":\n upstreamName = \"browser_hover\";\n upstreamArgs = baseArgs;\n break;\n case \"type\":\n upstreamName = \"browser_type\";\n upstreamArgs = {\n ...baseArgs,\n text: args[\"text\"],\n ...(args[\"submit\"] === true ? { submit: true } : {}),\n };\n break;\n default:\n return errorResult(`sightmap_act: unsupported action \"${action}\".`);\n }\n\n return this.upstream.callTool(upstreamName, upstreamArgs);\n }\n\n private async callSightmapSnapshot(): Promise<ToolResult> {\n if (this.upstream === undefined) {\n return errorResult(\n \"sightmap_snapshot: requires an upstream (e.g., @playwright/mcp) to be configured.\",\n );\n }\n\n // 1. Pull the ARIA snapshot from upstream.\n const snapResult = await this.upstream.callTool(\"browser_snapshot\", {});\n if (snapResult.isError === true) {\n return errorResult(\n \"sightmap_snapshot: upstream browser_snapshot failed: \" +\n (snapResult.content[0]?.text ?? \"unknown error\"),\n );\n }\n const ariaSnapshotText = snapResult.content.map((b) => b.text).join(\"\\n\");\n\n // 2. Determine the URL and find sightmap-applicable components for it.\n // We do this server-side via match(), so the in-page eval only needs\n // to look up `document.querySelectorAll(selector)` for each.\n const currentUrl = parsePageUrl(ariaSnapshotText) ?? \"\";\n const matchResult = sightmapMatch(this.sightmap, { url: currentUrl });\n const componentSelectors = matchResult.components.map((c) => ({\n name: c.name,\n selector: c.selector,\n }));\n\n // 3. In-page evaluate: query each component's selectors, return matchCount\n // and first match's bounding rect.\n const evalResult = await this.upstream.callTool(\"browser_evaluate\", {\n function: buildInPageEvalFunction(componentSelectors),\n });\n if (evalResult.isError === true) {\n return errorResult(\n \"sightmap_snapshot: upstream browser_evaluate failed: \" +\n (evalResult.content[0]?.text ?? \"unknown error\"),\n );\n }\n const inPageMatches = parseInPageEvalResult(\n evalResult.content.map((b) => b.text).join(\"\\n\"),\n );\n\n // 4. Synthesize the response.\n const response = buildSightmapSnapshotResponse({\n sightmap: this.sightmap,\n currentUrl,\n ariaSnapshotText,\n inPageMatches,\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(response, null, 2) }],\n };\n }\n\n private callSightmapMatch(args: Record<string, unknown>): ToolResult {\n if (typeof args[\"url\"] !== \"string\" || args[\"url\"].length === 0) {\n return errorResult(\"sightmap_match: required argument `url` (string) is missing or empty.\");\n }\n const input: { url: string; method?: string } = { url: args[\"url\"] };\n if (typeof args[\"method\"] === \"string\") {\n input.method = args[\"method\"];\n }\n const output = handleSightmapMatch(this.sightmap, input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(output, null, 2) }],\n };\n }\n\n private async callSightmapGetView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_get_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\"sightmap_get_view: required argument `name` (string) is missing or empty.\");\n }\n try {\n const result = await handleGetView({\n sightmapDir: this.curateRoot,\n name: args[\"name\"],\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapInitProject(args: Record<string, unknown>): Promise<ToolResult> {\n const input: InitProjectInput = {};\n if (typeof args[\"dir\"] === \"string\") input.dir = args[\"dir\"];\n if (args[\"force\"] === true) input.force = true;\n try {\n const result = await handleInitProject(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapRuntimeSnapshot(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n const source = args[\"source\"];\n if (source === null || typeof source !== \"object\" || Array.isArray(source)) {\n return errorResult(\n \"sightmap_runtime_snapshot: required argument `source` (object) is missing.\",\n );\n }\n const s = source as Record<string, unknown>;\n const kind = s[\"kind\"];\n if (kind !== \"endpoint\" && kind !== \"browser\" && kind !== \"literal\") {\n return errorResult(\n \"sightmap_runtime_snapshot: `source.kind` must be 'endpoint', 'browser', or 'literal'.\",\n );\n }\n let input: RuntimeSnapshotInput;\n if (kind === \"endpoint\") {\n if (typeof s[\"url\"] !== \"string\" || s[\"url\"].length === 0) {\n return errorResult(\n \"sightmap_runtime_snapshot: endpoint mode requires `source.url` (string).\",\n );\n }\n input = { source: { kind: \"endpoint\", url: s[\"url\"] } };\n } else if (kind === \"browser\") {\n if (typeof s[\"url\"] !== \"string\" || s[\"url\"].length === 0) {\n return errorResult(\n \"sightmap_runtime_snapshot: browser mode requires `source.url` (string).\",\n );\n }\n const browserSrc: { kind: \"browser\"; url: string; routes?: string[]; inject?: boolean } = {\n kind: \"browser\",\n url: s[\"url\"],\n };\n if (Array.isArray(s[\"routes\"])) {\n browserSrc.routes = (s[\"routes\"] as unknown[]).filter(\n (r): r is string => typeof r === \"string\",\n );\n }\n if (typeof s[\"inject\"] === \"boolean\") {\n browserSrc.inject = s[\"inject\"];\n }\n input = { source: browserSrc };\n } else {\n // literal\n if (!(\"snapshot\" in s)) {\n return errorResult(\n \"sightmap_runtime_snapshot: literal mode requires `source.snapshot`.\",\n );\n }\n input = { source: { kind: \"literal\", snapshot: s[\"snapshot\"] } };\n }\n try {\n const deps: import(\"./tools/runtime/snapshot.js\").RuntimeSnapshotDeps = {\n getInjectScript,\n };\n if (this.upstream !== undefined) deps.upstream = this.upstream;\n const result = await handleRuntimeSnapshot(input, deps);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapProposeView(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (typeof args[\"route\"] !== \"string\" || args[\"route\"].length === 0) {\n return errorResult(\n \"sightmap_propose_view: required argument `route` (string) is missing or empty.\",\n );\n }\n const input: ProposeViewInput = { route: args[\"route\"] };\n if (typeof args[\"name\"] === \"string\") input.name = args[\"name\"];\n if (typeof args[\"intent\"] === \"string\") input.intent = args[\"intent\"];\n if (typeof args[\"observed\"] === \"string\") input.observed = args[\"observed\"];\n if (Array.isArray(args[\"observed_components\"])) {\n input.observed_components = (args[\"observed_components\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n if (Array.isArray(args[\"memory_notes\"])) {\n input.memory_notes = (args[\"memory_notes\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n try {\n const result = await handleProposeView(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapProposeComponent(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_propose_component: required argument `name` (string) is missing or empty.\",\n );\n }\n const input: ProposeComponentInput = { name: args[\"name\"] };\n if (typeof args[\"selector_candidate\"] === \"string\") {\n input.selector_candidate = args[\"selector_candidate\"];\n }\n if (Array.isArray(args[\"observed_routes\"])) {\n input.observed_routes = (args[\"observed_routes\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n if (Array.isArray(args[\"notes\"])) {\n input.notes = (args[\"notes\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n try {\n const result = await handleProposeComponent(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapReviewProposals(): Promise<ToolResult> {\n try {\n const result = await handleReviewProposals();\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapCommitProposals(\n args: Record<string, unknown>,\n ): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_commit_proposals: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n const input: CommitProposalsInput = { sightmapDir: this.curateRoot };\n if (Array.isArray(args[\"ids\"])) {\n input.ids = (args[\"ids\"] as unknown[]).filter(\n (s): s is string => typeof s === \"string\",\n );\n }\n if (args[\"dry_run\"] === true) input.dry_run = true;\n try {\n const result = await handleCommitProposals(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapAddView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_add_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (\n args[\"view\"] === null ||\n typeof args[\"view\"] !== \"object\" ||\n Array.isArray(args[\"view\"])\n ) {\n return errorResult(\n \"sightmap_add_view: required argument `view` (object) is missing.\",\n );\n }\n const view = args[\"view\"] as Record<string, unknown>;\n if (typeof view[\"name\"] !== \"string\" || view[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_add_view: `view.name` (string) is required.\",\n );\n }\n if (typeof view[\"route\"] !== \"string\" || view[\"route\"].length === 0) {\n return errorResult(\n \"sightmap_add_view: `view.route` (string) is required.\",\n );\n }\n const input: { sightmapDir: string; view: View; file?: string } = {\n sightmapDir: this.curateRoot,\n view: view as unknown as View,\n };\n if (typeof args[\"file\"] === \"string\" && args[\"file\"].length > 0) {\n input.file = args[\"file\"];\n }\n try {\n const result = await handleAddView(input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapUpdateView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_update_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_update_view: required argument `name` (string) is missing or empty.\",\n );\n }\n if (\n args[\"patch\"] === null ||\n typeof args[\"patch\"] !== \"object\" ||\n Array.isArray(args[\"patch\"])\n ) {\n return errorResult(\n \"sightmap_update_view: required argument `patch` (object) is missing.\",\n );\n }\n try {\n const result = await handleUpdateView({\n sightmapDir: this.curateRoot,\n name: args[\"name\"],\n patch: args[\"patch\"] as ViewPatch,\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapDeleteView(args: Record<string, unknown>): Promise<ToolResult> {\n if (this.curateRoot === undefined) {\n return errorResult(\n \"sightmap_delete_view: no writable sightmap dir configured (pass --curate-root or --sightmap-dir).\",\n );\n }\n if (typeof args[\"name\"] !== \"string\" || args[\"name\"].length === 0) {\n return errorResult(\n \"sightmap_delete_view: required argument `name` (string) is missing or empty.\",\n );\n }\n try {\n const result = await handleDeleteView({\n sightmapDir: this.curateRoot,\n name: args[\"name\"],\n });\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n } catch (err) {\n return errorResult(err instanceof Error ? err.message : String(err));\n }\n }\n\n private async callSightmapCheck(args: Record<string, unknown>): Promise<ToolResult> {\n const input: CheckInput = {};\n if (args[\"level\"] === \"schema\" || args[\"level\"] === \"quality\") {\n input.level = args[\"level\"];\n } else if (args[\"level\"] !== undefined) {\n return errorResult(\n `sightmap_check: level must be \"schema\" or \"quality\".`,\n );\n }\n const result = await handleCheck(this.sightmap, input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(result, null, 2) }],\n };\n }\n\n private callSightmapListViews(args: Record<string, unknown>): ToolResult {\n const input: ListViewsInput = {};\n if (args[\"detail\"] === \"summary\" || args[\"detail\"] === \"full\") {\n input.detail = args[\"detail\"];\n } else if (args[\"detail\"] !== undefined) {\n return errorResult(\n `sightmap_list_views: detail must be \"summary\" or \"full\".`,\n );\n }\n const output = handleListViews(this.sightmap, input);\n return {\n content: [{ type: \"text\", text: JSON.stringify(output, null, 2) }],\n };\n }\n}\n\nfunction errorResult(text: string): ToolResult {\n return {\n content: [{ type: \"text\", text }],\n isError: true,\n };\n}\n\nfunction isSightmapTool(name: string): boolean {\n return name.startsWith(\"sightmap_\");\n}\n\n/** Extract the \"Page URL: ...\" line from an upstream browser_snapshot response. */\nfunction parsePageUrl(text: string): string | null {\n const m = /Page URL:\\s*(\\S+)/.exec(text);\n return m?.[1] ?? null;\n}\n\n/**\n * Parse the upstream `browser_evaluate` response text into a JSON payload.\n *\n * @playwright/mcp wraps the result like:\n * ### Result\n * {\"url\": \"...\", \"matches\": [...]}\n * ### Ran Playwright code\n * ...\n *\n * We extract the first JSON object after `### Result`. If the format changes,\n * fall back to a generic { from first '{' } scan.\n */\nfunction parseInPageEvalResult(text: string): InPageSightmapMatch[] {\n const afterResult = text.split(/^###\\s*Result/im)[1] ?? text;\n const start = afterResult.indexOf(\"{\");\n if (start < 0) return [];\n for (let end = afterResult.length; end > start; end--) {\n try {\n const parsed = JSON.parse(afterResult.slice(start, end)) as {\n url?: string;\n matches?: unknown[];\n };\n if (Array.isArray(parsed.matches)) {\n return parsed.matches.filter(isInPageMatch);\n }\n } catch {\n // try shorter window\n }\n }\n return [];\n}\n\n/**\n * Decode the value an upstream `browser_evaluate` returned to us.\n * Format is text after `### Result`, JSON-encoded: a number is `42`, a\n * string is `\"foo\"`, an object/array is the JSON literal.\n */\nfunction decodeMcpEvalResult(text: string): unknown {\n const afterResult = text.split(/^###\\s*Result/im)[1] ?? \"\";\n const trimmed = afterResult.trim();\n if (trimmed.length === 0) return undefined;\n // Find the first JSON-y token at the start of trimmed.\n for (let end = trimmed.length; end > 0; end--) {\n try {\n return JSON.parse(trimmed.slice(0, end));\n } catch {\n // try shorter\n }\n }\n return undefined;\n}\n\nfunction isInPageMatch(value: unknown): value is InPageSightmapMatch {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n return typeof v[\"name\"] === \"string\" && typeof v[\"matchCount\"] === \"number\";\n}\n","import { match as sightmapMatch, type Sightmap, type MatchResult } from \"@sightmap/sightmap\";\n\nexport interface SightmapMatchInput {\n url: string;\n method?: string;\n}\n\nexport interface SightmapMatchOutput {\n view: { name: string; route: string; description?: string } | null;\n components: Array<{\n name: string;\n selector: string[];\n memory: string[];\n scope: \"global\" | \"view-scoped\";\n }>;\n requests: Array<{\n name: string;\n route: string;\n method?: string;\n memory: string[];\n }>;\n /** Page-level aggregated memory from sightmap-js. */\n memory: string[];\n /** Memory attached to the matched view itself, if any. */\n viewMemory: string[];\n}\n\n/**\n * Pure handler for the `sightmap_match` MCP tool.\n *\n * Wraps sightmap-js's `match()` and shapes the response for agent consumption.\n * No browser involvement — this is the planning-side query: \"what should I\n * expect at this URL?\"\n */\nexport function handleSightmapMatch(\n sightmap: Sightmap,\n input: SightmapMatchInput,\n): SightmapMatchOutput {\n const result: MatchResult = sightmapMatch(sightmap, {\n url: input.url,\n ...(input.method !== undefined ? { method: input.method } : {}),\n });\n\n return {\n view: result.view\n ? {\n name: result.view.name,\n route: result.view.route,\n ...(result.view.description !== undefined\n ? { description: result.view.description }\n : {}),\n }\n : null,\n components: result.components.map((c) => ({\n name: c.name,\n selector: c.selector,\n memory: c.memory ?? [],\n scope: c.scope,\n })),\n requests: result.requests.map((r) => ({\n name: r.name,\n route: r.route,\n ...(r.method !== undefined ? { method: r.method } : {}),\n memory: r.memory ?? [],\n })),\n memory: result.memory ?? [],\n viewMemory: result.view?.memory ?? [],\n };\n}\n","import {\n enrichSnapshot,\n type EnrichedSnapshot,\n type InPageSightmapMatch,\n type BoundingRect,\n type SightmapSnapshotComponent,\n type Sightmap,\n} from \"@sightmap/sightmap\";\n\n// Re-export kernel types so existing MCP callers keep working unchanged.\nexport type { InPageSightmapMatch, BoundingRect, SightmapSnapshotComponent };\n\nexport interface BuildSnapshotOptions {\n sightmap: Sightmap;\n currentUrl: string;\n ariaSnapshotText: string;\n inPageMatches: InPageSightmapMatch[];\n}\n\nexport type SightmapSnapshotResponse = EnrichedSnapshot & {\n /** Raw ARIA tree text passthrough from browser_snapshot. */\n ariaSnapshot: string;\n};\n\n/**\n * Wraps the kernel's enrichSnapshot with the Playwright-MCP-specific\n * ariaSnapshot passthrough. The agent gets both the structured enrichment\n * (view, components, memory) and the raw a11y text for context.\n */\nexport function buildSightmapSnapshotResponse(\n opts: BuildSnapshotOptions,\n): SightmapSnapshotResponse {\n const enriched = enrichSnapshot({\n sightmap: opts.sightmap,\n currentUrl: opts.currentUrl,\n inPageMatches: opts.inPageMatches,\n });\n return { ...enriched, ariaSnapshot: opts.ariaSnapshotText };\n}\n","import type { ParsedNetworkRequest } from \"@sightmap/sightmap\";\n\n// Re-export so existing MCP callers continue to work.\nexport type {\n ParsedNetworkRequest,\n AnnotatedNetworkRequest,\n} from \"@sightmap/sightmap\";\nexport { annotateNetworkRequests } from \"@sightmap/sightmap\";\n\n/**\n * Parse the text output of `@playwright/mcp` `browser_network_requests`.\n *\n * Expected line format (one request per line, in the body after `### Result`):\n *\n * N. [METHOD] URL => [STATUS] STATUS_TEXT\n *\n * Lines that don't match are silently dropped — `browser_network_requests`\n * also emits notes about static resources, page-level metadata, etc.\n *\n * This parser is Playwright-MCP-specific and stays here; other engine\n * adapters write their own parser against their own engine's output.\n */\nexport function parseNetworkRequestsText(text: string): ParsedNetworkRequest[] {\n const lines = text.split(/\\r?\\n/);\n const requests: ParsedNetworkRequest[] = [];\n const re = /^\\s*\\d+\\.\\s*\\[([A-Z]+)\\]\\s+(\\S+)\\s+=>\\s+\\[(\\d+)\\]\\s+(.*?)\\s*$/;\n for (const line of lines) {\n const m = re.exec(line);\n if (m === null) continue;\n requests.push({\n method: m[1] ?? \"\",\n url: m[2] ?? \"\",\n status: Number.parseInt(m[3] ?? \"0\", 10),\n statusText: m[4] ?? \"\",\n });\n }\n return requests;\n}\n","// `sightmap_list_views` handler.\n//\n// Read-only; defaults to compact summaries (name + route + optional\n// description) so a single-call discovery in an agent's first turn fits in a\n// small token budget. `detail: \"full\"` returns the entire View object\n// including memory, components, and requests.\n\nimport type { Sightmap, View } from \"@sightmap/sightmap\";\n\nexport interface ListViewsInput {\n detail?: \"summary\" | \"full\";\n}\n\nexport interface ViewSummary {\n name: string;\n route: string;\n description?: string;\n}\n\nexport interface ListViewsOutput {\n views: Array<ViewSummary | View>;\n}\n\nexport function handleListViews(\n sightmap: Sightmap,\n input: ListViewsInput,\n): ListViewsOutput {\n const detail = input.detail ?? \"summary\";\n const sorted = [...sightmap.views].sort((a, b) =>\n a.name.localeCompare(b.name),\n );\n\n if (detail === \"full\") {\n return { views: sorted };\n }\n\n return {\n views: sorted.map((v) => {\n const summary: ViewSummary = { name: v.name, route: v.route };\n if (v.description !== undefined) summary.description = v.description;\n return summary;\n }),\n };\n}\n","// `sightmap_get_view` handler.\n//\n// Read-only single-view fetch. Returns the parsed view object plus the file\n// path it was read from, so callers can chain `update_view` against the same\n// file without an extra lookup.\n\nimport { readFile } from \"node:fs/promises\";\nimport { parse, type View } from \"@sightmap/sightmap\";\nimport { findFileForView } from \"../../curate/locator.js\";\n\nexport interface GetViewInput {\n sightmapDir: string;\n name: string;\n}\n\nexport interface GetViewOutput {\n view: View;\n file: string;\n}\n\nexport async function handleGetView(input: GetViewInput): Promise<GetViewOutput> {\n const file = await findFileForView(input.sightmapDir, input.name);\n if (file === null) {\n throw new Error(\n `View \"${input.name}\" not found in ${input.sightmapDir}`,\n );\n }\n const text = await readFile(file, \"utf8\");\n const parsed = parse(text, { sourceFile: file });\n const view = parsed.views?.find((v) => v.name === input.name);\n if (view === undefined) {\n throw new Error(\n `View \"${input.name}\" not found in ${file} (locator drift?)`,\n );\n }\n return { view, file };\n}\n","// Locate the YAML file in a `.sightmap/` directory that contains a given view.\n//\n// Used by curation tools (`get_view`, `update_view`) so callers can pass a view\n// name without also tracking which file declared it.\n\nimport { readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { parse } from \"@sightmap/sightmap\";\n\nexport type FindViewOptions = {\n onWarning?: (msg: string) => void;\n};\n\nexport async function findFileForView(\n sightmapDir: string,\n viewName: string,\n options: FindViewOptions = {},\n): Promise<string | null> {\n const entries = await readdir(sightmapDir);\n const yamlFiles = entries\n .filter((e) => e.endsWith(\".yaml\") || e.endsWith(\".yml\"))\n .sort();\n\n let firstMatch: string | null = null;\n let matchCount = 0;\n\n for (const file of yamlFiles) {\n const path = join(sightmapDir, file);\n let parsed;\n try {\n const text = await readFile(path, \"utf8\");\n parsed = parse(text, { sourceFile: path });\n } catch {\n // Skip unparseable files; `sightmap_check` is the right tool for those.\n continue;\n }\n if (parsed.views?.some((v) => v.name === viewName)) {\n matchCount++;\n if (firstMatch === null) firstMatch = path;\n }\n }\n\n if (matchCount > 1 && options.onWarning) {\n options.onWarning(\n `duplicate view name \"${viewName}\" found in ${matchCount} files; using ${firstMatch}`,\n );\n }\n\n return firstMatch;\n}\n","// `sightmap_check` handler.\n//\n// Wraps `@sightmap/sightmap`'s `lint` plus the merge/load diagnostics already\n// attached to the loaded `Sightmap` (parse errors, schema failures, merge\n// collisions). Two levels:\n//\n// schema - return only the schema-level diagnostics already on the sightmap.\n// quality - schema diagnostics plus lint output (duplicate routes, route\n// shadowing, selector syntax, etc.).\n\nimport { lint, type Sightmap, type Diagnostic } from \"@sightmap/sightmap\";\n\nexport interface CheckInput {\n level?: \"schema\" | \"quality\";\n}\n\nexport interface CheckOutput {\n diagnostics: Diagnostic[];\n}\n\nexport async function handleCheck(\n sightmap: Sightmap,\n input: CheckInput,\n): Promise<CheckOutput> {\n const level = input.level ?? \"quality\";\n const schemaDiag = [...sightmap.diagnostics];\n if (level === \"schema\") return { diagnostics: schemaDiag };\n const lintDiag = await lint(sightmap);\n return { diagnostics: [...schemaDiag, ...lintDiag] };\n}\n","// `sightmap_update_view` handler.\n//\n// Reads the YAML file containing the named view, applies a patch to the\n// view's fields, then re-writes the file via the canonical writer. The\n// emitted bytes are piped through `canonicalize()` so the result passes\n// `sightmap fmt --check` (per sightmap spec adapter-behavior guidance).\n//\n// Accepts both semantic edits (description, intent, memory_append/replace)\n// and structural edits (name, route, components). Memory edits use either\n// `memory_append` (the default operation) or `memory_replace` — never both\n// in the same patch. Components is a full array replacement; use\n// sightmap_add_view / sightmap_delete_view for whole-view lifecycle.\n\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport {\n parse,\n format,\n canonicalize,\n type FormatInput,\n type View,\n} from \"@sightmap/sightmap\";\nimport { findFileForView } from \"../../curate/locator.js\";\n\nexport interface ViewPatch {\n // Semantic fields (unchanged — backward-compatible)\n description?: string;\n intent?: string;\n memory_append?: string[];\n memory_replace?: string[];\n // Structural fields (new in 1.0-rc — replaces what codegen used to own)\n name?: string;\n route?: string;\n components?: { name: string; selector: string; memory?: string[] }[];\n}\n\nexport interface UpdateViewInput {\n sightmapDir: string;\n name: string;\n patch: ViewPatch;\n}\n\nexport interface UpdateViewOutput {\n ok: true;\n file: string;\n written: View;\n}\n\nexport async function handleUpdateView(\n input: UpdateViewInput,\n): Promise<UpdateViewOutput> {\n if (input.patch.memory_append && input.patch.memory_replace) {\n throw new Error(\n \"cannot use both memory_append and memory_replace in the same patch\",\n );\n }\n\n const file = await findFileForView(input.sightmapDir, input.name);\n if (file === null) {\n throw new Error(\n `View \"${input.name}\" not found in ${input.sightmapDir}`,\n );\n }\n\n const text = await readFile(file, \"utf8\");\n const parsed = parse(text, { sourceFile: file });\n const views = parsed.views ?? [];\n const idx = views.findIndex((v) => v.name === input.name);\n if (idx < 0) {\n throw new Error(\n `View \"${input.name}\" not found in ${file} (locator drift?)`,\n );\n }\n\n const before = views[idx]!;\n const after: View & { intent?: string } = { ...before };\n if (input.patch.description !== undefined) {\n after.description = input.patch.description;\n }\n if (input.patch.intent !== undefined) {\n after.intent = input.patch.intent;\n }\n if (input.patch.memory_append) {\n after.memory = [...(before.memory ?? []), ...input.patch.memory_append];\n }\n if (input.patch.memory_replace) {\n after.memory = [...input.patch.memory_replace];\n }\n if (input.patch.name !== undefined) {\n after.name = input.patch.name;\n }\n if (input.patch.route !== undefined) {\n after.route = input.patch.route;\n }\n if (input.patch.components !== undefined) {\n // Validate uniqueness of component names within this view.\n const seen = new Set<string>();\n for (const c of input.patch.components) {\n if (seen.has(c.name)) {\n throw new Error(`duplicate component name in patch: ${c.name}`);\n }\n seen.add(c.name);\n }\n after.components = input.patch.components;\n }\n\n const nextViews: View[] = [...views];\n nextViews[idx] = after;\n const nextDoc = stripFragmentBrand(parsed as unknown as Record<string, unknown>);\n nextDoc.views = nextViews;\n const out = format(nextDoc);\n // Pipe through `canonicalize()` so the rewritten file matches what\n // `sightmap fmt --check` expects (per-entry-type key order, top-level seq\n // sort, blank-line separators, etc.). The value object came from the parsed\n // file plus a narrow patch, so canonicalize won't return schema-invalid in\n // practice; fall back to the format() bytes if it does.\n const c = canonicalize(out, { file });\n const finalText = c.kind === \"canonical\" ? c.text : out;\n await writeFile(file, finalText, \"utf8\");\n\n return { ok: true, file, written: after };\n}\n\nfunction stripFragmentBrand(input: Record<string, unknown>): FormatInput {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(input)) {\n if (k === \"__brand\" || k === \"__sourceFile\") continue;\n out[k] = input[k];\n }\n return out as FormatInput;\n}\n","// `sightmap_add_view` handler.\n//\n// Creates a new view by writing a fresh .yaml file under the .sightmap/ dir.\n// The filename defaults to `kebab(view.name) + \".yaml\"` unless overridden via\n// the `file` hint. The emitted bytes are piped through `canonicalize()` so the\n// result passes `sightmap fmt --check` (per sightmap spec adapter-behavior\n// guidance).\n//\n// Refuses to write if a view with the same name already exists anywhere in\n// the corpus — duplicate names would collide at parse-time. Use\n// sightmap_update_view to edit existing views.\n\nimport { writeFile, readFile, readdir } from \"node:fs/promises\";\nimport { resolve, join } from \"node:path\";\nimport {\n format,\n canonicalize,\n type FormatInput,\n type View,\n} from \"@sightmap/sightmap\";\n\nexport interface AddViewInput {\n sightmapDir: string;\n view: View;\n /** Optional filename hint. Defaults to kebab(view.name) + \".yaml\". */\n file?: string;\n}\n\nexport interface AddViewOutput {\n ok: true;\n file: string;\n written: View;\n}\n\nexport async function handleAddView(input: AddViewInput): Promise<AddViewOutput> {\n await ensureNotExists(input.sightmapDir, input.view.name);\n const filename = input.file ?? kebab(input.view.name) + \".yaml\";\n const path = join(input.sightmapDir, filename);\n const doc: FormatInput = {\n version: 1,\n views: [input.view],\n };\n const out = format(doc);\n // Pipe through canonicalize() so the new file matches what `sightmap fmt\n // --check` expects (per-entry-type key order, blank-line separators, etc.).\n // Fall back to the raw format() bytes if canonicalize can't normalize.\n const c = canonicalize(out, { file: path });\n const text = c.kind === \"canonical\" ? c.text : out;\n await writeFile(path, text, \"utf8\");\n return { ok: true, file: path, written: input.view };\n}\n\nasync function ensureNotExists(dir: string, name: string): Promise<void> {\n let files: string[];\n try {\n files = await readdir(dir);\n } catch {\n return; // empty/missing dir, nothing to check\n }\n for (const f of files) {\n if (!f.endsWith(\".yaml\")) continue;\n const text = await readFile(resolve(dir, f), \"utf8\");\n if (new RegExp(`(^|\\\\n)\\\\s*-\\\\s+name:\\\\s+${escapeRe(name)}(\\\\s|$)`).test(text)) {\n throw new Error(`view \"${name}\" already exists in ${f}`);\n }\n }\n}\n\nfunction kebab(s: string): string {\n return s\n .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n .replace(/[\\s_]+/g, \"-\")\n .toLowerCase();\n}\n\nfunction escapeRe(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n","// `sightmap_delete_view` handler.\n//\n// Removes a view by name. Scans every .yaml file under the curate root for an\n// entry with the matching name. If the containing file has only the deleted\n// view, the file itself is unlinked; otherwise the view is spliced out and\n// the file rewritten via the canonical writer (so it still passes\n// `sightmap fmt --check`).\n//\n// Symmetric counterpart to sightmap_add_view: together they let an agent\n// fully manage view lifecycle without invoking codegen.\n\nimport { readFile, writeFile, unlink, readdir } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport {\n parse,\n format,\n canonicalize,\n type FormatInput,\n type View,\n} from \"@sightmap/sightmap\";\n\nexport interface DeleteViewInput {\n sightmapDir: string;\n name: string;\n}\n\nexport interface DeleteViewOutput {\n ok: true;\n file: string;\n fileDeleted: boolean;\n}\n\nexport async function handleDeleteView(\n input: DeleteViewInput,\n): Promise<DeleteViewOutput> {\n const entries = await readdir(input.sightmapDir);\n for (const entry of entries) {\n if (!entry.endsWith(\".yaml\")) continue;\n const path = resolve(input.sightmapDir, entry);\n const text = await readFile(path, \"utf8\");\n const parsed = parse(text, { sourceFile: path });\n const views = parsed.views ?? [];\n const idx = views.findIndex((v) => v.name === input.name);\n if (idx < 0) continue;\n const remaining = views.filter((_, i) => i !== idx);\n if (remaining.length === 0) {\n await unlink(path);\n return { ok: true, file: path, fileDeleted: true };\n }\n const nextDoc = stripFragmentBrand(parsed as unknown as Record<string, unknown>);\n nextDoc.views = remaining as View[];\n const out = format(nextDoc);\n // Pipe through `canonicalize()` so the rewritten file matches what\n // `sightmap fmt --check` expects (per-entry-type key order, top-level seq\n // sort, blank-line separators, etc.). Fall back to format() bytes if it\n // can't normalize.\n const c = canonicalize(out, { file: path });\n const finalText = c.kind === \"canonical\" ? c.text : out;\n await writeFile(path, finalText, \"utf8\");\n return { ok: true, file: path, fileDeleted: false };\n }\n throw new Error(`view \"${input.name}\" not found in ${input.sightmapDir}`);\n}\n\nfunction stripFragmentBrand(input: Record<string, unknown>): FormatInput {\n const out: Record<string, unknown> = {};\n for (const k of Object.keys(input)) {\n if (k === \"__brand\" || k === \"__sourceFile\") continue;\n out[k] = input[k];\n }\n return out as FormatInput;\n}\n","// `sightmap_init_project` handler.\n//\n// Scaffolds an empty `.sightmap/app.yaml` in a target project directory.\n// Refuses to overwrite an existing `.sightmap/` unless `force: true`.\n\nimport { mkdir, writeFile, access } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { makeStarterSightmap } from \"../../curate/scaffolder.js\";\n\nexport interface InitProjectInput {\n dir?: string;\n force?: boolean;\n}\n\nexport interface InitProjectOutput {\n ok: true;\n files: string[];\n}\n\nexport async function handleInitProject(\n input: InitProjectInput,\n): Promise<InitProjectOutput> {\n const root = input.dir ?? process.cwd();\n const sightmapDir = join(root, \".sightmap\");\n const appFile = join(sightmapDir, \"app.yaml\");\n\n if (input.force !== true) {\n let exists = false;\n try {\n await access(sightmapDir);\n exists = true;\n } catch {\n /* dir does not exist; continue */\n }\n if (exists) {\n throw new Error(\n `.sightmap/ already exists at ${sightmapDir} — pass force=true to overwrite`,\n );\n }\n }\n\n await mkdir(sightmapDir, { recursive: true });\n await writeFile(appFile, makeStarterSightmap(), \"utf8\");\n\n return { ok: true, files: [appFile] };\n}\n","// Starter `.sightmap/` scaffolding.\n//\n// `makeStarterSightmap` returns a minimal canonical YAML document — just a\n// `version: 1` line with no views/components/requests. Real content lands when\n// the user or the curating agent (via `sightmap_add_view` / `sightmap_update_view`)\n// adds files to the directory.\n//\n// Output is piped through `canonicalize()` so the emitted bytes match what\n// `sightmap fmt --check` expects. See sightmap/spec\n// docs/authoring-conventions.md#adapter-behavior.\n\nimport { format, canonicalize } from \"@sightmap/sightmap\";\n\nexport function makeStarterSightmap(): string {\n const text = format({ version: 1 });\n const c = canonicalize(text, { file: \"app.yaml\" });\n return c.kind === \"canonical\" ? c.text : text;\n}\n","// sightmap_runtime_snapshot: fetch a live SightmapSnapshot from a running app.\n//\n// Three capture modes:\n//\n// - `endpoint` — HTTP GET against the @sightmap/react Vite plugin endpoint.\n// Zero-config for Vite users; the plugin already serves the cached\n// snapshot at /__sightmap__/snapshot.json.\n//\n// - `browser` — drive the live browser via the @playwright/mcp passthrough.\n// Navigate to `url` (or each entry in `routes`), evaluate\n// `window.__sightmap__.snapshot()`, return the result. The bippy IIFE +\n// bootstrap are pre-navigate addInitScript'd at sightmap-mcp startup\n// (via @playwright/mcp's PLAYWRIGHT_MCP_INIT_SCRIPT env var) so the hook\n// is installed BEFORE React's first commit — works on any React app,\n// including static first-paint apps that previously yielded commits: 0.\n// A post-navigate browser_evaluate inject remains as a fallback for\n// environments where the pre-nav init script couldn't be wired.\n//\n// - `literal` — accept a pre-captured snapshot from any source (subtext's\n// live-eval-script, devtools console paste, custom Playwright scripts,\n// CI capture). Validates the shape; returns it. The universal escape\n// valve for cases where MCP can't reach the browser itself.\n\nimport type { UpstreamClient } from \"../../server.js\";\n\nexport interface RuntimeSnapshotInput {\n source:\n | { kind: \"endpoint\"; url: string }\n | {\n kind: \"browser\";\n url: string;\n routes?: string[];\n /**\n * If true (default when `window.__sightmap__` is missing), addInitScript\n * the bippy IIFE + snapshot bootstrap before navigation. Set to false\n * to require the app to already have @sightmap/react installed.\n */\n inject?: boolean;\n }\n | { kind: \"literal\"; snapshot: unknown };\n}\n\nexport type RuntimeSnapshotOutput =\n | { ok: true; snapshot: unknown; source: RuntimeSnapshotInput[\"source\"] }\n | {\n ok: true;\n snapshots: { url: string; snapshot: unknown }[];\n source: RuntimeSnapshotInput[\"source\"];\n };\n\nexport interface RuntimeSnapshotDeps {\n /** Upstream MCP client (typically @playwright/mcp). Required for browser mode. */\n upstream?: UpstreamClient;\n /** Provides the inject script (bippy IIFE + bootstrap) lazily. */\n getInjectScript?: () => Promise<string>;\n}\n\nexport async function handleRuntimeSnapshot(\n input: RuntimeSnapshotInput,\n deps: RuntimeSnapshotDeps = {},\n): Promise<RuntimeSnapshotOutput> {\n if (input.source.kind === \"endpoint\") {\n return runEndpoint(input.source);\n }\n if (input.source.kind === \"literal\") {\n return runLiteral(input.source);\n }\n return runBrowser(input.source, deps);\n}\n\nasync function runEndpoint(\n source: Extract<RuntimeSnapshotInput[\"source\"], { kind: \"endpoint\" }>,\n): Promise<RuntimeSnapshotOutput> {\n const res = await fetch(source.url);\n if (res.status === 404) {\n // The plugin returns 404 with a JSON body when no snapshot has been\n // cached yet (the user hasn't loaded a page that mounts a Provider).\n // Surface the body's `error` field so the agent's error includes the\n // root cause, not just the HTTP code.\n let detail = \"\";\n try {\n const body = (await res.json()) as { error?: string };\n detail = body.error ?? \"\";\n } catch {\n // body wasn't JSON; ignore\n }\n throw new Error(\n `no snapshot cached yet at ${source.url}${detail ? `: ${detail}` : \"\"}`,\n );\n }\n if (!res.ok) {\n throw new Error(`snapshot fetch failed: HTTP ${res.status}`);\n }\n const snapshot = (await res.json()) as unknown;\n return { ok: true, snapshot, source };\n}\n\nconst REQUIRED_SNAPSHOT_FIELDS = [\n \"capturedAt\",\n \"route\",\n \"components\",\n \"markers\",\n \"unmarkedCandidates\",\n] as const;\n\nfunction runLiteral(\n source: Extract<RuntimeSnapshotInput[\"source\"], { kind: \"literal\" }>,\n): RuntimeSnapshotOutput {\n validateSnapshotShape(source.snapshot, \"literal\");\n return { ok: true, snapshot: source.snapshot, source };\n}\n\n/**\n * Validate that `value` looks like a SightmapSnapshot. Throws a clear error\n * on the first missing field. Intentionally lenient: only checks for the\n * required top-level keys; nested shapes are trusted to the upstream\n * producer (the plugin, the user's eval, or our injected bootstrap).\n */\nfunction validateSnapshotShape(value: unknown, label: string): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `${label} snapshot: expected an object with fields ` +\n `{ capturedAt, route, components, markers, unmarkedCandidates }; ` +\n `got ${value === null ? \"null\" : Array.isArray(value) ? \"array\" : typeof value}`,\n );\n }\n const s = value as Record<string, unknown>;\n for (const field of REQUIRED_SNAPSHOT_FIELDS) {\n if (!(field in s)) {\n throw new Error(`${label} snapshot: missing required field \\`${field}\\``);\n }\n }\n if (!Array.isArray(s[\"components\"])) {\n throw new Error(`${label} snapshot: \\`components\\` must be an array`);\n }\n if (!Array.isArray(s[\"markers\"])) {\n throw new Error(`${label} snapshot: \\`markers\\` must be an array`);\n }\n if (!Array.isArray(s[\"unmarkedCandidates\"])) {\n throw new Error(`${label} snapshot: \\`unmarkedCandidates\\` must be an array`);\n }\n}\n\nasync function runBrowser(\n source: Extract<RuntimeSnapshotInput[\"source\"], { kind: \"browser\" }>,\n deps: RuntimeSnapshotDeps,\n): Promise<RuntimeSnapshotOutput> {\n if (deps.upstream === undefined) {\n throw new Error(\n \"browser-mode snapshot requires an upstream MCP server (e.g., @playwright/mcp). \" +\n \"Run sightmap-mcp without `--curate-only` so the @playwright/mcp passthrough is wired up.\",\n );\n }\n const upstream = deps.upstream;\n\n // Decide whether to inject. Defaults: when `inject` is explicit, honor it;\n // when omitted, auto-detect by probing window.__sightmap__ after navigation\n // — if absent, evaluate the inject script post-navigate as a fallback.\n const wantInject = source.inject === true;\n const allowAutoInject = source.inject === undefined;\n\n // Injection is normally wired pre-navigate via the upstream\n // (@playwright/mcp >= 0.0.75) `PLAYWRIGHT_MCP_INIT_SCRIPT` / `--init-script`,\n // configured at sightmap-mcp startup in cli.ts. That path installs bippy +\n // bootstrap BEFORE any page script runs, so window.__sightmap__.snapshot\n // is present before React's first commit. The post-navigate\n // browser_evaluate inject below is the belt-and-suspenders fallback for:\n // - servers where the pre-nav init script couldn't be written (rare),\n // - hosts that filter env vars and strip PLAYWRIGHT_MCP_INIT_SCRIPT,\n // - users running an older @playwright/mcp pinned via `--`,\n // and so on. When pre-nav inject works (the common case) the probe below\n // returns \"function\" and the post-nav inject is skipped.\n\n const urls = source.routes !== undefined && source.routes.length > 0\n ? source.routes.map((r) => absolutize(r, source.url))\n : [source.url];\n\n const captures: { url: string; snapshot: unknown }[] = [];\n for (const targetUrl of urls) {\n const captureOpts: CaptureOpts = {\n forceInject: wantInject,\n autoInject: allowAutoInject,\n };\n if (deps.getInjectScript !== undefined) {\n captureOpts.getInjectScript = deps.getInjectScript;\n }\n const cap = await captureOneUrl(upstream, targetUrl, captureOpts);\n validateSnapshotShape(cap, \"browser\");\n captures.push({ url: targetUrl, snapshot: cap });\n }\n\n if (source.routes === undefined || source.routes.length === 0) {\n return { ok: true, snapshot: captures[0]!.snapshot, source };\n }\n return { ok: true, snapshots: captures, source };\n}\n\nfunction absolutize(routeOrUrl: string, baseUrl: string): string {\n // If the entry parses as an absolute URL, return as-is. Otherwise treat it\n // as a path on the same origin as `baseUrl`.\n try {\n return new URL(routeOrUrl).toString();\n } catch {\n const base = new URL(baseUrl);\n return new URL(routeOrUrl, base).toString();\n }\n}\n\ninterface CaptureOpts {\n forceInject: boolean;\n autoInject: boolean;\n getInjectScript?: () => Promise<string>;\n}\n\nasync function captureOneUrl(\n upstream: UpstreamClient,\n url: string,\n opts: CaptureOpts,\n): Promise<unknown> {\n // Navigate first.\n const navResult = await upstream.callTool(\"browser_navigate\", { url });\n if (navResult.isError === true) {\n throw new Error(\n `browser_navigate to ${url} failed: ${navResult.content[0]?.text ?? \"unknown error\"}`,\n );\n }\n\n // Probe for window.__sightmap__. Decoded JSON value: \"function\" | \"object\" | \"undefined\".\n const probe = await evalAndDecode(\n upstream,\n `() => typeof (window.__sightmap__ && window.__sightmap__.snapshot)`,\n );\n const hasHook = probe === \"function\";\n\n if (!hasHook && (opts.forceInject || opts.autoInject)) {\n if (opts.getInjectScript === undefined) {\n throw new Error(\n \"browser-mode snapshot: page has no window.__sightmap__ and no inject script provider was configured. \" +\n \"Install @sightmap/react in the target app, or wire `getInjectScript` into the MCP server.\",\n );\n }\n const script = await opts.getInjectScript();\n // The script is a self-installing IIFE. Wrap it as a fn body for\n // browser_evaluate: it expects `() => { ... }` and the script's own\n // outermost IIFE runs as part of `value` evaluation.\n const wrapped = `() => { ${script}\\n; return typeof (window.__sightmap__ && window.__sightmap__.snapshot); }`;\n const injectResult = await evalAndDecode(upstream, wrapped);\n if (injectResult !== \"function\") {\n throw new Error(\n `browser-mode snapshot: inject script did not install window.__sightmap__.snapshot ` +\n `(typeof after inject: ${String(injectResult)}). The target page may not be a React app.`,\n );\n }\n } else if (!hasHook && opts.forceInject === false && opts.autoInject === false) {\n throw new Error(\n \"browser-mode snapshot: page has no window.__sightmap__.snapshot and `inject: false` was set. \" +\n \"Either install @sightmap/react in the app or pass `inject: true`.\",\n );\n }\n\n // Evaluate the snapshot. We wrap with JSON.parse(JSON.stringify(...)) to\n // force a plain serializable value (defends against Sets / Maps / Dates\n // that the upstream's stringify path might mangle).\n const snap = await evalAndDecode(\n upstream,\n `() => JSON.parse(JSON.stringify(window.__sightmap__.snapshot()))`,\n );\n return snap;\n}\n\nasync function evalAndDecode(\n upstream: UpstreamClient,\n fnSource: string,\n): Promise<unknown> {\n const r = await upstream.callTool(\"browser_evaluate\", { function: fnSource });\n if (r.isError === true) {\n throw new Error(\n `browser_evaluate failed: ${r.content[0]?.text ?? \"unknown error\"}`,\n );\n }\n const text = r.content.map((b) => b.text).join(\"\\n\");\n return decodeEvalText(text);\n}\n\n/**\n * Decode a @playwright/mcp `browser_evaluate` response into the raw JS value.\n *\n * The upstream wraps the result as a text block containing a `### Result`\n * header followed by the JSON-encoded value. We scan for the first complete\n * JSON token after the header.\n */\nfunction decodeEvalText(text: string): unknown {\n const afterResult = text.split(/^###\\s*Result/im)[1] ?? text;\n const trimmed = afterResult.trim();\n if (trimmed.length === 0) return undefined;\n // Try whole-string parse first (handles the simple case where the result\n // payload IS the trimmed text).\n for (let end = trimmed.length; end > 0; end--) {\n try {\n return JSON.parse(trimmed.slice(0, end));\n } catch {\n // try shorter\n }\n }\n return undefined;\n}\n","// Build the browser-side inject script for `sightmap_runtime_snapshot`'s\n// `kind: \"browser\"` mode.\n//\n// The script has two parts, concatenated:\n//\n// 1. bippy's IIFE bundle (read once from node_modules/bippy/dist/index.iife.js).\n// Exposes `window.Bippy` with `instrument`, `traverseFiber`, `getDisplayName`,\n// `isCompositeFiber`.\n//\n// 2. A small bootstrap (BOOTSTRAP_SRC below) that:\n// - calls `Bippy.instrument({ onCommitFiberRoot })` to capture FiberRoots\n// - defines `window.__sightmap__.snapshot()` that serializes the fiber\n// tree into the same SightmapSnapshot shape the @sightmap/react\n// runtime produces, so the rest of the pipeline (audit, propose,\n// match) treats inject-mode output identically to plugin-endpoint\n// output.\n//\n// This script is `addInitScript`-injected before navigation when the caller\n// requests `inject: true` (or when auto-detection finds `window.__sightmap__`\n// absent on the target page). One file, no build-time bundling — easier to\n// debug and keeps `@sightmap/mcp`'s tsup config unchanged.\n\nimport { createRequire } from \"node:module\";\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\nlet cachedScript: string | undefined;\n\n/**\n * Returns the full inject script (bippy IIFE + bootstrap), cached after the\n * first call. Reads bippy's IIFE lazily so test environments that never\n * exercise browser mode don't pay for it.\n */\nexport async function getInjectScript(): Promise<string> {\n if (cachedScript !== undefined) return cachedScript;\n const bippyIife = await loadBippyIife();\n cachedScript = `${bippyIife}\\n${BOOTSTRAP_SRC}`;\n return cachedScript;\n}\n\nasync function loadBippyIife(): Promise<string> {\n // Resolve bippy from this module's location. Works under both pnpm's\n // .pnpm/ layout and a flat hoisted node_modules.\n const require = createRequire(import.meta.url);\n const bippyPkgJson = require.resolve(\"bippy/package.json\");\n const iifePath = resolve(dirname(bippyPkgJson), \"dist/index.iife.js\");\n return readFile(iifePath, \"utf8\");\n}\n\n// Bootstrap script: pure JS string. Mirrors packages/react/src/runtime\n// (bippy-install + serialize + rank-selectors + portal-aware-walker), pared\n// down to the minimum needed by `sightmap_runtime_snapshot { kind: \"browser\" }`.\n//\n// Kept in sync with serialize.ts by convention; if the snapshot schema\n// evolves, update both call sites.\nconst BOOTSTRAP_SRC = String.raw`\n(function () {\n if (typeof window === \"undefined\") return;\n if (!window.Bippy || typeof window.Bippy.instrument !== \"function\") return;\n if (window.__sightmap__ && typeof window.__sightmap__.snapshot === \"function\") {\n // Already installed (e.g. @sightmap/react is present). Don't double-wire.\n return;\n }\n\n var trackedRoots = new Set();\n window.Bippy.instrument({\n onCommitFiberRoot: function (_id, root) {\n trackedRoots.add(root);\n },\n });\n\n var FRAMEWORK_NOISE = new Set([\n \"Routes\", \"Route\", \"RenderedRoute\", \"Outlet\", \"BrowserRouter\",\n \"Router\", \"RouterProvider\", \"DataRouterProvider\", \"RouterProviderImpl\",\n \"LinkWithRef\", \"StrictMode\", \"SightmapProvider\", \"Fragment\", \"Anonymous\",\n \"Suspense\", \"ErrorBoundary\", \"Provider\", \"Consumer\",\n \"ThemeProvider\", \"Hydration\", \"HydrateFallback\",\n \"RemixErrorBoundary\", \"HydratedRouter\", \"DataRoutes\",\n \"WithHydrateFallbackProps2\", \"RenderErrorBoundary\", \"Layout\",\n ]);\n\n var HOST_PORTAL_TAG = 4;\n\n function cssEsc(v) { return String(v).replace(/\"/g, '\\\\\"'); }\n function isHumanShapedId(id) {\n if (/[0-9]{6,}/.test(id)) return false;\n if (/^[a-z]+-[a-f0-9]{8,}/i.test(id)) return false;\n if (/:r[0-9a-z]+:/i.test(id)) return false;\n return true;\n }\n function rankSelectors(el) {\n var out = [];\n var dsm = el.getAttribute(\"data-sightmap\");\n if (dsm !== null) {\n out.push({ selector: '[data-sightmap=\"' + cssEsc(dsm) + '\"]', stability: \"high\", source: \"data-sightmap\" });\n }\n [\"data-testid\", \"data-cy\", \"data-test\"].forEach(function (attr) {\n var v = el.getAttribute(attr);\n if (v !== null) {\n out.push({ selector: \"[\" + attr + '=\"' + cssEsc(v) + '\"]', stability: \"high\", source: attr });\n }\n });\n var role = el.getAttribute(\"role\");\n var aria = el.getAttribute(\"aria-label\");\n if (role && aria) {\n out.push({ selector: '[role=\"' + cssEsc(role) + '\"][aria-label=\"' + cssEsc(aria) + '\"]', stability: \"medium\", source: \"aria\" });\n } else if (aria) {\n out.push({ selector: '[aria-label=\"' + cssEsc(aria) + '\"]', stability: \"medium\", source: \"aria-label\" });\n }\n var name = el.getAttribute(\"name\");\n if (name !== null && /^(form|input|button|select|textarea|nav)$/i.test(el.tagName)) {\n out.push({ selector: el.tagName.toLowerCase() + '[name=\"' + cssEsc(name) + '\"]', stability: \"medium\", source: \"semantic-name\" });\n }\n if (el.id && isHumanShapedId(el.id)) {\n out.push({ selector: \"#\" + cssEsc(el.id), stability: \"high\", source: \"id\" });\n }\n return out;\n }\n\n function findHostElementForFiber(fiber) {\n if (!fiber.child) return null;\n var stack = [fiber.child];\n var walks = 0;\n while (stack.length > 0 && walks < 5000) {\n walks++;\n var f = stack.pop();\n if (!f) continue;\n if (f.sibling) stack.push(f.sibling);\n if (f.tag === HOST_PORTAL_TAG) continue;\n var sn = f.stateNode;\n if (sn && typeof sn === \"object\" && \"tagName\" in sn && document.contains(sn)) {\n return sn;\n }\n if (f.child) stack.push(f.child);\n }\n return null;\n }\n\n function bridgeDomToFiber(el) {\n for (var i = 0, keys = Object.keys(el); i < keys.length; i++) {\n if (keys[i].indexOf(\"__reactFiber$\") === 0) return el[keys[i]] || null;\n }\n return null;\n }\n\n function nearestCompositeName(fiber) {\n var f = fiber, walks = 0;\n while (f && walks < 50) {\n if (window.Bippy.isCompositeFiber(f)) {\n var n = window.Bippy.getDisplayName(f);\n if (n) return n;\n }\n f = f.return;\n walks++;\n }\n return undefined;\n }\n\n function domDepth(el) {\n var d = 0, cur = el.parentElement;\n while (cur && cur !== document.body) { d++; cur = cur.parentElement; }\n return d;\n }\n\n function collectComponents(rootFiber) {\n var out = [];\n var depthByFiber = new Map();\n depthByFiber.set(rootFiber, 0);\n window.Bippy.traverseFiber(rootFiber, function (f) {\n var depth = depthByFiber.get(f) || 0;\n var c = f.child;\n while (c) { depthByFiber.set(c, depth + 1); c = c.sibling; }\n if (!window.Bippy.isCompositeFiber(f)) return false;\n var name = window.Bippy.getDisplayName(f);\n if (!name) return false;\n var childNames = [];\n var cc = f.child;\n while (cc) {\n if (window.Bippy.isCompositeFiber(cc)) {\n var n = window.Bippy.getDisplayName(cc);\n if (n) childNames.push(n);\n }\n cc = cc.sibling;\n }\n out.push({ displayName: name, depth: depth, children: childNames });\n return false;\n });\n return out;\n }\n\n function collectMarkers() {\n var out = [];\n if (typeof document === \"undefined\") return out;\n var els = document.querySelectorAll(\"[data-sightmap]\");\n for (var i = 0; i < els.length; i++) {\n var el = els[i];\n var name = el.getAttribute(\"data-sightmap\") || \"\";\n var fiber = bridgeDomToFiber(el);\n var nc = nearestCompositeName(fiber);\n var marker = {\n name: name,\n hostTag: el.tagName.toLowerCase(),\n domDepth: domDepth(el),\n candidateSelectors: rankSelectors(el),\n };\n if (nc !== undefined) marker.nearestComponent = nc;\n out.push(marker);\n }\n return out;\n }\n\n function collectUnmarkedCandidates(rootFiber) {\n var out = [];\n var seen = new Set();\n window.Bippy.traverseFiber(rootFiber, function (f) {\n if (!window.Bippy.isCompositeFiber(f)) return false;\n var name = window.Bippy.getDisplayName(f);\n if (!name || seen.has(name) || FRAMEWORK_NOISE.has(name)) return false;\n seen.add(name);\n var hostEl = findHostElementForFiber(f);\n if (!hostEl) return false;\n var selectors = rankSelectors(hostEl);\n if (selectors.length === 0) return false;\n out.push({\n displayName: name,\n hostTag: hostEl.tagName.toLowerCase(),\n selectors: selectors,\n domDepth: domDepth(hostEl),\n });\n return false;\n });\n return out;\n }\n\n function snapshot() {\n var roots = Array.from(trackedRoots);\n var now = new Date().toISOString();\n var loc = (typeof window !== \"undefined\" && window.location)\n ? (window.location.pathname + (window.location.search || \"\"))\n : \"?\";\n if (roots.length === 0) {\n return { capturedAt: now, route: loc === \"?\" ? \"?\" : loc, commits: 0, components: [], markers: [], unmarkedCandidates: [] };\n }\n var root = roots.find(function (r) { return r.current && r.current.child !== null; }) || roots[0];\n if (!root) {\n return { capturedAt: now, route: loc === \"?\" ? \"?\" : loc, commits: 0, components: [], markers: [], unmarkedCandidates: [] };\n }\n var rootFiber = root.current;\n return {\n capturedAt: now,\n route: loc,\n commits: roots.length,\n components: collectComponents(rootFiber),\n markers: collectMarkers(),\n unmarkedCandidates: collectUnmarkedCandidates(rootFiber),\n };\n }\n\n window.__sightmap__ = { snapshot: snapshot };\n})();\n`;\n","import type {\n ProposedView,\n ProposedComponent,\n ReviewResult,\n CommitInput,\n} from \"./types.js\";\n\nexport class ProposalStore {\n private views: ProposedView[] = [];\n private components: ProposedComponent[] = [];\n private nextId = 1;\n\n private mintId(prefix: string): string {\n return `${prefix}_${this.nextId++}`;\n }\n\n appendView(p: Omit<ProposedView, \"id\">): ProposedView {\n const v: ProposedView = { id: this.mintId(\"v\"), ...p };\n this.views.push(v);\n return v;\n }\n\n appendComponent(p: Omit<ProposedComponent, \"id\">): ProposedComponent {\n const c: ProposedComponent = { id: this.mintId(\"c\"), ...p };\n this.components.push(c);\n return c;\n }\n\n review(): ReviewResult {\n return { views: [...this.views], components: [...this.components] };\n }\n\n commit(input: CommitInput = {}): ReviewResult {\n if (!input.ids) {\n const out = this.review();\n this.views = [];\n this.components = [];\n return out;\n }\n const selected = new Set(input.ids);\n const consumedViews = this.views.filter((v) => selected.has(v.id));\n const consumedComponents = this.components.filter((c) => selected.has(c.id));\n this.views = this.views.filter((v) => !selected.has(v.id));\n this.components = this.components.filter((c) => !selected.has(c.id));\n return { views: consumedViews, components: consumedComponents };\n }\n}\n\n/**\n * Process-wide singleton. The MCP server is a single process per session, so\n * one global queue is correct. If we ever multi-tenant, replace with a per-\n * session map keyed off the JSON-RPC client id.\n */\nexport const proposalStore = new ProposalStore();\n","// `sightmap_propose_view` handler.\n//\n// Stages a proposed view observation in the in-memory proposal store. Does NOT\n// write to disk. Use `sightmap_commit_proposals` to persist staged proposals\n// via `sightmap_add_view`.\n//\n// Part of the agent-curation loop: agents call propose_view as they observe\n// noteworthy views during runtime exploration; the staging area is reviewed\n// and committed in a separate step.\n\nimport { proposalStore } from \"./store.js\";\nimport type { ProposedView } from \"./types.js\";\n\nexport type ProposeViewInput = Omit<ProposedView, \"id\">;\nexport interface ProposeViewOutput {\n ok: true;\n id: string;\n}\n\nexport async function handleProposeView(\n input: ProposeViewInput,\n): Promise<ProposeViewOutput> {\n const v = proposalStore.appendView(input);\n return { ok: true, id: v.id };\n}\n","// `sightmap_propose_component` handler.\n//\n// Stages a proposed component observation in the in-memory proposal store.\n// Does NOT write to disk. Components are usually attached to a view at commit\n// time (Phase 3); for now they accumulate alongside view proposals and surface\n// through `sightmap_review_proposals`.\n\nimport { proposalStore } from \"./store.js\";\nimport type { ProposedComponent } from \"./types.js\";\n\nexport type ProposeComponentInput = Omit<ProposedComponent, \"id\">;\nexport interface ProposeComponentOutput {\n ok: true;\n id: string;\n}\n\nexport async function handleProposeComponent(\n input: ProposeComponentInput,\n): Promise<ProposeComponentOutput> {\n const c = proposalStore.appendComponent(input);\n return { ok: true, id: c.id };\n}\n","// `sightmap_review_proposals` handler.\n//\n// Returns the current staged proposals (views + components) without consuming\n// the queue. Read-only — purely a peek into the proposal store so the agent\n// can sanity-check the batch before committing.\n\nimport { proposalStore } from \"./store.js\";\nimport type { ReviewResult } from \"./types.js\";\n\nexport async function handleReviewProposals(): Promise<ReviewResult> {\n return proposalStore.review();\n}\n","// `sightmap_commit_proposals` handler.\n//\n// Promotes staged proposals to disk by delegating to `sightmap_add_view` for\n// each consumed view. Two modes:\n// - dry_run: peek at what *would* be committed without consuming the queue\n// and without writing anything. Used by the plugin's skill to preview\n// before final write.\n// - real run: consume matching proposals from the store and write yaml files.\n//\n// `ids` (optional) restricts the operation to a selected subset; if omitted,\n// every staged proposal is consumed/peeked.\n//\n// Components in the queue are currently surfaced in the `committed` payload\n// but not written to their own files (Phase 3 will attach them to views).\n\nimport { proposalStore } from \"./store.js\";\nimport { handleAddView } from \"../curate/add.js\";\nimport type { ReviewResult } from \"./types.js\";\n\nexport interface CommitProposalsInput {\n sightmapDir: string;\n ids?: string[];\n dry_run?: boolean;\n}\n\nexport interface CommitProposalsOutput {\n ok: true;\n committed: ReviewResult;\n writes: { kind: \"view\"; file: string }[];\n}\n\nexport async function handleCommitProposals(\n input: CommitProposalsInput,\n): Promise<CommitProposalsOutput> {\n if (input.dry_run === true) {\n const peek = proposalStore.review();\n const selectedIds = input.ids ? new Set(input.ids) : null;\n const filtered: ReviewResult = {\n views: selectedIds\n ? peek.views.filter((v) => selectedIds.has(v.id))\n : peek.views,\n components: selectedIds\n ? peek.components.filter((c) => selectedIds.has(c.id))\n : peek.components,\n };\n return { ok: true, committed: filtered, writes: [] };\n }\n\n const consumed = proposalStore.commit(\n input.ids ? { ids: input.ids } : {},\n );\n const writes: { kind: \"view\"; file: string }[] = [];\n for (const v of consumed.views) {\n const r = await handleAddView({\n sightmapDir: input.sightmapDir,\n view: {\n name: v.name ?? deriveName(v.route),\n route: v.route,\n components: [],\n ...(v.intent !== undefined ? { intent: v.intent } : {}),\n ...(v.memory_notes && v.memory_notes.length > 0\n ? { memory: v.memory_notes }\n : {}),\n },\n });\n writes.push({ kind: \"view\", file: r.file });\n }\n return { ok: true, committed: consumed, writes };\n}\n\nfunction deriveName(route: string): string {\n const parts = route\n .replace(/^\\/+|\\/+$/g, \"\")\n .split(\"/\")\n .filter((p) => p.length > 0);\n const last = parts[parts.length - 1] ?? \"Index\";\n return last\n .replace(/[-_]/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n .replace(/\\s+/g, \"\");\n}\n","import type { PromptEntry, PromptResult } from \"./index.js\";\n\n/**\n * sightmap_sep_track — multi-phase prompt that walks an author through\n * writing a Sightmap Enhancement Proposal, the matching spec/ change,\n * and the matching conformance/ fixture.\n *\n * Phase model:\n * draft → write seps/NNNN-{slug}.md, then STOP for user confirmation\n * spec → propose a diff against spec/, then STOP for user confirmation\n * fixture → create conformance/NNN-{slug}/, then STOP for user confirmation\n * verify → terminal summary message, no further phases\n *\n * Confirmation gates are encoded as text directives in each non-final phase\n * because MCP prompts have no native \"wait for user\" primitive. The agent\n * is expected to honor them.\n *\n * Inspired by Archcore's architecture_track (Archcore audit §1.6).\n */\n\nconst VALID_PHASES = [\"draft\", \"spec\", \"fixture\", \"verify\"] as const;\ntype Phase = (typeof VALID_PHASES)[number];\n\nfunction buildDraftPhase(args: { slug?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n return [\n `# SEP track — phase 1 of 4: Draft the SEP`,\n ``,\n `You are helping the user author a Sightmap Enhancement Proposal (SEP).`,\n `An SEP is required for any change to the spec's schema, semantics, or`,\n `discovery rules. See \\`seps/README.md\\` for the full list.`,\n ``,\n `## Steps for this phase`,\n ``,\n `1. **Pick a number.** Look at \\`seps/\\` and find the lowest unused 4-digit`,\n ` integer (skip \\`0000-template.md\\`). Call this NNNN.`,\n `2. **Copy the template.** \\`cp seps/0000-template.md seps/NNNN-${slug}.md\\`.`,\n `3. **Fill in the front-matter.** Title, author, today's date, status: Draft.`,\n `4. **Write the body.** Sections from the template:`,\n ` - Summary (one paragraph; treat as the abstract)`,\n ` - Motivation (concrete user-facing problem; name a real app or pattern)`,\n ` - Proposal (Shape, Semantics, Conformance — show YAML, show JSON Schema diff)`,\n ` - Alternatives considered (at least two, including \"do nothing\")`,\n ` - Migration (what changes for existing users)`,\n ` - Open questions`,\n `5. **Read it back.** Does it pass the acceptance checklist in \\`seps/README.md\\`?`,\n ``,\n `## STOP HERE`,\n ``,\n `Show the draft to the user. Ask for explicit \"go\" before continuing.`,\n `Do **not** open the spec edit until the user confirms the SEP draft.`,\n ``,\n `When the user is ready, call this prompt again with`,\n `\\`phase: \"spec\"\\` and pass \\`sep_number: \"NNNN\"\\` and \\`slug: \"${slug}\"\\`.`,\n ].join(\"\\n\");\n}\n\nfunction buildSpecPhase(args: { slug?: string; sep_number?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n const sep = args.sep_number ?? \"NNNN\";\n return [\n `# SEP track — phase 2 of 4: Propose the spec change`,\n ``,\n `Building on \\`seps/${sep}-${slug}.md\\`.`,\n ``,\n `## Steps for this phase`,\n ``,\n `1. **Identify the spec files affected.** Most changes touch:`,\n ` - \\`spec/v1/sightmap.schema.json\\` (the JSON Schema)`,\n ` - \\`spec/v1/sightmap.spec.md\\` (the prose spec)`,\n ` - Possibly \\`spec/v1/examples/\\` if the change adds a shape worth showing`,\n `2. **Make the edits.** Keep the diff small. The SEP is the design doc;`,\n ` the spec edit is the precise textual change.`,\n `3. **Run \\`pnpm -F @sightmap/sightmap test\\`.** Existing examples must still`,\n ` parse and validate, unless the SEP is explicitly breaking — in which`,\n ` case the SEP's Migration section must say so.`,\n `4. **Cross-reference.** Add a \"Spec changes:\" line near the top of the SEP`,\n ` listing the touched files. Add a comment in the schema file pointing`,\n ` back to \\`seps/${sep}-${slug}.md\\` if the rationale isn't obvious from`,\n ` the diff alone.`,\n ``,\n `## STOP HERE`,\n ``,\n `Show the spec diff to the user. Ask for explicit \"go\" before continuing.`,\n `Do **not** start the conformance fixture until the user confirms the spec edit.`,\n ``,\n `When the user is ready, call this prompt again with`,\n `\\`phase: \"fixture\"\\`, \\`sep_number: \"${sep}\"\\`, \\`slug: \"${slug}\"\\`.`,\n ].join(\"\\n\");\n}\n\nfunction buildFixturePhase(args: { slug?: string; sep_number?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n const sep = args.sep_number ?? \"NNNN\";\n // Conformance fixture numbers in this repo are 3-digit; SEP numbers are 4-digit.\n // Drop the leading zero of the SEP number to suggest a fixture number, but\n // tell the agent to verify against existing fixtures.\n const fixtureGuess = sep.startsWith(\"0\") ? sep.slice(1) : sep;\n return [\n `# SEP track — phase 3 of 4: Write the conformance fixture`,\n ``,\n `Building on \\`seps/${sep}-${slug}.md\\` and the spec edit from phase 2.`,\n ``,\n `## Steps for this phase`,\n ``,\n `1. **Pick a fixture number.** Conformance fixtures use 3-digit numbers`,\n ` (\\`001-minimal\\`, \\`002-multi-file-merge\\`, …). Pick the lowest unused`,\n ` number — likely \\`${fixtureGuess}\\` if the SEP and fixture numberings`,\n ` line up, but verify against \\`conformance/\\`.`,\n `2. **Create the directory.** \\`mkdir conformance/${fixtureGuess}-${slug}\\`.`,\n `3. **Write the input.** \\`conformance/${fixtureGuess}-${slug}/sightmap/\\``,\n ` contains one or more \\`.yaml\\` files demonstrating the new behavior.`,\n ` Keep it minimal — one fixture, one behavior under test.`,\n `4. **Write the expected output.** \\`conformance/${fixtureGuess}-${slug}/expected.json\\``,\n ` is the canonical merged + resolved sightmap that any spec-conformant`,\n ` parser must produce. Use the existing \\`@sightmap/sightmap\\` parser`,\n ` to generate the baseline, then hand-audit it against the SEP.`,\n `5. **Run the conformance suite.** \\`pnpm -F @sightmap/sightmap test\\` should`,\n ` pick up the new fixture and validate it.`,\n ``,\n `## STOP HERE`,\n ``,\n `Show the fixture (input + expected.json) to the user. Ask for explicit`,\n `\"go\" before continuing. Do **not** declare the SEP ready for review until`,\n `the user confirms all three artefacts.`,\n ``,\n `When the user is ready, call this prompt again with`,\n `\\`phase: \"verify\"\\`, \\`sep_number: \"${sep}\"\\`, \\`slug: \"${slug}\"\\`.`,\n ].join(\"\\n\");\n}\n\nfunction buildVerifyPhase(args: { slug?: string; sep_number?: string }): string {\n const slug = args.slug ?? \"{slug}\";\n const sep = args.sep_number ?? \"NNNN\";\n return [\n `# SEP track — phase 4 of 4: Verify and hand off`,\n ``,\n `## Summary`,\n ``,\n `SEP ${sep} ← spec edit ← conformance fixture, ready for review.`,\n ``,\n `Three artefacts should now exist on this branch:`,\n ``,\n `- \\`seps/${sep}-${slug}.md\\` (Draft → flip to Review when filing the PR)`,\n `- spec/ edits (listed in the SEP's \"Spec changes:\" line)`,\n `- \\`conformance/<fixture-number>-${slug}/\\` with \\`sightmap/\\` input and`,\n ` \\`expected.json\\` output`,\n ``,\n `## Next steps for the user`,\n ``,\n `1. Open a draft PR titled \"SEP ${sep}: <short title>\".`,\n `2. PR description: link the SEP, the spec diff, and the fixture; link any`,\n ` prior Discussion or Issue.`,\n `3. Flip the SEP front-matter \\`status\\` from \\`Draft\\` to \\`Review\\` when`,\n ` ready for substantive feedback.`,\n `4. Per \\`seps/README.md\\`: minimum review window is 7 days for minor`,\n ` changes, 14 days for anything affecting the JSON Schema.`,\n ``,\n `Track is complete. No further phases.`,\n ].join(\"\\n\");\n}\n\nfunction buildPhase(args: Record<string, string>): string {\n if (typeof args[\"phase\"] !== \"string\" || args[\"phase\"].length === 0) {\n throw new Error(`sightmap_sep_track: argument \"phase\" is required`);\n }\n if (!(VALID_PHASES as readonly string[]).includes(args[\"phase\"])) {\n throw new Error(\n `sightmap_sep_track: unknown phase \"${args[\"phase\"]}\" — expected one of ${VALID_PHASES.join(\", \")}`,\n );\n }\n const phase = args[\"phase\"] as Phase;\n // Build the per-phase argument bag conditionally so undefined values are\n // omitted (required by `exactOptionalPropertyTypes: true`).\n const phaseArgs: { slug?: string; sep_number?: string } = {};\n if (typeof args[\"slug\"] === \"string\") phaseArgs.slug = args[\"slug\"];\n if (typeof args[\"sep_number\"] === \"string\") phaseArgs.sep_number = args[\"sep_number\"];\n switch (phase) {\n case \"draft\":\n return buildDraftPhase(phaseArgs);\n case \"spec\":\n return buildSpecPhase(phaseArgs);\n case \"fixture\":\n return buildFixturePhase(phaseArgs);\n case \"verify\":\n return buildVerifyPhase(phaseArgs);\n }\n}\n\nexport const sepTrackPrompt: PromptEntry = {\n definition: {\n name: \"sightmap_sep_track\",\n description:\n \"Walks an author through writing a Sightmap Enhancement Proposal (SEP), the matching spec/ change, and the matching conformance/ fixture in four phases (draft → spec → fixture → verify). Each non-final phase ends with a confirmation gate — call this prompt again with the next phase only after the user confirms. Inspired by Archcore's architecture_track pattern.\",\n arguments: [\n {\n name: \"phase\",\n description: 'One of \"draft\", \"spec\", \"fixture\", \"verify\". Required.',\n required: true,\n },\n {\n name: \"slug\",\n description: \"Short kebab-case slug for the SEP (e.g. 'extend-memory').\",\n required: false,\n },\n {\n name: \"sep_number\",\n description: 'Four-digit SEP number assigned in phase \"draft\" (e.g. \"0001\").',\n required: false,\n },\n ],\n },\n handler: (args): PromptResult => {\n const text = buildPhase(args);\n return {\n messages: [\n {\n role: \"user\",\n content: { type: \"text\", text },\n },\n ],\n };\n },\n};\n","import type { GetPromptResult } from \"@modelcontextprotocol/sdk/types.js\";\nimport { sepTrackPrompt } from \"./sepTrack.js\";\n\n/** MCP prompt argument descriptor (mirrors the SDK's PromptArgumentSchema). */\nexport interface PromptArgumentDef {\n name: string;\n description?: string;\n required?: boolean;\n}\n\n/** A prompt the server advertises in `prompts/list`. */\nexport interface PromptDefinition {\n name: string;\n description: string;\n arguments?: PromptArgumentDef[];\n}\n\n/** Result of `prompts/get` — what the agent gets. */\nexport type PromptResult = GetPromptResult;\n\n/** Handler signature: takes user-supplied string args, returns the result. */\nexport type PromptHandler = (args: Record<string, string>) => PromptResult;\n\n/**\n * Promise-tolerant variant for handlers that need IO. None today; reserved.\n */\nexport type AsyncPromptHandler = (args: Record<string, string>) => Promise<PromptResult>;\n\n/** Registry entry pairing a definition with its handler. */\nexport interface PromptEntry {\n definition: PromptDefinition;\n handler: PromptHandler;\n}\n\n/** All prompts the server exposes via `prompts/list` and `prompts/get`. */\nexport const PROMPT_REGISTRY: PromptEntry[] = [sepTrackPrompt];\n","import type { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type { ToolDefinition, ToolResult, UpstreamClient } from \"./server.js\";\n\ninterface SdkTool {\n name: string;\n description?: string;\n inputSchema: ToolDefinition[\"inputSchema\"];\n}\n\ninterface SdkToolsResponse {\n tools: SdkTool[];\n}\n\ninterface SdkContentBlock {\n type: string;\n text?: string;\n data?: string;\n mimeType?: string;\n}\n\ninterface SdkCallResponse {\n content?: SdkContentBlock[];\n isError?: boolean;\n}\n\n/**\n * Wraps a connected `@modelcontextprotocol/sdk` Client and exposes it as\n * the `UpstreamClient` interface that `SightmapMcpServer` consumes.\n *\n * The constructor takes an *already-connected* Client so testing can\n * substitute any duck-typed implementation. The CLI builds the real one.\n */\nexport class McpClientUpstream implements UpstreamClient {\n constructor(private readonly client: Client) {}\n\n async listTools(): Promise<ToolDefinition[]> {\n const r = (await this.client.listTools()) as unknown as SdkToolsResponse;\n return r.tools.map((t) => ({\n name: t.name,\n description: t.description ?? \"\",\n inputSchema: t.inputSchema,\n }));\n }\n\n async callTool(name: string, args: Record<string, unknown>): Promise<ToolResult> {\n const raw = (await this.client.callTool({\n name,\n arguments: args,\n })) as unknown as SdkCallResponse;\n\n const content = (raw.content ?? []).map((block) => {\n if (block.type === \"text\" && typeof block.text === \"string\") {\n return { type: \"text\" as const, text: block.text };\n }\n // Non-text content (image, audio, embedded resource): serialize to text\n // so nothing is silently dropped. Agent can decide what to do with the\n // string description.\n return {\n type: \"text\" as const,\n text: stringifyNonTextBlock(block),\n };\n });\n\n return {\n content: content.length > 0 ? content : [{ type: \"text\", text: \"\" }],\n ...(raw.isError === true ? { isError: true } : {}),\n };\n }\n}\n\nfunction stringifyNonTextBlock(block: SdkContentBlock): string {\n const parts: string[] = [`[${block.type}]`];\n if (block.mimeType) parts.push(`mimeType=${block.mimeType}`);\n if (typeof block.data === \"string\") {\n const preview = block.data.length > 64 ? block.data.slice(0, 64) + \"…\" : block.data;\n parts.push(`data=${preview}`);\n }\n return parts.join(\" \");\n}\n","import { Server } from \"@modelcontextprotocol/sdk/server/index.js\";\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListPromptsRequestSchema,\n GetPromptRequestSchema,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { SightmapMcpServer } from \"./server.js\";\n\n/**\n * Wraps a `SightmapMcpServer` (the dispatcher) in an MCP SDK `Server`,\n * registering tools/list, tools/call, prompts/list, and prompts/get handlers\n * that delegate to it.\n *\n * Returns the Server unconnected — caller chooses transport (stdio,\n * InMemoryTransport for tests, etc.) and calls `.connect(transport)`.\n */\nexport function buildMcpServer(dispatcher: SightmapMcpServer): Server {\n const server = new Server(\n { name: \"sightmap-mcp\", version: \"0.0.0\" },\n { capabilities: { tools: {}, prompts: {} } },\n );\n\n server.setRequestHandler(ListToolsRequestSchema, async () => {\n const tools = await dispatcher.listToolsAsync();\n return { tools };\n });\n\n server.setRequestHandler(CallToolRequestSchema, async (req) => {\n const name = req.params.name;\n const args = (req.params.arguments ?? {}) as Record<string, unknown>;\n const result = await dispatcher.callTool(name, args);\n // The SDK's CallToolResult is a discriminated union (regular result vs.\n // long-running task indicator). We always return a regular result.\n return result as unknown as { content: Array<{ type: \"text\"; text: string }>; isError?: boolean };\n });\n\n server.setRequestHandler(ListPromptsRequestSchema, async () => {\n return { prompts: dispatcher.listPrompts() };\n });\n\n server.setRequestHandler(GetPromptRequestSchema, async (req) => {\n const name = req.params.name;\n const args = (req.params.arguments ?? {}) as Record<string, string>;\n return dispatcher.getPrompt(name, args);\n });\n\n return server;\n}\n"],"mappings":";AAAA;AAAA,EACE,SAASA;AAAA,EACT;AAAA,EACA;AAAA,OAEK;;;ACLP,SA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AAI;AAAA,EACxC,CAAC;AAED,SAAO;AACT;","names":["sightmapMatch","readFile","parse","readFile","parse","readFile","parse","readFile","parse","c","writeFile","readFile","readdir","join","format","canonicalize","readFile","writeFile","readdir","resolve","parse","format","canonicalize","stripFragmentBrand","writeFile","join","format","canonicalize","join","writeFile","readFile","resolve","require","resolved","sightmapMatch"]}