redlinify 0.0.0-stage → 0.4.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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +341 -2
  3. package/dist/_shared/atomicFs.d.ts +10 -0
  4. package/dist/_shared/atomicFs.d.ts.map +1 -0
  5. package/dist/_shared/atomicFs.js +86 -0
  6. package/dist/_shared/atomicFs.js.map +1 -0
  7. package/dist/_shared/browser.d.ts +7 -0
  8. package/dist/_shared/browser.d.ts.map +1 -0
  9. package/dist/_shared/browser.js +7 -0
  10. package/dist/_shared/browser.js.map +1 -0
  11. package/dist/_shared/canonical.d.ts +8 -0
  12. package/dist/_shared/canonical.d.ts.map +1 -0
  13. package/dist/_shared/canonical.js +28 -0
  14. package/dist/_shared/canonical.js.map +1 -0
  15. package/dist/_shared/diff.d.ts +78 -0
  16. package/dist/_shared/diff.d.ts.map +1 -0
  17. package/dist/_shared/diff.js +350 -0
  18. package/dist/_shared/diff.js.map +1 -0
  19. package/dist/_shared/errors.d.ts +29 -0
  20. package/dist/_shared/errors.d.ts.map +1 -0
  21. package/dist/_shared/errors.js +46 -0
  22. package/dist/_shared/errors.js.map +1 -0
  23. package/dist/_shared/fileLock.d.ts +11 -0
  24. package/dist/_shared/fileLock.d.ts.map +1 -0
  25. package/dist/_shared/fileLock.js +114 -0
  26. package/dist/_shared/fileLock.js.map +1 -0
  27. package/dist/_shared/guards.d.ts +20 -0
  28. package/dist/_shared/guards.d.ts.map +1 -0
  29. package/dist/_shared/guards.js +395 -0
  30. package/dist/_shared/guards.js.map +1 -0
  31. package/dist/_shared/hash.d.ts +12 -0
  32. package/dist/_shared/hash.d.ts.map +1 -0
  33. package/dist/_shared/hash.js +80 -0
  34. package/dist/_shared/hash.js.map +1 -0
  35. package/dist/_shared/index.d.ts +9 -0
  36. package/dist/_shared/index.d.ts.map +1 -0
  37. package/dist/_shared/index.js +9 -0
  38. package/dist/_shared/index.js.map +1 -0
  39. package/dist/_shared/schemas.d.ts +727 -0
  40. package/dist/_shared/schemas.d.ts.map +1 -0
  41. package/dist/_shared/schemas.js +352 -0
  42. package/dist/_shared/schemas.js.map +1 -0
  43. package/dist/_shared/storage.d.ts +174 -0
  44. package/dist/_shared/storage.d.ts.map +1 -0
  45. package/dist/_shared/storage.js +801 -0
  46. package/dist/_shared/storage.js.map +1 -0
  47. package/dist/_shared/threadStatus.d.ts +5 -0
  48. package/dist/_shared/threadStatus.d.ts.map +1 -0
  49. package/dist/_shared/threadStatus.js +18 -0
  50. package/dist/_shared/threadStatus.js.map +1 -0
  51. package/dist/cli.d.ts +3 -0
  52. package/dist/cli.d.ts.map +1 -0
  53. package/dist/cli.js +269 -0
  54. package/dist/cli.js.map +1 -0
  55. package/dist/index.d.ts +5 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +5 -0
  58. package/dist/index.js.map +1 -0
  59. package/dist/mcp.d.ts +19 -0
  60. package/dist/mcp.d.ts.map +1 -0
  61. package/dist/mcp.js +654 -0
  62. package/dist/mcp.js.map +1 -0
  63. package/dist/preferences.d.ts +5 -0
  64. package/dist/preferences.d.ts.map +1 -0
  65. package/dist/preferences.js +56 -0
  66. package/dist/preferences.js.map +1 -0
  67. package/dist/uiDaemon.d.ts +47 -0
  68. package/dist/uiDaemon.d.ts.map +1 -0
  69. package/dist/uiDaemon.js +351 -0
  70. package/dist/uiDaemon.js.map +1 -0
  71. package/dist/updater.d.ts +35 -0
  72. package/dist/updater.d.ts.map +1 -0
  73. package/dist/updater.js +336 -0
  74. package/dist/updater.js.map +1 -0
  75. package/dist/web.d.ts +29 -0
  76. package/dist/web.d.ts.map +1 -0
  77. package/dist/web.js +648 -0
  78. package/dist/web.js.map +1 -0
  79. package/package.json +51 -4
  80. package/skill/SKILL.md +36 -0
  81. package/ui-dist/assets/elkjs-DuIp8wh-.js +26 -0
  82. package/ui-dist/assets/index-DhMWEByx.css +1 -0
  83. package/ui-dist/assets/index-Dy_FwyNG.js +99 -0
  84. package/ui-dist/assets/vendor-icons-IOjDvVjt.js +261 -0
  85. package/ui-dist/assets/vendor-react-5-35apmZ.js +49 -0
  86. package/ui-dist/assets/vendor-xyflow-BnuhLJ6X.css +1 -0
  87. package/ui-dist/assets/vendor-xyflow-cY2i6Lf0.js +23 -0
  88. package/ui-dist/index.html +29 -0
