redlinify 0.0.0-stage → 0.4.1

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 (92) 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 +275 -0
  54. package/dist/cli.js.map +1 -0
  55. package/dist/index.d.ts +7 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +7 -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 +880 -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 +51 -0
  72. package/dist/updater.d.ts.map +1 -0
  73. package/dist/updater.js +449 -0
  74. package/dist/updater.js.map +1 -0
  75. package/dist/version.d.ts +3 -0
  76. package/dist/version.d.ts.map +1 -0
  77. package/dist/version.js +19 -0
  78. package/dist/version.js.map +1 -0
  79. package/dist/web.d.ts +29 -0
  80. package/dist/web.d.ts.map +1 -0
  81. package/dist/web.js +648 -0
  82. package/dist/web.js.map +1 -0
  83. package/package.json +55 -4
  84. package/skill/SKILL.md +36 -0
  85. package/ui-dist/assets/elkjs-DuIp8wh-.js +26 -0
  86. package/ui-dist/assets/index-DhMWEByx.css +1 -0
  87. package/ui-dist/assets/index-Dy_FwyNG.js +99 -0
  88. package/ui-dist/assets/vendor-icons-IOjDvVjt.js +261 -0
  89. package/ui-dist/assets/vendor-react-5-35apmZ.js +49 -0
  90. package/ui-dist/assets/vendor-xyflow-BnuhLJ6X.css +1 -0
  91. package/ui-dist/assets/vendor-xyflow-cY2i6Lf0.js +23 -0
  92. package/ui-dist/index.html +29 -0
