@web-remarq/mcp 0.3.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/dist/server.js CHANGED
@@ -56,58 +56,255 @@ function createStorage(config) {
56
56
 
57
57
  // src/file-storage-adapter.ts
58
58
  import { EventEmitter } from "events";
59
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
60
- import { basename, dirname, join } from "path";
59
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
60
+ import { dirname } from "path";
61
+ import { AnnotationNotFoundError } from "web-remarq/core";
62
+
63
+ // src/local-config.ts
64
+ import { randomBytes } from "crypto";
65
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
66
+ import { basename, join } from "path";
67
+ var CONFIG_FILE = "config.json";
68
+ var LOCK_FILE = "server.lock";
69
+ var DEFAULT_ALLOWED_ORIGINS = ["http://localhost:*", "http://127.0.0.1:*", "http://[::1]:*"];
70
+ var LocalConfigError = class extends Error {
71
+ constructor(message) {
72
+ super(message);
73
+ this.name = "LocalConfigError";
74
+ }
75
+ };
76
+ function generateProjectId() {
77
+ return `prj_${randomBytes(8).toString("hex")}`;
78
+ }
79
+ function generateToken() {
80
+ return randomBytes(24).toString("hex");
81
+ }
82
+ function ensureSelfIgnored(dir) {
83
+ if (basename(dir) !== ".remarq") return;
84
+ const gitignore = join(dir, ".gitignore");
85
+ if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
86
+ }
87
+ function validate(raw, path) {
88
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
89
+ throw new LocalConfigError(`${path} must contain a JSON object`);
90
+ }
91
+ const obj = raw;
92
+ if (typeof obj.projectId !== "string" || !/^[A-Za-z0-9_-]{4,64}$/.test(obj.projectId)) {
93
+ throw new LocalConfigError(`${path}: projectId must be a 4-64 character id (letters, digits, _ -)`);
94
+ }
95
+ if (typeof obj.token !== "string" || obj.token.length < 16 || /\s/.test(obj.token)) {
96
+ throw new LocalConfigError(`${path}: token must be at least 16 characters with no whitespace`);
97
+ }
98
+ const origins = obj.allowedOrigins ?? DEFAULT_ALLOWED_ORIGINS;
99
+ if (!Array.isArray(origins) || !origins.every((o) => typeof o === "string")) {
100
+ throw new LocalConfigError(`${path}: allowedOrigins must be an array of origin strings`);
101
+ }
102
+ return { projectId: obj.projectId, token: obj.token, allowedOrigins: origins };
103
+ }
104
+ function readOrCreateLocalConfig(dir) {
105
+ const path = join(dir, CONFIG_FILE);
106
+ if (existsSync(path)) {
107
+ let parsed;
108
+ try {
109
+ parsed = JSON.parse(readFileSync(path, "utf8"));
110
+ } catch (err) {
111
+ throw new LocalConfigError(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
112
+ }
113
+ return validate(parsed, path);
114
+ }
115
+ const config = {
116
+ projectId: generateProjectId(),
117
+ token: generateToken(),
118
+ allowedOrigins: [...DEFAULT_ALLOWED_ORIGINS]
119
+ };
120
+ mkdirSync(dir, { recursive: true });
121
+ ensureSelfIgnored(dir);
122
+ writeFileSync(path, `${JSON.stringify(config, null, 2)}
123
+ `, { mode: 384 });
124
+ return config;
125
+ }
126
+ var StoreLockedError = class extends Error {
127
+ constructor(pid, port, path) {
128
+ super(
129
+ `another web-remarq MCP server (pid ${pid}, port ${port}) already serves this store - two processes on one store cannot guarantee atomic transitions. Stop it first, or remove ${path} if that process is gone.`
130
+ );
131
+ this.pid = pid;
132
+ this.port = port;
133
+ this.name = "StoreLockedError";
134
+ }
135
+ };
136
+ function pidAlive(pid) {
137
+ try {
138
+ process.kill(pid, 0);
139
+ return true;
140
+ } catch (err) {
141
+ return err.code === "EPERM";
142
+ }
143
+ }
144
+ function acquireStoreLock(dir, port) {
145
+ const path = join(dir, LOCK_FILE);
146
+ mkdirSync(dir, { recursive: true });
147
+ if (existsSync(path)) {
148
+ let owner = {};
149
+ try {
150
+ owner = JSON.parse(readFileSync(path, "utf8"));
151
+ } catch {
152
+ }
153
+ const pid = typeof owner.pid === "number" ? owner.pid : NaN;
154
+ if (Number.isInteger(pid) && pid !== process.pid && pidAlive(pid)) {
155
+ throw new StoreLockedError(pid, typeof owner.port === "number" ? owner.port : 0, path);
156
+ }
157
+ }
158
+ writeFileSync(path, `${JSON.stringify({ pid: process.pid, port, startedAt: (/* @__PURE__ */ new Date()).toISOString() })}
159
+ `);
160
+ let released = false;
161
+ const release = () => {
162
+ if (released) return;
163
+ released = true;
164
+ try {
165
+ const owner = JSON.parse(readFileSync(path, "utf8"));
166
+ if (owner.pid === process.pid) unlinkSync(path);
167
+ } catch {
168
+ }
169
+ };
170
+ const onSignal = (signal) => {
171
+ release();
172
+ process.exit(signal === "SIGINT" ? 130 : 143);
173
+ };
174
+ process.once("exit", release);
175
+ process.once("SIGINT", onSignal);
176
+ process.once("SIGTERM", onSignal);
177
+ return () => {
178
+ process.off("exit", release);
179
+ process.off("SIGINT", onSignal);
180
+ process.off("SIGTERM", onSignal);
181
+ release();
182
+ };
183
+ }
184
+
185
+ // src/file-storage-adapter.ts
61
186
  var FileStorageAdapter = class {
62
187
  constructor(filePath) {
63
188
  this.filePath = filePath;
64
- /** Monotonic revision — bumps on every mutation. Exposed via GET /store. */
189
+ /** Monotonic store revision - bumps on every persisted mutation. Exposed via GET /store. */
65
190
  this.rev = 0;
66
191
  this.emitter = new EventEmitter();
67
- /** Serializes mutations (save/remove/clear) so concurrent read-modify-write ops don't clobber each other. */
192
+ /** Serializes every read-check-write so concurrent ops observe each other's results. */
68
193
  this.queue = Promise.resolve();
69
194
  this.emitter.setMaxListeners(0);
70
195
  }
71
196
  async load() {
72
- if (!existsSync(this.filePath)) return null;
197
+ if (!existsSync2(this.filePath)) return null;
73
198
  let parsed;
74
199
  try {
75
- parsed = JSON.parse(readFileSync(this.filePath, "utf8"));
200
+ parsed = JSON.parse(readFileSync2(this.filePath, "utf8"));
76
201
  } catch (err) {
77
202
  const message = err instanceof Error ? err.message : String(err);
78
203
  throw new Error(`annotations store corrupted at ${this.filePath}: ${message}`);
79
204
  }
80
205
  const store = parsed;
206
+ const annotations = Array.isArray(store.annotations) ? store.annotations : [];
81
207
  return {
82
208
  version: 1,
83
- annotations: Array.isArray(store.annotations) ? store.annotations : []
209
+ annotations: annotations.map((a) => Number.isInteger(a.rev) && a.rev > 0 ? a : { ...a, rev: 1 })
84
210
  };
85
211
  }
212
+ /** Unconditional upsert (StorageAdapter contract). Bumps the record's rev. */
86
213
  async save(annotation) {
87
- return this.enqueue(async () => {
214
+ await this.enqueue(async () => {
215
+ const store = await this.load() ?? { version: 1, annotations: [] };
216
+ const idx = store.annotations.findIndex((a) => a.id === annotation.id);
217
+ const nextRev = idx === -1 ? 1 : (store.annotations[idx].rev ?? 0) + 1;
218
+ const saved = { ...annotation, rev: nextRev };
219
+ if (idx === -1) store.annotations.push(saved);
220
+ else store.annotations[idx] = saved;
221
+ this.persist(store);
222
+ });
223
+ }
224
+ /**
225
+ * Revision-checked upsert used by the HTTP endpoint. `expectedRev` is the
226
+ * revision the client last saw (`If-Match`); `null` means the client sent
227
+ * none. Creating a new record needs no expectation; updating an existing one
228
+ * requires a matching expectation, so a stale copy can never overwrite a
229
+ * newer status or history.
230
+ */
231
+ saveIfMatch(annotation, expectedRev) {
232
+ return this.enqueueResult(async () => {
88
233
  const store = await this.load() ?? { version: 1, annotations: [] };
89
234
  const idx = store.annotations.findIndex((a) => a.id === annotation.id);
90
- if (idx === -1) store.annotations.push(annotation);
91
- else store.annotations[idx] = annotation;
235
+ if (idx === -1) {
236
+ if (expectedRev !== null && expectedRev !== 0) {
237
+ return { ok: false, reason: "conflict", current: null, rev: this.rev };
238
+ }
239
+ const saved2 = { ...annotation, rev: 1 };
240
+ store.annotations.push(saved2);
241
+ this.persist(store);
242
+ return { ok: true, annotation: saved2, rev: this.rev };
243
+ }
244
+ const current = store.annotations[idx];
245
+ if (expectedRev === null) {
246
+ return { ok: false, reason: "precondition_required", current, rev: this.rev };
247
+ }
248
+ if (expectedRev !== current.rev) {
249
+ return { ok: false, reason: "conflict", current, rev: this.rev };
250
+ }
251
+ const saved = { ...annotation, rev: (current.rev ?? 0) + 1 };
252
+ store.annotations[idx] = saved;
92
253
  this.persist(store);
254
+ return { ok: true, annotation: saved, rev: this.rev };
93
255
  });
94
256
  }
95
257
  async remove(id) {
96
- return this.enqueue(async () => {
258
+ const result = await this.removeIfMatch(id, null);
259
+ if (!result.ok) throw new Error(`remove(${id}): unexpected ${result.reason}`);
260
+ }
261
+ /** Revision-checked delete; `expectedRev === null` skips the check. Deleting a missing id is a no-op success. */
262
+ removeIfMatch(id, expectedRev) {
263
+ return this.enqueueResult(async () => {
97
264
  const store = await this.load() ?? { version: 1, annotations: [] };
265
+ const current = store.annotations.find((a) => a.id === id) ?? null;
266
+ if (current && expectedRev !== null && expectedRev !== current.rev) {
267
+ return { ok: false, reason: "conflict", current, rev: this.rev };
268
+ }
98
269
  store.annotations = store.annotations.filter((a) => a.id !== id);
99
270
  this.persist(store);
271
+ return { ok: true, annotation: current ?? { id }, rev: this.rev };
100
272
  });
101
273
  }
102
274
  async clear() {
103
- return this.enqueue(async () => {
275
+ await this.enqueue(async () => {
104
276
  this.persist({ version: 1, annotations: [] });
105
277
  });
106
278
  }
279
+ /**
280
+ * Atomic read-check-write: load, apply, persist inside one queue slot, so two
281
+ * concurrent transitions on the same record see each other. `apply` throwing
282
+ * aborts without persisting; returning the same object persists nothing.
283
+ */
284
+ mutate(id, apply) {
285
+ return this.enqueueResult(async () => {
286
+ const store = await this.load() ?? { version: 1, annotations: [] };
287
+ const idx = store.annotations.findIndex((a) => a.id === id);
288
+ if (idx === -1) throw new AnnotationNotFoundError(id);
289
+ const current = store.annotations[idx];
290
+ const next = apply(current);
291
+ if (next === current) return current;
292
+ const saved = { ...next, id, rev: (current.rev ?? 0) + 1 };
293
+ store.annotations[idx] = saved;
294
+ this.persist(store);
295
+ return saved;
296
+ });
297
+ }
107
298
  /** Chains `op` onto the mutation queue; a rejected op doesn't poison later ops. */
108
299
  enqueue(op) {
300
+ return this.enqueueResult(op);
301
+ }
302
+ enqueueResult(op) {
109
303
  const result = this.queue.then(op);
110
- this.queue = result.catch(() => void 0);
304
+ this.queue = result.then(
305
+ () => void 0,
306
+ () => void 0
307
+ );
111
308
  return result;
112
309
  }
113
310
  /** Resolves true on the next mutation, false after timeoutMs. */
@@ -124,19 +321,16 @@ var FileStorageAdapter = class {
124
321
  this.emitter.once("change", onChange);
125
322
  });
126
323
  }
127
- /** Persistent listener for every mutation (save/remove/clear). */
324
+ /** Persistent listener for every persisted mutation (save/remove/clear/mutate). Conflicts and no-ops never fire it. */
128
325
  onChange(listener) {
129
326
  this.emitter.on("change", listener);
130
327
  }
131
328
  persist(store) {
132
329
  const dir = dirname(this.filePath);
133
- mkdirSync(dir, { recursive: true });
134
- if (basename(dir) === ".remarq") {
135
- const gitignore = join(dir, ".gitignore");
136
- if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
137
- }
330
+ mkdirSync2(dir, { recursive: true });
331
+ ensureSelfIgnored(dir);
138
332
  const tmp = `${this.filePath}.tmp`;
139
- writeFileSync(tmp, JSON.stringify(store, null, 2));
333
+ writeFileSync2(tmp, JSON.stringify(store, null, 2));
140
334
  renameSync(tmp, this.filePath);
141
335
  this.rev++;
142
336
  this.emitter.emit("change");
@@ -145,25 +339,80 @@ var FileStorageAdapter = class {
145
339
 
146
340
  // src/http-server.ts
147
341
  import * as http from "http";
148
- var CORS_HEADERS = {
149
- "Access-Control-Allow-Origin": "*",
150
- "Access-Control-Allow-Methods": "GET, PUT, DELETE, OPTIONS",
151
- "Access-Control-Allow-Headers": "content-type"
152
- };
153
- var MAX_BODY_BYTES = 1024 * 1024;
154
- function json(res, status, body) {
155
- res.writeHead(status, { ...CORS_HEADERS, "content-type": "application/json" });
342
+ import { timingSafeEqual } from "crypto";
343
+ import { isSafeAnnotationId, validateAnnotation } from "web-remarq/core";
344
+ var PROTOCOL_VERSION = 2;
345
+ var MAX_BODY_BYTES = 512 * 1024;
346
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
347
+ function send(res, status, body, cors) {
348
+ res.writeHead(status, { ...cors, "content-type": "application/json", "cache-control": "no-store" });
156
349
  res.end(JSON.stringify(body));
157
350
  }
351
+ function fail(res, status, code, error, cors, details) {
352
+ const body = { error, code };
353
+ if (details !== void 0) body.details = details;
354
+ send(res, status, body, cors);
355
+ }
356
+ function originAllowed(origin, allowed) {
357
+ let parsed;
358
+ try {
359
+ parsed = new URL(origin);
360
+ } catch {
361
+ return false;
362
+ }
363
+ if (parsed.username || parsed.password || parsed.pathname !== "/" && parsed.pathname !== "" || parsed.search || parsed.hash) {
364
+ return false;
365
+ }
366
+ const defaultPort = parsed.protocol === "https:" ? "443" : "80";
367
+ const originPort = parsed.port || defaultPort;
368
+ return allowed.some((pattern) => {
369
+ const m = pattern.match(/^(https?):\/\/(\[[0-9a-fA-F:]+\]|[A-Za-z0-9.-]+)(?::(\d{1,5}|\*))?$/);
370
+ if (!m) return false;
371
+ const [, scheme, host, port] = m;
372
+ if (parsed.protocol !== `${scheme}:`) return false;
373
+ if (parsed.hostname.toLowerCase() !== host.toLowerCase()) return false;
374
+ if (port === "*") return true;
375
+ return originPort === (port ?? (scheme === "https" ? "443" : "80"));
376
+ });
377
+ }
378
+ function hostAllowed(host, port) {
379
+ if (!host) return false;
380
+ let parsed;
381
+ try {
382
+ parsed = new URL(`http://${host}`);
383
+ } catch {
384
+ return false;
385
+ }
386
+ if (!LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return false;
387
+ return parsed.port === "" || parsed.port === String(port);
388
+ }
389
+ function tokenMatches(header, token) {
390
+ if (!header) return false;
391
+ const m = header.match(/^Bearer\s+(\S+)$/i);
392
+ if (!m) return false;
393
+ const given = Buffer.from(m[1]);
394
+ const expected = Buffer.from(token);
395
+ if (given.length !== expected.length) return false;
396
+ return timingSafeEqual(given, expected);
397
+ }
398
+ var BodyTooLarge = class extends Error {
399
+ };
158
400
  function readBody(req) {
159
401
  return new Promise((resolve, reject) => {
402
+ const declared = Number(req.headers["content-length"]);
403
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
404
+ req.resume();
405
+ reject(new BodyTooLarge());
406
+ return;
407
+ }
160
408
  let size = 0;
161
409
  const chunks = [];
162
410
  req.on("data", (chunk) => {
163
411
  size += chunk.length;
164
412
  if (size > MAX_BODY_BYTES) {
165
- reject(new Error("body too large"));
166
- req.destroy();
413
+ req.removeAllListeners("data");
414
+ req.resume();
415
+ reject(new BodyTooLarge());
167
416
  return;
168
417
  }
169
418
  chunks.push(chunk);
@@ -172,56 +421,149 @@ function readBody(req) {
172
421
  req.on("error", reject);
173
422
  });
174
423
  }
175
- async function handle(req, res, storage) {
424
+ function parseIfMatch(header) {
425
+ if (header === void 0) return void 0;
426
+ const value = Array.isArray(header) ? header[0] : header;
427
+ const m = value.trim().match(/^"?(\d{1,12})"?$/);
428
+ return m ? Number(m[1]) : null;
429
+ }
430
+ async function handle(req, res, storage, port, config) {
431
+ const noCors = {};
432
+ if (!hostAllowed(req.headers.host, port)) {
433
+ fail(res, 403, "bad_host", "request Host does not name this loopback server", noCors);
434
+ return;
435
+ }
436
+ let pathname;
437
+ try {
438
+ pathname = new URL(req.url ?? "/", "http://localhost").pathname;
439
+ } catch {
440
+ fail(res, 400, "bad_url", "malformed request URL", noCors);
441
+ return;
442
+ }
443
+ if (pathname === "/health" && (req.method === "GET" || req.method === "OPTIONS")) {
444
+ const openCors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS" };
445
+ if (req.method === "OPTIONS") {
446
+ res.writeHead(204, openCors);
447
+ res.end();
448
+ return;
449
+ }
450
+ send(res, 200, { ok: true, protocol: PROTOCOL_VERSION }, openCors);
451
+ return;
452
+ }
453
+ const origin = req.headers.origin;
454
+ let cors = noCors;
455
+ if (origin !== void 0) {
456
+ if (origin === "null" || !originAllowed(origin, config.allowedOrigins)) {
457
+ 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);
458
+ return;
459
+ }
460
+ cors = {
461
+ "Access-Control-Allow-Origin": origin,
462
+ "Vary": "Origin",
463
+ "Access-Control-Allow-Methods": "GET, PUT, DELETE, OPTIONS",
464
+ "Access-Control-Allow-Headers": "authorization, content-type, if-match",
465
+ "Access-Control-Max-Age": "600"
466
+ };
467
+ }
176
468
  if (req.method === "OPTIONS") {
177
- res.writeHead(204, CORS_HEADERS);
469
+ res.writeHead(204, cors);
178
470
  res.end();
179
471
  return;
180
472
  }
181
- const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
473
+ if (!tokenMatches(req.headers.authorization, config.token)) {
474
+ res.setHeader("WWW-Authenticate", 'Bearer realm="web-remarq"');
475
+ fail(res, 401, "unauthorized", "missing or wrong token; the widget and CLI read it from .remarq/config.json", cors);
476
+ return;
477
+ }
182
478
  const annMatch = pathname.match(/^\/annotations\/([^/]+)$/);
479
+ let id = null;
480
+ if (annMatch) {
481
+ try {
482
+ id = decodeURIComponent(annMatch[1]);
483
+ } catch {
484
+ fail(res, 400, "invalid_id", "annotation id is not valid URL encoding", cors);
485
+ return;
486
+ }
487
+ if (!isSafeAnnotationId(id)) {
488
+ fail(res, 400, "invalid_id", "invalid annotation id", cors);
489
+ return;
490
+ }
491
+ }
183
492
  try {
184
493
  if (req.method === "GET" && pathname === "/store") {
185
494
  const rev = storage.rev;
186
495
  const store = await storage.load() ?? { version: 1, annotations: [] };
187
- json(res, 200, { rev, store });
496
+ send(res, 200, { rev, protocol: PROTOCOL_VERSION, projectId: config.projectId, store }, cors);
188
497
  return;
189
498
  }
190
- if (req.method === "PUT" && annMatch) {
191
- const id = decodeURIComponent(annMatch[1]);
192
- let annotation;
499
+ if (req.method === "PUT" && id !== null) {
500
+ const contentType = String(req.headers["content-type"] ?? "");
501
+ if (!/^application\/json\b/i.test(contentType)) {
502
+ fail(res, 415, "unsupported_media_type", "content-type must be application/json", cors);
503
+ return;
504
+ }
505
+ const expectedRev = parseIfMatch(req.headers["if-match"]);
506
+ if (expectedRev === null) {
507
+ fail(res, 400, "invalid_if_match", "If-Match must be a revision number", cors);
508
+ return;
509
+ }
510
+ let raw;
193
511
  try {
194
- annotation = JSON.parse(await readBody(req));
195
- } catch {
196
- json(res, 400, { error: "invalid JSON body" });
512
+ raw = JSON.parse(await readBody(req));
513
+ } catch (err) {
514
+ if (err instanceof BodyTooLarge) {
515
+ fail(res, 413, "payload_too_large", `body exceeds ${MAX_BODY_BYTES} bytes`, cors);
516
+ } else {
517
+ fail(res, 400, "invalid_json", "invalid JSON body", cors);
518
+ }
519
+ return;
520
+ }
521
+ const validated = validateAnnotation(raw);
522
+ if (!validated.ok) {
523
+ fail(res, 400, "invalid_annotation", "annotation failed validation", cors, validated.errors);
524
+ return;
525
+ }
526
+ if (validated.annotation.id !== id) {
527
+ fail(res, 400, "id_mismatch", "annotation.id must match the URL id", cors);
197
528
  return;
198
529
  }
199
- if (!annotation || annotation.id !== id) {
200
- json(res, 400, { error: "annotation.id must match the URL id" });
530
+ const result = await storage.saveIfMatch(validated.annotation, expectedRev ?? null);
531
+ if (!result.ok) {
532
+ const status = result.reason === "conflict" ? 409 : 428;
533
+ 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 });
201
534
  return;
202
535
  }
203
- await storage.save(annotation);
204
- json(res, 200, { rev: storage.rev });
536
+ send(res, 200, { rev: result.rev, annotation: result.annotation }, cors);
205
537
  return;
206
538
  }
207
- if (req.method === "DELETE" && annMatch) {
208
- await storage.remove(decodeURIComponent(annMatch[1]));
209
- json(res, 200, { rev: storage.rev });
539
+ if (req.method === "DELETE" && id !== null) {
540
+ const expectedRev = parseIfMatch(req.headers["if-match"]);
541
+ if (expectedRev === null) {
542
+ fail(res, 400, "invalid_if_match", "If-Match must be a revision number", cors);
543
+ return;
544
+ }
545
+ const result = await storage.removeIfMatch(id, expectedRev ?? null);
546
+ if (!result.ok) {
547
+ fail(res, 409, "conflict", "annotation changed since you last read it", cors, { current: result.current, rev: result.rev });
548
+ return;
549
+ }
550
+ send(res, 200, { rev: result.rev }, cors);
210
551
  return;
211
552
  }
212
553
  if (req.method === "DELETE" && pathname === "/annotations") {
213
554
  await storage.clear();
214
- json(res, 200, { rev: storage.rev });
555
+ send(res, 200, { rev: storage.rev }, cors);
215
556
  return;
216
557
  }
217
- json(res, 404, { error: "not found" });
558
+ fail(res, 404, "not_found", "not found", cors);
218
559
  } catch (err) {
219
- json(res, 500, { error: err instanceof Error ? err.message : String(err) });
560
+ fail(res, 500, "internal", err instanceof Error ? err.message : String(err), cors);
220
561
  }
221
562
  }
222
- function startHttpServer(storage, port) {
563
+ function startHttpServer(storage, port, config) {
223
564
  const server = http.createServer((req, res) => {
224
- void handle(req, res, storage);
565
+ const boundPort = server.address()?.port ?? port;
566
+ void handle(req, res, storage, boundPort, config);
225
567
  });
226
568
  return new Promise((resolve, reject) => {
227
569
  server.once("error", reject);
@@ -230,9 +572,9 @@ function startHttpServer(storage, port) {
230
572
  }
231
573
 
232
574
  // src/task-folder.ts
233
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, readdirSync, unlinkSync, writeFileSync as writeFileSync2 } from "fs";
575
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, readdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "fs";
234
576
  import { join as join2 } from "path";
235
- import { actionableOnly, generateAgentExport } from "web-remarq/core";
577
+ import { actionableOnly, generateAgentExport, isSafeAnnotationId as isSafeAnnotationId2 } from "web-remarq/core";
236
578
  function yamlString(value) {
237
579
  return JSON.stringify(value);
238
580
  }
@@ -276,9 +618,9 @@ function renderTaskFile(annotation) {
276
618
  lines.push("");
277
619
  }
278
620
  lines.push("## Agent instructions", "");
279
- 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.`);
621
+ 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.`);
280
622
  lines.push("2. Apply the fix described in the comment.");
281
- 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.`);
623
+ 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.`);
282
624
  lines.push("");
283
625
  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.");
284
626
  lines.push("");
@@ -295,15 +637,31 @@ var TaskFolder = class {
295
637
  async sync() {
296
638
  const store = await this.storage.load();
297
639
  const actionable = actionableOnly(store?.annotations ?? []);
298
- const desired = new Map(actionable.map((a) => [`${a.id}.md`, renderTaskFile(a)]));
299
- mkdirSync2(this.dir, { recursive: true });
300
- for (const name of readdirSync(this.dir)) {
301
- if (name.endsWith(".md") && !desired.has(name)) unlinkSync(join2(this.dir, name));
640
+ const desired = /* @__PURE__ */ new Map();
641
+ for (const a of actionable) {
642
+ if (!isSafeAnnotationId2(a.id)) {
643
+ console.error(`[web-remarq-mcp] skipping annotation with unsafe id: ${JSON.stringify(a.id)}`);
644
+ continue;
645
+ }
646
+ desired.set(`${a.id}.md`, renderTaskFile(a));
647
+ }
648
+ mkdirSync3(this.dir, { recursive: true });
649
+ for (const entry of readdirSync(this.dir, { withFileTypes: true })) {
650
+ if (!entry.isFile() || !entry.name.endsWith(".md") || desired.has(entry.name)) continue;
651
+ try {
652
+ unlinkSync2(join2(this.dir, entry.name));
653
+ } catch (err) {
654
+ console.error(`[web-remarq-mcp] failed to remove stale task file ${entry.name}:`, err);
655
+ }
302
656
  }
303
657
  for (const [name, content] of desired) {
304
- const path = join2(this.dir, name);
305
- if (existsSync2(path) && readFileSync2(path, "utf8") === content) continue;
306
- writeFileSync2(path, content);
658
+ try {
659
+ const path = join2(this.dir, name);
660
+ if (existsSync3(path) && readFileSync3(path, "utf8") === content) continue;
661
+ writeFileSync3(path, content);
662
+ } catch (err) {
663
+ console.error(`[web-remarq-mcp] failed to write task file ${name}:`, err);
664
+ }
307
665
  }
308
666
  }
309
667
  /** Coalesces change bursts: at most one sync in flight, one more queued. Never throws. */
@@ -326,6 +684,21 @@ var TaskFolder = class {
326
684
  }
327
685
  };
328
686
 
687
+ // src/prompts.ts
688
+ var DUTY_PROMPT = "You are on annotation duty for this project. Designers drop feedback via the web-remarq MCP server. Run this loop until told to stop: call watch_annotations (timeoutSeconds: 60); if it times out, call it again. For EACH annotation it returns, call acknowledge with its id first, passing a fresh operationId you keep for retries; if acknowledge answers invalid_transition, another agent already holds it - skip it and do not start work; if the call fails without an answer, retry with the same operationId. Then, if you can run background subagents, dispatch one that applies the fix to the project files and calls claim_fix when done - do not fix anything yourself in the main loop and do not wait for subagents, go straight back to watch_annotations so new feedback is never missed. Without background subagents, apply the fix inline after acknowledging, then return to watch_annotations. If a comment is ambiguous or unactionable, dismiss it with a reason instead of guessing.";
689
+ function registerPrompts(server) {
690
+ server.registerPrompt(
691
+ "watch",
692
+ {
693
+ title: "Annotation duty (dispatcher loop)",
694
+ description: "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."
695
+ },
696
+ () => ({
697
+ messages: [{ role: "user", content: { type: "text", text: DUTY_PROMPT } }]
698
+ })
699
+ );
700
+ }
701
+
329
702
  // src/tools/list-annotations.ts
330
703
  import { z } from "zod";
331
704
 
@@ -424,12 +797,48 @@ async function handleGetAnnotation(input, storage) {
424
797
  }
425
798
 
426
799
  // src/tools/acknowledge.ts
800
+ import { z as z4 } from "zod";
801
+
802
+ // src/tools/transition-tool.ts
427
803
  import { z as z3 } from "zod";
428
- import { transition, InvalidTransitionError } from "web-remarq/core";
429
- var acknowledgeInputSchema = z3.object({
430
- id: z3.string()
431
- });
432
- async function handleAcknowledge(input, storage) {
804
+ import { transition, InvalidTransitionError, AnnotationNotFoundError as AnnotationNotFoundError2 } from "web-remarq/core";
805
+ var operationIdSchema = z3.string().min(1).max(128).optional();
806
+ async function runTransition(input, storage, action, requestedTransition) {
807
+ let replayed = false;
808
+ let seen = null;
809
+ const apply = (current) => {
810
+ seen = current;
811
+ if (input.operationId && current.lifecycle.some((e) => e.opId === input.operationId)) {
812
+ replayed = true;
813
+ return current;
814
+ }
815
+ const result = transition(current, action, { actor: "agent", reason: input.reason });
816
+ const event = input.operationId ? { ...result.event, opId: input.operationId } : result.event;
817
+ return { ...current, status: result.status, lifecycle: [...current.lifecycle, event] };
818
+ };
819
+ const conflict = (current, err) => {
820
+ const last = current.lifecycle[current.lifecycle.length - 1];
821
+ return toolError("invalid_transition", `${err.message} - another actor moved this annotation first; do not start work on it, re-read it with get_annotation`, {
822
+ conflict: true,
823
+ currentStatus: current.status,
824
+ currentRev: current.rev ?? null,
825
+ lastEvent: last ? { type: last.type, actor: last.actor, timestamp: last.timestamp } : null,
826
+ requestedTransition
827
+ });
828
+ };
829
+ if (typeof storage.mutate === "function") {
830
+ let saved;
831
+ try {
832
+ saved = await storage.mutate(input.id, apply);
833
+ } catch (err) {
834
+ if (err instanceof AnnotationNotFoundError2) {
835
+ return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
836
+ }
837
+ if (err instanceof InvalidTransitionError && seen) return conflict(seen, err);
838
+ return toolError("storage_error", err instanceof Error ? err.message : String(err));
839
+ }
840
+ return toolSuccess({ ok: true, status: saved.status, rev: saved.rev ?? null, ...replayed ? { replayed: true } : {} });
841
+ }
433
842
  let store;
434
843
  try {
435
844
  store = await storage.load();
@@ -440,121 +849,58 @@ async function handleAcknowledge(input, storage) {
440
849
  if (!annotation) {
441
850
  return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
442
851
  }
443
- let result;
852
+ let updated;
444
853
  try {
445
- result = transition(annotation, "acknowledge", { actor: "agent" });
854
+ updated = apply(annotation);
446
855
  } catch (err) {
447
- if (err instanceof InvalidTransitionError) {
448
- return toolError("invalid_transition", err.message, {
449
- currentStatus: annotation.status,
450
- requestedTransition: "acknowledge"
451
- });
452
- }
856
+ if (err instanceof InvalidTransitionError) return conflict(annotation, err);
453
857
  throw err;
454
858
  }
455
- const updated = {
456
- ...annotation,
457
- status: result.status,
458
- lifecycle: [...annotation.lifecycle, result.event]
459
- };
460
- try {
461
- await storage.save(updated);
462
- } catch (err) {
463
- return toolError("storage_error", err instanceof Error ? err.message : String(err));
859
+ if (!replayed) {
860
+ try {
861
+ await storage.save(updated);
862
+ } catch (err) {
863
+ return toolError("storage_error", err instanceof Error ? err.message : String(err));
864
+ }
464
865
  }
465
- return toolSuccess({ ok: true, status: result.status });
866
+ return toolSuccess({ ok: true, status: updated.status, atomic: false, ...replayed ? { replayed: true } : {} });
867
+ }
868
+
869
+ // src/tools/acknowledge.ts
870
+ var acknowledgeInputSchema = z4.object({
871
+ id: z4.string(),
872
+ operationId: operationIdSchema
873
+ });
874
+ async function handleAcknowledge(input, storage) {
875
+ return runTransition(input, storage, "acknowledge", "acknowledge");
466
876
  }
467
877
 
468
878
  // src/tools/claim-fix.ts
469
- import { z as z4 } from "zod";
470
- import { transition as transition2, InvalidTransitionError as InvalidTransitionError2 } from "web-remarq/core";
471
- var claimFixInputSchema = z4.object({
472
- id: z4.string()
879
+ import { z as z5 } from "zod";
880
+ var claimFixInputSchema = z5.object({
881
+ id: z5.string(),
882
+ operationId: operationIdSchema
473
883
  });
474
884
  async function handleClaimFix(input, storage) {
475
- let store;
476
- try {
477
- store = await storage.load();
478
- } catch (err) {
479
- return toolError("storage_error", err instanceof Error ? err.message : String(err));
480
- }
481
- const annotation = store?.annotations.find((a) => a.id === input.id);
482
- if (!annotation) {
483
- return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
484
- }
485
- let result;
486
- try {
487
- result = transition2(annotation, "claimFix", { actor: "agent" });
488
- } catch (err) {
489
- if (err instanceof InvalidTransitionError2) {
490
- return toolError("invalid_transition", err.message, {
491
- currentStatus: annotation.status,
492
- requestedTransition: "claimFix"
493
- });
494
- }
495
- throw err;
496
- }
497
- const updated = {
498
- ...annotation,
499
- status: result.status,
500
- lifecycle: [...annotation.lifecycle, result.event]
501
- };
502
- try {
503
- await storage.save(updated);
504
- } catch (err) {
505
- return toolError("storage_error", err instanceof Error ? err.message : String(err));
506
- }
507
- return toolSuccess({ ok: true, status: result.status });
885
+ return runTransition(input, storage, "claimFix", "claimFix");
508
886
  }
509
887
 
510
888
  // src/tools/dismiss.ts
511
- import { z as z5 } from "zod";
512
- import { transition as transition3, InvalidTransitionError as InvalidTransitionError3 } from "web-remarq/core";
513
- var dismissInputSchema = z5.object({
514
- id: z5.string(),
515
- reason: z5.string().optional()
889
+ import { z as z6 } from "zod";
890
+ var dismissInputSchema = z6.object({
891
+ id: z6.string(),
892
+ reason: z6.string().optional(),
893
+ operationId: operationIdSchema
516
894
  });
517
895
  async function handleDismiss(input, storage) {
518
- let store;
519
- try {
520
- store = await storage.load();
521
- } catch (err) {
522
- return toolError("storage_error", err instanceof Error ? err.message : String(err));
523
- }
524
- const annotation = store?.annotations.find((a) => a.id === input.id);
525
- if (!annotation) {
526
- return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
527
- }
528
- let result;
529
- try {
530
- result = transition3(annotation, "dismiss", { actor: "agent", reason: input.reason });
531
- } catch (err) {
532
- if (err instanceof InvalidTransitionError3) {
533
- return toolError("invalid_transition", err.message, {
534
- currentStatus: annotation.status,
535
- requestedTransition: "dismiss"
536
- });
537
- }
538
- throw err;
539
- }
540
- const updated = {
541
- ...annotation,
542
- status: result.status,
543
- lifecycle: [...annotation.lifecycle, result.event]
544
- };
545
- try {
546
- await storage.save(updated);
547
- } catch (err) {
548
- return toolError("storage_error", err instanceof Error ? err.message : String(err));
549
- }
550
- return toolSuccess({ ok: true, status: result.status });
896
+ return runTransition(input, storage, "dismiss", "dismiss");
551
897
  }
552
898
 
553
899
  // src/tools/watch-annotations.ts
554
- import { z as z6 } from "zod";
900
+ import { z as z7 } from "zod";
555
901
  var DEFAULT_TIMEOUT_SECONDS = 25;
556
- var watchAnnotationsInputSchema = z6.object({
557
- timeoutSeconds: z6.number().int().min(1).max(120).optional()
902
+ var watchAnnotationsInputSchema = z7.object({
903
+ timeoutSeconds: z7.number().int().min(1).max(120).optional()
558
904
  });
559
905
  async function handleWatchAnnotations(input, storage, waitForChange) {
560
906
  const timeoutMs = (input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1e3;
@@ -586,7 +932,7 @@ function registerTools(server, storage, opts) {
586
932
  server.registerTool(
587
933
  "list_annotations",
588
934
  {
589
- 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.",
935
+ 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/.",
590
936
  inputSchema: listAnnotationsInputSchema.shape
591
937
  },
592
938
  (input) => cast(handleListAnnotations(input, storage))
@@ -602,7 +948,7 @@ function registerTools(server, storage, opts) {
602
948
  server.registerTool(
603
949
  "acknowledge",
604
950
  {
605
- description: "Mark an annotation as in-progress (pending \u2192 in_progress).",
951
+ description: "Mark an annotation as in-progress (pending \u2192 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.",
606
952
  inputSchema: acknowledgeInputSchema.shape
607
953
  },
608
954
  (input) => cast(handleAcknowledge(input, storage))
@@ -610,7 +956,7 @@ function registerTools(server, storage, opts) {
610
956
  server.registerTool(
611
957
  "claim_fix",
612
958
  {
613
- description: "Claim a fix for an annotation (\u2192 fixed_unverified). Human verification still required.",
959
+ description: "Claim a fix for an annotation (\u2192 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.",
614
960
  inputSchema: claimFixInputSchema.shape
615
961
  },
616
962
  (input) => cast(handleClaimFix(input, storage))
@@ -618,7 +964,7 @@ function registerTools(server, storage, opts) {
618
964
  server.registerTool(
619
965
  "dismiss",
620
966
  {
621
- description: "Dismiss an annotation with an optional reason (terminal state).",
967
+ description: "Dismiss an annotation with an optional reason (terminal state). Atomic with the same operationId retry semantics as acknowledge.",
622
968
  inputSchema: dismissInputSchema.shape
623
969
  },
624
970
  (input) => cast(handleDismiss(input, storage))
@@ -649,13 +995,26 @@ async function main() {
649
995
  let storage;
650
996
  let waitForChange;
651
997
  if (config.mode === "local") {
998
+ const storeDir = dirname2(config.dataFile);
999
+ let local;
1000
+ try {
1001
+ local = readOrCreateLocalConfig(storeDir);
1002
+ acquireStoreLock(storeDir, config.port);
1003
+ } catch (err) {
1004
+ if (err instanceof LocalConfigError || err instanceof StoreLockedError) {
1005
+ console.error(`[web-remarq-mcp] ${err.message}`);
1006
+ process.exit(1);
1007
+ }
1008
+ throw err;
1009
+ }
652
1010
  const adapter = new FileStorageAdapter(config.dataFile);
653
- const taskFolder = new TaskFolder(adapter, join3(dirname2(config.dataFile), "tasks"));
1011
+ const tasksDir = join3(storeDir, "tasks");
1012
+ const taskFolder = new TaskFolder(adapter, tasksDir);
654
1013
  adapter.onChange(() => taskFolder.schedule());
655
1014
  taskFolder.schedule();
656
- await startHttpServer(adapter, config.port);
1015
+ await startHttpServer(adapter, config.port, local);
657
1016
  console.error(
658
- `[web-remarq-mcp] local mode \u2014 widget endpoint http://127.0.0.1:${config.port}, store ${config.dataFile}`
1017
+ `[web-remarq-mcp] local mode \u2014 project ${local.projectId}, widget endpoint http://127.0.0.1:${config.port} (token in ${join3(storeDir, "config.json")}), store ${config.dataFile}, tasks ${tasksDir}`
659
1018
  );
660
1019
  storage = adapter;
661
1020
  waitForChange = (ms) => adapter.waitForChange(ms);
@@ -665,9 +1024,10 @@ async function main() {
665
1024
  }
666
1025
  const server = new McpServer({
667
1026
  name: "web-remarq",
668
- version: "0.2.0"
1027
+ version: "0.5.0"
669
1028
  });
670
1029
  registerTools(server, storage, { waitForChange });
1030
+ registerPrompts(server);
671
1031
  const transport = new StdioServerTransport();
672
1032
  await server.connect(transport);
673
1033
  }