archgraph-argo-beta 0.27.0-beta.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 (85) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +107 -0
  3. package/argo/.env.example +170 -0
  4. package/argo/defaults/EA-model-template.qea +0 -0
  5. package/argo/defaults/design/KG/SystemArchitecture.json +128 -0
  6. package/argo/mcp-bridges/graph-mcp-stdio.js +98 -0
  7. package/argo/package.json +8 -0
  8. package/argo/plugins/argo-cost-collector.js +35 -0
  9. package/argo/plugins/argo-wakeup.js +29 -0
  10. package/argo/rules/archgraph.instructions.md +189 -0
  11. package/argo/schema/ImplementationToCodingHandoff.schema.json +252 -0
  12. package/argo/schema/ImplementationToIntentTraceProposal.schema.json +180 -0
  13. package/argo/schema/IntentToImplementationHandoff.schema.json +75 -0
  14. package/argo/schema/SystemArchitecture.schema.json +378 -0
  15. package/argo/schema/archimate3.2.md +7153 -0
  16. package/argo/schema/argob-rules.json +12229 -0
  17. package/argo/schema/argob.config.json +20 -0
  18. package/argo/scripts/ARCHITECTURE.md +58 -0
  19. package/argo/scripts/agentSearchDiagnose.js +407 -0
  20. package/argo/scripts/archimate32-rules.js +12301 -0
  21. package/argo/scripts/argo-mcp-server.js +952 -0
  22. package/argo/scripts/argo-paths.js +168 -0
  23. package/argo/scripts/argob-schema.js +574 -0
  24. package/argo/scripts/ea-qea-sync-lib.js +1014 -0
  25. package/argo/scripts/ea-qea-sync.js +110 -0
  26. package/argo/scripts/ensureArgoHarnessEnvironment.js +451 -0
  27. package/argo/scripts/external-graph-query.js +162 -0
  28. package/argo/scripts/generateArchitectureDiffPlantuml.js +466 -0
  29. package/argo/scripts/graph-rag/ARCHITECTURE.md +192 -0
  30. package/argo/scripts/graph-rag/agentCostLog.js +179 -0
  31. package/argo/scripts/graph-rag/canonicalProjectionAuthority.js +45 -0
  32. package/argo/scripts/graph-rag/defaultSemanticRetrieval.js +1244 -0
  33. package/argo/scripts/graph-rag/embeddingProviderProfile.js +89 -0
  34. package/argo/scripts/graph-rag/embeddingQualificationGate.js +59 -0
  35. package/argo/scripts/graph-rag/externalProductionConfig.js +74 -0
  36. package/argo/scripts/graph-rag/hybridRetrieval.js +114 -0
  37. package/argo/scripts/graph-rag/liveEmbeddingIndexGate.js +128 -0
  38. package/argo/scripts/graph-rag/liveEmbeddingNeo4jBoundary.js +137 -0
  39. package/argo/scripts/graph-rag/liveEmbeddingProviderClient.js +49 -0
  40. package/argo/scripts/graph-rag/liveEmbeddingProviderConfig.js +571 -0
  41. package/argo/scripts/graph-rag/mcpCrashDiagnostics.js +137 -0
  42. package/argo/scripts/graph-rag/mutationEmbeddingVectorLifecycle.js +1266 -0
  43. package/argo/scripts/graph-rag/neo4jNativeRetrieval.js +37 -0
  44. package/argo/scripts/graph-rag/productionGraphRagRuntime.js +1633 -0
  45. package/argo/scripts/graph-rag/rerankRetrieval.js +201 -0
  46. package/argo/scripts/graph-rag/semantic-persistence/ARCHITECTURE.md +51 -0
  47. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticBackfill.js +342 -0
  48. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticCheckpointStore.js +99 -0
  49. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticNeo4jAdapter.js +186 -0
  50. package/argo/scripts/graph-rag/semantic-persistence/productionSemanticProjectionStore.js +171 -0
  51. package/argo/scripts/graph-rag/semanticAlignmentLock.js +76 -0
  52. package/argo/scripts/graph-rag/semanticAlignmentRunner.js +131 -0
  53. package/argo/scripts/graph-rag/semanticInitConfiguration.js +24 -0
  54. package/argo/scripts/graph-rag/semanticOperatorError.js +38 -0
  55. package/argo/scripts/graph-rag/semanticOperatorJourney.js +459 -0
  56. package/argo/scripts/graph-rag/semanticReadinessAttestationStore.js +398 -0
  57. package/argo/scripts/graph-rag/semanticRecordText.js +75 -0
  58. package/argo/scripts/graph-rag/systemMetadataCommandAdapter.js +269 -0
  59. package/argo/scripts/graph-semantics.js +266 -0
  60. package/argo/scripts/lossless-write-gate.js +500 -0
  61. package/argo/scripts/neo4j-system-architecture-store.js +1066 -0
  62. package/argo/scripts/repair-subdiagram-views.js +288 -0
  63. package/argo/scripts/repositoryArgoEnvironment.js +101 -0
  64. package/argo/scripts/runArchitectureTests.js +591 -0
  65. package/argo/scripts/semanticOperatorJourneyCli.js +91 -0
  66. package/argo/scripts/syncSystemArchitectureToNeo4j.js +67 -0
  67. package/argo/scripts/systemarchitecture-mcp-server.js +4508 -0
  68. package/argo/scripts/test-executors/_template.js +58 -0
  69. package/argo/scripts/test-executors/default.js +199 -0
  70. package/argo/scripts/validateStageHandoff.js +459 -0
  71. package/argo/scripts/validateSystemArchitecture.js +261 -0
  72. package/argo/scripts/validateTraceProposal.js +181 -0
  73. package/argo/scripts/validator-mcp-server.js +347 -0
  74. package/argo/skills/agent-search-diagnosis/SKILL.md +60 -0
  75. package/argo/skills/argo-init/SKILL.md +86 -0
  76. package/argo/skills/ea-human-reconcile/SKILL.md +40 -0
  77. package/bin/argo-deploy.js +12 -0
  78. package/cordis.patch.yml +6 -0
  79. package/dsh-argo-wakeup/index.js +17 -0
  80. package/dsh-argo-wakeup/package.json +1 -0
  81. package/dsh-argo-workspace/index.js +142 -0
  82. package/dsh-argo-workspace/package.json +1 -0
  83. package/install-argo.ps1 +1162 -0
  84. package/package.json +56 -0
  85. package/vendor/neo4j-driver-6.2.0.tgz +0 -0