package/dist/mcp.js ADDED
@@ -0,0 +1,880 @@
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, ResourceTemplate } 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, NotFoundError, RelationKindSchema, ThreadKindSchema, ThreadTargetTypeSchema, ValidationError, ViewDirectionSchema, ViewPatchSchema, findProjectRoot, idSlugSchema, } from "./_shared/index.js";
9
+ import { readPackageVersion } from "./version.js";
10
+ 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).
11
+ - Start every turn with get_workspace() to inspect tabs, entity_ref slugs, pending diffs, view_requests, and open threads.
12
+ - 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.
13
+ - Ask in the diagram: set status="needs_input" and anchor a question via post_thread() instead of long chat replies.
14
+ - 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().`;
15
+ const WireCodeRefSchema = z.object({
16
+ path: z.string(),
17
+ symbol: z.string().optional(),
18
+ });
19
+ const WireSectionSchema = z.object({
20
+ id: z.string(),
21
+ heading: z.string(),
22
+ items: z.array(z.string()),
23
+ });
24
+ const WireSectionOpSchema = z.object({
25
+ op: z.enum(["add", "update", "remove"]),
26
+ id: z.string(),
27
+ index: z.number().int().nonnegative().optional(),
28
+ heading: z.string().optional(),
29
+ items: z.array(z.string()).optional(),
30
+ add_items: z.array(z.string()).optional(),
31
+ remove_items: z.array(z.string()).optional(),
32
+ });
33
+ const WireFieldSchema = z.object({
34
+ id: z.string(),
35
+ name: z.string(),
36
+ type: z.string().optional(),
37
+ pk: z.boolean().optional(),
38
+ fk: z.boolean().optional(),
39
+ unique: z.boolean().optional(),
40
+ nullable: z.boolean().optional(),
41
+ indexed: z.boolean().optional(),
42
+ default_value: z.string().optional(),
43
+ note: z.string().optional(),
44
+ });
45
+ const WireNodeSchema = z.object({
46
+ id: z.string(),
47
+ entity_ref: z.string().nullable().optional(),
48
+ kind: z.string().optional(),
49
+ shape: NodeShapeSchema.nullable().optional(),
50
+ title: z.string().optional(),
51
+ summary: z.string().nullable().optional(),
52
+ status: NodeStatusSchema.optional(),
53
+ locked: z.boolean().optional(),
54
+ sections: z.array(WireSectionSchema).optional(),
55
+ section_ops: z.array(WireSectionOpSchema).optional(),
56
+ fields: z.array(WireFieldSchema).optional(),
57
+ code_refs: z.array(WireCodeRefSchema).nullable().optional(),
58
+ });
59
+ const WireEdgeSchema = z.object({
60
+ id: z.string(),
61
+ source: z.string().optional(),
62
+ target: z.string().optional(),
63
+ label: z.string().nullable().optional(),
64
+ step: z.number().int().positive().nullable().optional(),
65
+ style: EdgeStyleSchema.nullable().optional(),
66
+ locked: z.boolean().nullable().optional(),
67
+ source_cardinality: CardinalitySchema.nullable().optional(),
68
+ target_cardinality: CardinalitySchema.nullable().optional(),
69
+ relation_kind: RelationKindSchema.nullable().optional(),
70
+ });
71
+ function okResult(data) {
72
+ return {
73
+ content: [
74
+ {
75
+ type: "text",
76
+ text: JSON.stringify(data),
77
+ },
78
+ ],
79
+ };
80
+ }
81
+ function errResult(err) {
82
+ if (err instanceof DesignError) {
83
+ return {
84
+ isError: true,
85
+ content: [
86
+ {
87
+ type: "text",
88
+ text: JSON.stringify({
89
+ error: err.code,
90
+ message: err.message,
91
+ ...(err.details !== undefined ? { details: err.details } : {}),
92
+ }),
93
+ },
94
+ ],
95
+ };
96
+ }
97
+ if (err instanceof ZodError) {
98
+ return {
99
+ isError: true,
100
+ content: [
101
+ {
102
+ type: "text",
103
+ text: JSON.stringify({
104
+ error: "VALIDATION_ERROR",
105
+ message: err.message,
106
+ details: err.issues,
107
+ }),
108
+ },
109
+ ],
110
+ };
111
+ }
112
+ return {
113
+ isError: true,
114
+ content: [
115
+ {
116
+ type: "text",
117
+ text: JSON.stringify({
118
+ error: "INTERNAL_ERROR",
119
+ message: err instanceof Error ? err.message : String(err),
120
+ }),
121
+ },
122
+ ],
123
+ };
124
+ }
125
+ function viewDeepLink(baseUrl, viewId) {
126
+ return `${baseUrl}/#view=${encodeURIComponent(viewId)}`;
127
+ }
128
+ function normalizeNodePatch(rawNode) {
129
+ if (!rawNode.section_ops?.length) {
130
+ return rawNode;
131
+ }
132
+ return {
133
+ ...rawNode,
134
+ section_ops: rawNode.section_ops.map((op) => {
135
+ if (op.op === "add") {
136
+ return {
137
+ op: "add",
138
+ section: {
139
+ id: op.id,
140
+ heading: op.heading ?? "",
141
+ items: op.items ?? [],
142
+ },
143
+ ...(op.index !== undefined ? { index: op.index } : {}),
144
+ };
145
+ }
146
+ if (op.op === "update") {
147
+ return {
148
+ op: "update",
149
+ id: op.id,
150
+ ...(op.heading !== undefined ? { heading: op.heading } : {}),
151
+ ...(op.items !== undefined ? { items: op.items } : {}),
152
+ ...(op.add_items !== undefined ? { add_items: op.add_items } : {}),
153
+ ...(op.remove_items !== undefined ? { remove_items: op.remove_items } : {}),
154
+ };
155
+ }
156
+ return {
157
+ op: "remove",
158
+ id: op.id,
159
+ };
160
+ }),
161
+ };
162
+ }
163
+ function omitNullFields(obj) {
164
+ const out = {};
165
+ for (const [k, v] of Object.entries(obj)) {
166
+ if (v !== null && v !== undefined) {
167
+ out[k] = v;
168
+ }
169
+ }
170
+ return out;
171
+ }
172
+ function readWorkflowGuideMarkdown() {
173
+ const here = path.dirname(fileURLToPath(import.meta.url));
174
+ const candidates = [
175
+ path.resolve(here, "../skill/SKILL.md"),
176
+ path.resolve(here, "../../../skill/SKILL.md"),
177
+ ];
178
+ for (const filePath of candidates) {
179
+ if (existsSync(filePath)) {
180
+ try {
181
+ return readFileSync(filePath, "utf8");
182
+ }
183
+ catch {
184
+ // Fall through to compact instructions
185
+ }
186
+ }
187
+ }
188
+ return MCP_WORKFLOW_INSTRUCTIONS;
189
+ }
190
+ function hasInitializedWorkspace(targetStorage) {
191
+ return existsSync(path.join(targetStorage.rootDir, DESIGN_DIR_NAME, "workspace.json"));
192
+ }
193
+ function normalizeComparePath(dirPath) {
194
+ const resolved = path.resolve(dirPath);
195
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
196
+ }
197
+ function isUnsafeDefaultRoot(rootDir, unsafeDirs) {
198
+ const resolved = path.resolve(rootDir);
199
+ const isFsRoot = path.dirname(resolved) === resolved;
200
+ const normalized = normalizeComparePath(resolved);
201
+ const matchesUnsafe = isFsRoot ||
202
+ unsafeDirs.some((candidate) => normalizeComparePath(candidate) === normalized);
203
+ if (!matchesUnsafe)
204
+ return false;
205
+ return (!existsSync(path.join(resolved, DESIGN_DIR_NAME, "workspace.json")) &&
206
+ !existsSync(path.join(resolved, ".git")));
207
+ }
208
+ export function createRedlinifyMcpServer(storage, options) {
209
+ const server = new McpServer({
210
+ name: "redlinify",
211
+ version: readPackageVersion(),
212
+ }, {
213
+ instructions: MCP_WORKFLOW_INSTRUCTIONS,
214
+ });
215
+ const unsafeDirs = options?.unsafeRootDirs ?? [os.homedir()];
216
+ let activeStorage = storage;
217
+ let pendingRootsSync = null;
218
+ const syncFromClientRoots = async () => {
219
+ if (options?.explicitDir)
220
+ return;
221
+ if (!server.server.getClientCapabilities()?.roots)
222
+ return;
223
+ try {
224
+ const { roots } = await server.server.listRoots();
225
+ for (const root of roots) {
226
+ if (!root.uri?.startsWith("file:"))
227
+ continue;
228
+ let candidatePath;
229
+ try {
230
+ candidatePath = fileURLToPath(root.uri);
231
+ }
232
+ catch {
233
+ continue;
234
+ }
235
+ if (!existsSync(candidatePath))
236
+ continue;
237
+ const nextRoot = await findProjectRoot(candidatePath);
238
+ if (normalizeComparePath(nextRoot) !==
239
+ normalizeComparePath(activeStorage.rootDir)) {
240
+ activeStorage = new DesignStorage(nextRoot);
241
+ options?.onRootDirChange?.(nextRoot);
242
+ }
243
+ break;
244
+ }
245
+ }
246
+ catch {
247
+ // Client does not support roots/list or timed out; retain activeStorage
248
+ }
249
+ };
250
+ server.server.oninitialized = () => {
251
+ pendingRootsSync = syncFromClientRoots().finally(() => {
252
+ pendingRootsSync = null;
253
+ });
254
+ };
255
+ server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
256
+ pendingRootsSync = syncFromClientRoots().finally(() => {
257
+ pendingRootsSync = null;
258
+ });
259
+ await pendingRootsSync;
260
+ });
261
+ const getActiveStorage = async (forWrite = false) => {
262
+ if (pendingRootsSync) {
263
+ await pendingRootsSync;
264
+ }
265
+ if (forWrite &&
266
+ !options?.explicitDir &&
267
+ isUnsafeDefaultRoot(activeStorage.rootDir, unsafeDirs)) {
268
+ 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.`);
269
+ }
270
+ return activeStorage;
271
+ };
272
+ const ensureViewUiUrl = async (viewId, targetRootDir) => {
273
+ if (!options?.ensureUi)
274
+ return undefined;
275
+ try {
276
+ const ui = await options.ensureUi({ rootDir: targetRootDir });
277
+ return ui?.url ? viewDeepLink(ui.url, viewId) : undefined;
278
+ }
279
+ catch {
280
+ return undefined;
281
+ }
282
+ };
283
+ server.registerTool("get_workspace", {
284
+ 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.",
285
+ inputSchema: {
286
+ view_id: z.string().optional(),
287
+ include_diff: z.boolean().optional(),
288
+ open_browser: z.boolean().optional(),
289
+ },
290
+ annotations: {
291
+ readOnlyHint: true,
292
+ idempotentHint: true,
293
+ },
294
+ }, async ({ view_id, include_diff, open_browser }) => {
295
+ try {
296
+ const currentStorage = await getActiveStorage(false);
297
+ const validViewId = view_id ? idSlugSchema("view_id").parse(view_id) : undefined;
298
+ if (!options?.explicitDir &&
299
+ isUnsafeDefaultRoot(currentStorage.rootDir, unsafeDirs)) {
300
+ return okResult({
301
+ root_dir: path.resolve(currentStorage.rootDir),
302
+ initialized: false,
303
+ project_name: path.basename(currentStorage.rootDir) || "redlinify-project",
304
+ tabs: [],
305
+ workspace_threads_waiting_on_agent: 0,
306
+ workspace_threads_waiting_on_human: 0,
307
+ view_requests: [],
308
+ entity_refs: {},
309
+ });
310
+ }
311
+ const status = await currentStorage.getWorkspaceStatus();
312
+ const feedback = include_diff === false
313
+ ? null
314
+ : await currentStorage.getPendingFeedback(validViewId);
315
+ let uiFields = {};
316
+ if (open_browser) {
317
+ if (!options?.ensureUi) {
318
+ uiFields = { ui_available: false };
319
+ }
320
+ else {
321
+ const ui = await options.ensureUi({
322
+ openBrowser: true,
323
+ rootDir: currentStorage.rootDir,
324
+ });
325
+ if (ui?.url) {
326
+ uiFields = {
327
+ ui_available: true,
328
+ ui_url: validViewId ? viewDeepLink(ui.url, validViewId) : ui.url,
329
+ ui_started: ui.started,
330
+ browser_opened: Boolean(ui.browser_opened),
331
+ };
332
+ }
333
+ else {
334
+ uiFields = { ui_available: false };
335
+ }
336
+ }
337
+ }
338
+ else if (options?.getRunningUiUrl) {
339
+ const runningUrl = await options
340
+ .getRunningUiUrl(currentStorage.rootDir)
341
+ .catch(() => null);
342
+ if (runningUrl) {
343
+ uiFields = {
344
+ ui_url: validViewId ? viewDeepLink(runningUrl, validViewId) : runningUrl,
345
+ };
346
+ }
347
+ }
348
+ return okResult({
349
+ root_dir: path.resolve(currentStorage.rootDir),
350
+ ...status,
351
+ ...(feedback
352
+ ? {
353
+ view_diffs: feedback.view_diffs,
354
+ view_hashes: feedback.view_hashes,
355
+ pending_threads: feedback.pending_threads,
356
+ }
357
+ : {}),
358
+ ...uiFields,
359
+ });
360
+ }
361
+ catch (err) {
362
+ return errResult(err);
363
+ }
364
+ });
365
+ server.registerTool("get_view", {
366
+ description: "Read a semantic DesignView (zero coordinates), view_hash, open threads, and optional 1-line ADR resolution summaries.",
367
+ inputSchema: {
368
+ view_id: z.string(),
369
+ include_resolved_summaries: z.boolean().optional(),
370
+ },
371
+ annotations: {
372
+ readOnlyHint: true,
373
+ idempotentHint: true,
374
+ },
375
+ }, async ({ view_id, include_resolved_summaries }) => {
376
+ try {
377
+ const currentStorage = await getActiveStorage(false);
378
+ const validViewId = idSlugSchema("view_id").parse(view_id);
379
+ const [{ view, view_hash }, open_threads] = await Promise.all([
380
+ currentStorage.readView(validViewId),
381
+ currentStorage.listThreads({ view_id: validViewId, status: "open" }),
382
+ ]);
383
+ if (!include_resolved_summaries) {
384
+ return okResult({ view, view_hash, open_threads });
385
+ }
386
+ const resolvedThreads = await currentStorage.listThreads({
387
+ view_id: validViewId,
388
+ status: "resolved",
389
+ });
390
+ const resolved_summaries = resolvedThreads.map((t) => ({
391
+ id: t.id,
392
+ target_type: t.target_type,
393
+ target_id: t.target_id,
394
+ entity_ref: t.entity_ref,
395
+ kind: t.kind,
396
+ resolution_summary: t.resolution_summary ?? "",
397
+ }));
398
+ return okResult({
399
+ view,
400
+ view_hash,
401
+ open_threads,
402
+ resolved_summaries,
403
+ });
404
+ }
405
+ catch (err) {
406
+ return errResult(err);
407
+ }
408
+ });
409
+ server.registerTool("get_decisions", {
410
+ description: "Query resolved Decision (ADR) transcripts—or open/all threads via status—filtered by view_id, target_id, entity_ref, or query.",
411
+ inputSchema: {
412
+ view_id: z.string().optional(),
413
+ target_id: z.string().optional(),
414
+ entity_ref: z.string().optional(),
415
+ query: z.string().optional(),
416
+ status: z.enum(["resolved", "open", "all"]).optional(),
417
+ },
418
+ annotations: {
419
+ readOnlyHint: true,
420
+ idempotentHint: true,
421
+ },
422
+ }, async ({ view_id, target_id, entity_ref, query, status }) => {
423
+ try {
424
+ const currentStorage = await getActiveStorage(false);
425
+ const threads = await currentStorage.listThreads({
426
+ status: status === "all" ? undefined : (status ?? "resolved"),
427
+ view_id: view_id ? idSlugSchema("view_id").parse(view_id) : undefined,
428
+ target_id: target_id ? idSlugSchema("target_id").parse(target_id) : undefined,
429
+ entity_ref: entity_ref ? EntityRefSchema.parse(entity_ref) : undefined,
430
+ query,
431
+ });
432
+ return okResult({ threads });
433
+ }
434
+ catch (err) {
435
+ return errResult(err);
436
+ }
437
+ });
438
+ server.registerTool("save_view", {
439
+ 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.',
440
+ inputSchema: {
441
+ view_id: z.string().optional(),
442
+ mode: z.enum(["replace", "patch", "acknowledge"]).optional(),
443
+ base_hash: z.string().optional(),
444
+ title: z.string().optional(),
445
+ diagram_type: DiagramTypeSchema.optional(),
446
+ direction: ViewDirectionSchema.optional(),
447
+ nodes: z.array(WireNodeSchema).optional(),
448
+ edges: z.array(WireEdgeSchema).optional(),
449
+ remove_nodes: z.array(z.string()).optional(),
450
+ remove_edges: z.array(z.string()).optional(),
451
+ fulfill_request_id: z.string().optional(),
452
+ force: z.boolean().optional(),
453
+ acknowledge_views: z
454
+ .array(z.object({ view_id: z.string(), base_hash: z.string() }))
455
+ .optional(),
456
+ },
457
+ annotations: {
458
+ readOnlyHint: false,
459
+ destructiveHint: false,
460
+ },
461
+ }, async ({ view_id, mode, base_hash, title, diagram_type, direction, nodes, edges, remove_nodes, remove_edges, fulfill_request_id, force, acknowledge_views, }) => {
462
+ try {
463
+ const currentStorage = await getActiveStorage(true);
464
+ const resolvedMode = mode ?? (acknowledge_views?.length ? "acknowledge" : "replace");
465
+ if (resolvedMode === "acknowledge") {
466
+ const entries = acknowledge_views && acknowledge_views.length > 0
467
+ ? acknowledge_views
468
+ : view_id && base_hash
469
+ ? [{ view_id, base_hash }]
470
+ : null;
471
+ if (!entries) {
472
+ throw new ValidationError("Provide acknowledge_views or view_id + base_hash for save_view mode='acknowledge'");
473
+ }
474
+ const validatedEntries = entries.map((e) => ({
475
+ view_id: idSlugSchema("view_id").parse(e.view_id),
476
+ base_hash: z.string().min(1, "base_hash is required").parse(e.base_hash),
477
+ }));
478
+ const res = await currentStorage.acknowledgeFeedback(validatedEntries);
479
+ return okResult({ mode: "acknowledge", ...res });
480
+ }
481
+ if (!view_id) {
482
+ throw new ValidationError("view_id is required for save_view");
483
+ }
484
+ const validViewId = idSlugSchema("view_id").parse(view_id);
485
+ if (resolvedMode === "patch") {
486
+ if (!base_hash) {
487
+ throw new ValidationError("base_hash is required for save_view mode='patch'");
488
+ }
489
+ const { view: currentView } = await currentStorage.readView(validViewId);
490
+ const existingNodeIds = new Set(currentView.nodes.map((n) => n.id));
491
+ const existingEdgeIds = new Set(currentView.edges.map((e) => e.id));
492
+ const add_nodes = [];
493
+ const update_nodes = [];
494
+ for (const rawNode of nodes ?? []) {
495
+ const validNodeId = idSlugSchema("node.id").parse(rawNode.id);
496
+ if (existingNodeIds.has(validNodeId)) {
497
+ update_nodes.push(normalizeNodePatch(rawNode));
498
+ }
499
+ else {
500
+ add_nodes.push(DesignNodeSchema.parse(omitNullFields(rawNode)));
501
+ }
502
+ }
503
+ const add_edges = [];
504
+ const update_edges = [];
505
+ for (const rawEdge of edges ?? []) {
506
+ const validEdgeId = idSlugSchema("edge.id").parse(rawEdge.id);
507
+ if (existingEdgeIds.has(validEdgeId)) {
508
+ update_edges.push(rawEdge);
509
+ }
510
+ else {
511
+ add_edges.push(DesignEdgeSchema.parse(omitNullFields(rawEdge)));
512
+ }
513
+ }
514
+ const meta = title !== undefined || direction !== undefined || diagram_type !== undefined
515
+ ? {
516
+ ...(title !== undefined ? { title } : {}),
517
+ ...(direction !== undefined ? { direction } : {}),
518
+ ...(diagram_type !== undefined ? { diagram_type } : {}),
519
+ }
520
+ : undefined;
521
+ const parsedPatch = ViewPatchSchema.parse({
522
+ ...(meta ? { meta } : {}),
523
+ ...(add_nodes.length > 0 ? { add_nodes } : {}),
524
+ ...(update_nodes.length > 0 ? { update_nodes } : {}),
525
+ ...(remove_nodes?.length ? { remove_nodes } : {}),
526
+ ...(add_edges.length > 0 ? { add_edges } : {}),
527
+ ...(update_edges.length > 0 ? { update_edges } : {}),
528
+ ...(remove_edges?.length ? { remove_edges } : {}),
529
+ });
530
+ const res = await currentStorage.patchView({
531
+ view_id: validViewId,
532
+ base_hash,
533
+ patch: parsedPatch,
534
+ actor: "agent",
535
+ });
536
+ const ui_url = await ensureViewUiUrl(res.view.id, currentStorage.rootDir);
537
+ return okResult({
538
+ mode: "patch",
539
+ view_id: res.view.id,
540
+ view_hash: res.view_hash,
541
+ node_count: res.view.nodes.length,
542
+ edge_count: res.view.edges.length,
543
+ ...(ui_url ? { ui_url } : {}),
544
+ });
545
+ }
546
+ if (!title || !title.trim()) {
547
+ throw new ValidationError("title is required when calling save_view in mode='replace'");
548
+ }
549
+ const sanitizedView = DesignViewSchema.parse({
550
+ id: validViewId,
551
+ title,
552
+ diagram_type: diagram_type ?? "general",
553
+ direction: direction ?? "TB",
554
+ nodes: (nodes ?? []).map((n) => omitNullFields(n)),
555
+ edges: (edges ?? []).map((e) => omitNullFields(e)),
556
+ });
557
+ const res = await currentStorage.upsertView({
558
+ view: sanitizedView,
559
+ base_hash,
560
+ fulfill_request_id: fulfill_request_id
561
+ ? idSlugSchema("fulfill_request_id").parse(fulfill_request_id)
562
+ : undefined,
563
+ actor: "agent",
564
+ force,
565
+ });
566
+ const ui_url = await ensureViewUiUrl(res.view.id, currentStorage.rootDir);
567
+ return okResult({
568
+ mode: "replace",
569
+ view_id: res.view.id,
570
+ view_hash: res.view_hash,
571
+ created: res.created,
572
+ node_count: res.view.nodes.length,
573
+ edge_count: res.view.edges.length,
574
+ ...(ui_url ? { ui_url } : {}),
575
+ });
576
+ }
577
+ catch (err) {
578
+ return errResult(err);
579
+ }
580
+ });
581
+ server.registerTool("post_thread", {
582
+ description: "Create an anchored thread (question, change_request, decision, drift_alert) or reply; resolve=true requires a 1-line resolution_summary (Decisions).",
583
+ inputSchema: {
584
+ thread_id: z.string().optional(),
585
+ target_type: ThreadTargetTypeSchema.optional(),
586
+ view_id: z.string().optional(),
587
+ target_id: z.string().optional(),
588
+ entity_ref: z.string().optional(),
589
+ kind: ThreadKindSchema.optional(),
590
+ body: z.string(),
591
+ resolve: z.boolean().optional(),
592
+ reopen: z.boolean().optional(),
593
+ resolution_summary: z.string().optional(),
594
+ },
595
+ annotations: {
596
+ readOnlyHint: false,
597
+ destructiveHint: false,
598
+ },
599
+ }, async (args) => {
600
+ try {
601
+ const currentStorage = await getActiveStorage(true);
602
+ const thread = await currentStorage.postThreadMessage({
603
+ thread_id: args.thread_id
604
+ ? idSlugSchema("thread_id").parse(args.thread_id)
605
+ : undefined,
606
+ target_type: args.target_type,
607
+ view_id: args.view_id ? idSlugSchema("view_id").parse(args.view_id) : undefined,
608
+ target_id: args.target_id
609
+ ? idSlugSchema("target_id").parse(args.target_id)
610
+ : undefined,
611
+ entity_ref: args.entity_ref
612
+ ? EntityRefSchema.parse(args.entity_ref)
613
+ : undefined,
614
+ kind: args.kind,
615
+ body: z.string().trim().min(1, "body is required").parse(args.body),
616
+ resolve: args.resolve,
617
+ reopen: args.reopen,
618
+ resolution_summary: args.resolution_summary,
619
+ author: "agent",
620
+ });
621
+ return okResult({ thread });
622
+ }
623
+ catch (err) {
624
+ return errResult(err);
625
+ }
626
+ });
627
+ server.registerTool("sync_code_refs", {
628
+ description: "Link source code_refs and status ('implemented' | 'drifted') onto nodes (including locked nodes) without clobbering unrelated pending human edits.",
629
+ inputSchema: {
630
+ view_id: z.string(),
631
+ updates: z.array(z.object({
632
+ node_id: z.string(),
633
+ status: z.enum(["implemented", "drifted"]),
634
+ code_refs: z.array(WireCodeRefSchema),
635
+ })),
636
+ },
637
+ annotations: {
638
+ readOnlyHint: false,
639
+ destructiveHint: false,
640
+ idempotentHint: true,
641
+ },
642
+ }, async ({ view_id, updates }) => {
643
+ try {
644
+ const currentStorage = await getActiveStorage(true);
645
+ if (updates.length === 0) {
646
+ throw new ValidationError("updates must contain at least one entry");
647
+ }
648
+ const parsedUpdates = updates.map((u) => CodeRefUpdateSchema.parse(u));
649
+ const res = await currentStorage.syncCodeRefs({
650
+ view_id,
651
+ updates: parsedUpdates,
652
+ });
653
+ return okResult({
654
+ view_id: res.view.id,
655
+ view_hash: res.view_hash,
656
+ updated_node_ids: res.updated_node_ids,
657
+ });
658
+ }
659
+ catch (err) {
660
+ return errResult(err);
661
+ }
662
+ });
663
+ server.registerPrompt("draft-architecture", {
664
+ title: "Draft Architecture View",
665
+ description: "Inspect the codebase and draft or refine a structured general architecture view in Redlinify.",
666
+ argsSchema: {
667
+ focus: z.string().optional(),
668
+ view_id: z.string().optional(),
669
+ },
670
+ }, ({ focus, view_id }) => ({
671
+ messages: [
672
+ {
673
+ role: "user",
674
+ content: {
675
+ type: "text",
676
+ text: [
677
+ "Follow the Redlinify MCP workflow to draft or update a general architecture view:",
678
+ "1. Call get_workspace() to inspect existing tabs, entity_ref slugs, pending edits, and open threads.",
679
+ focus
680
+ ? `2. Inspect source modules related to "${focus}" and identify core services, data stores, and entrypoints.`
681
+ : "2. Inspect the repository's modules, entrypoints, data stores, and external boundaries.",
682
+ `3. Call save_view() with mode="replace"${view_id ? ` on view_id="${view_id}"` : ""} (diagram_type="general", using node.shape "card" | "decision" | "terminal" | "store" where helpful, concise sections, and stable entity_ref slugs) and preserve any locked nodes/edges.`,
683
+ '4. For any ambiguous design decision, set status="needs_input" and anchor a question via post_thread() instead of guessing.',
684
+ ].join("\n"),
685
+ },
686
+ },
687
+ ],
688
+ }));
689
+ server.registerPrompt("draft-er-schema", {
690
+ title: "Draft ER Schema View",
691
+ description: "Model entities, typed attributes (PK/FK/UQ, nullable), and Crow's Foot cardinalities in Redlinify.",
692
+ argsSchema: {
693
+ domain: z.string().optional(),
694
+ view_id: z.string().optional(),
695
+ },
696
+ }, ({ domain, view_id }) => ({
697
+ messages: [
698
+ {
699
+ role: "user",
700
+ content: {
701
+ type: "text",
702
+ text: [
703
+ "Follow the Redlinify MCP workflow to model a Crow's Foot ER diagram:",
704
+ "1. Call get_workspace() to inspect existing views and entity_ref slugs.",
705
+ domain
706
+ ? `2. Extract entities, columns, constraints, and relationships for the "${domain}" domain.`
707
+ : "2. Extract entities, columns, constraints, and relationships from the project's schema/models.",
708
+ `3. Call save_view() with mode="replace"${view_id ? ` on view_id="${view_id}"` : ""} and diagram_type="er", populating node.fields (pk, fk, unique, nullable, type) and edge cardinalities ("1" | "0..1" | "1..*" | "0..*", relation_kind: "association" | "subtype").`,
709
+ '4. Flag open schema trade-offs with status="needs_input" and post_thread().',
710
+ ].join("\n"),
711
+ },
712
+ },
713
+ ],
714
+ }));
715
+ server.registerPrompt("review-feedback", {
716
+ title: "Review Human Feedback",
717
+ description: "Inspect pending human diagram edits, thread replies, and view requests, then apply and acknowledge them.",
718
+ }, () => ({
719
+ messages: [
720
+ {
721
+ role: "user",
722
+ content: {
723
+ type: "text",
724
+ text: [
725
+ "Review and incorporate pending human feedback from the Redlinify workbench:",
726
+ "1. Call get_workspace() to inspect pending view_diffs, pending_threads, and view_requests.",
727
+ "2. Call get_view(view_id) on any view with changes or threads to inspect exact details while respecting all locked (violet) nodes and edges.",
728
+ "3. Implement agreed changes in code/views, link files with sync_code_refs(), resolve discussions via post_thread(resolve=true, resolution_summary='...'), and advance checkpoints using save_view(mode='acknowledge').",
729
+ ].join("\n"),
730
+ },
731
+ },
732
+ ],
733
+ }));
734
+ server.registerResource("workspace", "redlinify://workspace", {
735
+ title: "Redlinify Workspace Status",
736
+ description: "Live .design workspace metadata, tabs, entity_ref slugs, pending diffs, view requests, and open threads.",
737
+ mimeType: "application/json",
738
+ }, async (uri) => {
739
+ const currentStorage = await getActiveStorage(false);
740
+ if (!hasInitializedWorkspace(currentStorage)) {
741
+ return {
742
+ contents: [
743
+ {
744
+ uri: uri.href,
745
+ mimeType: "application/json",
746
+ text: JSON.stringify({
747
+ initialized: false,
748
+ root_dir: currentStorage.rootDir,
749
+ tabs: [],
750
+ entity_refs: {},
751
+ view_requests: [],
752
+ pending_feedback: {
753
+ view_hashes: {},
754
+ view_diffs: [],
755
+ pending_threads: [],
756
+ view_requests: [],
757
+ },
758
+ }, null, 2),
759
+ },
760
+ ],
761
+ };
762
+ }
763
+ const [status, pending_feedback] = await Promise.all([
764
+ currentStorage.getWorkspaceStatus(),
765
+ currentStorage.getPendingFeedback(),
766
+ ]);
767
+ return {
768
+ contents: [
769
+ {
770
+ uri: uri.href,
771
+ mimeType: "application/json",
772
+ text: JSON.stringify({
773
+ root_dir: currentStorage.rootDir,
774
+ ...status,
775
+ pending_feedback,
776
+ }, null, 2),
777
+ },
778
+ ],
779
+ };
780
+ });
781
+ server.registerResource("decisions", "redlinify://decisions", {
782
+ title: "Redlinify Decision Log",
783
+ description: "Resolved architectural and schema discussion threads persisted as project Decisions (ADRs).",
784
+ mimeType: "application/json",
785
+ }, async (uri) => {
786
+ const currentStorage = await getActiveStorage(false);
787
+ if (!hasInitializedWorkspace(currentStorage)) {
788
+ return {
789
+ contents: [
790
+ {
791
+ uri: uri.href,
792
+ mimeType: "application/json",
793
+ text: JSON.stringify({
794
+ initialized: false,
795
+ root_dir: currentStorage.rootDir,
796
+ decisions: [],
797
+ }, null, 2),
798
+ },
799
+ ],
800
+ };
801
+ }
802
+ const decisions = await currentStorage.listThreads({
803
+ status: "resolved",
804
+ });
805
+ return {
806
+ contents: [
807
+ {
808
+ uri: uri.href,
809
+ mimeType: "application/json",
810
+ text: JSON.stringify({
811
+ initialized: true,
812
+ root_dir: currentStorage.rootDir,
813
+ decisions,
814
+ }, null, 2),
815
+ },
816
+ ],
817
+ };
818
+ });
819
+ server.registerResource("workflow", "redlinify://workflow", {
820
+ title: "Redlinify Agent Workflow Guide",
821
+ description: "Complete Redlinify skill & MCP collaboration workflow instructions (SKILL.md).",
822
+ mimeType: "text/markdown",
823
+ }, async (uri) => ({
824
+ contents: [
825
+ {
826
+ uri: uri.href,
827
+ mimeType: "text/markdown",
828
+ text: readWorkflowGuideMarkdown(),
829
+ },
830
+ ],
831
+ }));
832
+ server.registerResource("view", new ResourceTemplate("redlinify://views/{view_id}", {
833
+ list: async () => {
834
+ const currentStorage = await getActiveStorage(false);
835
+ if (!hasInitializedWorkspace(currentStorage)) {
836
+ return { resources: [] };
837
+ }
838
+ const status = await currentStorage.getWorkspaceStatus();
839
+ return {
840
+ resources: status.tabs.map((tab) => ({
841
+ uri: `redlinify://views/${tab.view_id}`,
842
+ name: tab.title,
843
+ description: tab.description ??
844
+ (tab.diagram_type === "er"
845
+ ? "Crow's Foot ER diagram view"
846
+ : "Architecture diagram view"),
847
+ mimeType: "application/json",
848
+ })),
849
+ };
850
+ },
851
+ }), {
852
+ title: "Redlinify Semantic View",
853
+ description: "Git-tracked semantic diagram JSON, canonical hash, and open threads for a specific view.",
854
+ mimeType: "application/json",
855
+ }, async (uri, variables) => {
856
+ const currentStorage = await getActiveStorage(false);
857
+ if (!hasInitializedWorkspace(currentStorage)) {
858
+ throw new NotFoundError(`Redlinify workspace is not initialized in ${currentStorage.rootDir}`);
859
+ }
860
+ const rawViewId = Array.isArray(variables.view_id)
861
+ ? variables.view_id[0]
862
+ : variables.view_id;
863
+ const viewId = idSlugSchema("view_id").parse(rawViewId ?? "");
864
+ const [{ view, view_hash }, open_threads] = await Promise.all([
865
+ currentStorage.readView(viewId),
866
+ currentStorage.listThreads({ view_id: viewId, status: "open" }),
867
+ ]);
868
+ return {
869
+ contents: [
870
+ {
871
+ uri: uri.href,
872
+ mimeType: "application/json",
873
+ text: JSON.stringify({ view, view_hash, open_threads }, null, 2),
874
+ },
875
+ ],
876
+ };
877
+ });
878
+ return server;
879
+ }
880
+ //# sourceMappingURL=mcp.js.map