@web-remarq/mcp 0.4.0 → 0.5.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/README.md +101 -14
- package/dist/server.js +548 -235
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/config.ts","../src/storage-factory.ts","../src/file-storage-adapter.ts","../src/http-server.ts","../src/task-folder.ts","../src/prompts.ts","../src/tools/list-annotations.ts","../src/errors.ts","../src/tools/get-annotation.ts","../src/tools/acknowledge.ts","../src/tools/claim-fix.ts","../src/tools/dismiss.ts","../src/tools/watch-annotations.ts","../src/tools/index.ts"],"sourcesContent":["import { dirname, join } from 'node:path'\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport type { StorageAdapter } from 'web-remarq'\nimport { parseEnv, ConfigError } from './config.js'\nimport { createStorage } from './storage-factory.js'\nimport { FileStorageAdapter } from './file-storage-adapter.js'\nimport { startHttpServer } from './http-server.js'\nimport { TaskFolder } from './task-folder.js'\nimport { registerPrompts } from './prompts.js'\nimport { registerTools, type WaitForChange } from './tools/index.js'\n\nconst CLOUD_POLL_MS = 3000\n\nasync function main(): Promise<void> {\n let config\n try {\n config = parseEnv(process.env)\n } catch (err) {\n if (err instanceof ConfigError) {\n console.error(`[web-remarq-mcp] config error: ${err.message}`)\n process.exit(1)\n }\n throw err\n }\n\n let storage: StorageAdapter\n let waitForChange: WaitForChange\n\n if (config.mode === 'local') {\n const adapter = new FileStorageAdapter(config.dataFile)\n const tasksDir = join(dirname(config.dataFile), 'tasks')\n const taskFolder = new TaskFolder(adapter, tasksDir)\n adapter.onChange(() => taskFolder.schedule())\n taskFolder.schedule() // project existing annotations on startup\n await startHttpServer(adapter, config.port)\n console.error(\n `[web-remarq-mcp] local mode — widget endpoint http://127.0.0.1:${config.port}, store ${config.dataFile}, tasks ${tasksDir}`,\n )\n storage = adapter\n waitForChange = (ms) => adapter.waitForChange(ms)\n } else {\n storage = createStorage(config)\n waitForChange = (ms) =>\n new Promise((resolve) => setTimeout(() => resolve(false), Math.min(ms, CLOUD_POLL_MS)))\n }\n\n const server = new McpServer({\n name: 'web-remarq',\n version: '0.4.0',\n })\n\n registerTools(server, storage, { waitForChange })\n registerPrompts(server)\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nmain().catch((err) => {\n console.error('[web-remarq-mcp] fatal:', err)\n process.exit(1)\n})\n","export interface CloudConfig {\n mode: 'cloud'\n projectKey: string\n supabaseUrl: string\n supabaseAnonKey: string\n}\n\nexport interface LocalConfig {\n mode: 'local'\n port: number\n dataFile: string\n}\n\nexport type MCPConfig = CloudConfig | LocalConfig\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConfigError'\n }\n}\n\nfunction require_(env: NodeJS.ProcessEnv, key: string): string {\n const v = env[key]\n if (!v || v.trim() === '') {\n throw new ConfigError(`Missing required env var: ${key}`)\n }\n return v\n}\n\nconst DEFAULT_PORT = 1817\nconst DEFAULT_DATA_FILE = '.remarq/annotations.json'\n\nexport function parseEnv(env: NodeJS.ProcessEnv): MCPConfig {\n const cloudRequested = Boolean(\n env.REMARQ_PROJECT_KEY || env.REMARQ_SUPABASE_URL || env.REMARQ_SUPABASE_ANON_KEY,\n )\n\n if (cloudRequested) {\n const projectKey = require_(env, 'REMARQ_PROJECT_KEY')\n const supabaseUrl = require_(env, 'REMARQ_SUPABASE_URL')\n const supabaseAnonKey = require_(env, 'REMARQ_SUPABASE_ANON_KEY')\n\n if (!projectKey.startsWith('pk_')) {\n throw new ConfigError('REMARQ_PROJECT_KEY must start with `pk_` (generated by `npx @web-remarq/cloud gen-key`)')\n }\n if (!supabaseUrl.startsWith('https://')) {\n throw new ConfigError('REMARQ_SUPABASE_URL must start with https://')\n }\n\n return { mode: 'cloud', projectKey, supabaseUrl, supabaseAnonKey }\n }\n\n const rawPort = env.REMARQ_PORT ?? String(DEFAULT_PORT)\n const port = Number(rawPort)\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new ConfigError(`REMARQ_PORT must be an integer between 1 and 65535, got \"${rawPort}\"`)\n }\n\n return { mode: 'local', port, dataFile: env.REMARQ_DATA_FILE ?? DEFAULT_DATA_FILE }\n}\n","import { createCloudStorage } from '@web-remarq/cloud'\nimport type { StorageAdapter } from 'web-remarq'\nimport type { CloudConfig } from './config'\n\nexport function createStorage(config: CloudConfig): StorageAdapter {\n return createCloudStorage({\n projectKey: config.projectKey,\n supabaseUrl: config.supabaseUrl,\n supabaseAnonKey: config.supabaseAnonKey,\n onError: 'throw',\n })\n}\n","import { EventEmitter } from 'node:events'\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { basename, dirname, join } from 'node:path'\nimport type { Annotation, AnnotationStore, StorageAdapter } from 'web-remarq'\n\n/**\n * Local-mode StorageAdapter over a JSON file (default .remarq/annotations.json).\n * All mutations flow through this process (MCP tools + the local HTTP server),\n * so change notification is a plain in-memory emitter — no fs.watch needed.\n */\nexport class FileStorageAdapter implements StorageAdapter {\n /** Monotonic revision — bumps on every mutation. Exposed via GET /store. */\n rev = 0\n private emitter = new EventEmitter()\n /** Serializes mutations (save/remove/clear) so concurrent read-modify-write ops don't clobber each other. */\n private queue: Promise<void> = Promise.resolve()\n\n constructor(private filePath: string) {\n this.emitter.setMaxListeners(0)\n }\n\n async load(): Promise<AnnotationStore | null> {\n if (!existsSync(this.filePath)) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(this.filePath, 'utf8'))\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`annotations store corrupted at ${this.filePath}: ${message}`)\n }\n const store = parsed as { annotations?: unknown }\n return {\n version: 1,\n annotations: Array.isArray(store.annotations) ? (store.annotations as Annotation[]) : [],\n }\n }\n\n async save(annotation: Annotation): Promise<void> {\n return this.enqueue(async () => {\n const store = (await this.load()) ?? { version: 1 as const, annotations: [] }\n const idx = store.annotations.findIndex((a) => a.id === annotation.id)\n if (idx === -1) store.annotations.push(annotation)\n else store.annotations[idx] = annotation\n this.persist(store)\n })\n }\n\n async remove(id: string): Promise<void> {\n return this.enqueue(async () => {\n const store = (await this.load()) ?? { version: 1 as const, annotations: [] }\n store.annotations = store.annotations.filter((a) => a.id !== id)\n this.persist(store)\n })\n }\n\n async clear(): Promise<void> {\n return this.enqueue(async () => {\n this.persist({ version: 1, annotations: [] })\n })\n }\n\n /** Chains `op` onto the mutation queue; a rejected op doesn't poison later ops. */\n private enqueue(op: () => Promise<void>): Promise<void> {\n const result = this.queue.then(op)\n // Swallow the rejection on the shared chain so the next enqueued op still runs;\n // the caller's own `result` promise still rejects with the original error.\n this.queue = result.catch(() => undefined)\n return result\n }\n\n /** Resolves true on the next mutation, false after timeoutMs. */\n waitForChange(timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n const onChange = (): void => {\n clearTimeout(timer)\n resolve(true)\n }\n const timer = setTimeout(() => {\n this.emitter.off('change', onChange)\n resolve(false)\n }, timeoutMs)\n this.emitter.once('change', onChange)\n })\n }\n\n /** Persistent listener for every mutation (save/remove/clear). */\n onChange(listener: () => void): void {\n this.emitter.on('change', listener)\n }\n\n private persist(store: AnnotationStore): void {\n const dir = dirname(this.filePath)\n mkdirSync(dir, { recursive: true })\n // Auto-ignore the store when it lives in the conventional .remarq dir.\n // NEVER write a wildcard .gitignore into an arbitrary user directory.\n if (basename(dir) === '.remarq') {\n const gitignore = join(dir, '.gitignore')\n if (!existsSync(gitignore)) writeFileSync(gitignore, '*\\n')\n }\n const tmp = `${this.filePath}.tmp`\n writeFileSync(tmp, JSON.stringify(store, null, 2))\n renameSync(tmp, this.filePath)\n this.rev++\n this.emitter.emit('change')\n }\n}\n","import * as http from 'node:http'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport type { FileStorageAdapter } from './file-storage-adapter.js'\nimport { isSafeAnnotationId } from './task-folder.js'\n\nconst CORS_HEADERS: Record<string, string> = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'content-type',\n}\n\nconst MAX_BODY_BYTES = 1024 * 1024\n\nfunction json(res: ServerResponse, status: number, body: unknown): void {\n res.writeHead(status, { ...CORS_HEADERS, 'content-type': 'application/json' })\n res.end(JSON.stringify(body))\n}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n let size = 0\n const chunks: Buffer[] = []\n req.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_BODY_BYTES) {\n reject(new Error('body too large'))\n req.destroy()\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))\n req.on('error', reject)\n })\n}\n\nasync function handle(req: IncomingMessage, res: ServerResponse, storage: FileStorageAdapter): Promise<void> {\n if (req.method === 'OPTIONS') {\n res.writeHead(204, CORS_HEADERS)\n res.end()\n return\n }\n\n const pathname = new URL(req.url ?? '/', 'http://localhost').pathname\n const annMatch = pathname.match(/^\\/annotations\\/([^/]+)$/)\n\n try {\n if (req.method === 'GET' && pathname === '/store') {\n // Capture rev before the await, not after: a concurrent mutation between\n // load() and reading storage.rev would pair a newer rev with the older\n // content this response body carries. Under-reporting is safe (the\n // client's next poll re-diffs); over-reporting is not.\n const rev = storage.rev\n const store = (await storage.load()) ?? { version: 1 as const, annotations: [] }\n json(res, 200, { rev, store })\n return\n }\n\n if (req.method === 'PUT' && annMatch) {\n const id = decodeURIComponent(annMatch[1])\n if (!isSafeAnnotationId(id)) {\n json(res, 400, { error: 'invalid annotation id' })\n return\n }\n let annotation: { id?: unknown }\n try {\n annotation = JSON.parse(await readBody(req))\n } catch {\n json(res, 400, { error: 'invalid JSON body' })\n return\n }\n if (!annotation || annotation.id !== id) {\n json(res, 400, { error: 'annotation.id must match the URL id' })\n return\n }\n // The store is trusted local input from the widget; no schema validation.\n await storage.save(annotation as never)\n json(res, 200, { rev: storage.rev })\n return\n }\n\n if (req.method === 'DELETE' && annMatch) {\n const id = decodeURIComponent(annMatch[1])\n if (!isSafeAnnotationId(id)) {\n json(res, 400, { error: 'invalid annotation id' })\n return\n }\n await storage.remove(id)\n json(res, 200, { rev: storage.rev })\n return\n }\n\n if (req.method === 'DELETE' && pathname === '/annotations') {\n await storage.clear()\n json(res, 200, { rev: storage.rev })\n return\n }\n\n json(res, 404, { error: 'not found' })\n } catch (err) {\n json(res, 500, { error: err instanceof Error ? err.message : String(err) })\n }\n}\n\n/** Starts the widget-facing endpoint on 127.0.0.1:port. Rejects on bind errors. */\nexport function startHttpServer(storage: FileStorageAdapter, port: number): Promise<http.Server> {\n const server = http.createServer((req, res) => {\n void handle(req, res, storage)\n })\n return new Promise((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, '127.0.0.1', () => resolve(server))\n })\n}\n","import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { Annotation, StorageAdapter } from 'web-remarq'\nimport { actionableOnly, generateAgentExport } from 'web-remarq/core'\n\n/** Double-quoted YAML scalar; JSON string escaping is valid YAML. */\nfunction yamlString(value: string): string {\n return JSON.stringify(value)\n}\n\n/**\n * Annotation ids become `<id>.md` filenames under a server-owned directory.\n * Ids normally come from core (filename-safe by construction) but the widget\n * HTTP endpoint accepts arbitrary strings, so both the file projection and\n * the HTTP layer must reject anything that isn't a plain filename segment\n * (no path separators, no leading dot, no traversal).\n */\nexport function isSafeAnnotationId(id: string): boolean {\n return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)\n}\n\n/**\n * Renders one annotation as a ticket file for .remarq/tasks/.\n * Deterministic: TaskFolder diffs the output against the file on disk\n * to skip no-op rewrites.\n */\nexport function renderTaskFile(annotation: Annotation): string {\n // Reuse core agent-export for source resolution + search hints (same pattern as get_annotation).\n const agent = generateAgentExport([annotation], annotation.viewportBucket).annotations[0]\n const lines: string[] = []\n\n lines.push('---')\n lines.push(`id: ${yamlString(agent.id)}`)\n lines.push(`route: ${yamlString(agent.route)}`)\n lines.push(`status: ${agent.status}`)\n lines.push(`viewportBucket: ${annotation.viewportBucket}`)\n if (annotation.qualityCheck) lines.push(`quality: ${annotation.qualityCheck.score}`)\n lines.push('---', '')\n\n lines.push(`# web-remarq annotation ${agent.id}`, '')\n lines.push('## Comment', '', agent.comment.trim(), '')\n\n lines.push('## Element', '')\n lines.push(`- Tag: \\`${agent.searchHints.tagName}\\``)\n lines.push(`- DOM: \\`${agent.searchHints.domContext}\\``)\n if (agent.source) {\n const component = agent.source.component ? ` (component \\`${agent.source.component}\\`)` : ''\n lines.push(`- Source: \\`${agent.source.file}:${agent.source.line}:${agent.source.column}\\`${component}`)\n }\n if (agent.searchHints.classes.length) {\n lines.push(`- Classes: ${agent.searchHints.classes.map((c) => `\\`${c}\\``).join(' ')}`)\n }\n lines.push('')\n\n if (agent.searchHints.grepQueries.length) {\n lines.push('## Search hints', '')\n for (const q of agent.searchHints.grepQueries) {\n lines.push(`- [${q.confidence}] \\`${q.query}\\` in \\`${q.glob}\\``)\n }\n lines.push('')\n }\n\n const qc = annotation.qualityCheck\n if (qc && qc.score !== 'clear') {\n lines.push('## Quality check', '')\n lines.push(`Verdict: **${qc.score}** - this comment may need designer clarification; if you cannot act on it confidently, dismiss with a reason instead of guessing.`, '')\n for (const issue of qc.issues) lines.push(`- Issue: ${issue}`)\n for (const q of qc.clarifyingQuestions) lines.push(`- Open question: ${q}`)\n if (qc.suggestedRewrite) lines.push(`- Suggested rewrite: ${qc.suggestedRewrite}`)\n lines.push('')\n }\n\n lines.push('## Agent instructions', '')\n lines.push(`1. BEFORE touching code, call the web-remarq MCP tool \\`acknowledge\\` with \\`{ \"id\": ${yamlString(agent.id)} }\\`. If it errors, another agent already owns this task - skip this file.`)\n lines.push('2. Apply the fix described in the comment.')\n lines.push(`3. When the fix is committed to the working tree, call \\`claim_fix\\` with \\`{ \"id\": ${yamlString(agent.id)} }\\`. A human verifies afterwards - never mark anything as done yourself.`)\n lines.push('')\n lines.push('This file is a live projection maintained by the web-remarq MCP server: it updates when the annotation changes and disappears once the annotation is verified or dismissed. Do not edit or delete it.')\n lines.push('')\n\n return lines.join('\\n')\n}\n\n/**\n * Live projection of actionable annotations (pending/in_progress) into a\n * folder of <id>.md ticket files. The folder is server-owned: every *.md in\n * it is managed - stale ones are deleted on sync. Non-md files are ignored.\n */\nexport class TaskFolder {\n private syncing = false\n private dirty = false\n\n constructor(\n private storage: Pick<StorageAdapter, 'load'>,\n private dir: string,\n ) {}\n\n /** Full idempotent resync: folder contents converge to the actionable set. */\n async sync(): Promise<void> {\n const store = await this.storage.load()\n const actionable = actionableOnly(store?.annotations ?? [])\n const desired = new Map<string, string>()\n for (const a of actionable) {\n if (!isSafeAnnotationId(a.id)) {\n console.error(`[web-remarq-mcp] skipping annotation with unsafe id: ${JSON.stringify(a.id)}`)\n continue\n }\n desired.set(`${a.id}.md`, renderTaskFile(a))\n }\n\n mkdirSync(this.dir, { recursive: true })\n for (const entry of readdirSync(this.dir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith('.md') || desired.has(entry.name)) continue\n try {\n unlinkSync(join(this.dir, entry.name))\n } catch (err) {\n console.error(`[web-remarq-mcp] failed to remove stale task file ${entry.name}:`, err)\n }\n }\n for (const [name, content] of desired) {\n try {\n const path = join(this.dir, name)\n if (existsSync(path) && readFileSync(path, 'utf8') === content) continue\n writeFileSync(path, content)\n } catch (err) {\n console.error(`[web-remarq-mcp] failed to write task file ${name}:`, err)\n }\n }\n }\n\n /** Coalesces change bursts: at most one sync in flight, one more queued. Never throws. */\n schedule(): void {\n this.dirty = true\n void this.run()\n }\n\n private async run(): Promise<void> {\n if (this.syncing) return\n this.syncing = true\n while (this.dirty) {\n this.dirty = false\n try {\n await this.sync()\n } catch (err) {\n console.error('[web-remarq-mcp] task folder sync failed:', err)\n }\n }\n this.syncing = false\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\n/**\n * The \"agent on duty\" dispatcher prompt, exposed via MCP prompts so clients\n * that support them (Claude Code renders it as /mcp__web-remarq__watch)\n * don't need the copy-paste block from the README.\n * Keep the text in sync with the README's \"Parallel mode\" section.\n */\nexport const DUTY_PROMPT =\n 'You are on annotation duty for this project. Designers drop feedback via ' +\n 'the web-remarq MCP server. Run this loop until told to stop: call ' +\n 'watch_annotations (timeoutSeconds: 60); if it times out, call it again. ' +\n 'For EACH annotation it returns, call acknowledge with its id first. Then, ' +\n 'if you can run background subagents, dispatch one that applies the fix to ' +\n 'the project files and calls claim_fix when done - do not fix anything ' +\n 'yourself in the main loop and do not wait for subagents, go straight back ' +\n 'to watch_annotations so new feedback is never missed. Without background ' +\n 'subagents, apply the fix inline after acknowledging, then return to ' +\n 'watch_annotations. If a comment is ambiguous or unactionable, dismiss it ' +\n 'with a reason instead of guessing.'\n\nexport function registerPrompts(server: McpServer): void {\n server.registerPrompt(\n 'watch',\n {\n title: 'Annotation duty (dispatcher loop)',\n description:\n 'Put this agent on annotation duty: loop on watch_annotations, acknowledge each annotation first, hand the fix to a background subagent that calls claim_fix, return to watching immediately.',\n },\n () => ({\n messages: [{ role: 'user' as const, content: { type: 'text' as const, text: DUTY_PROMPT } }],\n }),\n )\n}\n","import { z } from 'zod'\nimport type { Annotation, AnnotationStatus, QualityCheck, StorageAdapter } from 'web-remarq'\nimport { toolError, toolSuccess } from '../errors'\n\nconst STATUS_VALUES = ['draft', 'pending', 'in_progress', 'fixed_unverified', 'verified', 'dismissed'] as const\n\nexport const listAnnotationsInputSchema = z.object({\n route: z.string().optional(),\n status: z.union([z.enum(STATUS_VALUES), z.array(z.enum(STATUS_VALUES))]).optional(),\n viewportBucket: z.number().int().optional(),\n file: z.string().optional(),\n limit: z.number().int().min(1).max(200).optional(),\n})\n\nexport type ListAnnotationsInput = z.infer<typeof listAnnotationsInputSchema>\n\nexport interface ThinAnnotation {\n id: string\n route: string\n comment: string\n status: AnnotationStatus\n viewport: number\n timestamp: number\n source: { file: string; line: number; column: number; component?: string } | null\n quality?: QualityCheck['score']\n}\n\nfunction parseSource(annotation: Annotation): ThinAnnotation['source'] {\n const fp = annotation.fingerprint\n const raw = fp.sourceLocation ?? fp.detectedSource\n if (!raw) return null\n const parts = raw.split(':')\n if (parts.length < 2) return null\n const column = parseInt(parts.pop()!, 10)\n const line = parseInt(parts.pop()!, 10)\n const file = parts.join(':')\n if (!file || isNaN(line)) return null\n const component = fp.componentName ?? fp.detectedComponent ?? undefined\n return { file, line, column: isNaN(column) ? 0 : column, ...(component ? { component } : {}) }\n}\n\nexport function toThin(a: Annotation): ThinAnnotation {\n return {\n id: a.id,\n route: a.route,\n comment: a.comment,\n status: a.status,\n viewport: a.viewportBucket,\n timestamp: a.timestamp,\n source: parseSource(a),\n ...(a.qualityCheck ? { quality: a.qualityCheck.score } : {}),\n }\n}\n\nexport async function handleListAnnotations(input: ListAnnotationsInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const all = store?.annotations ?? []\n\n const statusFilter = Array.isArray(input.status)\n ? new Set(input.status)\n : input.status\n ? new Set([input.status])\n : null\n\n const filtered = all.filter((a) => {\n if (input.route !== undefined && a.route !== input.route) return false\n if (statusFilter && !statusFilter.has(a.status)) return false\n if (input.viewportBucket !== undefined && a.viewportBucket !== input.viewportBucket) return false\n if (input.file !== undefined) {\n const src = a.fingerprint.sourceLocation ?? a.fingerprint.detectedSource ?? ''\n if (!src.includes(input.file)) return false\n }\n return true\n })\n\n const limit = input.limit ?? 50\n const thinned = filtered.slice(0, limit).map(toThin)\n\n return toolSuccess({ annotations: thinned, total: filtered.length })\n}\n","export type ToolErrorCode =\n | 'annotation_not_found'\n | 'invalid_transition'\n | 'storage_error'\n | 'validation_error'\n\nexport interface ToolErrorPayload {\n code: ToolErrorCode\n message: string\n details?: Record<string, unknown>\n}\n\nexport interface ToolErrorResult {\n isError: true\n content: Array<{ type: 'text'; text: string }>\n}\n\nexport function toolError(code: ToolErrorCode, message: string, details?: Record<string, unknown>): ToolErrorResult {\n const payload: ToolErrorPayload = { code, message, details }\n return {\n isError: true,\n content: [{ type: 'text', text: JSON.stringify(payload) }],\n }\n}\n\nexport interface ToolSuccessResult {\n isError?: false\n content: Array<{ type: 'text'; text: string }>\n}\n\nexport function toolSuccess(value: unknown): ToolSuccessResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(value) }],\n }\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { generateAgentExport } from 'web-remarq/core'\nimport { toolError, toolSuccess } from '../errors'\n\nexport const getAnnotationInputSchema = z.object({\n id: z.string(),\n})\n\nexport type GetAnnotationInput = z.infer<typeof getAnnotationInputSchema>\n\nexport async function handleGetAnnotation(input: GetAnnotationInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const annotation = store?.annotations.find((a) => a.id === input.id)\n if (!annotation) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n\n // Reuse core agent-export to build the rich shape (source + searchHints + lifecycle).\n // generateAgentExport takes an array — pass the single annotation, then extract.\n const agentExport = generateAgentExport([annotation], annotation.viewportBucket)\n const agentAnnotation = agentExport.annotations[0]\n\n return toolSuccess(agentAnnotation)\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { transition, InvalidTransitionError } from 'web-remarq/core'\nimport { toolError, toolSuccess } from '../errors'\n\nexport const acknowledgeInputSchema = z.object({\n id: z.string(),\n})\n\nexport type AcknowledgeInput = z.infer<typeof acknowledgeInputSchema>\n\nexport async function handleAcknowledge(input: AcknowledgeInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const annotation = store?.annotations.find((a) => a.id === input.id)\n if (!annotation) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n\n let result\n try {\n result = transition(annotation, 'acknowledge', { actor: 'agent' })\n } catch (err) {\n if (err instanceof InvalidTransitionError) {\n return toolError('invalid_transition', err.message, {\n currentStatus: annotation.status,\n requestedTransition: 'acknowledge',\n })\n }\n throw err\n }\n\n const updated = {\n ...annotation,\n status: result.status,\n lifecycle: [...annotation.lifecycle, result.event],\n }\n\n try {\n await storage.save(updated)\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n\n return toolSuccess({ ok: true, status: result.status })\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { transition, InvalidTransitionError } from 'web-remarq/core'\nimport { toolError, toolSuccess } from '../errors'\n\nexport const claimFixInputSchema = z.object({\n id: z.string(),\n})\n\nexport type ClaimFixInput = z.infer<typeof claimFixInputSchema>\n\nexport async function handleClaimFix(input: ClaimFixInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const annotation = store?.annotations.find((a) => a.id === input.id)\n if (!annotation) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n\n let result\n try {\n result = transition(annotation, 'claimFix', { actor: 'agent' })\n } catch (err) {\n if (err instanceof InvalidTransitionError) {\n return toolError('invalid_transition', err.message, {\n currentStatus: annotation.status,\n requestedTransition: 'claimFix',\n })\n }\n throw err\n }\n\n const updated = {\n ...annotation,\n status: result.status,\n lifecycle: [...annotation.lifecycle, result.event],\n }\n\n try {\n await storage.save(updated)\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n\n return toolSuccess({ ok: true, status: result.status })\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { transition, InvalidTransitionError } from 'web-remarq/core'\nimport { toolError, toolSuccess } from '../errors'\n\nexport const dismissInputSchema = z.object({\n id: z.string(),\n reason: z.string().optional(),\n})\n\nexport type DismissInput = z.infer<typeof dismissInputSchema>\n\nexport async function handleDismiss(input: DismissInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const annotation = store?.annotations.find((a) => a.id === input.id)\n if (!annotation) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n\n let result\n try {\n result = transition(annotation, 'dismiss', { actor: 'agent', reason: input.reason })\n } catch (err) {\n if (err instanceof InvalidTransitionError) {\n return toolError('invalid_transition', err.message, {\n currentStatus: annotation.status,\n requestedTransition: 'dismiss',\n })\n }\n throw err\n }\n\n const updated = {\n ...annotation,\n status: result.status,\n lifecycle: [...annotation.lifecycle, result.event],\n }\n\n try {\n await storage.save(updated)\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n\n return toolSuccess({ ok: true, status: result.status })\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { toolError, toolSuccess } from '../errors'\nimport { toThin } from './list-annotations.js'\n\n/** Waits up to timeoutMs for a backend change. Local mode resolves early on\n * mutation events; cloud mode just sleeps a poll interval and returns false. */\nexport type WaitForChange = (timeoutMs: number) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_SECONDS = 25\n\nexport const watchAnnotationsInputSchema = z.object({\n timeoutSeconds: z.number().int().min(1).max(120).optional(),\n})\n\nexport type WatchAnnotationsInput = z.infer<typeof watchAnnotationsInputSchema>\n\nexport async function handleWatchAnnotations(\n input: WatchAnnotationsInput,\n storage: StorageAdapter,\n waitForChange: WaitForChange,\n) {\n const timeoutMs = (input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n\n const pending = (store?.annotations ?? []).filter((a) => a.status === 'pending')\n if (pending.length > 0) {\n return toolSuccess({ annotations: pending.map(toThin), total: pending.length, timedOut: false })\n }\n\n const remaining = deadline - Date.now()\n if (remaining <= 0) {\n return toolSuccess({ annotations: [], total: 0, timedOut: true })\n }\n\n await waitForChange(remaining)\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport type { StorageAdapter } from 'web-remarq'\n\nimport { listAnnotationsInputSchema, handleListAnnotations } from './list-annotations.js'\nimport { getAnnotationInputSchema, handleGetAnnotation } from './get-annotation.js'\nimport { acknowledgeInputSchema, handleAcknowledge } from './acknowledge.js'\nimport { claimFixInputSchema, handleClaimFix } from './claim-fix.js'\nimport { dismissInputSchema, handleDismiss } from './dismiss.js'\nimport { watchAnnotationsInputSchema, handleWatchAnnotations, type WaitForChange } from './watch-annotations.js'\n\nexport type { WaitForChange } from './watch-annotations.js'\n\n// Cast helper: our tool results satisfy CallToolResult at runtime; the SDK's\n// inferred type carries an index signature that our narrower types lack.\nfunction cast(p: Promise<{ isError?: boolean; content: Array<{ type: 'text'; text: string }> }>): Promise<CallToolResult> {\n return p as Promise<CallToolResult>\n}\n\nexport function registerTools(\n server: McpServer,\n storage: StorageAdapter,\n opts: { waitForChange: WaitForChange },\n): void {\n server.registerTool(\n 'list_annotations',\n {\n description: 'List annotations in the project with optional filters (route, status, viewport, file). Each item carries a `quality` score (clear | ambiguous | unactionable) when an AI pre-flight check ran. In local mode, actionable annotations (pending / in_progress) are also mirrored as ticket files in .remarq/tasks/.',\n inputSchema: listAnnotationsInputSchema.shape,\n },\n (input) => cast(handleListAnnotations(input, storage)),\n )\n\n server.registerTool(\n 'get_annotation',\n {\n description: 'Get full annotation details including source file:line:col, grep search hints, and the AI quality verdict (`qualityCheck`). If qualityCheck.score is \"ambiguous\" or \"unactionable\", the comment may need designer clarification before fixing — consider dismissing with a reason instead of guessing.',\n inputSchema: getAnnotationInputSchema.shape,\n },\n (input) => cast(handleGetAnnotation(input, storage)),\n )\n\n server.registerTool(\n 'acknowledge',\n {\n description: 'Mark an annotation as in-progress (pending → in_progress).',\n inputSchema: acknowledgeInputSchema.shape,\n },\n (input) => cast(handleAcknowledge(input, storage)),\n )\n\n server.registerTool(\n 'claim_fix',\n {\n description: 'Claim a fix for an annotation (→ fixed_unverified). Human verification still required.',\n inputSchema: claimFixInputSchema.shape,\n },\n (input) => cast(handleClaimFix(input, storage)),\n )\n\n server.registerTool(\n 'dismiss',\n {\n description: 'Dismiss an annotation with an optional reason (terminal state).',\n inputSchema: dismissInputSchema.shape,\n },\n (input) => cast(handleDismiss(input, storage)),\n )\n\n server.registerTool(\n 'watch_annotations',\n {\n description:\n 'Wait for pending annotations (long-poll). Returns immediately if pending annotations exist; otherwise blocks until one appears or timeoutSeconds (default 25) elapses, then returns {\"annotations\": [], \"timedOut\": true}. Call this in a loop to continuously pick up designer feedback. If your environment can run background subagents (e.g. a Task tool), act as a dispatcher: for each returned annotation call acknowledge first (so it stops being redelivered), hand the fix to a background subagent that will claim_fix when done, and return to watch_annotations immediately instead of fixing inline - new feedback must never wait on a fix in progress. Without subagents, acknowledge each annotation before you start fixing it.',\n inputSchema: watchAnnotationsInputSchema.shape,\n },\n (input) => cast(handleWatchAnnotations(input, storage, opts.waitForChange)),\n )\n}\n"],"mappings":";AAAA,SAAS,WAAAA,UAAS,QAAAC,aAAY;AAC9B,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACa9B,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,SAAS,KAAwB,KAAqB;AAC7D,QAAM,IAAI,IAAI,GAAG;AACjB,MAAI,CAAC,KAAK,EAAE,KAAK,MAAM,IAAI;AACzB,UAAM,IAAI,YAAY,6BAA6B,GAAG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ED,gBAAc,QAAQ,SAAS,EAAE,cAAc,CAAC;AAChD,kBAAgB,MAAM;AAEtB,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,2BAA2B,GAAG;AAC5C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["dirname","join","existsSync","mkdirSync","readFileSync","writeFileSync","join","z","generateAgentExport","z","generateAgentExport","z","z","z","transition","InvalidTransitionError","z","transition","InvalidTransitionError","z","transition","InvalidTransitionError","z","transition","InvalidTransitionError","z","z","join","dirname"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/config.ts","../src/storage-factory.ts","../src/file-storage-adapter.ts","../src/local-config.ts","../src/http-server.ts","../src/task-folder.ts","../src/prompts.ts","../src/tools/list-annotations.ts","../src/errors.ts","../src/tools/get-annotation.ts","../src/tools/acknowledge.ts","../src/tools/transition-tool.ts","../src/tools/claim-fix.ts","../src/tools/dismiss.ts","../src/tools/watch-annotations.ts","../src/tools/index.ts"],"sourcesContent":["import { dirname, join } from 'node:path'\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport type { StorageAdapter } from 'web-remarq'\nimport { parseEnv, ConfigError } from './config.js'\nimport { createStorage } from './storage-factory.js'\nimport { FileStorageAdapter } from './file-storage-adapter.js'\nimport { startHttpServer } from './http-server.js'\nimport { acquireStoreLock, LocalConfigError, readOrCreateLocalConfig, StoreLockedError } from './local-config.js'\nimport { TaskFolder } from './task-folder.js'\nimport { registerPrompts } from './prompts.js'\nimport { registerTools, type WaitForChange } from './tools/index.js'\n\nconst CLOUD_POLL_MS = 3000\n\nasync function main(): Promise<void> {\n let config\n try {\n config = parseEnv(process.env)\n } catch (err) {\n if (err instanceof ConfigError) {\n console.error(`[web-remarq-mcp] config error: ${err.message}`)\n process.exit(1)\n }\n throw err\n }\n\n let storage: StorageAdapter\n let waitForChange: WaitForChange\n\n if (config.mode === 'local') {\n const storeDir = dirname(config.dataFile)\n let local\n try {\n local = readOrCreateLocalConfig(storeDir)\n acquireStoreLock(storeDir, config.port)\n } catch (err) {\n if (err instanceof LocalConfigError || err instanceof StoreLockedError) {\n console.error(`[web-remarq-mcp] ${err.message}`)\n process.exit(1)\n }\n throw err\n }\n\n const adapter = new FileStorageAdapter(config.dataFile)\n const tasksDir = join(storeDir, 'tasks')\n const taskFolder = new TaskFolder(adapter, tasksDir)\n adapter.onChange(() => taskFolder.schedule())\n taskFolder.schedule() // project existing annotations on startup\n await startHttpServer(adapter, config.port, local)\n // The token itself is never logged: it lives only in the config file.\n console.error(\n `[web-remarq-mcp] local mode — project ${local.projectId}, widget endpoint http://127.0.0.1:${config.port} (token in ${join(storeDir, 'config.json')}), store ${config.dataFile}, tasks ${tasksDir}`,\n )\n storage = adapter\n waitForChange = (ms) => adapter.waitForChange(ms)\n } else {\n storage = createStorage(config)\n waitForChange = (ms) =>\n new Promise((resolve) => setTimeout(() => resolve(false), Math.min(ms, CLOUD_POLL_MS)))\n }\n\n const server = new McpServer({\n name: 'web-remarq',\n version: '0.5.0',\n })\n\n registerTools(server, storage, { waitForChange })\n registerPrompts(server)\n\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n\nmain().catch((err) => {\n console.error('[web-remarq-mcp] fatal:', err)\n process.exit(1)\n})\n","export interface CloudConfig {\n mode: 'cloud'\n projectKey: string\n supabaseUrl: string\n supabaseAnonKey: string\n}\n\nexport interface LocalConfig {\n mode: 'local'\n port: number\n dataFile: string\n}\n\nexport type MCPConfig = CloudConfig | LocalConfig\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ConfigError'\n }\n}\n\nfunction require_(env: NodeJS.ProcessEnv, key: string): string {\n const v = env[key]\n if (!v || v.trim() === '') {\n throw new ConfigError(`Missing required env var: ${key}`)\n }\n return v\n}\n\nconst DEFAULT_PORT = 1817\nconst DEFAULT_DATA_FILE = '.remarq/annotations.json'\n\nexport function parseEnv(env: NodeJS.ProcessEnv): MCPConfig {\n const cloudRequested = Boolean(\n env.REMARQ_PROJECT_KEY || env.REMARQ_SUPABASE_URL || env.REMARQ_SUPABASE_ANON_KEY,\n )\n\n if (cloudRequested) {\n const projectKey = require_(env, 'REMARQ_PROJECT_KEY')\n const supabaseUrl = require_(env, 'REMARQ_SUPABASE_URL')\n const supabaseAnonKey = require_(env, 'REMARQ_SUPABASE_ANON_KEY')\n\n if (!projectKey.startsWith('pk_')) {\n throw new ConfigError('REMARQ_PROJECT_KEY must start with `pk_` (generated by `npx @web-remarq/cloud gen-key`)')\n }\n if (!supabaseUrl.startsWith('https://')) {\n throw new ConfigError('REMARQ_SUPABASE_URL must start with https://')\n }\n\n return { mode: 'cloud', projectKey, supabaseUrl, supabaseAnonKey }\n }\n\n const rawPort = env.REMARQ_PORT ?? String(DEFAULT_PORT)\n const port = Number(rawPort)\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new ConfigError(`REMARQ_PORT must be an integer between 1 and 65535, got \"${rawPort}\"`)\n }\n\n return { mode: 'local', port, dataFile: env.REMARQ_DATA_FILE ?? DEFAULT_DATA_FILE }\n}\n","import { createCloudStorage } from '@web-remarq/cloud'\nimport type { StorageAdapter } from 'web-remarq'\nimport type { CloudConfig } from './config'\n\nexport function createStorage(config: CloudConfig): StorageAdapter {\n return createCloudStorage({\n projectKey: config.projectKey,\n supabaseUrl: config.supabaseUrl,\n supabaseAnonKey: config.supabaseAnonKey,\n onError: 'throw',\n })\n}\n","import { EventEmitter } from 'node:events'\nimport { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname } from 'node:path'\nimport type { Annotation, AnnotationStore, StorageAdapter } from 'web-remarq'\nimport { AnnotationNotFoundError } from 'web-remarq/core'\nimport { ensureSelfIgnored } from './local-config.js'\n\nexport type ConditionalWriteResult =\n | { ok: true; annotation: Annotation; rev: number }\n /** The record exists at a different revision than the caller expected. */\n | { ok: false; reason: 'conflict'; current: Annotation | null; rev: number }\n /** The record exists but the caller sent no expected revision. */\n | { ok: false; reason: 'precondition_required'; current: Annotation; rev: number }\n\n/**\n * Local-mode StorageAdapter over a JSON file (default .remarq/annotations.json).\n * All mutations flow through this process (MCP tools + the local HTTP server) -\n * see `acquireStoreLock` for how a second process on the same store is refused -\n * so change notification is a plain in-memory emitter and one promise queue\n * serialises every read-check-write.\n *\n * Every annotation carries a per-record `rev` (1 on creation, +1 per accepted\n * write). Records written by older versions get `rev: 1` on load.\n */\nexport class FileStorageAdapter implements StorageAdapter {\n /** Monotonic store revision - bumps on every persisted mutation. Exposed via GET /store. */\n rev = 0\n private emitter = new EventEmitter()\n /** Serializes every read-check-write so concurrent ops observe each other's results. */\n private queue: Promise<void> = Promise.resolve()\n\n constructor(private filePath: string) {\n this.emitter.setMaxListeners(0)\n }\n\n async load(): Promise<AnnotationStore | null> {\n if (!existsSync(this.filePath)) return null\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(this.filePath, 'utf8'))\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`annotations store corrupted at ${this.filePath}: ${message}`)\n }\n const store = parsed as { annotations?: unknown }\n const annotations = Array.isArray(store.annotations) ? (store.annotations as Annotation[]) : []\n return {\n version: 1,\n annotations: annotations.map((a) => (Number.isInteger(a.rev) && (a.rev as number) > 0 ? a : { ...a, rev: 1 })),\n }\n }\n\n /** Unconditional upsert (StorageAdapter contract). Bumps the record's rev. */\n async save(annotation: Annotation): Promise<void> {\n await this.enqueue(async () => {\n const store = (await this.load()) ?? { version: 1 as const, annotations: [] }\n const idx = store.annotations.findIndex((a) => a.id === annotation.id)\n const nextRev = idx === -1 ? 1 : (store.annotations[idx].rev ?? 0) + 1\n const saved = { ...annotation, rev: nextRev }\n if (idx === -1) store.annotations.push(saved)\n else store.annotations[idx] = saved\n this.persist(store)\n })\n }\n\n /**\n * Revision-checked upsert used by the HTTP endpoint. `expectedRev` is the\n * revision the client last saw (`If-Match`); `null` means the client sent\n * none. Creating a new record needs no expectation; updating an existing one\n * requires a matching expectation, so a stale copy can never overwrite a\n * newer status or history.\n */\n saveIfMatch(annotation: Annotation, expectedRev: number | null): Promise<ConditionalWriteResult> {\n return this.enqueueResult(async () => {\n const store = (await this.load()) ?? { version: 1 as const, annotations: [] }\n const idx = store.annotations.findIndex((a) => a.id === annotation.id)\n if (idx === -1) {\n if (expectedRev !== null && expectedRev !== 0) {\n return { ok: false, reason: 'conflict', current: null, rev: this.rev }\n }\n const saved = { ...annotation, rev: 1 }\n store.annotations.push(saved)\n this.persist(store)\n return { ok: true, annotation: saved, rev: this.rev }\n }\n const current = store.annotations[idx]\n if (expectedRev === null) {\n return { ok: false, reason: 'precondition_required', current, rev: this.rev }\n }\n if (expectedRev !== current.rev) {\n return { ok: false, reason: 'conflict', current, rev: this.rev }\n }\n const saved = { ...annotation, rev: (current.rev ?? 0) + 1 }\n store.annotations[idx] = saved\n this.persist(store)\n return { ok: true, annotation: saved, rev: this.rev }\n })\n }\n\n async remove(id: string): Promise<void> {\n const result = await this.removeIfMatch(id, null)\n if (!result.ok) throw new Error(`remove(${id}): unexpected ${result.reason}`)\n }\n\n /** Revision-checked delete; `expectedRev === null` skips the check. Deleting a missing id is a no-op success. */\n removeIfMatch(id: string, expectedRev: number | null): Promise<ConditionalWriteResult> {\n return this.enqueueResult(async () => {\n const store = (await this.load()) ?? { version: 1 as const, annotations: [] }\n const current = store.annotations.find((a) => a.id === id) ?? null\n if (current && expectedRev !== null && expectedRev !== current.rev) {\n return { ok: false, reason: 'conflict', current, rev: this.rev }\n }\n store.annotations = store.annotations.filter((a) => a.id !== id)\n this.persist(store)\n return { ok: true, annotation: current ?? ({ id } as Annotation), rev: this.rev }\n })\n }\n\n async clear(): Promise<void> {\n await this.enqueue(async () => {\n this.persist({ version: 1, annotations: [] })\n })\n }\n\n /**\n * Atomic read-check-write: load, apply, persist inside one queue slot, so two\n * concurrent transitions on the same record see each other. `apply` throwing\n * aborts without persisting; returning the same object persists nothing.\n */\n mutate(id: string, apply: (current: Annotation) => Annotation): Promise<Annotation> {\n return this.enqueueResult(async () => {\n const store = (await this.load()) ?? { version: 1 as const, annotations: [] }\n const idx = store.annotations.findIndex((a) => a.id === id)\n if (idx === -1) throw new AnnotationNotFoundError(id)\n const current = store.annotations[idx]\n const next = apply(current)\n if (next === current) return current\n const saved = { ...next, id, rev: (current.rev ?? 0) + 1 }\n store.annotations[idx] = saved\n this.persist(store)\n return saved\n })\n }\n\n /** Chains `op` onto the mutation queue; a rejected op doesn't poison later ops. */\n private enqueue(op: () => Promise<void>): Promise<void> {\n return this.enqueueResult(op)\n }\n\n private enqueueResult<T>(op: () => Promise<T>): Promise<T> {\n const result = this.queue.then(op)\n // Swallow the rejection on the shared chain so the next enqueued op still runs;\n // the caller's own `result` promise still rejects with the original error.\n this.queue = result.then(\n () => undefined,\n () => undefined,\n )\n return result\n }\n\n /** Resolves true on the next mutation, false after timeoutMs. */\n waitForChange(timeoutMs: number): Promise<boolean> {\n return new Promise((resolve) => {\n const onChange = (): void => {\n clearTimeout(timer)\n resolve(true)\n }\n const timer = setTimeout(() => {\n this.emitter.off('change', onChange)\n resolve(false)\n }, timeoutMs)\n this.emitter.once('change', onChange)\n })\n }\n\n /** Persistent listener for every persisted mutation (save/remove/clear/mutate). Conflicts and no-ops never fire it. */\n onChange(listener: () => void): void {\n this.emitter.on('change', listener)\n }\n\n private persist(store: AnnotationStore): void {\n const dir = dirname(this.filePath)\n mkdirSync(dir, { recursive: true })\n // Auto-ignore the store when it lives in the conventional .remarq dir.\n // NEVER write a wildcard .gitignore into an arbitrary user directory.\n ensureSelfIgnored(dir)\n const tmp = `${this.filePath}.tmp`\n writeFileSync(tmp, JSON.stringify(store, null, 2))\n renameSync(tmp, this.filePath)\n this.rev++\n this.emitter.emit('change')\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { basename, join } from 'node:path'\n\n/**\n * Local-mode project identity and HTTP credential, kept in `.remarq/config.json`\n * next to the store. `.remarq/` self-gitignores, so neither value ever lands in\n * source control, URLs, task files or diagnostics.\n *\n * - `projectId` is the stable identity of this store. The widget namespaces its\n * offline cache/outbox by it, so a different project later served on the same\n * port cannot receive another project's queued writes.\n * - `token` is the bearer credential every widget/CLI request must carry.\n * Rotating it (edit the file, restart the server) does not change the identity\n * and does not touch annotations.\n * - `allowedOrigins` is the exact list of browser origins the endpoint accepts.\n * `http://host:*` means any port on that exact host. Remote/staging origins are\n * never allowed unless listed here on purpose.\n */\nexport interface LocalProjectConfig {\n projectId: string\n token: string\n allowedOrigins: string[]\n}\n\nexport const CONFIG_FILE = 'config.json'\nexport const LOCK_FILE = 'server.lock'\nexport const DEFAULT_ALLOWED_ORIGINS = ['http://localhost:*', 'http://127.0.0.1:*', 'http://[::1]:*']\n\nexport class LocalConfigError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'LocalConfigError'\n }\n}\n\nexport function generateProjectId(): string {\n return `prj_${randomBytes(8).toString('hex')}`\n}\n\nexport function generateToken(): string {\n return randomBytes(24).toString('hex')\n}\n\n/** Write `*` into `<dir>/.gitignore` when `dir` is the conventional `.remarq` folder - never elsewhere. */\nexport function ensureSelfIgnored(dir: string): void {\n if (basename(dir) !== '.remarq') return\n const gitignore = join(dir, '.gitignore')\n if (!existsSync(gitignore)) writeFileSync(gitignore, '*\\n')\n}\n\nfunction validate(raw: unknown, path: string): LocalProjectConfig {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw new LocalConfigError(`${path} must contain a JSON object`)\n }\n const obj = raw as Record<string, unknown>\n if (typeof obj.projectId !== 'string' || !/^[A-Za-z0-9_-]{4,64}$/.test(obj.projectId)) {\n throw new LocalConfigError(`${path}: projectId must be a 4-64 character id (letters, digits, _ -)`)\n }\n if (typeof obj.token !== 'string' || obj.token.length < 16 || /\\s/.test(obj.token)) {\n throw new LocalConfigError(`${path}: token must be at least 16 characters with no whitespace`)\n }\n const origins = obj.allowedOrigins ?? DEFAULT_ALLOWED_ORIGINS\n if (!Array.isArray(origins) || !origins.every((o) => typeof o === 'string')) {\n throw new LocalConfigError(`${path}: allowedOrigins must be an array of origin strings`)\n }\n return { projectId: obj.projectId, token: obj.token, allowedOrigins: origins as string[] }\n}\n\n/**\n * Read `<dir>/config.json`, creating it with a fresh identity and token when\n * absent. A present-but-malformed file throws instead of being overwritten:\n * silently regenerating would orphan every widget outbox keyed by the old id.\n */\nexport function readOrCreateLocalConfig(dir: string): LocalProjectConfig {\n const path = join(dir, CONFIG_FILE)\n if (existsSync(path)) {\n let parsed: unknown\n try {\n parsed = JSON.parse(readFileSync(path, 'utf8'))\n } catch (err) {\n throw new LocalConfigError(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`)\n }\n return validate(parsed, path)\n }\n\n const config: LocalProjectConfig = {\n projectId: generateProjectId(),\n token: generateToken(),\n allowedOrigins: [...DEFAULT_ALLOWED_ORIGINS],\n }\n mkdirSync(dir, { recursive: true })\n ensureSelfIgnored(dir)\n writeFileSync(path, `${JSON.stringify(config, null, 2)}\\n`, { mode: 0o600 })\n return config\n}\n\nexport class StoreLockedError extends Error {\n constructor(public readonly pid: number, public readonly port: number, path: string) {\n super(\n `another web-remarq MCP server (pid ${pid}, port ${port}) already serves this store - ` +\n `two processes on one store cannot guarantee atomic transitions. Stop it first, or remove ${path} if that process is gone.`,\n )\n this.name = 'StoreLockedError'\n }\n}\n\nfunction pidAlive(pid: number): boolean {\n try {\n process.kill(pid, 0)\n return true\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM'\n }\n}\n\n/**\n * Single-process guard for the store: `<dir>/server.lock` names the pid that\n * owns it. A live owner refuses a second server (the in-process mutation queue\n * is the atomicity guarantee, and two queues are none); a dead owner's stale\n * lock is taken over. Returns a release function; the lock is also released\n * on normal exit and on SIGINT/SIGTERM.\n */\nexport function acquireStoreLock(dir: string, port: number): () => void {\n const path = join(dir, LOCK_FILE)\n mkdirSync(dir, { recursive: true })\n if (existsSync(path)) {\n let owner: { pid?: unknown; port?: unknown } = {}\n try {\n owner = JSON.parse(readFileSync(path, 'utf8'))\n } catch {\n // unreadable lock: treat as stale\n }\n const pid = typeof owner.pid === 'number' ? owner.pid : NaN\n if (Number.isInteger(pid) && pid !== process.pid && pidAlive(pid)) {\n throw new StoreLockedError(pid, typeof owner.port === 'number' ? owner.port : 0, path)\n }\n }\n writeFileSync(path, `${JSON.stringify({ pid: process.pid, port, startedAt: new Date().toISOString() })}\\n`)\n\n let released = false\n const release = (): void => {\n if (released) return\n released = true\n try {\n const owner = JSON.parse(readFileSync(path, 'utf8')) as { pid?: unknown }\n if (owner.pid === process.pid) unlinkSync(path)\n } catch {\n // already gone\n }\n }\n const onSignal = (signal: NodeJS.Signals): void => {\n release()\n process.exit(signal === 'SIGINT' ? 130 : 143)\n }\n process.once('exit', release)\n process.once('SIGINT', onSignal)\n process.once('SIGTERM', onSignal)\n return () => {\n process.off('exit', release)\n process.off('SIGINT', onSignal)\n process.off('SIGTERM', onSignal)\n release()\n }\n}\n","import * as http from 'node:http'\nimport { timingSafeEqual } from 'node:crypto'\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport { isSafeAnnotationId, validateAnnotation } from 'web-remarq/core'\nimport type { FileStorageAdapter } from './file-storage-adapter.js'\nimport type { LocalProjectConfig } from './local-config.js'\n\n/**\n * Widget-facing HTTP endpoint, local mode. Protocol 2 (mcp 0.5.0).\n *\n * Threat model: the endpoint listens on 127.0.0.1 only, but any page open in\n * the same browser can still issue requests to it, and DNS rebinding can make\n * a remote page's requests arrive with a foreign Host. This layer therefore\n * checks, in order, for every request:\n *\n * 1. Host - must name this loopback listener (127.0.0.1 / localhost / [::1],\n * optionally with this port). Anything else is 403.\n * 2. Origin - when present, must exactly match one of `allowedOrigins`\n * (scheme + host, port exact or `*`). `null` and foreign origins\n * are 403 with no CORS headers, preflight included. Absent Origin\n * (curl, CLI doctor) is allowed through to the token check.\n * 3. Token - every route except GET /health needs `Authorization: Bearer\n * <token>` from `.remarq/config.json`. Reads included: the store\n * is data, not a health signal. /health itself carries no data\n * and answers any origin, so a refused page can explain itself.\n *\n * Bodies are validated structurally (`validateAnnotation`) before anything is\n * persisted: an invalid record never reaches the store or the task folder.\n * Writes are revision-checked (`If-Match`) so a stale copy cannot overwrite a\n * newer status or history - see FileStorageAdapter.saveIfMatch.\n *\n * Out of scope, on purpose: a local process with filesystem access (it can\n * read the config file), remote/staging origins (not allowed by default).\n */\n\nexport const PROTOCOL_VERSION = 2\nconst MAX_BODY_BYTES = 512 * 1024\nconst LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]'])\n\ninterface ErrorBody {\n error: string\n code: string\n details?: unknown\n}\n\nfunction send(res: ServerResponse, status: number, body: unknown, cors: Record<string, string>): void {\n res.writeHead(status, { ...cors, 'content-type': 'application/json', 'cache-control': 'no-store' })\n res.end(JSON.stringify(body))\n}\n\nfunction fail(res: ServerResponse, status: number, code: string, error: string, cors: Record<string, string>, details?: unknown): void {\n const body: ErrorBody = { error, code }\n if (details !== undefined) body.details = details\n send(res, status, body, cors)\n}\n\n/** Exact origin match against the allowlist. `http://host:*` matches any port on that exact host. */\nexport function originAllowed(origin: string, allowed: string[]): boolean {\n let parsed: URL\n try {\n parsed = new URL(origin)\n } catch {\n return false\n }\n if (parsed.username || parsed.password || (parsed.pathname !== '/' && parsed.pathname !== '') || parsed.search || parsed.hash) {\n return false\n }\n const defaultPort = parsed.protocol === 'https:' ? '443' : '80'\n const originPort = parsed.port || defaultPort\n return allowed.some((pattern) => {\n const m = pattern.match(/^(https?):\\/\\/(\\[[0-9a-fA-F:]+\\]|[A-Za-z0-9.-]+)(?::(\\d{1,5}|\\*))?$/)\n if (!m) return false\n const [, scheme, host, port] = m\n if (parsed.protocol !== `${scheme}:`) return false\n if (parsed.hostname.toLowerCase() !== host.toLowerCase()) return false\n if (port === '*') return true\n return originPort === (port ?? (scheme === 'https' ? '443' : '80'))\n })\n}\n\n/** The Host header must name this loopback listener; a foreign name means DNS rebinding. */\nexport function hostAllowed(host: string | undefined, port: number): boolean {\n if (!host) return false\n let parsed: URL\n try {\n parsed = new URL(`http://${host}`)\n } catch {\n return false\n }\n if (!LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return false\n return parsed.port === '' || parsed.port === String(port)\n}\n\nfunction tokenMatches(header: string | undefined, token: string): boolean {\n if (!header) return false\n const m = header.match(/^Bearer\\s+(\\S+)$/i)\n if (!m) return false\n const given = Buffer.from(m[1])\n const expected = Buffer.from(token)\n if (given.length !== expected.length) return false\n return timingSafeEqual(given, expected)\n}\n\nclass BodyTooLarge extends Error {}\n\nfunction readBody(req: IncomingMessage): Promise<string> {\n return new Promise((resolve, reject) => {\n const declared = Number(req.headers['content-length'])\n if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {\n req.resume()\n reject(new BodyTooLarge())\n return\n }\n let size = 0\n const chunks: Buffer[] = []\n req.on('data', (chunk: Buffer) => {\n size += chunk.length\n if (size > MAX_BODY_BYTES) {\n req.removeAllListeners('data')\n req.resume()\n reject(new BodyTooLarge())\n return\n }\n chunks.push(chunk)\n })\n req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))\n req.on('error', reject)\n })\n}\n\n/** Parses `If-Match` as a plain revision number. `undefined` = header absent, `null` = malformed. */\nfunction parseIfMatch(header: string | string[] | undefined): number | null | undefined {\n if (header === undefined) return undefined\n const value = Array.isArray(header) ? header[0] : header\n const m = value.trim().match(/^\"?(\\d{1,12})\"?$/)\n return m ? Number(m[1]) : null\n}\n\nasync function handle(\n req: IncomingMessage,\n res: ServerResponse,\n storage: FileStorageAdapter,\n port: number,\n config: LocalProjectConfig,\n): Promise<void> {\n const noCors: Record<string, string> = {}\n\n if (!hostAllowed(req.headers.host, port)) {\n fail(res, 403, 'bad_host', 'request Host does not name this loopback server', noCors)\n return\n }\n\n let pathname: string\n try {\n pathname = new URL(req.url ?? '/', 'http://localhost').pathname\n } catch {\n fail(res, 400, 'bad_url', 'malformed request URL', noCors)\n return\n }\n\n // Liveness only - no data, no token. Answered for ANY origin so that a page\n // whose origin is refused can tell \"server up, origin not allowed\" apart from\n // \"server down\" (a CORS refusal and a dead socket look identical to fetch()).\n if (pathname === '/health' && (req.method === 'GET' || req.method === 'OPTIONS')) {\n const openCors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS' }\n if (req.method === 'OPTIONS') {\n res.writeHead(204, openCors)\n res.end()\n return\n }\n send(res, 200, { ok: true, protocol: PROTOCOL_VERSION }, openCors)\n return\n }\n\n const origin = req.headers.origin\n let cors = noCors\n if (origin !== undefined) {\n if (origin === 'null' || !originAllowed(origin, config.allowedOrigins)) {\n fail(res, 403, 'forbidden_origin', 'origin is not allowed to use this server; add it to allowedOrigins in .remarq/config.json if it is yours', noCors)\n return\n }\n cors = {\n 'Access-Control-Allow-Origin': origin,\n 'Vary': 'Origin',\n 'Access-Control-Allow-Methods': 'GET, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'authorization, content-type, if-match',\n 'Access-Control-Max-Age': '600',\n }\n }\n\n if (req.method === 'OPTIONS') {\n res.writeHead(204, cors)\n res.end()\n return\n }\n\n if (!tokenMatches(req.headers.authorization, config.token)) {\n res.setHeader('WWW-Authenticate', 'Bearer realm=\"web-remarq\"')\n fail(res, 401, 'unauthorized', 'missing or wrong token; the widget and CLI read it from .remarq/config.json', cors)\n return\n }\n\n const annMatch = pathname.match(/^\\/annotations\\/([^/]+)$/)\n let id: string | null = null\n if (annMatch) {\n try {\n id = decodeURIComponent(annMatch[1])\n } catch {\n fail(res, 400, 'invalid_id', 'annotation id is not valid URL encoding', cors)\n return\n }\n if (!isSafeAnnotationId(id)) {\n fail(res, 400, 'invalid_id', 'invalid annotation id', cors)\n return\n }\n }\n\n try {\n if (req.method === 'GET' && pathname === '/store') {\n // Capture rev before the await, not after: a concurrent mutation between\n // load() and reading storage.rev would pair a newer rev with the older\n // content this response body carries. Under-reporting is safe (the\n // client's next poll re-diffs); over-reporting is not.\n const rev = storage.rev\n const store = (await storage.load()) ?? { version: 1 as const, annotations: [] }\n send(res, 200, { rev, protocol: PROTOCOL_VERSION, projectId: config.projectId, store }, cors)\n return\n }\n\n if (req.method === 'PUT' && id !== null) {\n const contentType = String(req.headers['content-type'] ?? '')\n if (!/^application\\/json\\b/i.test(contentType)) {\n fail(res, 415, 'unsupported_media_type', 'content-type must be application/json', cors)\n return\n }\n const expectedRev = parseIfMatch(req.headers['if-match'])\n if (expectedRev === null) {\n fail(res, 400, 'invalid_if_match', 'If-Match must be a revision number', cors)\n return\n }\n let raw: unknown\n try {\n raw = JSON.parse(await readBody(req))\n } catch (err) {\n if (err instanceof BodyTooLarge) {\n fail(res, 413, 'payload_too_large', `body exceeds ${MAX_BODY_BYTES} bytes`, cors)\n } else {\n fail(res, 400, 'invalid_json', 'invalid JSON body', cors)\n }\n return\n }\n const validated = validateAnnotation(raw)\n if (!validated.ok) {\n fail(res, 400, 'invalid_annotation', 'annotation failed validation', cors, validated.errors)\n return\n }\n if (validated.annotation.id !== id) {\n fail(res, 400, 'id_mismatch', 'annotation.id must match the URL id', cors)\n return\n }\n const result = await storage.saveIfMatch(validated.annotation, expectedRev ?? null)\n if (!result.ok) {\n const status = result.reason === 'conflict' ? 409 : 428\n fail(res, status, result.reason, result.reason === 'conflict' ? 'annotation changed since you last read it' : 'If-Match is required to update an existing annotation', cors, { current: result.current, rev: result.rev })\n return\n }\n send(res, 200, { rev: result.rev, annotation: result.annotation }, cors)\n return\n }\n\n if (req.method === 'DELETE' && id !== null) {\n const expectedRev = parseIfMatch(req.headers['if-match'])\n if (expectedRev === null) {\n fail(res, 400, 'invalid_if_match', 'If-Match must be a revision number', cors)\n return\n }\n const result = await storage.removeIfMatch(id, expectedRev ?? null)\n if (!result.ok) {\n fail(res, 409, 'conflict', 'annotation changed since you last read it', cors, { current: result.current, rev: result.rev })\n return\n }\n send(res, 200, { rev: result.rev }, cors)\n return\n }\n\n if (req.method === 'DELETE' && pathname === '/annotations') {\n await storage.clear()\n send(res, 200, { rev: storage.rev }, cors)\n return\n }\n\n fail(res, 404, 'not_found', 'not found', cors)\n } catch (err) {\n fail(res, 500, 'internal', err instanceof Error ? err.message : String(err), cors)\n }\n}\n\n/** Starts the widget-facing endpoint on 127.0.0.1:port. Rejects on bind errors. */\nexport function startHttpServer(storage: FileStorageAdapter, port: number, config: LocalProjectConfig): Promise<http.Server> {\n const server = http.createServer((req, res) => {\n const boundPort = (server.address() as { port: number } | null)?.port ?? port\n void handle(req, res, storage, boundPort, config)\n })\n return new Promise((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, '127.0.0.1', () => resolve(server))\n })\n}\n","import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { Annotation, StorageAdapter } from 'web-remarq'\nimport { actionableOnly, generateAgentExport, isSafeAnnotationId } from 'web-remarq/core'\n\n/** Double-quoted YAML scalar; JSON string escaping is valid YAML. */\nfunction yamlString(value: string): string {\n return JSON.stringify(value)\n}\n\n// Annotation ids become `<id>.md` filenames under a server-owned directory.\n// The HTTP layer validates ids on the way in (core `isSafeAnnotationId`); the\n// projection re-checks so a legacy store can never produce a traversal path.\nexport { isSafeAnnotationId }\n\n/**\n * Renders one annotation as a ticket file for .remarq/tasks/.\n * Deterministic: TaskFolder diffs the output against the file on disk\n * to skip no-op rewrites.\n */\nexport function renderTaskFile(annotation: Annotation): string {\n // Reuse core agent-export for source resolution + search hints (same pattern as get_annotation).\n const agent = generateAgentExport([annotation], annotation.viewportBucket).annotations[0]\n const lines: string[] = []\n\n lines.push('---')\n lines.push(`id: ${yamlString(agent.id)}`)\n lines.push(`route: ${yamlString(agent.route)}`)\n lines.push(`status: ${agent.status}`)\n lines.push(`viewportBucket: ${annotation.viewportBucket}`)\n if (annotation.qualityCheck) lines.push(`quality: ${annotation.qualityCheck.score}`)\n lines.push('---', '')\n\n lines.push(`# web-remarq annotation ${agent.id}`, '')\n lines.push('## Comment', '', agent.comment.trim(), '')\n\n lines.push('## Element', '')\n lines.push(`- Tag: \\`${agent.searchHints.tagName}\\``)\n lines.push(`- DOM: \\`${agent.searchHints.domContext}\\``)\n if (agent.source) {\n const component = agent.source.component ? ` (component \\`${agent.source.component}\\`)` : ''\n lines.push(`- Source: \\`${agent.source.file}:${agent.source.line}:${agent.source.column}\\`${component}`)\n }\n if (agent.searchHints.classes.length) {\n lines.push(`- Classes: ${agent.searchHints.classes.map((c) => `\\`${c}\\``).join(' ')}`)\n }\n lines.push('')\n\n if (agent.searchHints.grepQueries.length) {\n lines.push('## Search hints', '')\n for (const q of agent.searchHints.grepQueries) {\n lines.push(`- [${q.confidence}] \\`${q.query}\\` in \\`${q.glob}\\``)\n }\n lines.push('')\n }\n\n const qc = annotation.qualityCheck\n if (qc && qc.score !== 'clear') {\n lines.push('## Quality check', '')\n lines.push(`Verdict: **${qc.score}** - this comment may need designer clarification; if you cannot act on it confidently, dismiss with a reason instead of guessing.`, '')\n for (const issue of qc.issues) lines.push(`- Issue: ${issue}`)\n for (const q of qc.clarifyingQuestions) lines.push(`- Open question: ${q}`)\n if (qc.suggestedRewrite) lines.push(`- Suggested rewrite: ${qc.suggestedRewrite}`)\n lines.push('')\n }\n\n lines.push('## Agent instructions', '')\n lines.push(`1. BEFORE touching code, call the web-remarq MCP tool \\`acknowledge\\` with \\`{ \"id\": ${yamlString(agent.id)}, \"operationId\": \"<a fresh unique id you keep for retries>\" }\\`. Exactly one caller wins this transition. If it returns \\`invalid_transition\\`, someone else already moved this annotation: do NOT start work, re-read it with \\`get_annotation\\` and skip this file. If the call itself fails without an answer (timeout, transport error), retry with the SAME operationId - a retry is recognised and never counted twice.`)\n lines.push('2. Apply the fix described in the comment.')\n lines.push(`3. When the fix is committed to the working tree, call \\`claim_fix\\` with \\`{ \"id\": ${yamlString(agent.id)}, \"operationId\": \"<another fresh id>\" }\\`. A human verifies afterwards - never mark anything as done yourself. An \\`invalid_transition\\` here means the annotation changed under you (dismissed, reopened, edited): re-read it before deciding anything.`)\n lines.push('')\n lines.push('This file is a live projection maintained by the web-remarq MCP server: it updates when the annotation changes and disappears once the annotation is verified or dismissed. Do not edit or delete it.')\n lines.push('')\n\n return lines.join('\\n')\n}\n\n/**\n * Live projection of actionable annotations (pending/in_progress) into a\n * folder of <id>.md ticket files. The folder is server-owned: every *.md in\n * it is managed - stale ones are deleted on sync. Non-md files are ignored.\n */\nexport class TaskFolder {\n private syncing = false\n private dirty = false\n\n constructor(\n private storage: Pick<StorageAdapter, 'load'>,\n private dir: string,\n ) {}\n\n /** Full idempotent resync: folder contents converge to the actionable set. */\n async sync(): Promise<void> {\n const store = await this.storage.load()\n const actionable = actionableOnly(store?.annotations ?? [])\n const desired = new Map<string, string>()\n for (const a of actionable) {\n if (!isSafeAnnotationId(a.id)) {\n console.error(`[web-remarq-mcp] skipping annotation with unsafe id: ${JSON.stringify(a.id)}`)\n continue\n }\n desired.set(`${a.id}.md`, renderTaskFile(a))\n }\n\n mkdirSync(this.dir, { recursive: true })\n for (const entry of readdirSync(this.dir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith('.md') || desired.has(entry.name)) continue\n try {\n unlinkSync(join(this.dir, entry.name))\n } catch (err) {\n console.error(`[web-remarq-mcp] failed to remove stale task file ${entry.name}:`, err)\n }\n }\n for (const [name, content] of desired) {\n try {\n const path = join(this.dir, name)\n if (existsSync(path) && readFileSync(path, 'utf8') === content) continue\n writeFileSync(path, content)\n } catch (err) {\n console.error(`[web-remarq-mcp] failed to write task file ${name}:`, err)\n }\n }\n }\n\n /** Coalesces change bursts: at most one sync in flight, one more queued. Never throws. */\n schedule(): void {\n this.dirty = true\n void this.run()\n }\n\n private async run(): Promise<void> {\n if (this.syncing) return\n this.syncing = true\n while (this.dirty) {\n this.dirty = false\n try {\n await this.sync()\n } catch (err) {\n console.error('[web-remarq-mcp] task folder sync failed:', err)\n }\n }\n this.syncing = false\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\n\n/**\n * The \"agent on duty\" dispatcher prompt, exposed via MCP prompts so clients\n * that support them (Claude Code renders it as /mcp__web-remarq__watch)\n * don't need the copy-paste block from the README.\n * Keep the text in sync with the README's \"Parallel mode\" section.\n */\nexport const DUTY_PROMPT =\n 'You are on annotation duty for this project. Designers drop feedback via ' +\n 'the web-remarq MCP server. Run this loop until told to stop: call ' +\n 'watch_annotations (timeoutSeconds: 60); if it times out, call it again. ' +\n 'For EACH annotation it returns, call acknowledge with its id first, passing ' +\n 'a fresh operationId you keep for retries; if acknowledge answers ' +\n 'invalid_transition, another agent already holds it - skip it and do not ' +\n 'start work; if the call fails without an answer, retry with the same ' +\n 'operationId. Then, ' +\n 'if you can run background subagents, dispatch one that applies the fix to ' +\n 'the project files and calls claim_fix when done - do not fix anything ' +\n 'yourself in the main loop and do not wait for subagents, go straight back ' +\n 'to watch_annotations so new feedback is never missed. Without background ' +\n 'subagents, apply the fix inline after acknowledging, then return to ' +\n 'watch_annotations. If a comment is ambiguous or unactionable, dismiss it ' +\n 'with a reason instead of guessing.'\n\nexport function registerPrompts(server: McpServer): void {\n server.registerPrompt(\n 'watch',\n {\n title: 'Annotation duty (dispatcher loop)',\n description:\n 'Put this agent on annotation duty: loop on watch_annotations, acknowledge each annotation first, hand the fix to a background subagent that calls claim_fix, return to watching immediately.',\n },\n () => ({\n messages: [{ role: 'user' as const, content: { type: 'text' as const, text: DUTY_PROMPT } }],\n }),\n )\n}\n","import { z } from 'zod'\nimport type { Annotation, AnnotationStatus, QualityCheck, StorageAdapter } from 'web-remarq'\nimport { toolError, toolSuccess } from '../errors'\n\nconst STATUS_VALUES = ['draft', 'pending', 'in_progress', 'fixed_unverified', 'verified', 'dismissed'] as const\n\nexport const listAnnotationsInputSchema = z.object({\n route: z.string().optional(),\n status: z.union([z.enum(STATUS_VALUES), z.array(z.enum(STATUS_VALUES))]).optional(),\n viewportBucket: z.number().int().optional(),\n file: z.string().optional(),\n limit: z.number().int().min(1).max(200).optional(),\n})\n\nexport type ListAnnotationsInput = z.infer<typeof listAnnotationsInputSchema>\n\nexport interface ThinAnnotation {\n id: string\n route: string\n comment: string\n status: AnnotationStatus\n viewport: number\n timestamp: number\n source: { file: string; line: number; column: number; component?: string } | null\n quality?: QualityCheck['score']\n}\n\nfunction parseSource(annotation: Annotation): ThinAnnotation['source'] {\n const fp = annotation.fingerprint\n const raw = fp.sourceLocation ?? fp.detectedSource\n if (!raw) return null\n const parts = raw.split(':')\n if (parts.length < 2) return null\n const column = parseInt(parts.pop()!, 10)\n const line = parseInt(parts.pop()!, 10)\n const file = parts.join(':')\n if (!file || isNaN(line)) return null\n const component = fp.componentName ?? fp.detectedComponent ?? undefined\n return { file, line, column: isNaN(column) ? 0 : column, ...(component ? { component } : {}) }\n}\n\nexport function toThin(a: Annotation): ThinAnnotation {\n return {\n id: a.id,\n route: a.route,\n comment: a.comment,\n status: a.status,\n viewport: a.viewportBucket,\n timestamp: a.timestamp,\n source: parseSource(a),\n ...(a.qualityCheck ? { quality: a.qualityCheck.score } : {}),\n }\n}\n\nexport async function handleListAnnotations(input: ListAnnotationsInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const all = store?.annotations ?? []\n\n const statusFilter = Array.isArray(input.status)\n ? new Set(input.status)\n : input.status\n ? new Set([input.status])\n : null\n\n const filtered = all.filter((a) => {\n if (input.route !== undefined && a.route !== input.route) return false\n if (statusFilter && !statusFilter.has(a.status)) return false\n if (input.viewportBucket !== undefined && a.viewportBucket !== input.viewportBucket) return false\n if (input.file !== undefined) {\n const src = a.fingerprint.sourceLocation ?? a.fingerprint.detectedSource ?? ''\n if (!src.includes(input.file)) return false\n }\n return true\n })\n\n const limit = input.limit ?? 50\n const thinned = filtered.slice(0, limit).map(toThin)\n\n return toolSuccess({ annotations: thinned, total: filtered.length })\n}\n","export type ToolErrorCode =\n | 'annotation_not_found'\n | 'invalid_transition'\n | 'storage_error'\n | 'validation_error'\n\nexport interface ToolErrorPayload {\n code: ToolErrorCode\n message: string\n details?: Record<string, unknown>\n}\n\nexport interface ToolErrorResult {\n isError: true\n content: Array<{ type: 'text'; text: string }>\n}\n\nexport function toolError(code: ToolErrorCode, message: string, details?: Record<string, unknown>): ToolErrorResult {\n const payload: ToolErrorPayload = { code, message, details }\n return {\n isError: true,\n content: [{ type: 'text', text: JSON.stringify(payload) }],\n }\n}\n\nexport interface ToolSuccessResult {\n isError?: false\n content: Array<{ type: 'text'; text: string }>\n}\n\nexport function toolSuccess(value: unknown): ToolSuccessResult {\n return {\n content: [{ type: 'text', text: JSON.stringify(value) }],\n }\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { generateAgentExport } from 'web-remarq/core'\nimport { toolError, toolSuccess } from '../errors'\n\nexport const getAnnotationInputSchema = z.object({\n id: z.string(),\n})\n\nexport type GetAnnotationInput = z.infer<typeof getAnnotationInputSchema>\n\nexport async function handleGetAnnotation(input: GetAnnotationInput, storage: StorageAdapter) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const annotation = store?.annotations.find((a) => a.id === input.id)\n if (!annotation) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n\n // Reuse core agent-export to build the rich shape (source + searchHints + lifecycle).\n // generateAgentExport takes an array — pass the single annotation, then extract.\n const agentExport = generateAgentExport([annotation], annotation.viewportBucket)\n const agentAnnotation = agentExport.annotations[0]\n\n return toolSuccess(agentAnnotation)\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { operationIdSchema, runTransition } from './transition-tool.js'\n\nexport const acknowledgeInputSchema = z.object({\n id: z.string(),\n operationId: operationIdSchema,\n})\n\nexport type AcknowledgeInput = z.infer<typeof acknowledgeInputSchema>\n\nexport async function handleAcknowledge(input: AcknowledgeInput, storage: StorageAdapter) {\n return runTransition(input, storage, 'acknowledge', 'acknowledge')\n}\n","import { z } from 'zod'\nimport type { Annotation, StorageAdapter } from 'web-remarq'\nimport { transition, InvalidTransitionError, AnnotationNotFoundError } from 'web-remarq/core'\nimport type { LifecycleAction } from 'web-remarq/core'\nimport { toolError, toolSuccess } from '../errors'\n\n/**\n * Shared implementation of the three agent-side transitions (acknowledge,\n * claim_fix, dismiss).\n *\n * Atomicity: when the storage adapter offers `mutate` (local file store, cloud\n * adapter), the read-check-write happens inside the adapter's own critical\n * section, so concurrent callers on one annotation are serialised and exactly\n * one of them wins a given transition. Adapters without `mutate` fall back to\n * load()+save() and the response says so (`atomic: false`).\n *\n * Idempotency: a caller may pass `operationId`. The event written to the\n * lifecycle carries it as `opId`; a retry with the same id after a lost\n * response finds the event already there and returns success (`replayed:\n * true`) without appending a second one. A *different* id on an annotation\n * that has already moved on gets the normal conflict - it never impersonates\n * the earlier winner.\n *\n * Boundary of the guarantee: \"one winner of the transition\" is not \"an\n * authenticated owner\". Nothing here identifies *which* agent won; the\n * lifecycle records `actor: 'agent'` only.\n */\n\nexport const operationIdSchema = z.string().min(1).max(128).optional()\n\nexport interface TransitionInput {\n id: string\n operationId?: string\n reason?: string\n}\n\nexport async function runTransition(\n input: TransitionInput,\n storage: StorageAdapter,\n action: LifecycleAction,\n requestedTransition: string,\n) {\n let replayed = false\n let seen: Annotation | null = null\n\n const apply = (current: Annotation): Annotation => {\n seen = current\n if (input.operationId && current.lifecycle.some((e) => e.opId === input.operationId)) {\n replayed = true\n return current\n }\n const result = transition(current, action, { actor: 'agent', reason: input.reason })\n const event = input.operationId ? { ...result.event, opId: input.operationId } : result.event\n return { ...current, status: result.status, lifecycle: [...current.lifecycle, event] }\n }\n\n const conflict = (current: Annotation, err: InvalidTransitionError) => {\n const last = current.lifecycle[current.lifecycle.length - 1]\n return toolError('invalid_transition', `${err.message} - another actor moved this annotation first; do not start work on it, re-read it with get_annotation`, {\n conflict: true,\n currentStatus: current.status,\n currentRev: current.rev ?? null,\n lastEvent: last ? { type: last.type, actor: last.actor, timestamp: last.timestamp } : null,\n requestedTransition,\n })\n }\n\n if (typeof storage.mutate === 'function') {\n let saved: Annotation\n try {\n saved = await storage.mutate(input.id, apply)\n } catch (err) {\n if (err instanceof AnnotationNotFoundError) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n if (err instanceof InvalidTransitionError && seen) return conflict(seen, err)\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n return toolSuccess({ ok: true, status: saved.status, rev: saved.rev ?? null, ...(replayed ? { replayed: true } : {}) })\n }\n\n // Non-atomic fallback for adapters without mutate(). Documented as such.\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n const annotation = store?.annotations.find((a) => a.id === input.id)\n if (!annotation) {\n return toolError('annotation_not_found', `Annotation ${input.id} not found in this project`)\n }\n\n let updated: Annotation\n try {\n updated = apply(annotation)\n } catch (err) {\n if (err instanceof InvalidTransitionError) return conflict(annotation, err)\n throw err\n }\n\n if (!replayed) {\n try {\n await storage.save(updated)\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n }\n\n return toolSuccess({ ok: true, status: updated.status, atomic: false, ...(replayed ? { replayed: true } : {}) })\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { operationIdSchema, runTransition } from './transition-tool.js'\n\nexport const claimFixInputSchema = z.object({\n id: z.string(),\n operationId: operationIdSchema,\n})\n\nexport type ClaimFixInput = z.infer<typeof claimFixInputSchema>\n\nexport async function handleClaimFix(input: ClaimFixInput, storage: StorageAdapter) {\n return runTransition(input, storage, 'claimFix', 'claimFix')\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { operationIdSchema, runTransition } from './transition-tool.js'\n\nexport const dismissInputSchema = z.object({\n id: z.string(),\n reason: z.string().optional(),\n operationId: operationIdSchema,\n})\n\nexport type DismissInput = z.infer<typeof dismissInputSchema>\n\nexport async function handleDismiss(input: DismissInput, storage: StorageAdapter) {\n return runTransition(input, storage, 'dismiss', 'dismiss')\n}\n","import { z } from 'zod'\nimport type { StorageAdapter } from 'web-remarq'\nimport { toolError, toolSuccess } from '../errors'\nimport { toThin } from './list-annotations.js'\n\n/** Waits up to timeoutMs for a backend change. Local mode resolves early on\n * mutation events; cloud mode just sleeps a poll interval and returns false. */\nexport type WaitForChange = (timeoutMs: number) => Promise<boolean>\n\nconst DEFAULT_TIMEOUT_SECONDS = 25\n\nexport const watchAnnotationsInputSchema = z.object({\n timeoutSeconds: z.number().int().min(1).max(120).optional(),\n})\n\nexport type WatchAnnotationsInput = z.infer<typeof watchAnnotationsInputSchema>\n\nexport async function handleWatchAnnotations(\n input: WatchAnnotationsInput,\n storage: StorageAdapter,\n waitForChange: WaitForChange,\n) {\n const timeoutMs = (input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1000\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n let store\n try {\n store = await storage.load()\n } catch (err) {\n return toolError('storage_error', err instanceof Error ? err.message : String(err))\n }\n\n const pending = (store?.annotations ?? []).filter((a) => a.status === 'pending')\n if (pending.length > 0) {\n return toolSuccess({ annotations: pending.map(toThin), total: pending.length, timedOut: false })\n }\n\n const remaining = deadline - Date.now()\n if (remaining <= 0) {\n return toolSuccess({ annotations: [], total: 0, timedOut: true })\n }\n\n await waitForChange(remaining)\n }\n}\n","import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'\nimport type { StorageAdapter } from 'web-remarq'\n\nimport { listAnnotationsInputSchema, handleListAnnotations } from './list-annotations.js'\nimport { getAnnotationInputSchema, handleGetAnnotation } from './get-annotation.js'\nimport { acknowledgeInputSchema, handleAcknowledge } from './acknowledge.js'\nimport { claimFixInputSchema, handleClaimFix } from './claim-fix.js'\nimport { dismissInputSchema, handleDismiss } from './dismiss.js'\nimport { watchAnnotationsInputSchema, handleWatchAnnotations, type WaitForChange } from './watch-annotations.js'\n\nexport type { WaitForChange } from './watch-annotations.js'\n\n// Cast helper: our tool results satisfy CallToolResult at runtime; the SDK's\n// inferred type carries an index signature that our narrower types lack.\nfunction cast(p: Promise<{ isError?: boolean; content: Array<{ type: 'text'; text: string }> }>): Promise<CallToolResult> {\n return p as Promise<CallToolResult>\n}\n\nexport function registerTools(\n server: McpServer,\n storage: StorageAdapter,\n opts: { waitForChange: WaitForChange },\n): void {\n server.registerTool(\n 'list_annotations',\n {\n description: 'List annotations in the project with optional filters (route, status, viewport, file). Each item carries a `quality` score (clear | ambiguous | unactionable) when an AI pre-flight check ran. In local mode, actionable annotations (pending / in_progress) are also mirrored as ticket files in .remarq/tasks/.',\n inputSchema: listAnnotationsInputSchema.shape,\n },\n (input) => cast(handleListAnnotations(input, storage)),\n )\n\n server.registerTool(\n 'get_annotation',\n {\n description: 'Get full annotation details including source file:line:col, grep search hints, and the AI quality verdict (`qualityCheck`). If qualityCheck.score is \"ambiguous\" or \"unactionable\", the comment may need designer clarification before fixing — consider dismissing with a reason instead of guessing.',\n inputSchema: getAnnotationInputSchema.shape,\n },\n (input) => cast(handleGetAnnotation(input, storage)),\n )\n\n server.registerTool(\n 'acknowledge',\n {\n description: 'Mark an annotation as in-progress (pending → in_progress). Atomic: of several concurrent callers exactly one wins; the others get invalid_transition with details.conflict=true - then do not start work, re-read the annotation. Pass operationId (any unique string you keep) so a retry after a lost response is recognised instead of double-counted.',\n inputSchema: acknowledgeInputSchema.shape,\n },\n (input) => cast(handleAcknowledge(input, storage)),\n )\n\n server.registerTool(\n 'claim_fix',\n {\n description: 'Claim a fix for an annotation (→ fixed_unverified). Human verification still required. Atomic with the same operationId retry semantics as acknowledge; invalid_transition means the annotation changed under you - re-read it.',\n inputSchema: claimFixInputSchema.shape,\n },\n (input) => cast(handleClaimFix(input, storage)),\n )\n\n server.registerTool(\n 'dismiss',\n {\n description: 'Dismiss an annotation with an optional reason (terminal state). Atomic with the same operationId retry semantics as acknowledge.',\n inputSchema: dismissInputSchema.shape,\n },\n (input) => cast(handleDismiss(input, storage)),\n )\n\n server.registerTool(\n 'watch_annotations',\n {\n description:\n 'Wait for pending annotations (long-poll). Returns immediately if pending annotations exist; otherwise blocks until one appears or timeoutSeconds (default 25) elapses, then returns {\"annotations\": [], \"timedOut\": true}. Call this in a loop to continuously pick up designer feedback. If your environment can run background subagents (e.g. a Task tool), act as a dispatcher: for each returned annotation call acknowledge first (so it stops being redelivered), hand the fix to a background subagent that will claim_fix when done, and return to watch_annotations immediately instead of fixing inline - new feedback must never wait on a fix in progress. Without subagents, acknowledge each annotation before you start fixing it.',\n inputSchema: watchAnnotationsInputSchema.shape,\n },\n (input) => cast(handleWatchAnnotations(input, storage, opts.waitForChange)),\n )\n}\n"],"mappings":";AAAA,SAAS,WAAAA,UAAS,QAAAC,aAAY;AAC9B,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;;;ACa9B,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,SAAS,KAAwB,KAAqB;AAC7D,QAAM,IAAI,IAAI,GAAG;AACjB,MAAI,CAAC,KAAK,EAAE,KAAK,MAAM,IAAI;AACzB,UAAM,IAAI,YAAY,6BAA6B,GAAG,EAAE;AAAA,EAC1D;AACA,SAAO;AACT;AAEA,IAAM,eAAe;AACrB,IAAM,oBAAoB;AAEnB,SAAS,SAAS,KAAmC;AAC1D,QAAM,iBAAiB;AAAA,IACrB,IAAI,sBAAsB,IAAI,uBAAuB,IAAI;AAAA,EAC3D;AAEA,MAAI,gBAAgB;AAClB,UAAM,aAAa,SAAS,KAAK,oBAAoB;AACrD,UAAM,cAAc,SAAS,KAAK,qBAAqB;AACvD,U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AEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,2BAA2B,GAAG;AAC5C,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["dirname","join","existsSync","mkdirSync","readFileSync","writeFileSync","existsSync","readFileSync","saved","mkdirSync","writeFileSync","existsSync","mkdirSync","readFileSync","unlinkSync","writeFileSync","join","isSafeAnnotationId","isSafeAnnotationId","mkdirSync","unlinkSync","join","existsSync","readFileSync","writeFileSync","z","generateAgentExport","z","generateAgentExport","z","z","AnnotationNotFoundError","z","AnnotationNotFoundError","z","z","z","z","z","z","z","dirname","join"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@web-remarq/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "MCP server for web-remarq - gives AI agents access to annotations via a local file store or Supabase cloud backend",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/server.js",
|
|
@@ -46,10 +46,10 @@
|
|
|
46
46
|
"dependencies": {
|
|
47
47
|
"@modelcontextprotocol/sdk": "^1.0.0",
|
|
48
48
|
"zod": "^3.23.0",
|
|
49
|
-
"@web-remarq/cloud": "^0.
|
|
49
|
+
"@web-remarq/cloud": "^0.4.0"
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
52
|
-
"web-remarq": ">=0.
|
|
52
|
+
"web-remarq": ">=0.9.0"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/node": "^20.0.0",
|