package/dist/mcp.js ADDED
@@ -0,0 +1,654 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
+ import { RootsListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
7
+ import { ZodError, z } from "zod";
8
+ import { CardinalitySchema, CodeRefUpdateSchema, DESIGN_DIR_NAME, DesignEdgeSchema, DesignError, DesignNodeSchema, DesignStorage, DesignViewSchema, DiagramTypeSchema, EdgeStyleSchema, EntityRefSchema, NodeShapeSchema, NodeStatusSchema, RelationKindSchema, ThreadKindSchema, ThreadTargetTypeSchema, ValidationError, ViewDirectionSchema, ViewPatchSchema, findProjectRoot, idSlugSchema, } from "./_shared/index.js";
9
+ export const MCP_WORKFLOW_INSTRUCTIONS = `Redlinify is a Git-native architecture & ER workbench in .design/ (IDs: lowercase slugs a-z0-9_-; entity_ref: snake_case).
10
+ - Start every turn with get_workspace() to inspect tabs, entity_ref slugs, pending diffs, view_requests, and open threads.
11
+ - Edit views via save_view(): mode="replace" (diagram_type: "general"|"er"; optional node.shape: "card"|"decision"|"terminal"|"store"), mode="patch", or mode="acknowledge". Auto-starts UI and returns ui_url.
12
+ - Ask in the diagram: set status="needs_input" and anchor a question via post_thread() instead of long chat replies.
13
+ - Respect violet locks: never mutate/delete/unlock locked nodes or edges; resolve threads with a 1-line resolution_summary, query get_decisions(), and link code via sync_code_refs().`;
14
+ const WireCodeRefSchema = z.object({
15
+ path: z.string(),
16
+ symbol: z.string().optional(),
17
+ });
18
+ const WireSectionSchema = z.object({
19
+ id: z.string(),
20
+ heading: z.string(),
21
+ items: z.array(z.string()),
22
+ });
23
+ const WireSectionOpSchema = z.object({
24
+ op: z.enum(["add", "update", "remove"]),
25
+ id: z.string(),
26
+ index: z.number().int().nonnegative().optional(),
27
+ heading: z.string().optional(),
28
+ items: z.array(z.string()).optional(),
29
+ add_items: z.array(z.string()).optional(),
30
+ remove_items: z.array(z.string()).optional(),
31
+ });
32
+ const WireFieldSchema = z.object({
33
+ id: z.string(),
34
+ name: z.string(),
35
+ type: z.string().optional(),
36
+ pk: z.boolean().optional(),
37
+ fk: z.boolean().optional(),
38
+ unique: z.boolean().optional(),
39
+ nullable: z.boolean().optional(),
40
+ indexed: z.boolean().optional(),
41
+ default_value: z.string().optional(),
42
+ note: z.string().optional(),
43
+ });
44
+ const WireNodeSchema = z.object({
45
+ id: z.string(),
46
+ entity_ref: z.string().nullable().optional(),
47
+ kind: z.string().optional(),
48
+ shape: NodeShapeSchema.nullable().optional(),
49
+ title: z.string().optional(),
50
+ summary: z.string().nullable().optional(),
51
+ status: NodeStatusSchema.optional(),
52
+ locked: z.boolean().optional(),
53
+ sections: z.array(WireSectionSchema).optional(),
54
+ section_ops: z.array(WireSectionOpSchema).optional(),
55
+ fields: z.array(WireFieldSchema).optional(),
56
+ code_refs: z.array(WireCodeRefSchema).nullable().optional(),
57
+ });
58
+ const WireEdgeSchema = z.object({
59
+ id: z.string(),
60
+ source: z.string().optional(),
61
+ target: z.string().optional(),
62
+ label: z.string().nullable().optional(),
63
+ step: z.number().int().positive().nullable().optional(),
64
+ style: EdgeStyleSchema.nullable().optional(),
65
+ locked: z.boolean().nullable().optional(),
66
+ source_cardinality: CardinalitySchema.nullable().optional(),
67
+ target_cardinality: CardinalitySchema.nullable().optional(),
68
+ relation_kind: RelationKindSchema.nullable().optional(),
69
+ });
70
+ function okResult(data) {
71
+ return {
72
+ content: [
73
+ {
74
+ type: "text",
75
+ text: JSON.stringify(data),
76
+ },
77
+ ],
78
+ };
79
+ }
80
+ function errResult(err) {
81
+ if (err instanceof DesignError) {
82
+ return {
83
+ isError: true,
84
+ content: [
85
+ {
86
+ type: "text",
87
+ text: JSON.stringify({
88
+ error: err.code,
89
+ message: err.message,
90
+ ...(err.details !== undefined ? { details: err.details } : {}),
91
+ }),
92
+ },
93
+ ],
94
+ };
95
+ }
96
+ if (err instanceof ZodError) {
97
+ return {
98
+ isError: true,
99
+ content: [
100
+ {
101
+ type: "text",
102
+ text: JSON.stringify({
103
+ error: "VALIDATION_ERROR",
104
+ message: err.message,
105
+ details: err.issues,
106
+ }),
107
+ },
108
+ ],
109
+ };
110
+ }
111
+ return {
112
+ isError: true,
113
+ content: [
114
+ {
115
+ type: "text",
116
+ text: JSON.stringify({
117
+ error: "INTERNAL_ERROR",
118
+ message: err instanceof Error ? err.message : String(err),
119
+ }),
120
+ },
121
+ ],
122
+ };
123
+ }
124
+ function viewDeepLink(baseUrl, viewId) {
125
+ return `${baseUrl}/#view=${encodeURIComponent(viewId)}`;
126
+ }
127
+ function normalizeNodePatch(rawNode) {
128
+ if (!rawNode.section_ops?.length) {
129
+ return rawNode;
130
+ }
131
+ return {
132
+ ...rawNode,
133
+ section_ops: rawNode.section_ops.map((op) => {
134
+ if (op.op === "add") {
135
+ return {
136
+ op: "add",
137
+ section: {
138
+ id: op.id,
139
+ heading: op.heading ?? "",
140
+ items: op.items ?? [],
141
+ },
142
+ ...(op.index !== undefined ? { index: op.index } : {}),
143
+ };
144
+ }
145
+ if (op.op === "update") {
146
+ return {
147
+ op: "update",
148
+ id: op.id,
149
+ ...(op.heading !== undefined ? { heading: op.heading } : {}),
150
+ ...(op.items !== undefined ? { items: op.items } : {}),
151
+ ...(op.add_items !== undefined ? { add_items: op.add_items } : {}),
152
+ ...(op.remove_items !== undefined ? { remove_items: op.remove_items } : {}),
153
+ };
154
+ }
155
+ return {
156
+ op: "remove",
157
+ id: op.id,
158
+ };
159
+ }),
160
+ };
161
+ }
162
+ function omitNullFields(obj) {
163
+ const out = {};
164
+ for (const [k, v] of Object.entries(obj)) {
165
+ if (v !== null && v !== undefined) {
166
+ out[k] = v;
167
+ }
168
+ }
169
+ return out;
170
+ }
171
+ function readPackageVersion() {
172
+ try {
173
+ const here = path.dirname(fileURLToPath(import.meta.url));
174
+ const pkgPath = path.resolve(here, "../package.json");
175
+ const parsed = JSON.parse(readFileSync(pkgPath, "utf8"));
176
+ return typeof parsed.version === "string" ? parsed.version : "0.4.0";
177
+ }
178
+ catch {
179
+ return "0.4.0";
180
+ }
181
+ }
182
+ function normalizeComparePath(dirPath) {
183
+ const resolved = path.resolve(dirPath);
184
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
185
+ }
186
+ function isUnsafeDefaultRoot(rootDir, unsafeDirs) {
187
+ const resolved = path.resolve(rootDir);
188
+ const isFsRoot = path.dirname(resolved) === resolved;
189
+ const normalized = normalizeComparePath(resolved);
190
+ const matchesUnsafe = isFsRoot ||
191
+ unsafeDirs.some((candidate) => normalizeComparePath(candidate) === normalized);
192
+ if (!matchesUnsafe)
193
+ return false;
194
+ return (!existsSync(path.join(resolved, DESIGN_DIR_NAME, "workspace.json")) &&
195
+ !existsSync(path.join(resolved, ".git")));
196
+ }
197
+ export function createRedlinifyMcpServer(storage, options) {
198
+ const server = new McpServer({
199
+ name: "redlinify",
200
+ version: readPackageVersion(),
201
+ }, {
202
+ instructions: MCP_WORKFLOW_INSTRUCTIONS,
203
+ });
204
+ const unsafeDirs = options?.unsafeRootDirs ?? [os.homedir()];
205
+ let activeStorage = storage;
206
+ let pendingRootsSync = null;
207
+ const syncFromClientRoots = async () => {
208
+ if (options?.explicitDir)
209
+ return;
210
+ if (!server.server.getClientCapabilities()?.roots)
211
+ return;
212
+ try {
213
+ const { roots } = await server.server.listRoots();
214
+ for (const root of roots) {
215
+ if (!root.uri?.startsWith("file:"))
216
+ continue;
217
+ let candidatePath;
218
+ try {
219
+ candidatePath = fileURLToPath(root.uri);
220
+ }
221
+ catch {
222
+ continue;
223
+ }
224
+ if (!existsSync(candidatePath))
225
+ continue;
226
+ const nextRoot = await findProjectRoot(candidatePath);
227
+ if (normalizeComparePath(nextRoot) !==
228
+ normalizeComparePath(activeStorage.rootDir)) {
229
+ activeStorage = new DesignStorage(nextRoot);
230
+ options?.onRootDirChange?.(nextRoot);
231
+ }
232
+ break;
233
+ }
234
+ }
235
+ catch {
236
+ // Client does not support roots/list or timed out; retain activeStorage
237
+ }
238
+ };
239
+ server.server.oninitialized = () => {
240
+ pendingRootsSync = syncFromClientRoots().finally(() => {
241
+ pendingRootsSync = null;
242
+ });
243
+ };
244
+ server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
245
+ pendingRootsSync = syncFromClientRoots().finally(() => {
246
+ pendingRootsSync = null;
247
+ });
248
+ await pendingRootsSync;
249
+ });
250
+ const getActiveStorage = async (forWrite = false) => {
251
+ if (pendingRootsSync) {
252
+ await pendingRootsSync;
253
+ }
254
+ if (forWrite &&
255
+ !options?.explicitDir &&
256
+ isUnsafeDefaultRoot(activeStorage.rootDir, unsafeDirs)) {
257
+ throw new ValidationError(`Refusing to initialize .design/ in home or filesystem root directory (${activeStorage.rootDir}) because multiple projects would share it. Run 'redlinify mcp' inside a project repo, pass '--dir /path/to/project', or enable MCP workspace roots.`);
258
+ }
259
+ return activeStorage;
260
+ };
261
+ const ensureViewUiUrl = async (viewId, targetRootDir) => {
262
+ if (!options?.ensureUi)
263
+ return undefined;
264
+ try {
265
+ const ui = await options.ensureUi({ rootDir: targetRootDir });
266
+ return ui?.url ? viewDeepLink(ui.url, viewId) : undefined;
267
+ }
268
+ catch {
269
+ return undefined;
270
+ }
271
+ };
272
+ server.registerTool("get_workspace", {
273
+ description: "Inspect workspace tabs (view_hash, triage/drifted counts), entity_ref slugs, pending semantic diffs, view_requests, and open threads awaiting agent response. Set include_diff=false for status only, or open_browser=true to launch the UI.",
274
+ inputSchema: {
275
+ view_id: z.string().optional(),
276
+ include_diff: z.boolean().optional(),
277
+ open_browser: z.boolean().optional(),
278
+ },
279
+ annotations: {
280
+ readOnlyHint: true,
281
+ idempotentHint: true,
282
+ },
283
+ }, async ({ view_id, include_diff, open_browser }) => {
284
+ try {
285
+ const currentStorage = await getActiveStorage(false);
286
+ const validViewId = view_id ? idSlugSchema("view_id").parse(view_id) : undefined;
287
+ if (!options?.explicitDir &&
288
+ isUnsafeDefaultRoot(currentStorage.rootDir, unsafeDirs)) {
289
+ return okResult({
290
+ root_dir: path.resolve(currentStorage.rootDir),
291
+ initialized: false,
292
+ project_name: path.basename(currentStorage.rootDir) || "redlinify-project",
293
+ tabs: [],
294
+ workspace_threads_waiting_on_agent: 0,
295
+ workspace_threads_waiting_on_human: 0,
296
+ view_requests: [],
297
+ entity_refs: {},
298
+ });
299
+ }
300
+ const status = await currentStorage.getWorkspaceStatus();
301
+ const feedback = include_diff === false
302
+ ? null
303
+ : await currentStorage.getPendingFeedback(validViewId);
304
+ let uiFields = {};
305
+ if (open_browser) {
306
+ if (!options?.ensureUi) {
307
+ uiFields = { ui_available: false };
308
+ }
309
+ else {
310
+ const ui = await options.ensureUi({
311
+ openBrowser: true,
312
+ rootDir: currentStorage.rootDir,
313
+ });
314
+ if (ui?.url) {
315
+ uiFields = {
316
+ ui_available: true,
317
+ ui_url: validViewId ? viewDeepLink(ui.url, validViewId) : ui.url,
318
+ ui_started: ui.started,
319
+ browser_opened: Boolean(ui.browser_opened),
320
+ };
321
+ }
322
+ else {
323
+ uiFields = { ui_available: false };
324
+ }
325
+ }
326
+ }
327
+ else if (options?.getRunningUiUrl) {
328
+ const runningUrl = await options
329
+ .getRunningUiUrl(currentStorage.rootDir)
330
+ .catch(() => null);
331
+ if (runningUrl) {
332
+ uiFields = {
333
+ ui_url: validViewId ? viewDeepLink(runningUrl, validViewId) : runningUrl,
334
+ };
335
+ }
336
+ }
337
+ return okResult({
338
+ root_dir: path.resolve(currentStorage.rootDir),
339
+ ...status,
340
+ ...(feedback
341
+ ? {
342
+ view_diffs: feedback.view_diffs,
343
+ view_hashes: feedback.view_hashes,
344
+ pending_threads: feedback.pending_threads,
345
+ }
346
+ : {}),
347
+ ...uiFields,
348
+ });
349
+ }
350
+ catch (err) {
351
+ return errResult(err);
352
+ }
353
+ });
354
+ server.registerTool("get_view", {
355
+ description: "Read a semantic DesignView (zero coordinates), view_hash, open threads, and optional 1-line ADR resolution summaries.",
356
+ inputSchema: {
357
+ view_id: z.string(),
358
+ include_resolved_summaries: z.boolean().optional(),
359
+ },
360
+ annotations: {
361
+ readOnlyHint: true,
362
+ idempotentHint: true,
363
+ },
364
+ }, async ({ view_id, include_resolved_summaries }) => {
365
+ try {
366
+ const currentStorage = await getActiveStorage(false);
367
+ const validViewId = idSlugSchema("view_id").parse(view_id);
368
+ const [{ view, view_hash }, open_threads] = await Promise.all([
369
+ currentStorage.readView(validViewId),
370
+ currentStorage.listThreads({ view_id: validViewId, status: "open" }),
371
+ ]);
372
+ if (!include_resolved_summaries) {
373
+ return okResult({ view, view_hash, open_threads });
374
+ }
375
+ const resolvedThreads = await currentStorage.listThreads({
376
+ view_id: validViewId,
377
+ status: "resolved",
378
+ });
379
+ const resolved_summaries = resolvedThreads.map((t) => ({
380
+ id: t.id,
381
+ target_type: t.target_type,
382
+ target_id: t.target_id,
383
+ entity_ref: t.entity_ref,
384
+ kind: t.kind,
385
+ resolution_summary: t.resolution_summary ?? "",
386
+ }));
387
+ return okResult({
388
+ view,
389
+ view_hash,
390
+ open_threads,
391
+ resolved_summaries,
392
+ });
393
+ }
394
+ catch (err) {
395
+ return errResult(err);
396
+ }
397
+ });
398
+ server.registerTool("get_decisions", {
399
+ description: "Query resolved Decision (ADR) transcripts—or open/all threads via status—filtered by view_id, target_id, entity_ref, or query.",
400
+ inputSchema: {
401
+ view_id: z.string().optional(),
402
+ target_id: z.string().optional(),
403
+ entity_ref: z.string().optional(),
404
+ query: z.string().optional(),
405
+ status: z.enum(["resolved", "open", "all"]).optional(),
406
+ },
407
+ annotations: {
408
+ readOnlyHint: true,
409
+ idempotentHint: true,
410
+ },
411
+ }, async ({ view_id, target_id, entity_ref, query, status }) => {
412
+ try {
413
+ const currentStorage = await getActiveStorage(false);
414
+ const threads = await currentStorage.listThreads({
415
+ status: status === "all" ? undefined : (status ?? "resolved"),
416
+ view_id: view_id ? idSlugSchema("view_id").parse(view_id) : undefined,
417
+ target_id: target_id ? idSlugSchema("target_id").parse(target_id) : undefined,
418
+ entity_ref: entity_ref ? EntityRefSchema.parse(entity_ref) : undefined,
419
+ query,
420
+ });
421
+ return okResult({ threads });
422
+ }
423
+ catch (err) {
424
+ return errResult(err);
425
+ }
426
+ });
427
+ server.registerTool("save_view", {
428
+ description: 'Create, patch, or acknowledge a DesignView (auto-initializes .design/ & starts the local UI). mode="replace" writes full nodes/edges; mode="patch" upserts nodes/edges by id (supports section_ops & null clears) and applies remove_nodes/remove_edges; mode="acknowledge" advances checkpoints.',
429
+ inputSchema: {
430
+ view_id: z.string().optional(),
431
+ mode: z.enum(["replace", "patch", "acknowledge"]).optional(),
432
+ base_hash: z.string().optional(),
433
+ title: z.string().optional(),
434
+ diagram_type: DiagramTypeSchema.optional(),
435
+ direction: ViewDirectionSchema.optional(),
436
+ nodes: z.array(WireNodeSchema).optional(),
437
+ edges: z.array(WireEdgeSchema).optional(),
438
+ remove_nodes: z.array(z.string()).optional(),
439
+ remove_edges: z.array(z.string()).optional(),
440
+ fulfill_request_id: z.string().optional(),
441
+ force: z.boolean().optional(),
442
+ acknowledge_views: z
443
+ .array(z.object({ view_id: z.string(), base_hash: z.string() }))
444
+ .optional(),
445
+ },
446
+ annotations: {
447
+ readOnlyHint: false,
448
+ destructiveHint: false,
449
+ },
450
+ }, async ({ view_id, mode, base_hash, title, diagram_type, direction, nodes, edges, remove_nodes, remove_edges, fulfill_request_id, force, acknowledge_views, }) => {
451
+ try {
452
+ const currentStorage = await getActiveStorage(true);
453
+ const resolvedMode = mode ?? (acknowledge_views?.length ? "acknowledge" : "replace");
454
+ if (resolvedMode === "acknowledge") {
455
+ const entries = acknowledge_views && acknowledge_views.length > 0
456
+ ? acknowledge_views
457
+ : view_id && base_hash
458
+ ? [{ view_id, base_hash }]
459
+ : null;
460
+ if (!entries) {
461
+ throw new ValidationError("Provide acknowledge_views or view_id + base_hash for save_view mode='acknowledge'");
462
+ }
463
+ const validatedEntries = entries.map((e) => ({
464
+ view_id: idSlugSchema("view_id").parse(e.view_id),
465
+ base_hash: z.string().min(1, "base_hash is required").parse(e.base_hash),
466
+ }));
467
+ const res = await currentStorage.acknowledgeFeedback(validatedEntries);
468
+ return okResult({ mode: "acknowledge", ...res });
469
+ }
470
+ if (!view_id) {
471
+ throw new ValidationError("view_id is required for save_view");
472
+ }
473
+ const validViewId = idSlugSchema("view_id").parse(view_id);
474
+ if (resolvedMode === "patch") {
475
+ if (!base_hash) {
476
+ throw new ValidationError("base_hash is required for save_view mode='patch'");
477
+ }
478
+ const { view: currentView } = await currentStorage.readView(validViewId);
479
+ const existingNodeIds = new Set(currentView.nodes.map((n) => n.id));
480
+ const existingEdgeIds = new Set(currentView.edges.map((e) => e.id));
481
+ const add_nodes = [];
482
+ const update_nodes = [];
483
+ for (const rawNode of nodes ?? []) {
484
+ const validNodeId = idSlugSchema("node.id").parse(rawNode.id);
485
+ if (existingNodeIds.has(validNodeId)) {
486
+ update_nodes.push(normalizeNodePatch(rawNode));
487
+ }
488
+ else {
489
+ add_nodes.push(DesignNodeSchema.parse(omitNullFields(rawNode)));
490
+ }
491
+ }
492
+ const add_edges = [];
493
+ const update_edges = [];
494
+ for (const rawEdge of edges ?? []) {
495
+ const validEdgeId = idSlugSchema("edge.id").parse(rawEdge.id);
496
+ if (existingEdgeIds.has(validEdgeId)) {
497
+ update_edges.push(rawEdge);
498
+ }
499
+ else {
500
+ add_edges.push(DesignEdgeSchema.parse(omitNullFields(rawEdge)));
501
+ }
502
+ }
503
+ const meta = title !== undefined || direction !== undefined || diagram_type !== undefined
504
+ ? {
505
+ ...(title !== undefined ? { title } : {}),
506
+ ...(direction !== undefined ? { direction } : {}),
507
+ ...(diagram_type !== undefined ? { diagram_type } : {}),
508
+ }
509
+ : undefined;
510
+ const parsedPatch = ViewPatchSchema.parse({
511
+ ...(meta ? { meta } : {}),
512
+ ...(add_nodes.length > 0 ? { add_nodes } : {}),
513
+ ...(update_nodes.length > 0 ? { update_nodes } : {}),
514
+ ...(remove_nodes?.length ? { remove_nodes } : {}),
515
+ ...(add_edges.length > 0 ? { add_edges } : {}),
516
+ ...(update_edges.length > 0 ? { update_edges } : {}),
517
+ ...(remove_edges?.length ? { remove_edges } : {}),
518
+ });
519
+ const res = await currentStorage.patchView({
520
+ view_id: validViewId,
521
+ base_hash,
522
+ patch: parsedPatch,
523
+ actor: "agent",
524
+ });
525
+ const ui_url = await ensureViewUiUrl(res.view.id, currentStorage.rootDir);
526
+ return okResult({
527
+ mode: "patch",
528
+ view_id: res.view.id,
529
+ view_hash: res.view_hash,
530
+ node_count: res.view.nodes.length,
531
+ edge_count: res.view.edges.length,
532
+ ...(ui_url ? { ui_url } : {}),
533
+ });
534
+ }
535
+ if (!title || !title.trim()) {
536
+ throw new ValidationError("title is required when calling save_view in mode='replace'");
537
+ }
538
+ const sanitizedView = DesignViewSchema.parse({
539
+ id: validViewId,
540
+ title,
541
+ diagram_type: diagram_type ?? "general",
542
+ direction: direction ?? "TB",
543
+ nodes: (nodes ?? []).map((n) => omitNullFields(n)),
544
+ edges: (edges ?? []).map((e) => omitNullFields(e)),
545
+ });
546
+ const res = await currentStorage.upsertView({
547
+ view: sanitizedView,
548
+ base_hash,
549
+ fulfill_request_id: fulfill_request_id
550
+ ? idSlugSchema("fulfill_request_id").parse(fulfill_request_id)
551
+ : undefined,
552
+ actor: "agent",
553
+ force,
554
+ });
555
+ const ui_url = await ensureViewUiUrl(res.view.id, currentStorage.rootDir);
556
+ return okResult({
557
+ mode: "replace",
558
+ view_id: res.view.id,
559
+ view_hash: res.view_hash,
560
+ created: res.created,
561
+ node_count: res.view.nodes.length,
562
+ edge_count: res.view.edges.length,
563
+ ...(ui_url ? { ui_url } : {}),
564
+ });
565
+ }
566
+ catch (err) {
567
+ return errResult(err);
568
+ }
569
+ });
570
+ server.registerTool("post_thread", {
571
+ description: "Create an anchored thread (question, change_request, decision, drift_alert) or reply; resolve=true requires a 1-line resolution_summary (Decisions).",
572
+ inputSchema: {
573
+ thread_id: z.string().optional(),
574
+ target_type: ThreadTargetTypeSchema.optional(),
575
+ view_id: z.string().optional(),
576
+ target_id: z.string().optional(),
577
+ entity_ref: z.string().optional(),
578
+ kind: ThreadKindSchema.optional(),
579
+ body: z.string(),
580
+ resolve: z.boolean().optional(),
581
+ reopen: z.boolean().optional(),
582
+ resolution_summary: z.string().optional(),
583
+ },
584
+ annotations: {
585
+ readOnlyHint: false,
586
+ destructiveHint: false,
587
+ },
588
+ }, async (args) => {
589
+ try {
590
+ const currentStorage = await getActiveStorage(true);
591
+ const thread = await currentStorage.postThreadMessage({
592
+ thread_id: args.thread_id
593
+ ? idSlugSchema("thread_id").parse(args.thread_id)
594
+ : undefined,
595
+ target_type: args.target_type,
596
+ view_id: args.view_id ? idSlugSchema("view_id").parse(args.view_id) : undefined,
597
+ target_id: args.target_id
598
+ ? idSlugSchema("target_id").parse(args.target_id)
599
+ : undefined,
600
+ entity_ref: args.entity_ref
601
+ ? EntityRefSchema.parse(args.entity_ref)
602
+ : undefined,
603
+ kind: args.kind,
604
+ body: z.string().trim().min(1, "body is required").parse(args.body),
605
+ resolve: args.resolve,
606
+ reopen: args.reopen,
607
+ resolution_summary: args.resolution_summary,
608
+ author: "agent",
609
+ });
610
+ return okResult({ thread });
611
+ }
612
+ catch (err) {
613
+ return errResult(err);
614
+ }
615
+ });
616
+ server.registerTool("sync_code_refs", {
617
+ description: "Link source code_refs and status ('implemented' | 'drifted') onto nodes (including locked nodes) without clobbering unrelated pending human edits.",
618
+ inputSchema: {
619
+ view_id: z.string(),
620
+ updates: z.array(z.object({
621
+ node_id: z.string(),
622
+ status: z.enum(["implemented", "drifted"]),
623
+ code_refs: z.array(WireCodeRefSchema),
624
+ })),
625
+ },
626
+ annotations: {
627
+ readOnlyHint: false,
628
+ destructiveHint: false,
629
+ idempotentHint: true,
630
+ },
631
+ }, async ({ view_id, updates }) => {
632
+ try {
633
+ const currentStorage = await getActiveStorage(true);
634
+ if (updates.length === 0) {
635
+ throw new ValidationError("updates must contain at least one entry");
636
+ }
637
+ const parsedUpdates = updates.map((u) => CodeRefUpdateSchema.parse(u));
638
+ const res = await currentStorage.syncCodeRefs({
639
+ view_id,
640
+ updates: parsedUpdates,
641
+ });
642
+ return okResult({
643
+ view_id: res.view.id,
644
+ view_hash: res.view_hash,
645
+ updated_node_ids: res.updated_node_ids,
646
+ });
647
+ }
648
+ catch (err) {
649
+ return errResult(err);
650
+ }
651
+ });
652
+ return server;
653
+ }
654
+ //# sourceMappingURL=mcp.js.map