@@ -0,0 +1,952 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const readline = require('node:readline');
4
+ const { AsyncLocalStorage } = require('node:async_hooks');
5
+ const { spawnSync } = require('node:child_process');
6
+
7
+ const validatorMcp = require('./validator-mcp-server.js');
8
+ const systemArchitectureMcp = require('./systemarchitecture-mcp-server.js');
9
+ const {
10
+ semanticOperatorErrorResult,
11
+ } = require('./graph-rag/semanticOperatorError.js');
12
+ const {
13
+ loadRepositoryArgoEnvironment,
14
+ } = require('./repositoryArgoEnvironment.js');
15
+ const {
16
+ loadSchemaBundleAndOntology,
17
+ } = require('./argob-schema.js');
18
+ const {
19
+ externalQueryRequested,
20
+ queryExternalRead,
21
+ } = require('./external-graph-query.js');
22
+ const {
23
+ getWorkspaceRoot,
24
+ hasStaticWorkspace,
25
+ resolveArgoPath,
26
+ resolveCallWorkspaceRoot,
27
+ setMcpWorkspaceRoots,
28
+ } = require('./argo-paths.js');
29
+ const canonicalSemanticInitStorage = new AsyncLocalStorage();
30
+
31
+ const HANDOFF_FILES_TO_RESET = [
32
+ ['.argo', 'temp', 'IntentToImplementationHandoff.json'],
33
+ ['.argo', 'temp', 'ImplementationToCodingHandoff.json'],
34
+ ];
35
+ const WORKSPACE_GRAPH_PATH_SEGMENTS = ['design', 'KG', 'SystemArchitecture.json'];
36
+ const BUNDLED_GRAPH_DEFAULT_SEGMENTS = ['defaults', 'design', 'KG', 'SystemArchitecture.json'];
37
+ const BUNDLED_EA_TEMPLATE_SEGMENTS = ['defaults', 'EA-model-template.qea'];
38
+ const EA_TEMPLATE_PATH_CANDIDATES = [
39
+ ['.opencode', 'customtools', 'EA-model-template.qea'],
40
+ ['.opencode', 'EA-model-template.qea'],
41
+ ['eatool', 'EA-model-template.qea'],
42
+ ['EA-model-template.qea'],
43
+ ];
44
+ const EA_MODEL_EXTENSIONS = new Set(['.qea', '.feap', '.eap']);
45
+ const WINDOWS_RESERVED_NAMES = new Set([
46
+ 'CON', 'PRN', 'AUX', 'NUL',
47
+ 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9',
48
+ 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9',
49
+ ]);
50
+
51
+ const VALIDATOR_TOOL_NAMES = new Set([
52
+ 'validateSystemArchitecture',
53
+ 'runArchitectureTests',
54
+ ]);
55
+ const SYSTEM_ARCHITECTURE_TOOL_NAMES = new Set([
56
+ 'getSystemArchitecture',
57
+ 'getIntentElementContext',
58
+ 'getArchitectureViewContext',
59
+ 'previewSystemArchitectureMutation',
60
+ 'applySystemArchitectureMutation',
61
+ 'addArchitectureElement',
62
+ 'updateArchitectureElement',
63
+ 'removeArchitectureElement',
64
+ 'addArchitectureRelationship',
65
+ 'updateArchitectureRelationship',
66
+ 'removeArchitectureRelationship',
67
+ 'addArchitectureView',
68
+ 'updateArchitectureView',
69
+ 'removeArchitectureView',
70
+ 'queryNeo4jGraph',
71
+ 'memory_search',
72
+ ]);
73
+
74
+ const TOOLS = [
75
+ {
76
+ name: 'initializeWorkspace',
77
+ description: 'Bootstrap an Argo workspace by copying the EA template target and resetting stage handoff artifacts.',
78
+ inputSchema: {
79
+ type: 'object',
80
+ properties: {},
81
+ additionalProperties: false,
82
+ },
83
+ },
84
+ {
85
+ name: 'runArchitectureTests',
86
+ description: 'Execute explicit architecture testcases from the intent graph and refresh design/KG/test-failure-records.json. This MCP call can exceed client timeouts; if it times out, run the same test runner directly with: node .argo/scripts/runArchitectureTests.js',
87
+ inputSchema: {
88
+ type: 'object',
89
+ properties: {
90
+ architecturePath: {
91
+ type: 'string',
92
+ description: 'Optional architecture graph path relative to workspace root. Default: design/KG/SystemArchitecture.json',
93
+ },
94
+ },
95
+ additionalProperties: false,
96
+ },
97
+ },
98
+ {
99
+ name: 'getSystemArchitecture',
100
+ description: 'Start here, but prefer an explicit semantic query instead of an omitted-query full graph read. Provide query.purpose and query.intent to get a compact business/architecture result, then use returned element ids with getIntentElementContext for focused dependency context. Omit query only when an exact full canonical snapshot is explicitly required.',
101
+ inputSchema: {
102
+ type: 'object',
103
+ required: ['query'],
104
+ properties: {
105
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
106
+ query: {
107
+ type: 'object',
108
+ description: 'Required semantic query. Provide query.purpose + query.intent; combine the returned element ids with getIntentElementContext when deeper local context is needed.',
109
+ properties: {
110
+ purpose: {
111
+ type: 'string',
112
+ enum: ['general', 'audit'],
113
+ description: 'Declared reading purpose: general for generic semantic/memory retrieval, or audit for strict proof-closure reads (subject required).',
114
+ },
115
+ intent: { type: 'string', description: 'Natural-language intent for semantic retrieval, for example "summarize business features for high-risk audit".' },
116
+ subject: { type: 'string', description: 'Required for audit; optional anchor/focus id for other semantic purposes.' },
117
+ scope: {
118
+ type: 'object',
119
+ description: 'Optional subgraph scope to bound semantic retrieval and limit the returned content to a local region. Provide view_id to search within one view membership, or element_id (+ depth) to search within an element subtree.',
120
+ properties: {
121
+ view_id: { type: 'string', description: 'Restrict retrieval to the members of this view.' },
122
+ element_id: { type: 'string', description: 'Restrict retrieval to this element and its mounted sub-view subtree.' },
123
+ depth: { type: 'number', description: 'Default: 2. Subtree depth for element scope.' },
124
+ },
125
+ additionalProperties: false,
126
+ },
127
+ },
128
+ additionalProperties: true,
129
+ },
130
+ },
131
+ additionalProperties: false,
132
+ },
133
+ outputSchema: systemArchitectureMcp.GET_SYSTEM_ARCHITECTURE_OUTPUT_SCHEMA,
134
+ },
135
+ {
136
+ name: 'getIntentElementContext',
137
+ description: 'read-only query that returns an intent subgraph context for one element. Uses ArchiMate semantic dependency traversal with dependencyDepth and dependentDepth, preserving native subgraph elements, relationships, and views.',
138
+ inputSchema: intentElementContextInputSchema(),
139
+ },
140
+ {
141
+ name: 'previewSystemArchitectureMutation',
142
+ description: 'Use before apply for complex or risky changes. Performs a dry-run of one or more mutations, runs schema, graph, view, and modeling-language validation, and does not write the graph.',
143
+ inputSchema: mutationInputSchema(),
144
+ },
145
+ {
146
+ name: 'applySystemArchitectureMutation',
147
+ description: 'Use for multi-step or dependent graph changes that should be validated and written atomically. Prefer focused tools for a single simple add, update, or remove operation.',
148
+ inputSchema: mutationInputSchema(),
149
+ },
150
+ {
151
+ name: 'addArchitectureElement',
152
+ description: 'Use for one element. Creates a new element or adds an existing element to view_ids. view_ids is required so elements never exist outside views.',
153
+ inputSchema: {
154
+ type: 'object',
155
+ required: ['element', 'view_ids'],
156
+ properties: {
157
+ element: { type: 'object' },
158
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
159
+ onConflict: { type: 'string', enum: ['reuse', 'allowDuplicate'], description: 'Dedup policy (default reuse). reuse: find-or-create — attach an existing exact (type, name) match; a same-type semantic near-duplicate also blocks creation. allowDuplicate: create anyway (even if a duplicate exists), requires a justification.' },
160
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate.' },
161
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
162
+ },
163
+ additionalProperties: false,
164
+ },
165
+ },
166
+ {
167
+ name: 'updateArchitectureElement',
168
+ description: 'Use for one global element metadata patch. Does not change view membership. Element id and type are immutable; remove and re-add to change them. patch.attributes is a targeted merge: single-valued attributes upsert by name; multi-valued ledgers (e.g. commit) upsert by name+value — a new value appends a new entry, re-registering the same value updates its description; {name, op:"remove"} (optionally with value) deletes the matching entries; attributes NOT mentioned are preserved — updating one attribute never wipes out the others.',
169
+ inputSchema: {
170
+ type: 'object',
171
+ required: ['id', 'patch'],
172
+ properties: {
173
+ id: { type: 'string' },
174
+ patch: { type: 'object' },
175
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
176
+ },
177
+ additionalProperties: false,
178
+ },
179
+ },
180
+ {
181
+ name: 'removeArchitectureElement',
182
+ description: 'Use for one element removal. With view_ids, removes only from those views and cascades related relationships in the same views; without view_ids, removes from all views and the graph.',
183
+ inputSchema: {
184
+ type: 'object',
185
+ required: ['id'],
186
+ properties: {
187
+ id: { type: 'string' },
188
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
189
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
190
+ },
191
+ additionalProperties: false,
192
+ },
193
+ },
194
+ {
195
+ name: 'addArchitectureRelationship',
196
+ description: 'Use for one relationship. Creates a new relationship or adds an existing relationship to view_ids. relationship.type is the ArchiMate 3.2 relationship type and is validated against endpoint element types.',
197
+ inputSchema: {
198
+ type: 'object',
199
+ required: ['relationship', 'view_ids'],
200
+ properties: {
201
+ relationship: { type: 'object' },
202
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
203
+ onConflict: { type: 'string', enum: ['reuse', 'allowDuplicate'], description: 'Dedup policy (default reuse). reuse: find-or-create — attach an existing exact (source, type, target, name) match. allowDuplicate: create anyway, requires a justification.' },
204
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate.' },
205
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
206
+ },
207
+ additionalProperties: false,
208
+ },
209
+ },
210
+ {
211
+ name: 'updateArchitectureRelationship',
212
+ description: 'Use for one global relationship metadata patch, such as name, statement, source_name, or target_name. Relationship id and type are immutable; remove and re-add to change them.',
213
+ inputSchema: {
214
+ type: 'object',
215
+ required: ['id', 'patch'],
216
+ properties: {
217
+ id: { type: 'string' },
218
+ patch: { type: 'object' },
219
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
220
+ },
221
+ additionalProperties: false,
222
+ },
223
+ },
224
+ {
225
+ name: 'removeArchitectureRelationship',
226
+ description: 'Use for one relationship removal. With view_ids, removes only from those views; without view_ids, removes from all views and deletes it from the graph.',
227
+ inputSchema: {
228
+ type: 'object',
229
+ required: ['id'],
230
+ properties: {
231
+ id: { type: 'string' },
232
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
233
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
234
+ },
235
+ additionalProperties: false,
236
+ },
237
+ },
238
+ {
239
+ name: 'addArchitectureView',
240
+ description: 'Use for one view. The graph must have exactly one top-level view named SystemArchitecture; all sub-views must attach to an element with parent_element_id.',
241
+ inputSchema: {
242
+ type: 'object',
243
+ required: ['view'],
244
+ properties: {
245
+ view: { type: 'object' },
246
+ onConflict: { type: 'string', enum: ['reuse', 'allowDuplicate'], description: 'Dedup policy (default reuse). reuse: attach an existing exact (parent, view name) match. allowDuplicate: create anyway, requires a justification.' },
247
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate.' },
248
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
249
+ },
250
+ additionalProperties: false,
251
+ },
252
+ },
253
+ {
254
+ name: 'updateArchitectureView',
255
+ description: 'Use for one view metadata or membership patch. Keep the one top-level view named SystemArchitecture and attach sub-views to parent elements.',
256
+ inputSchema: {
257
+ type: 'object',
258
+ required: ['view_id', 'patch'],
259
+ properties: {
260
+ view_id: { type: 'string' },
261
+ patch: { type: 'object' },
262
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
263
+ },
264
+ additionalProperties: false,
265
+ },
266
+ },
267
+ {
268
+ name: 'removeArchitectureView',
269
+ description: 'Use for one view removal. After removal, every remaining element and relationship must still belong to at least one view.',
270
+ inputSchema: {
271
+ type: 'object',
272
+ required: ['view_id'],
273
+ properties: {
274
+ view_id: { type: 'string' },
275
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
276
+ },
277
+ additionalProperties: false,
278
+ },
279
+ },
280
+ ];
281
+
282
+ // Every tool accepts an optional per-call `workspaceRoot` (absolute path,
283
+ // honored unconditionally when provided). The DeepSeek Harness bridge injects
284
+ // the current session's workspace directory here automatically.
285
+ // (tools/list dedupes with systemArchitectureMcp/validatorMcp tools, which
286
+ // carry the same field; this covers the local-only rows like initializeWorkspace.)
287
+ const WORKSPACE_ROOT_PARAM = Object.freeze({
288
+ type: 'string',
289
+ description:
290
+ 'Optional absolute workspace root for this call. When provided it is used as-is; otherwise the server launch directory is used.',
291
+ });
292
+ for (const tool of TOOLS) {
293
+ const inputSchema = tool && tool.inputSchema;
294
+ if (inputSchema && inputSchema.type === 'object' && inputSchema.properties) {
295
+ if (!Object.prototype.hasOwnProperty.call(inputSchema.properties, 'workspaceRoot')) {
296
+ inputSchema.properties.workspaceRoot = WORKSPACE_ROOT_PARAM;
297
+ }
298
+ }
299
+ }
300
+
301
+ // Lossless write gate acknowledgement params for the update/remove helpers
302
+ // (see lossless-write-gate.js). add* is purely additive and left alone.
303
+ const LOSS_ACK_INPUT_PROPS = Object.freeze({
304
+ acknowledgeLoss: {
305
+ type: 'boolean',
306
+ description: 'Set true to confirm an intentional content reduction: a text rewrite that drops prior segments, or a destructive removal. Without it the lossless write gate blocks the write and returns the exact removed content.',
307
+ },
308
+ lossJustification: {
309
+ type: 'string',
310
+ description: 'Required for MAJOR text loss (large removedChars or most of the value): the reason the prior content is being intentionally replaced.',
311
+ },
312
+ });
313
+ for (const tool of TOOLS) {
314
+ if (tool && tool.name && /^(update|remove)Architecture/.test(tool.name)
315
+ && tool.inputSchema && tool.inputSchema.properties) {
316
+ for (const [key, value] of Object.entries(LOSS_ACK_INPUT_PROPS)) {
317
+ if (!Object.prototype.hasOwnProperty.call(tool.inputSchema.properties, key)) {
318
+ tool.inputSchema.properties[key] = value;
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ function intentElementContextInputSchema() {
325
+ return {
326
+ type: 'object',
327
+ properties: {
328
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
329
+ elementId: { type: 'string' },
330
+ elementName: { type: 'string' },
331
+ profile: {
332
+ type: 'string',
333
+ enum: ['implementation-design', 'coding-repair', 'audit', 'generic-agent'],
334
+ description: 'Default: generic-agent. Affects workContext enrichment only; subgraph shape stays native.',
335
+ },
336
+ dependencyDepth: { type: 'number', description: 'Default: 2. Semantic dependencies needed by the focus element.' },
337
+ dependentDepth: { type: 'number', description: 'Default: 1. Semantic dependents that rely on the focus element.' },
338
+ associationDepth: { type: 'number', description: 'Default: 1. Association neighbors are expanded at least one layer.' },
339
+ associationNeighborDependencyDepth: { type: 'number', description: 'Default: 0. Optional dependency expansion from association neighbors.' },
340
+ includeAttributes: { type: 'boolean', description: 'Default: false. Include `attributes` (commit/session/release ledgers) verbatim; omitted by default from this structural read (the focus element always keeps its own).' },
341
+ includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim; omitted by default from this structural read.' },
342
+ },
343
+ additionalProperties: false,
344
+ };
345
+ }
346
+
347
+ function mutationInputSchema() {
348
+ return {
349
+ type: 'object',
350
+ required: ['mutations'],
351
+ properties: {
352
+ architecturePath: { type: 'string', description: 'Default: design/KG/SystemArchitecture.json' },
353
+ acknowledgeLoss: { type: 'boolean', description: 'Batch-level loss acknowledgement: set true to confirm every intentional content reduction in this mutation set (a text rewrite that drops prior segments, or destructive removals). Counts for all mutations — one confirmation for a whole batch.' },
354
+ lossJustification: { type: 'string', description: 'Batch-level justification for MAJOR text loss in this mutation set.' },
355
+ mutations: {
356
+ type: 'array',
357
+ minItems: 1,
358
+ items: {
359
+ type: 'object',
360
+ required: ['type'],
361
+ properties: {
362
+ type: {
363
+ type: 'string',
364
+ enum: [
365
+ 'addElement',
366
+ 'updateElement',
367
+ 'removeElement',
368
+ 'addRelationship',
369
+ 'updateRelationship',
370
+ 'removeRelationship',
371
+ 'addView',
372
+ 'updateView',
373
+ 'removeView',
374
+ ],
375
+ },
376
+ element: { type: 'object' },
377
+ relationship: { type: 'object' },
378
+ view: { type: 'object' },
379
+ id: { type: 'string' },
380
+ patch: { type: 'object' },
381
+ view_id: { type: 'string' },
382
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
383
+ element_ids: { type: 'array', items: { type: 'string' } },
384
+ relationship_ids: { type: 'array', items: { type: 'string' } },
385
+ acknowledgeLoss: { type: 'boolean', description: 'Set true to confirm an intentional content reduction: a text rewrite that drops prior segments, or a destructive removal. Without it the lossless write gate blocks the write and returns the exact removed content.' },
386
+ lossJustification: { type: 'string', description: 'Required for MAJOR text loss (large removedChars or most of the value): the reason the prior content is being intentionally replaced.' },
387
+ },
388
+ additionalProperties: false,
389
+ },
390
+ },
391
+ },
392
+ additionalProperties: false,
393
+ };
394
+ }
395
+
396
+ function resolveWorkspaceRoot() {
397
+ return getWorkspaceRoot();
398
+ }
399
+
400
+ function resolveWorkspaceRoot(args) {
401
+ // Per-call workspaceRoot override, honored unconditionally when provided;
402
+ // defaults to the launch-directory root.
403
+ return resolveCallWorkspaceRoot(args);
404
+ }
405
+
406
+ async function callTool(name, args = {}, progressToken = null, dependencies = undefined) {
407
+ loadRepositoryArgoEnvironment(resolveWorkspaceRoot(args));
408
+ try {
409
+ const crash = require('./graph-rag/mcpCrashDiagnostics.js');
410
+ crash.installCrashDiagnostics(resolveWorkspaceRoot(args));
411
+ crash.markPhase('tool:' + name);
412
+ } catch {
413
+ // diagnostics are best-effort; never block a tool call
414
+ }
415
+ // Cross-project read: a read tool with `projectId` is routed to the federation
416
+ // center (never silently served from the local graph).
417
+ if (externalQueryRequested(name, args)) {
418
+ const result = await queryExternalRead({
419
+ workspaceRoot: resolveWorkspaceRoot(args),
420
+ tool: name,
421
+ args,
422
+ });
423
+ return toolResult(result);
424
+ }
425
+ if (name === 'initializeWorkspace') {
426
+ const workspace = await initializeWorkspace(resolveWorkspaceRoot(args));
427
+ // Deterministic argo-init harness report (Neo4j structural sync, semantic
428
+ // lifecycle, canonical validation, subdiagram_views consistency), built
429
+ // in-process so the argo-init skill needs no workspace-external script.
430
+ // Lazy require avoids a circular dependency (ensureArgoHarnessEnvironment
431
+ // requires this module at its top).
432
+ const { buildHarnessReport } = require('./ensureArgoHarnessEnvironment.js');
433
+ const report = await buildHarnessReport({
434
+ checkOnly: false,
435
+ workspaceRoot: workspace.workspaceRoot,
436
+ includeBootstrap: false,
437
+ });
438
+ return toolResult({
439
+ status: report.status,
440
+ workspaceRoot: workspace.workspaceRoot,
441
+ // The resolved modeling language for this workspace (default ArgoBument vs
442
+ // the repository's own .argo/schema bundle) so init names the active schema.
443
+ schema: workspace.schema,
444
+ schemaBundle: report.schemaBundle,
445
+ targetEaName: workspace.targetEaName,
446
+ createdFiles: workspace.createdFiles,
447
+ updatedFiles: workspace.updatedFiles,
448
+ removedFiles: workspace.removedFiles,
449
+ skippedSteps: workspace.skippedSteps,
450
+ workspaceBootstrap: {
451
+ status: 'ok',
452
+ workspaceRoot: workspace.workspaceRoot,
453
+ targetEaName: workspace.targetEaName,
454
+ createdFiles: workspace.createdFiles,
455
+ updatedFiles: workspace.updatedFiles,
456
+ removedFiles: workspace.removedFiles,
457
+ skippedSteps: workspace.skippedSteps,
458
+ },
459
+ mcp: report.mcp,
460
+ systemArchitecture: report.systemArchitecture,
461
+ subdiagramViews: report.subdiagramViews,
462
+ neo4j: report.neo4j,
463
+ qeaFullProjection: workspace.qeaFullProjection,
464
+ semanticLifecycle: report.semanticLifecycle,
465
+ semanticState: report.semanticLifecycle && report.semanticLifecycle.state,
466
+ alignment: report.semanticLifecycle && report.semanticLifecycle.alignment,
467
+ reportPath: report.reportPath,
468
+ });
469
+ }
470
+ if (VALIDATOR_TOOL_NAMES.has(name)) {
471
+ return validatorMcp.callTool(name, args, progressToken);
472
+ }
473
+ if (SYSTEM_ARCHITECTURE_TOOL_NAMES.has(name)) {
474
+ return systemArchitectureMcp.callTool(name, args, dependencies);
475
+ }
476
+ throw new Error(`Unknown tool: ${name}`);
477
+ }
478
+
479
+ async function withCanonicalSemanticInitTestComposition(composition, callback) {
480
+ if (!composition || typeof callback !== 'function') {
481
+ throw new TypeError('Canonical semantic init composition and callback are required');
482
+ }
483
+ return canonicalSemanticInitStorage.run(Object.freeze({ ...composition }), callback);
484
+ }
485
+
486
+ function resolveQeaProjectionTarget(workspaceRoot) {
487
+ try {
488
+ if (!workspaceRoot || !fs.existsSync(workspaceRoot)) { return null; }
489
+ const pick = (p) => (p && fs.existsSync(p) ? path.resolve(p) : null);
490
+ const qeaPath = pick(process.env.ARGO_EA_QEA);
491
+ if (qeaPath) { return { qeaPath, workspaceRoot }; }
492
+ let qeas = [];
493
+ try { qeas = fs.readdirSync(workspaceRoot).filter((n) => n.toLowerCase().endsWith('.qea')); } catch { /* ignore */ }
494
+ if (qeas.length === 1) { return { qeaPath: path.resolve(workspaceRoot, qeas[0]), workspaceRoot }; }
495
+ console.log('[ea-qea] init projection target: none' + (qeas.length > 1 ? ' (' + qeas.length + ' *.qea found; expected exactly one or ARGO_EA_QEA)' : '') + ' in ' + workspaceRoot);
496
+ return null;
497
+ } catch (error) {
498
+ console.log('[ea-qea] init projection target resolution failed: ' + String(error && error.message ? error.message : error));
499
+ return null;
500
+ }
501
+ }
502
+
503
+ // argo init .qea FULL projection (mirrors Neo4j initial full sync): wipes the whole target
504
+ // .qea then rebuilds it purely from the canonical graph. Non-fatal by contract.
505
+ function runQeaFullProjection(workspaceRoot, graphTargetPath) {
506
+ const target = resolveQeaProjectionTarget(workspaceRoot);
507
+ const script = path.join(__dirname, 'ea-qea-sync.js');
508
+ if (!target || !fs.existsSync(script)) {
509
+ return { status: 'noop', reason: !target ? 'no .qea target (env ARGO_EA_QEA or exactly one root *.qea)' : 'argo/scripts/ea-qea-sync.js missing' };
510
+ }
511
+ const snapshotDir = path.join(workspaceRoot, '.argo', 'temp', 'qea-backups');
512
+ const args = [script, '--mode', 'full', '--graph', graphTargetPath, '--qea', target.qeaPath, '--snapshot-dir', snapshotDir];
513
+ const started = Date.now();
514
+ try {
515
+ const res = spawnSync(process.execPath, args, { cwd: workspaceRoot, encoding: 'utf8', windowsHide: true, timeout: 120000 });
516
+ const ok = res.status === 0;
517
+ return {
518
+ status: ok ? 'ok' : 'failed',
519
+ qea: target.qeaPath,
520
+ ms: Date.now() - started,
521
+ ...(ok ? {} : { error: String((res.stderr || '').slice(0, 600) || ('exit ' + res.status)) }),
522
+ };
523
+ } catch (error) {
524
+ return { status: 'failed', qea: target.qeaPath, ms: Date.now() - started, error: String(error && error.message ? error.message : error) };
525
+ }
526
+ }
527
+
528
+ async function initializeWorkspace(workspaceRoot) {
529
+ const workspaceName = path.basename(workspaceRoot);
530
+ const createdFiles = [];
531
+ const updatedFiles = [];
532
+ const removedFiles = [];
533
+ const skippedSteps = [];
534
+
535
+ const graphTargetPath = path.join(workspaceRoot, ...WORKSPACE_GRAPH_PATH_SEGMENTS);
536
+ const graphRelativePath = normalizeRelativePath(path.relative(workspaceRoot, graphTargetPath));
537
+ if (!fs.existsSync(graphTargetPath)) {
538
+ // Only the built-in ArgoBument default schema auto-provides a graph (the
539
+ // packaged default). For any custom / replaced schema the graph is the user's
540
+ // own: never copy the packaged (mismatched) graph — fail closed if missing.
541
+ let ontology = null;
542
+ try { ontology = loadSchemaBundleAndOntology(workspaceRoot).ontology; } catch { ontology = null; }
543
+ const usesPackagedDefaultGraph = !!ontology && ontology.kind === 'default' && ontology.dialect === 'archimate-class-matrix';
544
+ if (!usesPackagedDefaultGraph) {
545
+ const label = ontology ? `${ontology.kind} / ${ontology.language}` : 'unknown';
546
+ const error = new Error(
547
+ `No default graph for the custom schema (${label}): the workspace has no ${graphRelativePath}. ` +
548
+ 'A custom schema must author its own graph; the packaged default graph is not copied because it would not match the schema. ' +
549
+ `Add ${graphRelativePath} to the workspace.`,
550
+ );
551
+ error.code = 'NO_DEFAULT_GRAPH';
552
+ throw error;
553
+ }
554
+ const graphSourcePath = resolveGraphDefaultSourcePath();
555
+ await fs.promises.mkdir(path.dirname(graphTargetPath), { recursive: true });
556
+ await fs.promises.copyFile(graphSourcePath, graphTargetPath);
557
+ createdFiles.push(graphRelativePath);
558
+ } else {
559
+ skippedSteps.push(`${graphRelativePath} already exists`);
560
+ }
561
+
562
+ const templateSourcePath = resolveTemplateSourcePath(workspaceRoot);
563
+ const targetEaName = buildEaTargetFileName(workspaceName);
564
+ const targetEaPath = path.join(workspaceRoot, targetEaName);
565
+ const existingEaFiles = listExistingEaModelFiles(workspaceRoot);
566
+ if (existingEaFiles.length === 0) {
567
+ // No EA model file in the workspace: bootstrap a project-named .qea from the
568
+ // template (EA 17.2+ .qea/SQLite). Never generate a legacy .feap anymore.
569
+ await fs.promises.copyFile(templateSourcePath, targetEaPath);
570
+ createdFiles.push(normalizeRelativePath(targetEaName));
571
+ } else if (existingEaFiles.includes(targetEaName)) {
572
+ skippedSteps.push(`${normalizeRelativePath(targetEaName)} already exists`);
573
+ } else {
574
+ skippedSteps.push(`EA model already present (${existingEaFiles.join(', ')}); skip bootstrapping ${normalizeRelativePath(targetEaName)}`);
575
+ }
576
+
577
+ for (const handoffPath of HANDOFF_FILES_TO_RESET) {
578
+ const absolutePath = path.join(workspaceRoot, ...handoffPath);
579
+ if (fs.existsSync(absolutePath)) {
580
+ await fs.promises.rm(absolutePath, { force: true });
581
+ removedFiles.push(normalizeRelativePath(path.relative(workspaceRoot, absolutePath)));
582
+ }
583
+ }
584
+
585
+ // WP2791: init .qea FULL projection (parallel to Neo4j initial full sync in the harness
586
+ // report). Non-fatal: a qea failure must never fail workspace init.
587
+ let qeaFullProjection = null;
588
+ try {
589
+ qeaFullProjection = runQeaFullProjection(workspaceRoot, graphTargetPath);
590
+ } catch (error) {
591
+ qeaFullProjection = { status: 'failed', error: String(error && error.message ? error.message : error) };
592
+ }
593
+ // Report which schema this workspace resolves to (default ArgoBument vs a
594
+ // repository's own .argo/schema bundle) so the caller/human can see the active
595
+ // modeling language right after init.
596
+ let schema;
597
+ try {
598
+ const { bundle, ontology } = loadSchemaBundleAndOntology(workspaceRoot);
599
+ schema = {
600
+ kind: bundle.kind,
601
+ language: ontology.language,
602
+ dialect: ontology.dialect,
603
+ dir: bundle.relativeDir,
604
+ guide: bundle.guidePath ? bundle.guidePath.relativePath : null,
605
+ actorElementType: ontology.actorElementType,
606
+ bundleValidation: ontology.bundleValidation ? ontology.bundleValidation.status : null,
607
+ };
608
+ } catch (error) {
609
+ schema = { kind: 'unknown', error: String(error && error.message ? error.message : error) };
610
+ }
611
+
612
+ return {
613
+ workspaceRoot,
614
+ schema,
615
+ qeaFullProjection,
616
+ targetEaName,
617
+ createdFiles,
618
+ updatedFiles,
619
+ removedFiles,
620
+ skippedSteps,
621
+ status: 'ok',
622
+ };
623
+ }
624
+
625
+ function resolveTemplateSourcePath(workspaceRoot) {
626
+ for (const candidate of EA_TEMPLATE_PATH_CANDIDATES) {
627
+ const absolutePath = path.join(workspaceRoot, ...candidate);
628
+ if (fs.existsSync(absolutePath)) {
629
+ return absolutePath;
630
+ }
631
+ }
632
+
633
+ const bundledPath = resolveArgoPath(...BUNDLED_EA_TEMPLATE_SEGMENTS);
634
+ if (fs.existsSync(bundledPath)) {
635
+ return bundledPath;
636
+ }
637
+
638
+ throw new Error(`Unable to locate EA template. Checked: ${EA_TEMPLATE_PATH_CANDIDATES.map(candidate => candidate.join('/')).join(', ')}, and bundled ${BUNDLED_EA_TEMPLATE_SEGMENTS.join('/')}`);
639
+ }
640
+
641
+ function resolveGraphDefaultSourcePath() {
642
+ const bundledPath = resolveArgoPath(...BUNDLED_GRAPH_DEFAULT_SEGMENTS);
643
+ if (fs.existsSync(bundledPath)) {
644
+ return bundledPath;
645
+ }
646
+
647
+ throw new Error(`Unable to locate default SystemArchitecture template. Checked: bundled ${BUNDLED_GRAPH_DEFAULT_SEGMENTS.join('/')}`);
648
+ }
649
+
650
+ function listExistingEaModelFiles(workspaceRoot) {
651
+ let names = [];
652
+ try {
653
+ names = fs.readdirSync(workspaceRoot).filter(name =>
654
+ EA_MODEL_EXTENSIONS.has(path.extname(name).toLowerCase()),
655
+ );
656
+ } catch {
657
+ /* treat an unreadable root as having no EA model file */
658
+ }
659
+ return names.sort();
660
+ }
661
+
662
+ function buildEaTargetFileName(workspaceName) {
663
+ const sanitized = sanitizeFileName(workspaceName) || 'workspace';
664
+ const safeBaseName = WINDOWS_RESERVED_NAMES.has(sanitized.toUpperCase())
665
+ ? `${sanitized}_workspace`
666
+ : sanitized;
667
+ return `${safeBaseName}.qea`;
668
+ }
669
+
670
+ function sanitizeFileName(value) {
671
+ return value
672
+ .replace(/[<>:"/\\|?*\x00-\x1F]/g, '_')
673
+ .replace(/[.\s]+$/g, '')
674
+ .trim();
675
+ }
676
+
677
+ function normalizeRelativePath(value) {
678
+ return String(value).replace(/\\/g, '/');
679
+ }
680
+
681
+ function toolResult(payload) {
682
+ return {
683
+ content: [
684
+ {
685
+ type: 'text',
686
+ text: JSON.stringify(payload, null, 2),
687
+ },
688
+ ],
689
+ isError: payload.status === 'failed',
690
+ };
691
+ }
692
+
693
+ function canonicalInitErrorResult(error) {
694
+ // Workspace-bootstrap faults (e.g. a schema with no default graph) are not
695
+ // semantic-lifecycle secrets and must surface their message to the caller.
696
+ if (error && error.code === 'NO_DEFAULT_GRAPH') {
697
+ return toolResult({
698
+ status: 'failed',
699
+ error: { category: 'WORKSPACE_INIT_FAILED', code: error.code, message: String(error.message) },
700
+ });
701
+ }
702
+ const result = semanticOperatorErrorResult(error);
703
+ if (error.safeSemanticLifecycleMessage !== true) return result;
704
+ const payload = Object.freeze({
705
+ status: 'failed',
706
+ error: Object.freeze({
707
+ ...result.error,
708
+ message: error.message,
709
+ }),
710
+ });
711
+ return Object.freeze({
712
+ ...result,
713
+ ...payload,
714
+ content: Object.freeze([
715
+ Object.freeze({
716
+ type: 'text',
717
+ text: JSON.stringify(payload),
718
+ }),
719
+ ]),
720
+ });
721
+ }
722
+
723
+ function send(message) {
724
+ process.stdout.write(`${JSON.stringify(message)}\n`);
725
+ }
726
+
727
+ let rootRequestSeq = 0;
728
+ let rootRequestInFlight = false;
729
+ let rootRequestTimer = null;
730
+ let rootsSettled = false;
731
+ const pendingRootRequests = new Map();
732
+ const deferredToolCalls = [];
733
+
734
+ function flushDeferredToolCalls() {
735
+ const pending = deferredToolCalls.splice(0);
736
+ for (const request of pending) {
737
+ void (async () => {
738
+ const response = await handleRequest(request);
739
+ if (response) {
740
+ send(response);
741
+ }
742
+ })();
743
+ }
744
+ }
745
+
746
+ function settleRoots() {
747
+ if (rootsSettled) {
748
+ return;
749
+ }
750
+ rootsSettled = true;
751
+ if (rootRequestTimer) {
752
+ clearTimeout(rootRequestTimer);
753
+ rootRequestTimer = null;
754
+ }
755
+ rootRequestInFlight = false;
756
+ pendingRootRequests.clear();
757
+ flushDeferredToolCalls();
758
+ }
759
+
760
+ function requestRoots() {
761
+ if (rootRequestInFlight || rootsSettled) {
762
+ return;
763
+ }
764
+ rootRequestInFlight = true;
765
+ const id = `argo-roots-${++rootRequestSeq}`;
766
+ rootRequestTimer = setTimeout(() => {
767
+ rootRequestTimer = null;
768
+ rootRequestInFlight = false;
769
+ settleRoots();
770
+ }, 8000);
771
+ pendingRootRequests.set(id, (result) => {
772
+ if (result && Array.isArray(result.roots)) {
773
+ setMcpWorkspaceRoots(result.roots);
774
+ }
775
+ settleRoots();
776
+ });
777
+ send({ jsonrpc: '2.0', id, method: 'roots/list', params: {} });
778
+ }
779
+
780
+ async function handleRequest(request, dependencies = undefined) {
781
+ const { id, method, params } = request;
782
+
783
+ if (method === 'initialize') {
784
+ return {
785
+ jsonrpc: '2.0',
786
+ id,
787
+ result: {
788
+ protocolVersion: '2024-11-05',
789
+ capabilities: { tools: {}, roots: { listChanged: true } },
790
+ serverInfo: {
791
+ name: 'argo',
792
+ version: '1.0.0',
793
+ },
794
+ },
795
+ };
796
+ }
797
+
798
+ if (method === 'notifications/initialized') {
799
+ return null;
800
+ }
801
+
802
+ if (method === 'notifications/roots/list_changed') {
803
+ setMcpWorkspaceRoots(params && params.roots);
804
+ if (params && Array.isArray(params.roots) && params.roots.length > 0) {
805
+ settleRoots();
806
+ }
807
+ return null;
808
+ }
809
+
810
+ if (method === 'tools/list') {
811
+ // Deduplicate tools by name — last writer wins.
812
+ // Priority order: validatorMcp > systemArchitectureMcp > local TOOLS.
813
+ // This ensures zero duplicate tool names in the response, which would
814
+ // cause VS Code's MCP client to silently drop tools.
815
+ const toolMap = new Map();
816
+ for (const tool of [...TOOLS, ...systemArchitectureMcp.TOOLS, ...validatorMcp.TOOLS]) {
817
+ toolMap.set(tool.name, tool);
818
+ }
819
+ return {
820
+ jsonrpc: '2.0',
821
+ id,
822
+ result: { tools: [...toolMap.values()] },
823
+ };
824
+ }
825
+
826
+ if (method === 'tools/call') {
827
+ try {
828
+ const progressToken = (params._meta && params._meta.progressToken) || null;
829
+ let activeDependencies = dependencies;
830
+ if (
831
+ !activeDependencies
832
+ && params.name === 'getSystemArchitecture'
833
+ && params.arguments
834
+ && Object.prototype.hasOwnProperty.call(params.arguments, 'query')
835
+ && params.arguments.query
836
+ && !externalQueryRequested(params.name, params.arguments)
837
+ ) {
838
+ activeDependencies = {
839
+ semanticOperatorJourney:
840
+ await systemArchitectureMcp.createDefaultProductionSemanticOperatorJourney({
841
+ repositoryRoot: resolveWorkspaceRoot(params.arguments),
842
+ }),
843
+ };
844
+ }
845
+ const result = await callTool(
846
+ params.name,
847
+ params.arguments || {},
848
+ progressToken,
849
+ activeDependencies,
850
+ );
851
+ return { jsonrpc: '2.0', id, result };
852
+ } catch (error) {
853
+ return {
854
+ jsonrpc: '2.0',
855
+ id,
856
+ result: params.name === 'initializeWorkspace'
857
+ ? canonicalInitErrorResult(error)
858
+ : semanticOperatorErrorResult(error),
859
+ };
860
+ }
861
+ }
862
+
863
+ if (method === 'ping') {
864
+ return { jsonrpc: '2.0', id, result: {} };
865
+ }
866
+
867
+ return {
868
+ jsonrpc: '2.0',
869
+ id,
870
+ error: {
871
+ code: -32601,
872
+ message: `Method not found: ${method}`,
873
+ },
874
+ };
875
+ }
876
+
877
+ async function main() {
878
+ // Recall-safe warm-up: if the semantic readiness record is not Aligned when the
879
+ // server starts, rebuild the index in the BACKGROUND (async, logged) so the
880
+ // first query rarely pays the multi-second reconstruction. No-op when aligned.
881
+ if (process.env.ARGO_REPO_ROOT && process.env.ARGO_REPO_ROOT.trim() !== '') {
882
+ try {
883
+ require('./graph-rag/mcpCrashDiagnostics.js')
884
+ .installCrashDiagnostics(process.env.ARGO_REPO_ROOT);
885
+ } catch {
886
+ // diagnostics are best-effort; never block server startup
887
+ }
888
+ try {
889
+ require('./graph-rag/semanticAlignmentRunner.js')
890
+ .preheatSemanticAlignment(process.env.ARGO_REPO_ROOT);
891
+ } catch {
892
+ // preheat is best-effort; never block server startup
893
+ }
894
+ }
895
+ const rl = readline.createInterface({
896
+ input: process.stdin,
897
+ crlfDelay: Infinity,
898
+ });
899
+
900
+ for await (const line of rl) {
901
+ if (!line.trim()) {
902
+ continue;
903
+ }
904
+ let request;
905
+ try {
906
+ request = JSON.parse(line);
907
+ } catch {
908
+ continue;
909
+ }
910
+
911
+ // A JSON-RPC message without a `method` is a response to a server-sent request.
912
+ if (typeof request.method === 'undefined' && request.id !== undefined) {
913
+ const resolver = pendingRootRequests.get(request.id);
914
+ if (resolver) {
915
+ pendingRootRequests.delete(request.id);
916
+ resolver(request.result);
917
+ }
918
+ continue;
919
+ }
920
+
921
+ // Workspace-dependent tool calls must wait for roots so the global server
922
+ // targets the current workspace instead of the home directory.
923
+ if (request.method === 'tools/call' && !hasStaticWorkspace() && !rootsSettled) {
924
+ deferredToolCalls.push(request);
925
+ continue;
926
+ }
927
+
928
+ const response = await handleRequest(request);
929
+ if (response) {
930
+ send(response);
931
+ }
932
+ if ((request.method === 'initialize' || request.method === 'notifications/initialized')
933
+ && !hasStaticWorkspace()) {
934
+ requestRoots();
935
+ }
936
+ }
937
+ }
938
+
939
+ if (require.main === module) {
940
+ main().catch((error) => {
941
+ console.error(error);
942
+ process.exit(1);
943
+ });
944
+ }
945
+
946
+ module.exports = {
947
+ callTool,
948
+ handleRequest,
949
+ initializeWorkspace,
950
+ main,
951
+ withCanonicalSemanticInitTestComposition,
952
+ };