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,4508 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { spawn, spawnSync } = require('node:child_process');
4
+ const { markPhase } = require('./graph-rag/mcpCrashDiagnostics.js');
5
+ const readline = require('node:readline');
6
+ const crypto = require('node:crypto');
7
+
8
+ const {
9
+ resolveCallWorkspaceRoot,
10
+ } = require('./argo-paths.js');
11
+
12
+ const {
13
+ buildSemanticRecordText,
14
+ } = require('./graph-rag/semanticRecordText.js');
15
+
16
+ const DEFAULT_GRAPH_PATH = 'design/KG/SystemArchitecture.json';
17
+ const LEGAL_QUERY_PURPOSES = new Set([
18
+ 'general',
19
+ 'audit',
20
+ ]);
21
+ const FORBIDDEN_RESPONSE_SHAPE_CONTROL_FIELDS = Object.freeze([
22
+ 'responseProfile',
23
+ 'detail',
24
+ 'outputMode',
25
+ ]);
26
+ const FORBIDDEN_RESPONSE_SHAPE_CONTROL_VALUES = new Set([
27
+ 'debug',
28
+ 'full',
29
+ 'evidence',
30
+ ]);
31
+ const FORBIDDEN_RESPONSE_SHAPE_CONTROL_FLAGS = Object.freeze([
32
+ 'debug',
33
+ 'full',
34
+ 'evidence',
35
+ ]);
36
+ const GET_SYSTEM_ARCHITECTURE_OUTPUT_SCHEMA = {
37
+ type: 'object',
38
+ required: ['version', 'mode', 'document', 'query', 'error'],
39
+ properties: {
40
+ version: {
41
+ type: 'string',
42
+ const: '1.0',
43
+ description: 'Version of the typed getSystemArchitecture output contract.',
44
+ },
45
+ mode: {
46
+ type: 'string',
47
+ enum: ['semantic-query', 'error'],
48
+ description: 'Discriminator for the response variant.',
49
+ },
50
+ document: {
51
+ type: ['object', 'null'],
52
+ description: 'Canonical graph snapshot for semantic responses; semantic business-summary responses may use result in the text payload and set this to null; null for errors.',
53
+ },
54
+ query: {
55
+ type: ['object', 'null'],
56
+ properties: {
57
+ purpose: { type: 'string', enum: Array.from(LEGAL_QUERY_PURPOSES) },
58
+ intent: { type: 'string' },
59
+ subject: { type: 'string' },
60
+ mode: { type: 'string', enum: ['semantic-query'] },
61
+ semanticRetrieval: { type: 'string', enum: ['invoked'] },
62
+ },
63
+ additionalProperties: true,
64
+ description: 'Normalized explicit query metadata; null for errors.',
65
+ },
66
+ error: {
67
+ oneOf: [
68
+ {
69
+ type: 'object',
70
+ required: ['category', 'message'],
71
+ properties: {
72
+ category: { type: 'string' },
73
+ message: { type: 'string' },
74
+ action: { type: 'string' },
75
+ fullSnapshotFallback: { type: 'boolean' },
76
+ state: { type: ['string', 'null'] },
77
+ canonicalVersion: { type: ['string', 'null'] },
78
+ contentVersion: { type: ['string', 'null'] },
79
+ indexVersion: { type: ['string', 'null'] },
80
+ completedChannels: { type: 'array', items: { type: 'string' } },
81
+ missingChannels: { type: 'array', items: { type: 'string' } },
82
+ mismatchedChannels: { type: 'array', items: { type: 'string' } },
83
+ },
84
+ additionalProperties: false,
85
+ },
86
+ { type: 'null' },
87
+ ],
88
+ description: 'Stable typed error details; null for successful responses.',
89
+ },
90
+ },
91
+ oneOf: [
92
+ {
93
+ properties: {
94
+ mode: { const: 'semantic-query' },
95
+ document: { type: ['object', 'null'] },
96
+ query: { type: 'object' },
97
+ error: { type: 'null' },
98
+ },
99
+ },
100
+ {
101
+ properties: {
102
+ mode: { const: 'error' },
103
+ document: { type: 'null' },
104
+ query: { type: 'null' },
105
+ error: {
106
+ type: 'object',
107
+ required: ['category', 'message'],
108
+ },
109
+ },
110
+ },
111
+ ],
112
+ additionalProperties: false,
113
+ };
114
+ const SCHEMA_PATH_CANDIDATES = [
115
+ '.argo/schema/SystemArchitecture.schema.json',
116
+ ];
117
+ const W31_LIVE_OPT_IN = 'ARGO_W31_LIVE_MUTATION_VECTOR_E2E';
118
+ const LIVE_PROVIDER_OPT_IN = 'ARGO_LIVE_PROVIDER_E2E';
119
+ const W31_APPROVED_PROFILE = Object.freeze({
120
+ approvedByHuman: true,
121
+ provider: 'alibaba-cloud-model-studio-openai-compatible-cn-beijing',
122
+ baseUrl: 'https://llm-clids9mqc5o1mbvb.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
123
+ model: 'qwen3.7-text-embedding',
124
+ version: 'qualification-2026-07-25',
125
+ dimensions: 1536,
126
+ source: 'explicit-human-approval',
127
+ });
128
+
129
+ const {
130
+ validateGraphSemantics,
131
+ validateArchiMateEndpointMatrix,
132
+ validateViewElementLimits,
133
+ } = require('./graph-semantics.js');
134
+ const {
135
+ loadSchemaBundleAndOntology,
136
+ resolveSchemaBundle,
137
+ resolveTypeEnums,
138
+ } = require('./argob-schema.js');
139
+ const {
140
+ createProductionGraphRagRuntime,
141
+ } = require('./graph-rag/productionGraphRagRuntime.js');
142
+ const {
143
+ createDefaultSemanticRetrieval,
144
+ } = require('./graph-rag/defaultSemanticRetrieval.js');
145
+ const {
146
+ createProductionSemanticOperatorJourney,
147
+ } = require('./graph-rag/semanticOperatorJourney.js');
148
+ const {
149
+ semanticOperatorErrorResult,
150
+ } = require('./graph-rag/semanticOperatorError.js');
151
+ const {
152
+ resolveApprovedLiveConfiguration,
153
+ } = require('./graph-rag/liveEmbeddingProviderConfig.js');
154
+ const {
155
+ buildDefaultSemanticConfiguration,
156
+ } = require('./graph-rag/semanticInitConfiguration.js');
157
+ const {
158
+ createLiveEmbeddingProviderClient,
159
+ } = require('./graph-rag/liveEmbeddingProviderClient.js');
160
+ const {
161
+ createProductionSemanticReadinessStore,
162
+ } = require('./graph-rag/mutationEmbeddingVectorLifecycle.js');
163
+ const {
164
+ DEFAULT_GRAPH_PATH: NEO4J_DEFAULT_GRAPH_PATH,
165
+ assertReadOnlyCypher,
166
+ buildGraphKey,
167
+ buildNeo4jGraphSchema,
168
+ recoverNeo4jSyncIfNeeded,
169
+ runNeo4jCypherQuery,
170
+ syncArchitectureToNeo4j,
171
+ verifyArchitectureSync,
172
+ } = require('./neo4j-system-architecture-store.js');
173
+
174
+ const losslessWriteGate = require('./lossless-write-gate.js');
175
+ const { EXTERNAL_READ_TOOLS } = require('./external-graph-query.js');
176
+
177
+ const HANDLED_MUTATION_TYPES = new Set([
178
+ 'addElement',
179
+ 'updateElement',
180
+ 'removeElement',
181
+ 'addRelationship',
182
+ 'updateRelationship',
183
+ 'removeRelationship',
184
+ 'addView',
185
+ 'updateView',
186
+ 'removeView',
187
+ ]);
188
+
189
+ const TOOLS = [
190
+ {
191
+ name: 'getSystemArchitecture',
192
+ description: 'Read-only intent architecture access via explicit semantic query. Always provide query.purpose and query.intent to get a compact business/architecture result, then use returned element ids with getIntentElementContext for focused dependency context. Full-graph snapshot access is not exposed; query is required.',
193
+ inputSchema: {
194
+ type: 'object',
195
+ required: ['query'],
196
+ properties: {
197
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
198
+ query: {
199
+ type: 'object',
200
+ description: 'Required semantic query. Provide query.purpose + query.intent; combine the returned element ids with getIntentElementContext when deeper local context is needed.',
201
+ properties: {
202
+ purpose: {
203
+ type: 'string',
204
+ enum: Array.from(LEGAL_QUERY_PURPOSES),
205
+ description: 'Declared reading purpose: general for generic semantic/memory retrieval, or audit for strict proof-closure reads (subject required).',
206
+ },
207
+ intent: { type: 'string', description: 'Natural-language intent for semantic retrieval, for example "summarize business features for high-risk audit".' },
208
+ subject: { type: 'string', description: 'Required for audit; optional anchor/focus id for other semantic purposes.' },
209
+ scope: {
210
+ type: 'object',
211
+ 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.',
212
+ properties: {
213
+ view_id: { type: 'string', description: 'Restrict retrieval to the members of this view.' },
214
+ element_id: { type: 'string', description: 'Restrict retrieval to this element and its mounted sub-view subtree.' },
215
+ depth: { type: 'number', description: 'Default: 2. Subtree depth for element scope.' },
216
+ },
217
+ additionalProperties: false,
218
+ },
219
+ },
220
+ additionalProperties: true,
221
+ },
222
+ },
223
+ additionalProperties: false,
224
+ },
225
+ outputSchema: GET_SYSTEM_ARCHITECTURE_OUTPUT_SCHEMA,
226
+ },
227
+ {
228
+ name: 'getIntentElementContext',
229
+ 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.',
230
+ inputSchema: intentElementContextInputSchema(),
231
+ },
232
+ {
233
+ name: 'getArchitectureViewContext',
234
+ description: 'read-only query that resolves one view by view_id into its complete membership: the view object, every member element (from included_elements), every member relationship (from included_relationships), the parent element, and optionally child sub-views declared by member elements. Resolves ids into full canonical objects instead of returning raw id lists. Optional includeEaGeometry (default false) additionally returns the EA diagram geometry of the resolved view: element boxes plus each connector ROUTE (t_diagramlinks.Path as `path` + parsed `points`, with the non-route Geometry override kept separately under `geometry`).',
235
+ inputSchema: viewContextInputSchema(),
236
+ },
237
+ {
238
+ name: 'previewSystemArchitectureMutation',
239
+ 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.',
240
+ inputSchema: mutationInputSchema(),
241
+ },
242
+ {
243
+ name: 'applySystemArchitectureMutation',
244
+ 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.',
245
+ inputSchema: mutationInputSchema(),
246
+ },
247
+ {
248
+ name: 'addArchitectureElement',
249
+ 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. Set dryRun to preview without writing.',
250
+ inputSchema: {
251
+ type: 'object',
252
+ required: ['element', 'view_ids'],
253
+ properties: {
254
+ element: { type: 'object' },
255
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
256
+ 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.' },
257
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate.' },
258
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
259
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
260
+ },
261
+ additionalProperties: false,
262
+ },
263
+ },
264
+ {
265
+ name: 'updateArchitectureElement',
266
+ 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. Set dryRun to preview without writing.',
267
+ inputSchema: {
268
+ type: 'object',
269
+ required: ['id', 'patch'],
270
+ properties: {
271
+ id: { type: 'string' },
272
+ patch: { type: 'object' },
273
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
274
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
275
+ },
276
+ additionalProperties: false,
277
+ },
278
+ },
279
+ {
280
+ name: 'removeArchitectureElement',
281
+ 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. Set dryRun to preview without writing.',
282
+ inputSchema: {
283
+ type: 'object',
284
+ required: ['id'],
285
+ properties: {
286
+ id: { type: 'string' },
287
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
288
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
289
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
290
+ },
291
+ additionalProperties: false,
292
+ },
293
+ },
294
+ {
295
+ name: 'addArchitectureRelationship',
296
+ 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. Set dryRun to preview without writing.',
297
+ inputSchema: {
298
+ type: 'object',
299
+ required: ['relationship', 'view_ids'],
300
+ properties: {
301
+ relationship: { type: 'object' },
302
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
303
+ 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.' },
304
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate.' },
305
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
306
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
307
+ },
308
+ additionalProperties: false,
309
+ },
310
+ },
311
+ {
312
+ name: 'updateArchitectureRelationship',
313
+ 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. Set dryRun to preview without writing.',
314
+ inputSchema: {
315
+ type: 'object',
316
+ required: ['id', 'patch'],
317
+ properties: {
318
+ id: { type: 'string' },
319
+ patch: { type: 'object' },
320
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
321
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
322
+ },
323
+ additionalProperties: false,
324
+ },
325
+ },
326
+ {
327
+ name: 'removeArchitectureRelationship',
328
+ 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. Set dryRun to preview without writing.',
329
+ inputSchema: {
330
+ type: 'object',
331
+ required: ['id'],
332
+ properties: {
333
+ id: { type: 'string' },
334
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
335
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
336
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
337
+ },
338
+ additionalProperties: false,
339
+ },
340
+ },
341
+ {
342
+ name: 'addArchitectureView',
343
+ 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. Set dryRun to preview without writing.',
344
+ inputSchema: {
345
+ type: 'object',
346
+ required: ['view'],
347
+ properties: {
348
+ view: { type: 'object' },
349
+ 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.' },
350
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate.' },
351
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
352
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
353
+ },
354
+ additionalProperties: false,
355
+ },
356
+ },
357
+ {
358
+ name: 'updateArchitectureView',
359
+ description: 'Use for one view metadata or membership patch. Keep the one top-level view named SystemArchitecture and attach sub-views to parent elements. Set dryRun to preview without writing.',
360
+ inputSchema: {
361
+ type: 'object',
362
+ required: ['view_id', 'patch'],
363
+ properties: {
364
+ view_id: { type: 'string' },
365
+ patch: { type: 'object' },
366
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
367
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
368
+ },
369
+ additionalProperties: false,
370
+ },
371
+ },
372
+ {
373
+ name: 'removeArchitectureView',
374
+ description: 'Use for one view removal. After removal, every remaining element and relationship must still belong to at least one view. Set dryRun to preview without writing.',
375
+ inputSchema: {
376
+ type: 'object',
377
+ required: ['view_id'],
378
+ properties: {
379
+ view_id: { type: 'string' },
380
+ dryRun: { type: 'boolean', description: 'When true, validates and returns the result without writing to the graph. Default: false.' },
381
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
382
+ },
383
+ additionalProperties: false,
384
+ },
385
+ },
386
+ {
387
+ name: 'queryNeo4jGraph',
388
+ description: 'Run a read-only Cypher query against the Neo4j structural projection of the intent architecture, or request the projection schema so an agent can construct its own Cypher. Pass {schema: true} to return node labels, relationship types, property keys, and the legal element/relationship type enums of the workspace-resolved schema bundle. Pass {cypher: "..."} to execute a read-only query; scope it with {graphKey: $graphKey}. Write clauses (CREATE/MERGE/DELETE/SET/REMOVE/DROP/LOAD CSV/FOREACH/IN TRANSACTIONS) are rejected.',
389
+ inputSchema: {
390
+ type: 'object',
391
+ properties: {
392
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
393
+ cypher: { type: 'string', description: 'Read-only Cypher query to execute. Use $graphKey to scope to the current architecture graph, e.g. MATCH (e:Element {graphKey: $graphKey}) RETURN e.id, e.name.' },
394
+ schema: { type: 'boolean', description: 'When true, return the Neo4j projection schema instead of running a Cypher query.' },
395
+ },
396
+ additionalProperties: false,
397
+ },
398
+ },
399
+ {
400
+ name: 'memory_search',
401
+ description: 'Semantic memory search: retrieve the user\'s memory by natural-language query. Runs embedding-based semantic retrieval (memory-retrieval purpose) over the intent graph and returns the top-k relevant memory items (id, name, type, similarity score, and a description excerpt with its full length). Each hit is a lightweight card: to keep the tool result compact, description is truncated to max_desc_len characters (default 800) and the full text length is reported as description_length. To read the full text of a hit, call getIntentElementContext with its id. Agents SHOULD call this tool to look up the user\'s memory before answering a question about the user.',
402
+ inputSchema: {
403
+ type: 'object',
404
+ properties: {
405
+ query: { type: 'string', description: 'Natural-language query describing the user memory to retrieve.' },
406
+ top_k: { type: 'integer', description: 'Optional max number of hits to return (default 8).' },
407
+ max_desc_len: { type: 'integer', description: 'Optional max characters of description to return per hit. Default 800. Use 0 for the full description, or -1 to omit description and return only the length.' },
408
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
409
+ },
410
+ additionalProperties: false,
411
+ },
412
+ },
413
+ ];
414
+
415
+ // Every tool accepts an optional per-call `workspaceRoot` (absolute path,
416
+ // honored unconditionally when provided). The DeepSeek Harness bridge injects
417
+ // the current session's workspace directory here automatically.
418
+ const WORKSPACE_ROOT_PARAM = Object.freeze({
419
+ type: 'string',
420
+ description:
421
+ 'Optional absolute workspace root for this call. When provided it is used as-is; otherwise the server launch directory is used.',
422
+ });
423
+ // Cross-project graph query: the 5 read tools accept an optional `projectId`;
424
+ // provided => routed to the federation center, omitted => the local workspace.
425
+ const PROJECT_ID_PARAM = Object.freeze({
426
+ type: 'string',
427
+ description:
428
+ 'Optional external project id. When provided, the query is routed to the federation center to read that project\'s graph (this project must be registered in .argo/federation.json); omitted = the local workspace (unchanged).',
429
+ });
430
+ // Lossless write gate: every update/remove helper accepts an explicit loss
431
+ // acknowledgement (see lossless-write-gate.js). add* is purely additive and is
432
+ // left alone. Without the acknowledgement a shrinking text edit or a destructive
433
+ // removal is blocked at the buildMutationResult funnel.
434
+ const LOSS_ACK_INPUT_PROPS = Object.freeze({
435
+ acknowledgeLoss: {
436
+ type: 'boolean',
437
+ 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.',
438
+ },
439
+ lossJustification: {
440
+ type: 'string',
441
+ description: 'Required for MAJOR text loss (large removedChars or most of the value): the reason the prior content is being intentionally replaced.',
442
+ },
443
+ });
444
+
445
+ for (const tool of TOOLS) {
446
+ const inputSchema = tool && tool.inputSchema;
447
+ if (!inputSchema || inputSchema.type !== 'object' || !inputSchema.properties) continue;
448
+ if (!Object.prototype.hasOwnProperty.call(inputSchema.properties, 'workspaceRoot')) {
449
+ inputSchema.properties.workspaceRoot = WORKSPACE_ROOT_PARAM;
450
+ }
451
+ if (EXTERNAL_READ_TOOLS.has(tool.name) && !Object.prototype.hasOwnProperty.call(inputSchema.properties, 'projectId')) {
452
+ inputSchema.properties.projectId = PROJECT_ID_PARAM;
453
+ }
454
+ if (tool.name && /^(update|remove)Architecture/.test(tool.name)) {
455
+ for (const [key, value] of Object.entries(LOSS_ACK_INPUT_PROPS)) {
456
+ if (!Object.prototype.hasOwnProperty.call(inputSchema.properties, key)) {
457
+ inputSchema.properties[key] = value;
458
+ }
459
+ }
460
+ }
461
+ }
462
+
463
+ function intentElementContextInputSchema() {
464
+ return {
465
+ type: 'object',
466
+ properties: {
467
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
468
+ elementId: { type: 'string' },
469
+ elementName: { type: 'string' },
470
+ profile: {
471
+ type: 'string',
472
+ enum: ['implementation-design', 'coding-repair', 'audit', 'generic-agent'],
473
+ description: 'Default: generic-agent. Affects workContext enrichment only; subgraph shape stays native.',
474
+ },
475
+ dependencyDepth: { type: 'number', description: 'Default: 2. Semantic dependencies needed by the focus element.' },
476
+ dependentDepth: { type: 'number', description: 'Default: 1. Semantic dependents that rely on the focus element.' },
477
+ associationDepth: { type: 'number', description: 'Default: 1. Association neighbors are expanded at least one layer.' },
478
+ associationNeighborDependencyDepth: { type: 'number', description: 'Default: 0. Optional dependency expansion from association neighbors.' },
479
+ 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. Semantic retrieval embeds attributes, so semantic hits keep them.' },
480
+ includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim. Omitted by default from this structural read (bookkeeping); pass true when you need acceptance cases. Semantic retrieval embeds testcase descriptions, so semantic hits keep them.' },
481
+ },
482
+ additionalProperties: false,
483
+ };
484
+ }
485
+
486
+ function viewContextInputSchema() {
487
+ return {
488
+ type: 'object',
489
+ required: ['view_id'],
490
+ properties: {
491
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
492
+ view_id: { type: 'string', description: 'The id of the view to resolve.' },
493
+ includeParentElement: { type: 'boolean', description: 'Default: true. Resolve the parent element referenced by the view.' },
494
+ includeChildViews: { type: 'boolean', description: 'Default: false. Include child views declared by member elements through subdiagram_views.' },
495
+ includeAttributes: { type: 'boolean', description: 'Default: false. Include member/relationship `attributes` (commit/session/release ledgers) verbatim. Omitted by default from this structural read (bookkeeping); pass true when you need provenance.' },
496
+ includeTestcases: { type: 'boolean', description: 'Default: false. Include member `testcases` verbatim. Omitted by default from this structural read; pass true for acceptance-case lookups.' },
497
+ includeEaGeometry: { type: 'boolean', description: 'Default: false (opt-in). When true, additionally resolve the diagram GEOMETRY (element boxes + connector line routes) for this view from the workspace EA model (.qea) and return it under a `geometry` field aligned by schema id with the resolved members. Each geometry relationship carries: `path` (the EA route from t_diagramlinks.Path, "" when EA auto-routes), `points` (the parsed [{x,y}] waypoints), `edge` (the EDGE route-style token or null) and `geometry` (the raw SX/SY/EX/EY override string, which contains NO waypoints). By default the EA model is never touched and no `geometry` field is returned; a missing EA model/diagram yields geometry.present=false, never an error.' },
498
+ },
499
+ additionalProperties: false,
500
+ };
501
+ }
502
+
503
+ function mutationInputSchema() {
504
+ return {
505
+ type: 'object',
506
+ required: ['mutations'],
507
+ properties: {
508
+ architecturePath: { type: 'string', description: `Default: ${DEFAULT_GRAPH_PATH}` },
509
+ 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.' },
510
+ lossJustification: { type: 'string', description: 'Batch-level justification for MAJOR text loss in this mutation set.' },
511
+ mutations: {
512
+ type: 'array',
513
+ minItems: 1,
514
+ items: {
515
+ type: 'object',
516
+ required: ['type'],
517
+ properties: {
518
+ type: { type: 'string', enum: Array.from(HANDLED_MUTATION_TYPES) },
519
+ element: { type: 'object' },
520
+ relationship: { type: 'object' },
521
+ view: { type: 'object' },
522
+ id: { type: 'string' },
523
+ patch: { type: 'object' },
524
+ view_id: { type: 'string' },
525
+ view_ids: { type: 'array', minItems: 1, items: { type: 'string' } },
526
+ element_ids: { type: 'array', items: { type: 'string' } },
527
+ relationship_ids: { type: 'array', items: { type: 'string' } },
528
+ onConflict: { type: 'string', enum: ['reuse', 'allowDuplicate'], description: 'Dedup policy for add* mutations. reuse (default): find-or-create — attach an existing exact-natural-key match instead of creating a duplicate; a same-type semantic near-duplicate also blocks creation unless allowDuplicate is set. allowDuplicate: create a new object even if a duplicate exists, requires a non-empty justification.' },
529
+ justification: { type: 'string', description: 'Required when onConflict is allowDuplicate; recorded as the reason a semantically-equal duplicate is intentionally created.' },
530
+ 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.' },
531
+ 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.' },
532
+ },
533
+ additionalProperties: false,
534
+ },
535
+ },
536
+ },
537
+ additionalProperties: false,
538
+ };
539
+ }
540
+
541
+ function resolveWorkspaceRoot(args) {
542
+ // Per-call workspaceRoot override, honored unconditionally when provided;
543
+ // defaults to the launch-directory root.
544
+ return resolveCallWorkspaceRoot(args);
545
+ }
546
+
547
+ function initializeWorkspace(request) {
548
+ return require('./argo-mcp-server.js').initializeWorkspace(
549
+ request && request.repositoryRoot ? request.repositoryRoot : resolveWorkspaceRoot(request),
550
+ );
551
+ }
552
+
553
+ async function syncCanonicalStructuralProjection(request) {
554
+ const context = await loadContext(request);
555
+ return syncArchitectureToNeo4j({
556
+ architecturePath: context.graphPath.relativePath,
557
+ document: context.document,
558
+ workspaceRoot: context.workspaceRoot,
559
+ });
560
+ }
561
+
562
+ function resolveWorkspacePath(workspaceRoot, relativePath) {
563
+ const normalizedPath = normalizeRelativePath(relativePath || DEFAULT_GRAPH_PATH);
564
+ const absolutePath = path.resolve(workspaceRoot, normalizedPath);
565
+ const normalizedRoot = path.resolve(workspaceRoot);
566
+ if (!absolutePath.startsWith(normalizedRoot)) {
567
+ throw new Error(`Path escapes workspace root: ${relativePath}`);
568
+ }
569
+ return { absolutePath, relativePath: normalizedPath };
570
+ }
571
+
572
+ function normalizeRelativePath(value) {
573
+ return String(value).replace(/\\/g, '/').replace(/^\/+/, '');
574
+ }
575
+
576
+ function resolveSchemaPath(workspaceRoot) {
577
+ return resolveSchemaBundle(workspaceRoot).schema;
578
+ }
579
+
580
+ function readJson(filePath, label) {
581
+ try {
582
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
583
+ } catch (error) {
584
+ throw new Error(`Failed to parse ${label}: ${String(error)}`);
585
+ }
586
+ }
587
+
588
+ async function loadContext(args = {}) {
589
+ const workspaceRoot = resolveWorkspaceRoot(args);
590
+ const graphPath = resolveWorkspacePath(workspaceRoot, args.architecturePath || DEFAULT_GRAPH_PATH);
591
+ // Resolve the modeling language for THIS workspace: a repository that ships
592
+ // its own bundle under .argo/schema is validated against that schema.
593
+ const { bundle, ontology } = loadSchemaBundleAndOntology(workspaceRoot);
594
+ const context = {
595
+ workspaceRoot,
596
+ graphPath,
597
+ schemaPath: bundle.schema,
598
+ schemaBundle: bundle,
599
+ ontology,
600
+ document: readJson(graphPath.absolutePath, graphPath.relativePath),
601
+ schema: bundle.schemaDocument,
602
+ };
603
+ context.neo4jSyncRecovery = await recoverNeo4jSyncIfNeeded({
604
+ architecturePath: graphPath.relativePath,
605
+ document: context.document,
606
+ workspaceRoot: context.workspaceRoot,
607
+ });
608
+ return context;
609
+ }
610
+
611
+ function validateDocument(document, schema, options = {}) {
612
+ const ontology = options.ontology;
613
+ const errors = [];
614
+ if (ontology && ontology.bundleValidation && ontology.bundleValidation.status === 'failed') {
615
+ errors.push(...ontology.bundleValidation.errors.map(error => `schema bundle: ${error}`));
616
+ }
617
+ validateAgainstSchema(document, schema, '#', errors, schema);
618
+ validateGraphSemantics(document, errors, ontology);
619
+ validateArchiMateEndpointMatrix(document, errors, {
620
+ ontology,
621
+ touchedRelationshipIds: options.touchedRelationshipIds,
622
+ });
623
+ validateViewElementLimits(document, errors, {
624
+ ontology,
625
+ touchedViewIds: options.validateAllViewElementLimits
626
+ ? (document.views || []).map(view => view && view.view_id)
627
+ : options.touchedViewIds,
628
+ });
629
+ return errors;
630
+ }
631
+
632
+ // Agent-facing projection of canonical records for STRUCTURAL reads (view
633
+ // membership / intent-element subgraph). `attributes` (commit/session/release
634
+ // ledgers) and `testcases` are bookkeeping: measured as ~52% of the element
635
+ // bytes but NOT needed to answer structural reads, so they are omitted by
636
+ // default and returned only on opt-in (includeAttributes / includeTestcases).
637
+ //
638
+ // This is NOT summarisation: every retained field is returned verbatim. It is
639
+ // also NOT the semantic match surface — semantic retrieval embeds attributes and
640
+ // testcase descriptions (semanticRecordText.js), so semantic results keep them;
641
+ // and the focus element of an intent-element read always keeps its own.
642
+ function byteLenLocal(value) {
643
+ try { return Buffer.byteLength(JSON.stringify(value)); } catch (_) { return 0; }
644
+ }
645
+
646
+ function projectAgentFields(record, opts = {}) {
647
+ const value = clone(record);
648
+ let omittedAttributes = 0;
649
+ let omittedTestcases = 0;
650
+ let omittedBytes = 0;
651
+ if (!opts.includeAttributes && Array.isArray(value.attributes) && value.attributes.length) {
652
+ omittedAttributes = value.attributes.length;
653
+ omittedBytes += byteLenLocal(value.attributes);
654
+ delete value.attributes;
655
+ }
656
+ if (!opts.includeTestcases && Array.isArray(value.testcases) && value.testcases.length) {
657
+ omittedTestcases = value.testcases.length;
658
+ omittedBytes += byteLenLocal(value.testcases);
659
+ delete value.testcases;
660
+ }
661
+ return { value, omittedAttributes, omittedTestcases, omittedBytes };
662
+ }
663
+
664
+ function buildAgentProjection(omitted) {
665
+ if (!omitted || (omitted.attributes === 0 && omitted.testcases === 0)) {
666
+ return null;
667
+ }
668
+ // Only attach the explanation when the omission actually saves more than the
669
+ // note costs, so trimming a read can NEVER make it larger (cross-scenario
670
+ // no-degradation). The opt-in flags are documented in the tool description.
671
+ if ((omitted.bytes || 0) < 160) {
672
+ return null;
673
+ }
674
+ return {
675
+ attributesOmitted: omitted.attributes,
676
+ testcasesOmitted: omitted.testcases,
677
+ note: 'includeAttributes/includeTestcases=true to include (omitted by default; semantic hits keep them).',
678
+ };
679
+ }
680
+
681
+ function buildIntentElementContext(context, args = {}) {
682
+ const profile = args.profile || 'generic-agent';
683
+ const focusResult = resolveFocusElement(context.document, args);
684
+ if (focusResult.status !== 'passed') {
685
+ return focusResult;
686
+ }
687
+
688
+ const dependencyDepth = normalizeDepth(args.dependencyDepth, 2);
689
+ const dependentDepth = normalizeDepth(args.dependentDepth, 1);
690
+ const associationDepth = Math.max(1, normalizeDepth(args.associationDepth, 1));
691
+ const associationNeighborDependencyDepth = normalizeDepth(args.associationNeighborDependencyDepth, 0);
692
+ const graphIndex = buildGraphIndex(context.document, context.ontology);
693
+ const focusElement = focusResult.element;
694
+ const includedElementIds = new Set([focusElement.id]);
695
+ const includedRelationshipIds = new Set();
696
+ const dependencyDepthByElement = new Map([[focusElement.id, 0]]);
697
+ const dependentDepthByElement = new Map([[focusElement.id, 0]]);
698
+ const associationDepthByElement = new Map([[focusElement.id, 0]]);
699
+
700
+ traverseSemanticContext({
701
+ startId: focusElement.id,
702
+ maxDepth: dependencyDepth,
703
+ mode: 'dependency',
704
+ graphIndex,
705
+ includedElementIds,
706
+ includedRelationshipIds,
707
+ depthByElement: dependencyDepthByElement,
708
+ });
709
+ traverseSemanticContext({
710
+ startId: focusElement.id,
711
+ maxDepth: dependentDepth,
712
+ mode: 'dependent',
713
+ graphIndex,
714
+ includedElementIds,
715
+ includedRelationshipIds,
716
+ depthByElement: dependentDepthByElement,
717
+ });
718
+ traverseSemanticContext({
719
+ startId: focusElement.id,
720
+ maxDepth: associationDepth,
721
+ mode: 'association',
722
+ graphIndex,
723
+ includedElementIds,
724
+ includedRelationshipIds,
725
+ depthByElement: associationDepthByElement,
726
+ });
727
+
728
+ if (associationNeighborDependencyDepth > 0) {
729
+ for (const [elementId, depth] of associationDepthByElement.entries()) {
730
+ if (elementId === focusElement.id || depth < 1) {
731
+ continue;
732
+ }
733
+ traverseSemanticContext({
734
+ startId: elementId,
735
+ maxDepth: associationNeighborDependencyDepth,
736
+ mode: 'dependency',
737
+ graphIndex,
738
+ includedElementIds,
739
+ includedRelationshipIds,
740
+ depthByElement: new Map([[elementId, 0]]),
741
+ });
742
+ }
743
+ }
744
+
745
+ includeViewAnchors(context.document, includedElementIds, includedRelationshipIds, graphIndex);
746
+ const boundary = buildBoundary({
747
+ graphIndex,
748
+ includedElementIds,
749
+ dependencyDepthByElement,
750
+ dependentDepthByElement,
751
+ associationDepthByElement,
752
+ dependencyDepth,
753
+ dependentDepth,
754
+ associationDepth,
755
+ });
756
+ const explorationHints = buildExplorationHints(boundary, {
757
+ profile,
758
+ dependencyDepth,
759
+ dependentDepth,
760
+ associationDepth,
761
+ });
762
+
763
+ const subgraph = buildNativeSubgraph(context.document, includedElementIds, includedRelationshipIds);
764
+ const includeAttributes = args.includeAttributes === true;
765
+ const includeTestcases = args.includeTestcases === true;
766
+ const omitted = { attributes: 0, testcases: 0, bytes: 0 };
767
+ if (!(includeAttributes && includeTestcases)) {
768
+ subgraph.elements = subgraph.elements.map((element) => {
769
+ if (element.id === focusElement.id) {
770
+ return element; // the focus element keeps its own bookkeeping
771
+ }
772
+ const projected = projectAgentFields(element, { includeAttributes, includeTestcases });
773
+ omitted.attributes += projected.omittedAttributes;
774
+ omitted.testcases += projected.omittedTestcases;
775
+ omitted.bytes += projected.omittedBytes;
776
+ return projected.value;
777
+ });
778
+ subgraph.relationships = subgraph.relationships.map((relationship) => {
779
+ const projected = projectAgentFields(relationship, { includeAttributes });
780
+ omitted.attributes += projected.omittedAttributes;
781
+ omitted.bytes += projected.omittedBytes;
782
+ return projected.value;
783
+ });
784
+ }
785
+ const result = {
786
+ status: 'passed',
787
+ query: {
788
+ architecturePath: context.graphPath.relativePath,
789
+ elementId: focusElement.id,
790
+ elementName: focusElement.name,
791
+ profile,
792
+ dependencyDepth,
793
+ dependentDepth,
794
+ associationDepth,
795
+ associationNeighborDependencyDepth,
796
+ traversalMode: 'archimate-semantic',
797
+ },
798
+ focusElementId: focusElement.id,
799
+ subgraph,
800
+ boundary,
801
+ explorationHints,
802
+ workContext: {},
803
+ diagnostics: [],
804
+ };
805
+ const projection = buildAgentProjection(omitted);
806
+ if (projection) result.projection = projection;
807
+ return result;
808
+ }
809
+
810
+ // ---------------------------------------------------------------------------
811
+ // Optional EA diagram GEOMETRY (opt-in, default off)
812
+ // ---------------------------------------------------------------------------
813
+ // getArchitectureViewContext is a canonical-graph read; it never touches the EA
814
+ // model unless the caller explicitly sets includeEaGeometry=true. The workspace's
815
+ // EA model (.qea, the SQLite carrier this toolchain can read) may hold human-laid-out
816
+ // diagram geometry for a view — element boxes (t_diagramobjects rects) and connector
817
+ // routes (t_diagramlinks.Path). When present it is returned under `geometry`, aligned
818
+ // by schema id with the resolved members, so an image-capable LLM can redraw the view
819
+ // faithfully. Each connector also carries the non-route t_diagramlinks.Geometry override
820
+ // string under a distinct `geometry` key, so the route is never confused with the
821
+ // SX/SY/EX/EY/EDGE tokens. Absent model/diagram → present:false (never an error).
822
+ const EA_GEOMETRY_MODEL_EXTENSIONS = new Set(['.qea']);
823
+ function findEaGeometryModelPath(workspaceRoot) {
824
+ try {
825
+ const entries = fs.readdirSync(workspaceRoot, { withFileTypes: true });
826
+ const names = entries
827
+ .filter((entry) => entry.isFile() && EA_GEOMETRY_MODEL_EXTENSIONS.has(path.extname(entry.name).toLowerCase()))
828
+ .map((entry) => entry.name)
829
+ .sort();
830
+ return names.length > 0 ? path.join(workspaceRoot, names[0]) : null;
831
+ } catch {
832
+ return null;
833
+ }
834
+ }
835
+ function readEaViewGeometry(workspaceRoot, viewId) {
836
+ // Lazily require the .qea projection lib: it depends on node:sqlite (Node >= 22),
837
+ // so it is only loaded when geometry is actually requested, never for other calls.
838
+ let modelRel = null;
839
+ try {
840
+ const modelPath = findEaGeometryModelPath(workspaceRoot);
841
+ if (!modelPath) {
842
+ return { source: null, present: false, elements: [], relationships: [] };
843
+ }
844
+ modelRel = normalizeRelativePath(path.relative(workspaceRoot, modelPath)) || null;
845
+ const eaQeaLib = require('./ea-qea-sync-lib.js');
846
+ const geo = eaQeaLib.readViewDiagramGeometry(modelPath, viewId);
847
+ if (!geo) {
848
+ return { source: modelRel, present: false, elements: [], relationships: [] };
849
+ }
850
+ return { source: modelRel, present: true, elements: geo.elements, relationships: geo.relationships };
851
+ } catch {
852
+ return { source: modelRel, present: false, elements: [], relationships: [] };
853
+ }
854
+ }
855
+
856
+ function buildViewContext(context, args = {}) {
857
+ const viewId = typeof args.view_id === 'string' ? args.view_id.trim() : '';
858
+ if (!viewId) {
859
+ return {
860
+ status: 'failed',
861
+ error: { category: 'VIEW_ID_REQUIRED', message: 'view_id is required' },
862
+ };
863
+ }
864
+
865
+ const document = context.document;
866
+ const view = findView(document.views, viewId);
867
+ if (!view) {
868
+ return {
869
+ status: 'failed',
870
+ error: { category: 'VIEW_NOT_FOUND', message: `View '${viewId}' does not exist` },
871
+ };
872
+ }
873
+
874
+ const elementById = new Map((document.elements || []).map(element => [element.id, element]));
875
+ const relationshipById = new Map((document.relationships || []).map(relationship => [relationship.id, relationship]));
876
+
877
+ const includeAttributes = args.includeAttributes === true;
878
+ const includeTestcases = args.includeTestcases === true;
879
+ const omitted = { attributes: 0, testcases: 0, bytes: 0 };
880
+ const project = (record) => {
881
+ const projected = projectAgentFields(record, { includeAttributes, includeTestcases });
882
+ omitted.attributes += projected.omittedAttributes;
883
+ omitted.testcases += projected.omittedTestcases;
884
+ omitted.bytes += projected.omittedBytes;
885
+ return projected.value;
886
+ };
887
+
888
+ const elements = [];
889
+ const missingElementIds = [];
890
+ for (const elementId of view.included_elements || []) {
891
+ const element = elementById.get(elementId);
892
+ if (element) {
893
+ elements.push(project(element));
894
+ } else {
895
+ missingElementIds.push(elementId);
896
+ }
897
+ }
898
+
899
+ const relationships = [];
900
+ const missingRelationshipIds = [];
901
+ for (const relationshipId of view.included_relationships || []) {
902
+ const relationship = relationshipById.get(relationshipId);
903
+ if (relationship) {
904
+ relationships.push(project(relationship));
905
+ } else {
906
+ missingRelationshipIds.push(relationshipId);
907
+ }
908
+ }
909
+
910
+ const includeParentElement = args.includeParentElement !== false;
911
+ let parentElement = null;
912
+ if (includeParentElement && view.parent_element_id) {
913
+ const parent = elementById.get(view.parent_element_id);
914
+ parentElement = parent ? project(parent) : null;
915
+ }
916
+
917
+ const includeChildViews = args.includeChildViews === true;
918
+ const childViews = [];
919
+ if (includeChildViews) {
920
+ const childViewIds = new Set();
921
+ for (const element of elements) {
922
+ for (const subview of element.subdiagram_views || []) {
923
+ if (subview && subview.view_id) {
924
+ childViewIds.add(subview.view_id);
925
+ }
926
+ }
927
+ }
928
+ for (const entry of document.views || []) {
929
+ if (childViewIds.has(entry.view_id)) {
930
+ childViews.push(clone(entry));
931
+ }
932
+ }
933
+ }
934
+
935
+ const result = {
936
+ status: 'passed',
937
+ graphPath: context.graphPath.relativePath,
938
+ view: clone(view),
939
+ elements,
940
+ relationships,
941
+ missingElementIds,
942
+ missingRelationshipIds,
943
+ parentElement,
944
+ childViews,
945
+ };
946
+ if (args.includeEaGeometry === true) {
947
+ result.geometry = readEaViewGeometry(context.workspaceRoot, viewId);
948
+ }
949
+ const projection = buildAgentProjection(omitted);
950
+ if (projection) result.projection = projection;
951
+ return result;
952
+ }
953
+
954
+ function resolveFocusElement(document, args) {
955
+ if (args.elementId) {
956
+ const element = (document.elements || []).find(entry => entry.id === args.elementId);
957
+ if (!element) {
958
+ return {
959
+ status: 'failed',
960
+ error: `Element '${args.elementId}' does not exist`,
961
+ candidates: [],
962
+ };
963
+ }
964
+ return { status: 'passed', element };
965
+ }
966
+
967
+ if (!args.elementName) {
968
+ return {
969
+ status: 'failed',
970
+ error: 'elementId or elementName is required',
971
+ candidates: [],
972
+ };
973
+ }
974
+
975
+ const matches = (document.elements || []).filter(element => element.name === args.elementName);
976
+ if (matches.length === 1) {
977
+ return { status: 'passed', element: matches[0] };
978
+ }
979
+ if (matches.length > 1) {
980
+ return {
981
+ status: 'ambiguous',
982
+ error: `Element name '${args.elementName}' matched multiple elements`,
983
+ candidates: matches.map(element => ({ id: element.id, name: element.name, type: element.type })),
984
+ };
985
+ }
986
+ return {
987
+ status: 'failed',
988
+ error: `Element name '${args.elementName}' does not exist`,
989
+ candidates: [],
990
+ };
991
+ }
992
+
993
+ function normalizeDepth(value, defaultValue) {
994
+ if (value === undefined || value === null || value === '') {
995
+ return defaultValue;
996
+ }
997
+ const numericValue = Number(value);
998
+ if (!Number.isFinite(numericValue) || numericValue < 0) {
999
+ return defaultValue;
1000
+ }
1001
+ return Math.floor(numericValue);
1002
+ }
1003
+
1004
+ function buildGraphIndex(document, ontology) {
1005
+ const relationshipById = new Map();
1006
+ const elementById = new Map((document.elements || []).map(element => [element.id, element]));
1007
+ const relationshipsByElementId = new Map();
1008
+ for (const relationship of document.relationships || []) {
1009
+ relationshipById.set(relationship.id, relationship);
1010
+ addIndexedRelationship(relationshipsByElementId, relationship.source_id, relationship);
1011
+ addIndexedRelationship(relationshipsByElementId, relationship.target_id, relationship);
1012
+ }
1013
+ const deliveryDependencies = ontology && ontology.deliveryDependencies
1014
+ ? ontology.deliveryDependencies
1015
+ : DEFAULT_DELIVERY_DEPENDENCIES;
1016
+ return { elementById, relationshipById, relationshipsByElementId, deliveryDependencies };
1017
+ }
1018
+
1019
+ // Dependency direction for the semantic-edge walk comes from the active schema
1020
+ // bundle's deliveryDependencies; this is the ArgoBument fallback by default.
1021
+ const DEFAULT_DELIVERY_DEPENDENCIES = Object.freeze({
1022
+ sourceDependsOnTarget: Object.freeze(['Access', 'Assignment', 'Specialization', 'Composition', 'Aggregation']),
1023
+ targetDependsOnSource: Object.freeze(['Serving', 'Realization', 'Flow', 'Triggering', 'Influence']),
1024
+ });
1025
+
1026
+ function addIndexedRelationship(index, elementId, relationship) {
1027
+ if (!index.has(elementId)) {
1028
+ index.set(elementId, []);
1029
+ }
1030
+ index.get(elementId).push(relationship);
1031
+ }
1032
+
1033
+ function traverseSemanticContext(options) {
1034
+ const {
1035
+ startId,
1036
+ maxDepth,
1037
+ mode,
1038
+ graphIndex,
1039
+ includedElementIds,
1040
+ includedRelationshipIds,
1041
+ depthByElement,
1042
+ } = options;
1043
+ if (maxDepth < 1) {
1044
+ return;
1045
+ }
1046
+
1047
+ const queue = [{ elementId: startId, depth: 0 }];
1048
+ for (let index = 0; index < queue.length; index += 1) {
1049
+ const current = queue[index];
1050
+ if (current.depth >= maxDepth) {
1051
+ continue;
1052
+ }
1053
+ for (const edge of resolveSemanticEdges(current.elementId, graphIndex)) {
1054
+ if (edge.kind !== mode) {
1055
+ continue;
1056
+ }
1057
+ const nextDepth = current.depth + 1;
1058
+ includedElementIds.add(edge.neighborId);
1059
+ includedRelationshipIds.add(edge.relationship.id);
1060
+ if (!depthByElement.has(edge.neighborId) || nextDepth < depthByElement.get(edge.neighborId)) {
1061
+ depthByElement.set(edge.neighborId, nextDepth);
1062
+ queue.push({ elementId: edge.neighborId, depth: nextDepth });
1063
+ }
1064
+ }
1065
+ }
1066
+ }
1067
+
1068
+ function resolveSemanticEdges(elementId, graphIndex) {
1069
+ const edges = [];
1070
+ for (const relationship of graphIndex.relationshipsByElementId.get(elementId) || []) {
1071
+ const isSource = relationship.source_id === elementId;
1072
+ const neighborId = isSource ? relationship.target_id : relationship.source_id;
1073
+ const relationshipType = relationship.type;
1074
+
1075
+ if (relationshipType === 'Association') {
1076
+ edges.push({ kind: 'association', neighborId, relationship });
1077
+ continue;
1078
+ }
1079
+
1080
+ const deliveryDependencies = graphIndex.deliveryDependencies || DEFAULT_DELIVERY_DEPENDENCIES;
1081
+ const sourceDependsOnTarget = deliveryDependencies.sourceDependsOnTarget.includes(relationshipType);
1082
+ const targetDependsOnSource = deliveryDependencies.targetDependsOnSource.includes(relationshipType);
1083
+ if (sourceDependsOnTarget) {
1084
+ edges.push({ kind: isSource ? 'dependency' : 'dependent', neighborId, relationship });
1085
+ continue;
1086
+ }
1087
+ if (targetDependsOnSource) {
1088
+ edges.push({ kind: isSource ? 'dependent' : 'dependency', neighborId, relationship });
1089
+ }
1090
+ }
1091
+ return edges;
1092
+ }
1093
+
1094
+ function includeViewAnchors(document, includedElementIds, includedRelationshipIds, graphIndex) {
1095
+ let changed = true;
1096
+ while (changed) {
1097
+ changed = false;
1098
+ for (const view of document.views || []) {
1099
+ if (!viewTouchesSubgraph(view, includedElementIds, includedRelationshipIds)) {
1100
+ continue;
1101
+ }
1102
+ if (view.parent_element_id && !includedElementIds.has(view.parent_element_id) && graphIndex.elementById.has(view.parent_element_id)) {
1103
+ includedElementIds.add(view.parent_element_id);
1104
+ changed = true;
1105
+ }
1106
+ }
1107
+ for (const elementId of Array.from(includedElementIds)) {
1108
+ const element = graphIndex.elementById.get(elementId);
1109
+ if (element && element.parent && !includedElementIds.has(element.parent) && graphIndex.elementById.has(element.parent)) {
1110
+ includedElementIds.add(element.parent);
1111
+ changed = true;
1112
+ }
1113
+ }
1114
+ }
1115
+ }
1116
+
1117
+ function viewTouchesSubgraph(view, includedElementIds, includedRelationshipIds) {
1118
+ return (view.included_elements || []).some(elementId => includedElementIds.has(elementId))
1119
+ || (view.included_relationships || []).some(relationshipId => includedRelationshipIds.has(relationshipId));
1120
+ }
1121
+
1122
+ function buildBoundary(options) {
1123
+ return {
1124
+ truncatedDependencies: collectTruncatedBoundary({
1125
+ ...options,
1126
+ depthByElement: mergeBoundaryDepths(options.dependencyDepthByElement, options.associationDepthByElement),
1127
+ maxDepth: options.dependencyDepth,
1128
+ kind: 'dependency',
1129
+ }),
1130
+ truncatedDependents: collectTruncatedBoundary({
1131
+ ...options,
1132
+ depthByElement: options.dependentDepthByElement,
1133
+ maxDepth: options.dependentDepth,
1134
+ kind: 'dependent',
1135
+ }),
1136
+ };
1137
+ }
1138
+
1139
+ function mergeBoundaryDepths(primaryDepths, associationDepths) {
1140
+ const merged = new Map(primaryDepths);
1141
+ for (const [elementId, depth] of associationDepths.entries()) {
1142
+ if (!merged.has(elementId) || depth < merged.get(elementId)) {
1143
+ merged.set(elementId, depth);
1144
+ }
1145
+ }
1146
+ return merged;
1147
+ }
1148
+
1149
+ function collectTruncatedBoundary(options) {
1150
+ const {
1151
+ graphIndex,
1152
+ includedElementIds,
1153
+ depthByElement,
1154
+ maxDepth,
1155
+ kind,
1156
+ } = options;
1157
+ const truncated = [];
1158
+ if (maxDepth < 0) {
1159
+ return truncated;
1160
+ }
1161
+ for (const [elementId, depth] of depthByElement.entries()) {
1162
+ if (depth < maxDepth && kind !== 'dependency') {
1163
+ continue;
1164
+ }
1165
+ const unexpandedEdges = resolveSemanticEdges(elementId, graphIndex).filter(edge => (
1166
+ (edge.kind === kind || (kind === 'dependency' && edge.kind === 'association'))
1167
+ && !includedElementIds.has(edge.neighborId)
1168
+ ));
1169
+ if (unexpandedEdges.length === 0) {
1170
+ continue;
1171
+ }
1172
+ const element = graphIndex.elementById.get(elementId);
1173
+ truncated.push({
1174
+ elementId,
1175
+ elementName: element ? element.name : undefined,
1176
+ direction: kind,
1177
+ remainingEdgeCount: unexpandedEdges.length,
1178
+ relationshipIds: unexpandedEdges.map(edge => edge.relationship.id),
1179
+ reason: `${kind} depth limit reached`,
1180
+ });
1181
+ }
1182
+ return truncated;
1183
+ }
1184
+
1185
+ function buildExplorationHints(boundary, defaults) {
1186
+ const hints = [];
1187
+ for (const entry of boundary.truncatedDependencies || []) {
1188
+ hints.push({
1189
+ reason: `Element ${entry.elementId} has unexpanded dependency context`,
1190
+ suggestedTool: 'getIntentElementContext',
1191
+ suggestedArguments: {
1192
+ elementId: entry.elementId,
1193
+ profile: defaults.profile,
1194
+ dependencyDepth: Math.max(1, defaults.dependencyDepth),
1195
+ dependentDepth: 0,
1196
+ associationDepth: defaults.associationDepth,
1197
+ },
1198
+ });
1199
+ }
1200
+ for (const entry of boundary.truncatedDependents || []) {
1201
+ hints.push({
1202
+ reason: `Element ${entry.elementId} has unexpanded dependent context`,
1203
+ suggestedTool: 'getIntentElementContext',
1204
+ suggestedArguments: {
1205
+ elementId: entry.elementId,
1206
+ profile: defaults.profile,
1207
+ dependencyDepth: 0,
1208
+ dependentDepth: Math.max(1, defaults.dependentDepth),
1209
+ associationDepth: defaults.associationDepth,
1210
+ },
1211
+ });
1212
+ }
1213
+ return hints;
1214
+ }
1215
+
1216
+ function buildNativeSubgraph(document, includedElementIds, includedRelationshipIds) {
1217
+ const elements = (document.elements || [])
1218
+ .filter(element => includedElementIds.has(element.id))
1219
+ .map(clone);
1220
+ const relationships = (document.relationships || [])
1221
+ .filter(relationship => includedRelationshipIds.has(relationship.id))
1222
+ .map(clone);
1223
+ const views = (document.views || [])
1224
+ .filter(view => viewTouchesSubgraph(view, includedElementIds, includedRelationshipIds))
1225
+ .map(view => {
1226
+ const viewCopy = clone(view);
1227
+ if (Array.isArray(viewCopy.included_elements)) {
1228
+ viewCopy.included_elements = viewCopy.included_elements.filter(elementId => includedElementIds.has(elementId));
1229
+ }
1230
+ if (Array.isArray(viewCopy.included_relationships)) {
1231
+ viewCopy.included_relationships = viewCopy.included_relationships.filter(relationshipId => includedRelationshipIds.has(relationshipId));
1232
+ }
1233
+ return viewCopy;
1234
+ });
1235
+ return { elements, relationships, views };
1236
+ }
1237
+
1238
+ /**
1239
+ * Attribute names that are MULTI-VALUED ledgers (many attributes share the same
1240
+ * `name` but carry distinct `value`s). The canonical example is the `commit`
1241
+ * ledger: an element accumulates one `{ name: 'commit', value: <sha> }` per
1242
+ * commit. For these, a patch entry upserts by (name, value) — a new value
1243
+ * APPENDS a new entry, re-registering the same value updates its description.
1244
+ */
1245
+ const MULTI_VALUE_ATTRIBUTE_NAMES = new Set(['commit']);
1246
+
1247
+ /**
1248
+ * Merge a targeted attribute patch into the element's existing attributes.
1249
+ *
1250
+ * Each patch entry is an object with a non-empty `name`:
1251
+ * - `{ name, op: 'remove' }` / `{ name, value, op: 'remove' }`
1252
+ * -> remove matching attribute(s); with `value`, only the exact entry.
1253
+ * - `{ name, value }` / `{ name, value, description }` -> upsert.
1254
+ *
1255
+ * Upsert semantics:
1256
+ * - Multi-valued ledgers (e.g. `commit`): match by (name, value). Same value
1257
+ * -> update description in place; new value -> APPEND a new entry.
1258
+ * - Single-valued attributes (e.g. `deliveryStatus`): match by name and
1259
+ * update value/description in place; absent -> append.
1260
+ *
1261
+ * Attributes NOT mentioned in the patch are preserved. This avoids the
1262
+ * full-array replacement footgun where updating one attribute would wipe out the
1263
+ * rest (e.g. a stale deliveryStatus being re-written when registering a commit
1264
+ * attribute), while still letting the commit ledger accumulate entries.
1265
+ */
1266
+ function mergeAttributesPatch(existing, patchEntries) {
1267
+ const result = Array.isArray(existing)
1268
+ ? existing.map(attr => ({ ...attr }))
1269
+ : [];
1270
+ if (!Array.isArray(patchEntries)) {
1271
+ throw new Error('patch.attributes must be an array of { name, ... } entries');
1272
+ }
1273
+ for (const entry of patchEntries) {
1274
+ if (!entry || typeof entry !== 'object' || typeof entry.name !== 'string' || entry.name.trim() === '') {
1275
+ throw new Error('patch.attributes entries must have a non-empty string name');
1276
+ }
1277
+ if (entry.op === 'remove') {
1278
+ // Remove ALL matching entries; when a value is given, restrict to that
1279
+ // exact (name, value) entry so a single ledger line can be removed.
1280
+ for (let i = result.length - 1; i >= 0; i -= 1) {
1281
+ const attr = result[i];
1282
+ const nameMatches = attr.name === entry.name;
1283
+ const valueMatches = !Object.prototype.hasOwnProperty.call(entry, 'value') || attr.value === entry.value;
1284
+ if (nameMatches && valueMatches) result.splice(i, 1);
1285
+ }
1286
+ continue;
1287
+ }
1288
+ if (MULTI_VALUE_ATTRIBUTE_NAMES.has(entry.name)) {
1289
+ const index = result.findIndex(attr => attr.name === entry.name && attr.value === entry.value);
1290
+ if (index >= 0) {
1291
+ if (Object.prototype.hasOwnProperty.call(entry, 'description')) result[index].description = entry.description;
1292
+ } else {
1293
+ const newAttribute = { name: entry.name };
1294
+ if (Object.prototype.hasOwnProperty.call(entry, 'value')) newAttribute.value = entry.value;
1295
+ if (Object.prototype.hasOwnProperty.call(entry, 'description')) newAttribute.description = entry.description;
1296
+ result.push(newAttribute);
1297
+ }
1298
+ } else {
1299
+ const index = result.findIndex(attr => attr.name === entry.name);
1300
+ if (index >= 0) {
1301
+ if (Object.prototype.hasOwnProperty.call(entry, 'value')) result[index].value = entry.value;
1302
+ if (Object.prototype.hasOwnProperty.call(entry, 'description')) result[index].description = entry.description;
1303
+ } else {
1304
+ const newAttribute = { name: entry.name };
1305
+ if (Object.prototype.hasOwnProperty.call(entry, 'value')) newAttribute.value = entry.value;
1306
+ if (Object.prototype.hasOwnProperty.call(entry, 'description')) newAttribute.description = entry.description;
1307
+ result.push(newAttribute);
1308
+ }
1309
+ }
1310
+ }
1311
+ return result;
1312
+ }
1313
+
1314
+ const DUPLICATE_CONFLICT_POLICIES = new Set(['reuse', 'allowDuplicate']);
1315
+
1316
+ // L0 dedup gate: normalize a name to a stable natural-key component. NFKC folds
1317
+ // full-width forms, whitespace is collapsed, and case is folded, so " Widget ",
1318
+ // "widget", and "Widget" all collide.
1319
+ function normalizeDedupName(value) {
1320
+ return String(value === undefined || value === null ? '' : value)
1321
+ .normalize('NFKC')
1322
+ .replace(/\s+/g, ' ')
1323
+ .trim()
1324
+ .toLowerCase();
1325
+ }
1326
+
1327
+ function findDuplicateElements(elements, element) {
1328
+ const nameKey = normalizeDedupName(element.name);
1329
+ return (elements || [])
1330
+ .filter(candidate => candidate && candidate.type === element.type && normalizeDedupName(candidate.name) === nameKey)
1331
+ .map(candidate => ({ id: candidate.id, type: candidate.type, name: candidate.name }));
1332
+ }
1333
+
1334
+ function findDuplicateRelationships(relationships, relationship) {
1335
+ const nameKey = normalizeDedupName(relationship.name);
1336
+ return (relationships || [])
1337
+ .filter(candidate => candidate
1338
+ && candidate.source_id === relationship.source_id
1339
+ && candidate.type === relationship.type
1340
+ && candidate.target_id === relationship.target_id
1341
+ && normalizeDedupName(candidate.name) === nameKey)
1342
+ .map(candidate => ({
1343
+ id: candidate.id,
1344
+ type: candidate.type,
1345
+ source_id: candidate.source_id,
1346
+ target_id: candidate.target_id,
1347
+ name: candidate.name,
1348
+ }));
1349
+ }
1350
+
1351
+ function findDuplicateViews(views, view) {
1352
+ const parentId = view.parent_element_id || '';
1353
+ const nameKey = normalizeDedupName(view.view_name);
1354
+ return (views || [])
1355
+ .filter(candidate => candidate
1356
+ && (candidate.parent_element_id || '') === parentId
1357
+ && normalizeDedupName(candidate.view_name) === nameKey)
1358
+ .map(candidate => ({
1359
+ view_id: candidate.view_id,
1360
+ view_name: candidate.view_name,
1361
+ parent_element_id: candidate.parent_element_id,
1362
+ }));
1363
+ }
1364
+
1365
+ // Resolve an add against its exact natural-key candidates under the caller's
1366
+ // onConflict policy: reuse (default) is find-or-create (attach the existing
1367
+ // object); allowDuplicate creates only with a non-empty justification. Semantic
1368
+ // similarity is handled separately (the semantic dedup gate), never here.
1369
+ function resolveDuplicateConflict(options, candidates) {
1370
+ const onConflict = options.onConflict === undefined || options.onConflict === null
1371
+ ? 'reuse'
1372
+ : options.onConflict;
1373
+ if (!DUPLICATE_CONFLICT_POLICIES.has(onConflict)) {
1374
+ throw new Error(`onConflict must be one of reuse, allowDuplicate (got '${onConflict}')`);
1375
+ }
1376
+ if (candidates.length === 0) {
1377
+ return { action: 'create' };
1378
+ }
1379
+ if (onConflict === 'reuse') {
1380
+ return { action: 'reuse', existing: candidates[0] };
1381
+ }
1382
+ if (typeof options.justification !== 'string' || options.justification.trim() === '') {
1383
+ const error = new Error(
1384
+ `onConflict "allowDuplicate" for ${options.label} requires a non-empty justification.`,
1385
+ );
1386
+ error.duplicateConflicts = candidates;
1387
+ throw error;
1388
+ }
1389
+ return { action: 'create', justification: options.justification };
1390
+ }
1391
+
1392
+ function applyMutations(document, mutations, options = {}) {
1393
+ const nextDocument = clone(document);
1394
+ const touchedElementIds = new Set();
1395
+ const touchedRelationshipIds = new Set();
1396
+ const touchedViewIds = new Set();
1397
+ const viewLimitCheckIds = new Set();
1398
+ const mutationSummaries = [];
1399
+
1400
+ if (!Array.isArray(mutations) || mutations.length === 0) {
1401
+ throw new Error('mutations must contain at least one mutation');
1402
+ }
1403
+
1404
+ for (const mutation of mutations) {
1405
+ if (!mutation || typeof mutation !== 'object' || !HANDLED_MUTATION_TYPES.has(mutation.type)) {
1406
+ throw new Error(`Unsupported mutation type: ${mutation && mutation.type}`);
1407
+ }
1408
+
1409
+ if (mutation.type === 'addElement') {
1410
+ requireObject(mutation.element, 'mutation.element');
1411
+ const scopedViews = requireViewScope(nextDocument.views, mutation.view_ids, 'mutation.view_ids');
1412
+ requireId(mutation.element.id, 'mutation.element.id');
1413
+ const existingElement = findById(nextDocument.elements, mutation.element.id);
1414
+ let targetElementId = mutation.element.id;
1415
+ let reusedElement = false;
1416
+ if (!existingElement) {
1417
+ const candidates = findDuplicateElements(nextDocument.elements, mutation.element);
1418
+ const resolution = resolveDuplicateConflict({
1419
+ onConflict: mutation.onConflict,
1420
+ justification: mutation.justification,
1421
+ label: `element (type '${mutation.element.type}', name '${mutation.element.name}')`,
1422
+ }, candidates);
1423
+ if (resolution.action === 'reuse') {
1424
+ targetElementId = resolution.existing.id;
1425
+ reusedElement = true;
1426
+ } else {
1427
+ nextDocument.elements.push(clone(mutation.element));
1428
+ syncViewsToElementSubdiagramViews(nextDocument, findById(nextDocument.elements, mutation.element.id));
1429
+ }
1430
+ }
1431
+ for (const view of scopedViews) {
1432
+ view.included_elements = addUnique(view.included_elements || [], [targetElementId]);
1433
+ touchedViewIds.add(view.view_id);
1434
+ viewLimitCheckIds.add(view.view_id);
1435
+ }
1436
+ touchedElementIds.add(targetElementId);
1437
+ mutationSummaries.push({
1438
+ type: mutation.type,
1439
+ id: targetElementId,
1440
+ view_ids: mutation.view_ids,
1441
+ created: !existingElement && !reusedElement,
1442
+ ...(reusedElement ? { reused: true, reusedId: targetElementId, requestedId: mutation.element.id } : {}),
1443
+ });
1444
+ continue;
1445
+ }
1446
+
1447
+ if (mutation.type === 'updateElement') {
1448
+ requireId(mutation.id, 'mutation.id');
1449
+ requireObject(mutation.patch, 'mutation.patch');
1450
+ const element = findById(nextDocument.elements, mutation.id);
1451
+ if (!element) {
1452
+ throw new Error(`Element '${mutation.id}' does not exist`);
1453
+ }
1454
+ requirePatchDoesNotChangeElementIdentityOrType(mutation.id, mutation.patch);
1455
+ const patchesSubdiagramViews = Object.prototype.hasOwnProperty.call(mutation.patch, 'subdiagram_views');
1456
+ const patchesName = Object.prototype.hasOwnProperty.call(mutation.patch, 'name');
1457
+ const patch = clone(mutation.patch);
1458
+ if (Object.prototype.hasOwnProperty.call(patch, 'attributes')) {
1459
+ // Targeted attribute merge by name (upsert / op:'remove'), preserving every
1460
+ // attribute not mentioned in the patch — never a full-array replacement,
1461
+ // so updating one attribute cannot wipe out the others.
1462
+ patch.attributes = mergeAttributesPatch(
1463
+ Array.isArray(element.attributes) ? element.attributes : [],
1464
+ patch.attributes,
1465
+ );
1466
+ }
1467
+ if (Array.isArray(patch.testcases)) {
1468
+ // G1: merge testcases by name so an omitted testcase is preserved; only
1469
+ // an explicit { name, op:'remove' } deletes one.
1470
+ patch.testcases = losslessWriteGate.mergeTestcasesPatch(
1471
+ Array.isArray(element.testcases) ? element.testcases : [],
1472
+ patch.testcases,
1473
+ );
1474
+ }
1475
+ Object.assign(element, patch);
1476
+ if (patchesSubdiagramViews || patchesName) {
1477
+ reconcileSubdiagramViewsForElement(nextDocument, element);
1478
+ }
1479
+ touchedElementIds.add(element.id);
1480
+ mutationSummaries.push({ type: mutation.type, id: element.id });
1481
+ continue;
1482
+ }
1483
+
1484
+ if (mutation.type === 'removeElement') {
1485
+ requireId(mutation.id, 'mutation.id');
1486
+ const element = findById(nextDocument.elements, mutation.id);
1487
+ if (!element) {
1488
+ throw new Error(`Element '${mutation.id}' does not exist`);
1489
+ }
1490
+ const childViewIds = collectChildViewIds(nextDocument, mutation.id);
1491
+ if (childViewIds.length > 0) {
1492
+ throw new Error(`Element '${mutation.id}' cannot be removed: it still has ${childViewIds.length} sub-view(s) mounted under it (${childViewIds.join(', ')}). Remove or re-parent those sub-views first.`);
1493
+ }
1494
+ const scopedViews = mutation.view_ids === undefined
1495
+ ? nextDocument.views
1496
+ : requireViewScope(nextDocument.views, mutation.view_ids, 'mutation.view_ids');
1497
+ const relatedRelationshipIds = nextDocument.relationships
1498
+ .filter(relationship => relationship.source_id === mutation.id || relationship.target_id === mutation.id)
1499
+ .map(relationship => relationship.id);
1500
+ for (const view of scopedViews) {
1501
+ view.included_elements = removeEntries(view.included_elements || [], [mutation.id]);
1502
+ view.included_relationships = removeEntries(view.included_relationships || [], relatedRelationshipIds);
1503
+ touchedViewIds.add(view.view_id);
1504
+ }
1505
+ const stillIncludedInView = nextDocument.views.some(view => (
1506
+ Array.isArray(view.included_elements) && view.included_elements.includes(mutation.id)
1507
+ ));
1508
+ if (!stillIncludedInView) {
1509
+ for (const view of nextDocument.views) {
1510
+ view.included_relationships = removeEntries(view.included_relationships || [], relatedRelationshipIds);
1511
+ touchedViewIds.add(view.view_id);
1512
+ }
1513
+ nextDocument.elements = nextDocument.elements.filter(entry => entry.id !== mutation.id);
1514
+ }
1515
+ const relationshipIdsStillInViews = new Set();
1516
+ for (const view of nextDocument.views) {
1517
+ for (const relationshipId of view.included_relationships || []) {
1518
+ relationshipIdsStillInViews.add(relationshipId);
1519
+ }
1520
+ }
1521
+ nextDocument.relationships = nextDocument.relationships.filter(relationship => (
1522
+ !relatedRelationshipIds.includes(relationship.id) || relationshipIdsStillInViews.has(relationship.id)
1523
+ ));
1524
+ touchedElementIds.add(mutation.id);
1525
+ for (const relationshipId of relatedRelationshipIds) {
1526
+ touchedRelationshipIds.add(relationshipId);
1527
+ }
1528
+ mutationSummaries.push({
1529
+ type: mutation.type,
1530
+ id: mutation.id,
1531
+ view_ids: mutation.view_ids,
1532
+ removed_from_graph: !stillIncludedInView,
1533
+ removed_relationship_ids: relatedRelationshipIds.filter(relationshipId => !relationshipIdsStillInViews.has(relationshipId)),
1534
+ });
1535
+ continue;
1536
+ }
1537
+
1538
+ if (mutation.type === 'addRelationship') {
1539
+ requireObject(mutation.relationship, 'mutation.relationship');
1540
+ const scopedViews = requireViewScope(nextDocument.views, mutation.view_ids, 'mutation.view_ids');
1541
+ requireId(mutation.relationship.id, 'mutation.relationship.id');
1542
+ const existingRelationship = findById(nextDocument.relationships, mutation.relationship.id);
1543
+ let targetRelationshipId = mutation.relationship.id;
1544
+ let sourceElementId = mutation.relationship.source_id;
1545
+ let targetEndpointId = mutation.relationship.target_id;
1546
+ let reusedRelationship = false;
1547
+ if (!existingRelationship) {
1548
+ const candidates = findDuplicateRelationships(nextDocument.relationships, mutation.relationship);
1549
+ const resolution = resolveDuplicateConflict({
1550
+ onConflict: mutation.onConflict,
1551
+ justification: mutation.justification,
1552
+ label: `relationship (source '${mutation.relationship.source_id}', type '${mutation.relationship.type}', target '${mutation.relationship.target_id}', name '${mutation.relationship.name || ''}')`,
1553
+ }, candidates);
1554
+ if (resolution.action === 'reuse') {
1555
+ targetRelationshipId = resolution.existing.id;
1556
+ sourceElementId = resolution.existing.source_id;
1557
+ targetEndpointId = resolution.existing.target_id;
1558
+ reusedRelationship = true;
1559
+ } else {
1560
+ nextDocument.relationships.push(clone(mutation.relationship));
1561
+ }
1562
+ }
1563
+ for (const view of scopedViews) {
1564
+ view.included_elements = addUnique(view.included_elements || [], [
1565
+ sourceElementId,
1566
+ targetEndpointId,
1567
+ ]);
1568
+ view.included_relationships = addUnique(view.included_relationships || [], [targetRelationshipId]);
1569
+ touchedViewIds.add(view.view_id);
1570
+ }
1571
+ touchedRelationshipIds.add(targetRelationshipId);
1572
+ mutationSummaries.push({
1573
+ type: mutation.type,
1574
+ id: targetRelationshipId,
1575
+ view_ids: mutation.view_ids,
1576
+ created: !existingRelationship && !reusedRelationship,
1577
+ ...(reusedRelationship ? { reused: true, reusedId: targetRelationshipId, requestedId: mutation.relationship.id } : {}),
1578
+ });
1579
+ continue;
1580
+ }
1581
+
1582
+ if (mutation.type === 'updateRelationship') {
1583
+ requireId(mutation.id, 'mutation.id');
1584
+ requireObject(mutation.patch, 'mutation.patch');
1585
+ const relationship = findById(nextDocument.relationships, mutation.id);
1586
+ if (!relationship) {
1587
+ throw new Error(`Relationship '${mutation.id}' does not exist`);
1588
+ }
1589
+ requirePatchDoesNotChangeRelationshipIdentityOrType(mutation.id, mutation.patch);
1590
+ const oldSourceId = relationship.source_id;
1591
+ const oldTargetId = relationship.target_id;
1592
+ const relationshipPatch = clone(mutation.patch);
1593
+ if (Array.isArray(relationshipPatch.attributes)) {
1594
+ // G1: merge relationship attributes by name (unmentioned preserved).
1595
+ relationshipPatch.attributes = losslessWriteGate.mergeRelationshipAttributesPatch(
1596
+ Array.isArray(relationship.attributes) ? relationship.attributes : [],
1597
+ relationshipPatch.attributes,
1598
+ );
1599
+ }
1600
+ Object.assign(relationship, relationshipPatch);
1601
+ for (const view of nextDocument.views) {
1602
+ if (!(view.included_relationships || []).includes(relationship.id)) {
1603
+ continue;
1604
+ }
1605
+ view.included_elements = addUnique(view.included_elements || [], [
1606
+ relationship.source_id,
1607
+ relationship.target_id,
1608
+ ]);
1609
+ for (const oldEndpointId of [oldSourceId, oldTargetId]) {
1610
+ if (oldEndpointId === relationship.source_id || oldEndpointId === relationship.target_id) {
1611
+ continue;
1612
+ }
1613
+ if (isElementUsedByRelationship(nextDocument, view, oldEndpointId, relationship.id)) {
1614
+ continue;
1615
+ }
1616
+ view.included_elements = removeEntries(view.included_elements || [], [oldEndpointId]);
1617
+ }
1618
+ }
1619
+ touchedRelationshipIds.add(relationship.id);
1620
+ mutationSummaries.push({ type: mutation.type, id: relationship.id });
1621
+ continue;
1622
+ }
1623
+
1624
+ if (mutation.type === 'removeRelationship') {
1625
+ requireId(mutation.id, 'mutation.id');
1626
+ const relationship = findById(nextDocument.relationships, mutation.id);
1627
+ if (!relationship) {
1628
+ throw new Error(`Relationship '${mutation.id}' does not exist`);
1629
+ }
1630
+ const scopedViews = mutation.view_ids === undefined
1631
+ ? nextDocument.views
1632
+ : requireViewScope(nextDocument.views, mutation.view_ids, 'mutation.view_ids');
1633
+ for (const view of scopedViews) {
1634
+ view.included_relationships = removeEntries(view.included_relationships || [], [mutation.id]);
1635
+ for (const endpointId of [relationship.source_id, relationship.target_id]) {
1636
+ if (isElementUsedByRelationship(nextDocument, view, endpointId, mutation.id)) {
1637
+ continue;
1638
+ }
1639
+ view.included_elements = removeEntries(view.included_elements || [], [endpointId]);
1640
+ }
1641
+ touchedViewIds.add(view.view_id);
1642
+ }
1643
+ const stillIncludedInView = nextDocument.views.some(view => (
1644
+ Array.isArray(view.included_relationships) && view.included_relationships.includes(mutation.id)
1645
+ ));
1646
+ if (!stillIncludedInView) {
1647
+ nextDocument.relationships = nextDocument.relationships.filter(entry => entry.id !== mutation.id);
1648
+ }
1649
+ touchedRelationshipIds.add(mutation.id);
1650
+ mutationSummaries.push({
1651
+ type: mutation.type,
1652
+ id: mutation.id,
1653
+ view_ids: mutation.view_ids,
1654
+ removed_from_graph: !stillIncludedInView,
1655
+ });
1656
+ continue;
1657
+ }
1658
+
1659
+ if (mutation.type === 'addView') {
1660
+ requireObject(mutation.view, 'mutation.view');
1661
+ if (findView(nextDocument.views, mutation.view.view_id)) {
1662
+ throw new Error(`View '${mutation.view.view_id}' already exists`);
1663
+ }
1664
+ const candidates = findDuplicateViews(nextDocument.views, mutation.view);
1665
+ const resolution = resolveDuplicateConflict({
1666
+ onConflict: mutation.onConflict,
1667
+ justification: mutation.justification,
1668
+ label: `view (name '${mutation.view.view_name}')`,
1669
+ }, candidates);
1670
+ if (resolution.action === 'reuse') {
1671
+ mutationSummaries.push({
1672
+ type: mutation.type,
1673
+ id: resolution.existing.view_id,
1674
+ created: false,
1675
+ reused: true,
1676
+ reusedId: resolution.existing.view_id,
1677
+ requestedId: mutation.view.view_id,
1678
+ });
1679
+ } else {
1680
+ const newView = clone(mutation.view);
1681
+ if (Array.isArray(newView.included_elements)) {
1682
+ newView.included_elements = addUnique([], newView.included_elements);
1683
+ }
1684
+ if (Array.isArray(newView.included_relationships)) {
1685
+ newView.included_relationships = addUnique([], newView.included_relationships);
1686
+ }
1687
+ nextDocument.views.push(newView);
1688
+ upsertSubdiagramViewIntoElement(nextDocument, newView.parent_element_id, newView);
1689
+ touchedViewIds.add(newView.view_id);
1690
+ viewLimitCheckIds.add(newView.view_id);
1691
+ mutationSummaries.push({ type: mutation.type, id: newView.view_id });
1692
+ }
1693
+ continue;
1694
+ }
1695
+
1696
+ if (mutation.type === 'updateView') {
1697
+ const viewId = mutation.view_id || mutation.id;
1698
+ requireId(viewId, 'mutation.view_id');
1699
+ requireObject(mutation.patch, 'mutation.patch');
1700
+ const view = findView(nextDocument.views, viewId);
1701
+ if (!view) {
1702
+ throw new Error(`View '${viewId}' does not exist`);
1703
+ }
1704
+ const oldParentId = view.parent_element_id;
1705
+ const oldViewId = view.view_id;
1706
+ const patch = clone(mutation.patch);
1707
+ if (Object.prototype.hasOwnProperty.call(patch, 'included_elements')) {
1708
+ // G1: full list (legacy replace) or lossless delta { add, remove }.
1709
+ patch.included_elements = losslessWriteGate.applyViewMembershipPatch(view.included_elements || [], patch.included_elements).list;
1710
+ }
1711
+ if (Object.prototype.hasOwnProperty.call(patch, 'included_relationships')) {
1712
+ patch.included_relationships = losslessWriteGate.applyViewMembershipPatch(view.included_relationships || [], patch.included_relationships).list;
1713
+ }
1714
+ Object.assign(view, patch);
1715
+ if (oldParentId !== view.parent_element_id) {
1716
+ removeSubdiagramViewFromElement(nextDocument, oldParentId, oldViewId);
1717
+ }
1718
+ upsertSubdiagramViewIntoElement(nextDocument, view.parent_element_id, view);
1719
+ touchedViewIds.add(view.view_id);
1720
+ if (Object.prototype.hasOwnProperty.call(mutation.patch, 'included_elements')) {
1721
+ viewLimitCheckIds.add(view.view_id);
1722
+ }
1723
+ mutationSummaries.push({ type: mutation.type, id: view.view_id });
1724
+ continue;
1725
+ }
1726
+
1727
+ if (mutation.type === 'removeView') {
1728
+ requireId(mutation.view_id, 'mutation.view_id');
1729
+ const view = findView(nextDocument.views, mutation.view_id);
1730
+ if (!view) {
1731
+ throw new Error(`View '${mutation.view_id}' does not exist`);
1732
+ }
1733
+ removeSubdiagramViewFromElement(nextDocument, view.parent_element_id, mutation.view_id);
1734
+ nextDocument.views = nextDocument.views.filter(entry => entry.view_id !== mutation.view_id);
1735
+ touchedViewIds.add(mutation.view_id);
1736
+ mutationSummaries.push({ type: mutation.type, id: mutation.view_id });
1737
+ continue;
1738
+ }
1739
+
1740
+ }
1741
+
1742
+ return {
1743
+ document: nextDocument,
1744
+ touchedElementIds: Array.from(touchedElementIds),
1745
+ touchedRelationshipIds: Array.from(touchedRelationshipIds),
1746
+ touchedViewIds: Array.from(touchedViewIds),
1747
+ viewLimitCheckIds: Array.from(viewLimitCheckIds),
1748
+ mutationSummaries,
1749
+ lossReport: losslessWriteGate.buildLossReport({
1750
+ baseDocument: document,
1751
+ mutations,
1752
+ nextDocument,
1753
+ lossAck: options.lossAck,
1754
+ }),
1755
+ };
1756
+ }
1757
+
1758
+ function requireObject(value, label) {
1759
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
1760
+ throw new Error(`${label} must be an object`);
1761
+ }
1762
+ }
1763
+
1764
+ function requireId(value, label) {
1765
+ if (typeof value !== 'string' || value.length === 0) {
1766
+ throw new Error(`${label} must be a non-empty string`);
1767
+ }
1768
+ }
1769
+
1770
+ function requireViewScope(views, viewIds, label) {
1771
+ if (!Array.isArray(viewIds) || viewIds.length === 0) {
1772
+ throw new Error(`${label} must contain at least one view id`);
1773
+ }
1774
+
1775
+ const scopedViews = [];
1776
+ const seenViewIds = new Set();
1777
+ for (const viewId of viewIds) {
1778
+ requireId(viewId, `${label}[]`);
1779
+ if (seenViewIds.has(viewId)) {
1780
+ continue;
1781
+ }
1782
+ const view = findView(views, viewId);
1783
+ if (!view) {
1784
+ throw new Error(`View '${viewId}' does not exist`);
1785
+ }
1786
+ scopedViews.push(view);
1787
+ seenViewIds.add(viewId);
1788
+ }
1789
+ return scopedViews;
1790
+ }
1791
+
1792
+ function requirePatchDoesNotChangeElementIdentityOrType(elementId, patch) {
1793
+ if (Object.prototype.hasOwnProperty.call(patch, 'id')) {
1794
+ throw new Error(`Element '${elementId}' id cannot be updated; remove and re-add the element to change its id`);
1795
+ }
1796
+ if (Object.prototype.hasOwnProperty.call(patch, 'type')) {
1797
+ throw new Error(`Element '${elementId}' type cannot be updated; remove and re-add the element to change its type`);
1798
+ }
1799
+ }
1800
+
1801
+ function requirePatchDoesNotChangeRelationshipIdentityOrType(relationshipId, patch) {
1802
+ if (Object.prototype.hasOwnProperty.call(patch, 'id')) {
1803
+ throw new Error(`Relationship '${relationshipId}' id cannot be updated; remove and re-add the relationship to change its id`);
1804
+ }
1805
+ if (Object.prototype.hasOwnProperty.call(patch, 'type')) {
1806
+ throw new Error(`Relationship '${relationshipId}' type cannot be updated; remove and re-add the relationship to change its type`);
1807
+ }
1808
+ }
1809
+
1810
+ function findById(entries, id) {
1811
+ return Array.isArray(entries) ? entries.find(entry => entry && entry.id === id) : undefined;
1812
+ }
1813
+
1814
+ function findView(entries, viewId) {
1815
+ return Array.isArray(entries) ? entries.find(entry => entry && entry.view_id === viewId) : undefined;
1816
+ }
1817
+
1818
+ function removeSubdiagramViewFromElement(document, elementId, viewId) {
1819
+ if (!elementId || !viewId) {
1820
+ return;
1821
+ }
1822
+ const element = findById(document.elements, elementId);
1823
+ if (!element || !Array.isArray(element.subdiagram_views)) {
1824
+ return;
1825
+ }
1826
+ element.subdiagram_views = element.subdiagram_views.filter(entry => !(entry && entry.view_id === viewId));
1827
+ }
1828
+
1829
+ function upsertSubdiagramViewIntoElement(document, elementId, view) {
1830
+ if (!elementId || !view || !view.view_id) {
1831
+ return;
1832
+ }
1833
+ const element = findById(document.elements, elementId);
1834
+ if (!element) {
1835
+ return;
1836
+ }
1837
+ if (!Array.isArray(element.subdiagram_views)) {
1838
+ element.subdiagram_views = [];
1839
+ }
1840
+ const existing = element.subdiagram_views.find(entry => entry && entry.view_id === view.view_id);
1841
+ if (existing) {
1842
+ existing.view_name = view.view_name;
1843
+ } else {
1844
+ element.subdiagram_views.push({ view_id: view.view_id, view_name: view.view_name });
1845
+ }
1846
+ }
1847
+
1848
+ // Forward-sync: make every view listed in `element.subdiagram_views` point back
1849
+ // to this element (stealing the view from any previous parent when necessary).
1850
+ function syncViewsToElementSubdiagramViews(document, element) {
1851
+ if (!element || !Array.isArray(element.subdiagram_views)) {
1852
+ return;
1853
+ }
1854
+ for (const entry of element.subdiagram_views) {
1855
+ if (!entry || !entry.view_id) {
1856
+ continue;
1857
+ }
1858
+ const view = findView(document.views, entry.view_id);
1859
+ if (!view) {
1860
+ continue;
1861
+ }
1862
+ if (view.parent_element_id && view.parent_element_id !== element.id) {
1863
+ removeSubdiagramViewFromElement(document, view.parent_element_id, view.view_id);
1864
+ }
1865
+ view.parent_element_id = element.id;
1866
+ view.parent_element_name = element.name;
1867
+ }
1868
+ }
1869
+
1870
+ // Bidirectional sync after an element's subdiagram_views (or name) changed:
1871
+ // listed views point back, and views no longer listed stop pointing at this element.
1872
+ function reconcileSubdiagramViewsForElement(document, element) {
1873
+ const currentViewIds = new Set(
1874
+ (element.subdiagram_views || [])
1875
+ .filter(entry => entry && entry.view_id)
1876
+ .map(entry => entry.view_id),
1877
+ );
1878
+ syncViewsToElementSubdiagramViews(document, element);
1879
+ for (const view of document.views || []) {
1880
+ if (view && view.parent_element_id === element.id && !currentViewIds.has(view.view_id)) {
1881
+ delete view.parent_element_id;
1882
+ delete view.parent_element_name;
1883
+ }
1884
+ }
1885
+ }
1886
+
1887
+ function collectChildViewIds(document, elementId) {
1888
+ const viewIds = new Set();
1889
+ const element = findById(document.elements, elementId);
1890
+ if (element && Array.isArray(element.subdiagram_views)) {
1891
+ for (const entry of element.subdiagram_views) {
1892
+ if (entry && entry.view_id) {
1893
+ viewIds.add(entry.view_id);
1894
+ }
1895
+ }
1896
+ }
1897
+ for (const view of document.views || []) {
1898
+ if (view && view.parent_element_id === elementId && view.view_id) {
1899
+ viewIds.add(view.view_id);
1900
+ }
1901
+ }
1902
+ return Array.from(viewIds);
1903
+ }
1904
+
1905
+ // Whether any relationship in the view (other than exceptRelationshipId) still
1906
+ // references elementId as one of its endpoints.
1907
+ function isElementUsedByRelationship(document, view, elementId, exceptRelationshipId) {
1908
+ for (const relationshipId of view.included_relationships || []) {
1909
+ if (relationshipId === exceptRelationshipId) {
1910
+ continue;
1911
+ }
1912
+ const relationship = findById(document.relationships, relationshipId);
1913
+ if (relationship && (relationship.source_id === elementId || relationship.target_id === elementId)) {
1914
+ return true;
1915
+ }
1916
+ }
1917
+ return false;
1918
+ }
1919
+
1920
+ function addUnique(existing, additions) {
1921
+ const result = Array.isArray(existing) ? [...existing] : [];
1922
+ for (const addition of additions) {
1923
+ if (!result.includes(addition)) {
1924
+ result.push(addition);
1925
+ }
1926
+ }
1927
+ return result;
1928
+ }
1929
+
1930
+ function removeEntries(existing, removals) {
1931
+ const removalSet = new Set(removals);
1932
+ return (Array.isArray(existing) ? existing : []).filter(entry => !removalSet.has(entry));
1933
+ }
1934
+
1935
+ async function buildMutationResult(context, mutations, write, dependencies, lossAck) {
1936
+ markPhase('mutation:' + (write ? 'apply' : 'preview'));
1937
+ const beforeSummary = summarizeDocument(context.document);
1938
+ let mutationResult;
1939
+ try {
1940
+ mutationResult = applyMutations(context.document, mutations, { lossAck });
1941
+ } catch (error) {
1942
+ const errors = [String(error && error.message ? error.message : error)];
1943
+ const failed = {
1944
+ status: 'failed',
1945
+ written: false,
1946
+ graphPath: context.graphPath.relativePath,
1947
+ schemaPath: context.schemaPath.relativePath,
1948
+ mutations: [],
1949
+ touchedElementIds: [],
1950
+ touchedRelationshipIds: [],
1951
+ before: beforeSummary,
1952
+ after: beforeSummary,
1953
+ errors,
1954
+ guidance: buildFailureGuidance(errors, context.ontology),
1955
+ };
1956
+ if (error && Array.isArray(error.duplicateConflicts) && error.duplicateConflicts.length > 0) {
1957
+ failed.duplicateConflicts = error.duplicateConflicts;
1958
+ failed.guidance = addUnique(failed.guidance || [], [
1959
+ 'Duplicate write blocked (L0 dedup gate): reuse the existing id with onConflict:"reuse" (find-or-create), or pass onConflict:"allowDuplicate" with a non-empty justification to create a new object.',
1960
+ ]);
1961
+ }
1962
+ return failed;
1963
+ }
1964
+ const errors = validateDocument(mutationResult.document, context.schema, {
1965
+ ontology: context.ontology,
1966
+ touchedRelationshipIds: mutationResult.touchedRelationshipIds,
1967
+ touchedViewIds: mutationResult.viewLimitCheckIds,
1968
+ });
1969
+ const afterSummary = summarizeDocument(mutationResult.document);
1970
+ const result = {
1971
+ status: errors.length === 0 ? 'passed' : 'failed',
1972
+ written: false,
1973
+ graphPath: context.graphPath.relativePath,
1974
+ schemaPath: context.schemaPath.relativePath,
1975
+ mutations: mutationResult.mutationSummaries,
1976
+ touchedElementIds: mutationResult.touchedElementIds,
1977
+ touchedRelationshipIds: mutationResult.touchedRelationshipIds,
1978
+ touchedViewIds: mutationResult.touchedViewIds,
1979
+ viewLimitCheckIds: mutationResult.viewLimitCheckIds,
1980
+ before: beforeSummary,
1981
+ after: afterSummary,
1982
+ errors,
1983
+ };
1984
+ if (errors.length > 0) {
1985
+ result.guidance = buildFailureGuidance(errors, context.ontology);
1986
+ }
1987
+
1988
+ // Semantic dedup gate: a would-be element create is blocked when a same-type
1989
+ // semantic near-duplicate exists, unless the caller explicitly passed
1990
+ // onConflict:'allowDuplicate' (with justification). Never blocks on an
1991
+ // unavailable semantic backend. Both preview and apply surface the outcome.
1992
+ let semanticBlocked = false;
1993
+ if (errors.length === 0) {
1994
+ const createdAdds = selectCreatedElementAdds(mutations, mutationResult.mutationSummaries);
1995
+ const semanticDedup = await buildSemanticDedupAdvisory(context, createdAdds, dependencies);
1996
+ if (semanticDedup) {
1997
+ result.semanticDedup = semanticDedup;
1998
+ const gate = evaluateSemanticDedupGate(semanticDedup, createdAdds);
1999
+ if (gate.blocked) {
2000
+ semanticBlocked = true;
2001
+ result.status = 'failed';
2002
+ result.after = beforeSummary;
2003
+ result.semanticConflicts = gate.conflicts;
2004
+ result.errors = gate.conflicts.map(entry => (
2005
+ `Semantic duplicate for element (type '${entry.requested.type}', name '${entry.requested.name}'): `
2006
+ + `${entry.matches.map(match => `${match.id} (score ${match.score})`).join(', ')}. `
2007
+ + 'Reuse the existing element (re-call with that element id), or pass onConflict:"allowDuplicate" with a justification to create a new one.'
2008
+ ));
2009
+ result.guidance = addUnique(result.guidance || [], result.errors);
2010
+ }
2011
+ }
2012
+ }
2013
+
2014
+ // Lossless write gate: block any unacknowledged content reduction (text shrink,
2015
+ // membership drop, destructive removal). Preview reports it too (status failed)
2016
+ // so the loss is visible before writing.
2017
+ const lossReport = mutationResult.lossReport;
2018
+ const hasLoss = lossReport && (
2019
+ lossReport.text.length > 0
2020
+ || lossReport.membersRemoved.length > 0
2021
+ || lossReport.objectsRemoved.length > 0
2022
+ || lossReport.testcasesRemoved.length > 0
2023
+ );
2024
+ let losslessBlocked = false;
2025
+ if (hasLoss) {
2026
+ result.lossless = lossReport;
2027
+ if (errors.length === 0 && lossReport.blocked) {
2028
+ losslessBlocked = true;
2029
+ result.status = 'failed';
2030
+ result.after = beforeSummary;
2031
+ result.errors = lossReport.reasons;
2032
+ result.guidance = addUnique(result.guidance || [], [
2033
+ ...lossReport.reasons,
2034
+ 'Lossless write gate: read the current value first. For an intentional text rewrite pass acknowledgeLoss:true (and lossJustification for major loss); for a destructive removal pass acknowledgeLoss:true (a tombstone snapshot is recorded). Prefer lossless forms: testcases merge by name, view membership delta { add, remove }.',
2035
+ ]);
2036
+ }
2037
+ }
2038
+
2039
+ if (errors.length > 0 || semanticBlocked || losslessBlocked || !write) {
2040
+ return result;
2041
+ }
2042
+
2043
+ writeGraph(context.graphPath.absolutePath, mutationResult.document);
2044
+ result.written = true;
2045
+
2046
+ {
2047
+ const removedObjects = losslessWriteGate.collectRemovedObjects(context.document, mutations, mutationResult.document);
2048
+ if (removedObjects.length > 0) {
2049
+ try {
2050
+ const tomb = losslessWriteGate.appendTombstones(context.graphPath.absolutePath, removedObjects);
2051
+ result.tombstones = { status: 'passed', path: tomb.path, count: tomb.count };
2052
+ } catch (error) {
2053
+ const message = String(error && error.message ? error.message : error);
2054
+ result.tombstones = { status: 'failed', error: message };
2055
+ result.warnings = addUnique(result.warnings || [], ['tombstone snapshot failed (non-fatal): ' + message]);
2056
+ }
2057
+ }
2058
+ }
2059
+
2060
+ // WP2791: .qea projection parallel to the Neo4j trigger — non-fatal, best-effort,
2061
+ // but ALWAYS reported on the result (passed / failed / noop+reason) so a missing EA
2062
+ // update is never silent.
2063
+ {
2064
+ markPhase('mutation:qeaProjection');
2065
+ const resolved = resolveQeaProjectionTarget(context);
2066
+ const qeaTarget = resolved && resolved.target;
2067
+ if (qeaTarget) {
2068
+ try {
2069
+ const projection = await runQeaProjection(qeaTarget);
2070
+ if (projection.ok) {
2071
+ result.qeaProjection = { status: 'passed', qea: qeaTarget.qeaPath, ms: projection.ms };
2072
+ } else {
2073
+ result.qeaProjection = { status: 'failed', qea: qeaTarget.qeaPath, error: projection.error || ('exit ' + projection.code), ms: projection.ms };
2074
+ result.warnings = addUnique(result.warnings || [], ['ea-qea projection failed (non-fatal): ' + (projection.error || ('exit code ' + projection.code))]);
2075
+ }
2076
+ } catch (error) {
2077
+ result.qeaProjection = { status: 'failed', error: String(error && error.message ? error.message : error) };
2078
+ result.warnings = addUnique(result.warnings || [], ['ea-qea projection error (non-fatal): ' + String(error && error.message ? error.message : error)]);
2079
+ }
2080
+ } else {
2081
+ result.qeaProjection = {
2082
+ status: 'noop',
2083
+ reason: (resolved && resolved.reason) || 'no .qea target',
2084
+ workspaceRoot: context.workspaceRoot,
2085
+ };
2086
+ if (resolved && resolved.hasEaSignals) {
2087
+ result.warnings = addUnique(result.warnings || [], ['ea-qea projection not run: ' + ((resolved && resolved.reason) || 'no .qea target')]);
2088
+ }
2089
+ }
2090
+ }
2091
+
2092
+ if (shouldSyncCanonicalGraphToNeo4j(context.graphPath.relativePath)) {
2093
+ markPhase('mutation:neo4jSync');
2094
+ try {
2095
+ const syncResult = await syncArchitectureToNeo4j({
2096
+ architecturePath: context.graphPath.relativePath,
2097
+ document: mutationResult.document,
2098
+ workspaceRoot: context.workspaceRoot,
2099
+ });
2100
+ result.neo4jSync = {
2101
+ status: 'passed',
2102
+ graphKey: syncResult.graphKey,
2103
+ counts: syncResult.counts,
2104
+ };
2105
+ } catch (error) {
2106
+ const errorMessage = String(error && error.message ? error.message : error);
2107
+ result.neo4jSync = {
2108
+ status: 'failed',
2109
+ error: errorMessage,
2110
+ };
2111
+ result.warnings = addUnique(result.warnings || [], [
2112
+ `SystemArchitecture.json was written, but Neo4j sync failed: ${errorMessage}`,
2113
+ 'Run node .argo/scripts/syncSystemArchitectureToNeo4j.js to rebuild the Neo4j projection for the canonical intent graph.',
2114
+ ]);
2115
+ }
2116
+ }
2117
+
2118
+ markPhase('mutation:embeddingLifecycle');
2119
+ await attachMutationEmbeddingLifecycle(context, result, mutationResult.document);
2120
+ markPhase('mutation:done');
2121
+
2122
+ return result;
2123
+ }
2124
+
2125
+ function shouldSyncCanonicalGraphToNeo4j(relativeGraphPath) {
2126
+ return normalizeRelativePath(relativeGraphPath) === normalizeRelativePath(NEO4J_DEFAULT_GRAPH_PATH);
2127
+ }
2128
+
2129
+ async function attachMutationEmbeddingLifecycle(context, result, document) {
2130
+ if (!shouldRunMutationEmbeddingLifecycle(result)) {
2131
+ return;
2132
+ }
2133
+ try {
2134
+ const lifecycle = require(
2135
+ './graph-rag/mutationEmbeddingVectorLifecycle.js'
2136
+ ).createPersistentMutationEmbeddingLifecycle({
2137
+ repositoryRoot: context.workspaceRoot,
2138
+ });
2139
+ const embeddingLifecycle = await lifecycle.reconcile({
2140
+ canonicalWrite: {
2141
+ written: true,
2142
+ architecturePath: result.graphPath,
2143
+ document,
2144
+ mutations: result.mutations,
2145
+ touchedElementIds: result.touchedElementIds,
2146
+ touchedRelationshipIds: result.touchedRelationshipIds,
2147
+ touchedViewIds: result.touchedViewIds,
2148
+ },
2149
+ preview: false,
2150
+ gates: {
2151
+ [LIVE_PROVIDER_OPT_IN]: process.env[LIVE_PROVIDER_OPT_IN],
2152
+ [W31_LIVE_OPT_IN]: process.env[W31_LIVE_OPT_IN],
2153
+ },
2154
+ });
2155
+ result.embeddingLifecycle = embeddingLifecycle;
2156
+ result.alignment = embeddingLifecycle.alignment || buildMutationAlignment(embeddingLifecycle);
2157
+ result.businessComplete = result.alignment && result.alignment.state === 'Aligned';
2158
+ } catch (error) {
2159
+ result.embeddingLifecycle = buildMutationEmbeddingLifecycleFailure(error, result);
2160
+ result.alignment = buildMutationAlignment(result.embeddingLifecycle);
2161
+ result.businessComplete = false;
2162
+ }
2163
+ }
2164
+
2165
+ function shouldRunMutationEmbeddingLifecycle(result) {
2166
+ return result
2167
+ && result.status === 'passed'
2168
+ && result.written === true
2169
+ && normalizeRelativePath(result.graphPath) === normalizeRelativePath(DEFAULT_GRAPH_PATH)
2170
+ && (
2171
+ (Array.isArray(result.touchedElementIds) && result.touchedElementIds.length > 0)
2172
+ || (Array.isArray(result.touchedRelationshipIds) && result.touchedRelationshipIds.length > 0)
2173
+ || (Array.isArray(result.touchedViewIds) && result.touchedViewIds.length > 0)
2174
+ );
2175
+ }
2176
+
2177
+ function buildMutationAlignment(embeddingLifecycle) {
2178
+ const state = embeddingLifecycle && embeddingLifecycle.alignmentState
2179
+ ? embeddingLifecycle.alignmentState
2180
+ : 'Failed';
2181
+ return Object.freeze({
2182
+ state,
2183
+ pureSemanticQueryRejected: state !== 'Aligned',
2184
+ category: state === 'Aligned' ? 'SEMANTIC_INDEX_ALIGNED' : 'SEMANTIC_INDEX_NOT_ALIGNED',
2185
+ fullSnapshotFallback: false,
2186
+ });
2187
+ }
2188
+
2189
+ function buildMutationEmbeddingLifecycleFailure(error, result) {
2190
+ const category = error && error.category ? error.category : 'W31_MUTATION_VECTOR_LIFECYCLE_FAILED';
2191
+ return Object.freeze({
2192
+ mutation: Object.freeze({
2193
+ applied: true,
2194
+ architecturePath: result.graphPath,
2195
+ }),
2196
+ touchedRecords: [],
2197
+ provider: Object.freeze({
2198
+ profile: Object.freeze({
2199
+ provider: W31_APPROVED_PROFILE.provider,
2200
+ model: W31_APPROVED_PROFILE.model,
2201
+ version: W31_APPROVED_PROFILE.version,
2202
+ dimensions: W31_APPROVED_PROFILE.dimensions,
2203
+ }),
2204
+ offlineEvidenceAccepted: false,
2205
+ realRequestCount: 0,
2206
+ }),
2207
+ vectorEvidence: [],
2208
+ vectorQuery: Object.freeze({
2209
+ returnedTouchedRecordIds: [],
2210
+ }),
2211
+ alignmentState: 'Failed',
2212
+ failureMatrix: Object.freeze([
2213
+ Object.freeze({
2214
+ name: 'automatic-mutation-lifecycle-failure',
2215
+ alignmentState: 'Failed',
2216
+ category,
2217
+ pureSemanticQueryRejected: true,
2218
+ semanticQueryRejection: Object.freeze({
2219
+ request: null,
2220
+ status: 'rejected',
2221
+ alignmentState: 'Failed',
2222
+ category: 'SEMANTIC_INDEX_NOT_ALIGNED',
2223
+ fullSnapshotFallback: false,
2224
+ }),
2225
+ offlineEvidenceAccepted: false,
2226
+ }),
2227
+ ]),
2228
+ pureSemanticQueryRejected: true,
2229
+ semanticQueryRejection: Object.freeze({
2230
+ request: null,
2231
+ status: 'rejected',
2232
+ alignmentState: 'Failed',
2233
+ category: 'SEMANTIC_INDEX_NOT_ALIGNED',
2234
+ fullSnapshotFallback: false,
2235
+ }),
2236
+ secretLeaks: [],
2237
+ });
2238
+ }
2239
+
2240
+ function buildFailureGuidance(errors, ontology) {
2241
+ const guidance = [];
2242
+ for (const error of errors || []) {
2243
+ addGuidanceForError(guidance, String(error), ontology);
2244
+ }
2245
+ if (guidance.length === 0 && Array.isArray(errors) && errors.length > 0) {
2246
+ guidance.push('Inspect the error text, call getSystemArchitecture with an explicit semantic query to refresh relevant ids, use getIntentElementContext for focused dependency context when needed, then retry with previewSystemArchitectureMutation before writing. Use an omitted-query full snapshot only when exact complete view membership is required.');
2247
+ }
2248
+ return guidance;
2249
+ }
2250
+
2251
+ function addGuidanceForError(guidance, error, ontology) {
2252
+ const language = ontology && ontology.language ? ontology.language : 'ArchiMate 3.2';
2253
+ const matrixLabel = ontology && ontology.matrixErrorLabel ? ontology.matrixErrorLabel : 'ArchiMate 3.2 relationship matrix';
2254
+ if (error.includes('mutation.view_ids must contain at least one view id')) {
2255
+ pushUnique(guidance, 'Select the target view_ids explicitly. Prefer getSystemArchitecture with an explicit semantic query to find relevant views, then use getIntentElementContext for focused element dependencies when needed. Use a full snapshot only if exact complete view membership is required.');
2256
+ }
2257
+ if (error.includes(`violates ${matrixLabel}`)) {
2258
+ pushUnique(guidance, `Check relationship.type and the source and target element types against ${language}. If the intended meaning is still valid, choose a compliant relationship type or change the endpoint element types by remove-and-add.`);
2259
+ }
2260
+ if (error.includes('uses unsupported') && error.includes('relationship type')) {
2261
+ pushUnique(guidance, `Use relationship.type for the relationship type and choose one of the schema-supported ${language} relationship types.`);
2262
+ }
2263
+ if (error.includes('id cannot be updated') || error.includes('type cannot be updated')) {
2264
+ pushUnique(guidance, 'Do not patch immutable identity or type fields. To change an id or type, remove the existing element or relationship, then add the replacement with the desired id or type.');
2265
+ }
2266
+ if (error.includes('must be included in at least one view')) {
2267
+ pushUnique(guidance, 'Every element and relationship must belong to at least one view. Add it with view_ids, or add the existing object to an appropriate view before validating again.');
2268
+ }
2269
+ if (error.includes('must declare parent_element_id') || error.includes('top-level view')) {
2270
+ const rootViewName = ontology && ontology.invariants && ontology.invariants.rootViewName
2271
+ ? ontology.invariants.rootViewName
2272
+ : 'SystemArchitecture';
2273
+ pushUnique(guidance, `Keep exactly one top-level view${rootViewName ? ` named ${rootViewName}` : ''}. For any sub-view, set parent_element_id to an existing element and keep parent_element_name aligned with that element name.`);
2274
+ }
2275
+ if (error.includes('must contain at most') && error.includes('elements')) {
2276
+ const maxElements = ontology && ontology.invariants && ontology.invariants.maxElementsPerView !== undefined && ontology.invariants.maxElementsPerView !== null
2277
+ ? ontology.invariants.maxElementsPerView
2278
+ : 15;
2279
+ pushUnique(guidance, `Do not force more than ${maxElements} included_elements into one view. Pause and think about layered architecture: split the view into layered sub-views, attach each sub-view with parent_element_id, and move lower-level elements into the appropriate child view before retrying.`);
2280
+ }
2281
+ if (error.includes('does not exist') || error.includes('references missing')) {
2282
+ pushUnique(guidance, 'Refresh current ids with getSystemArchitecture semantic query first, then call getIntentElementContext for any returned element that needs dependency context. Do not guess ids; use existing element, relationship, and view ids or create missing objects first.');
2283
+ }
2284
+ }
2285
+
2286
+ function pushUnique(entries, entry) {
2287
+ if (!entries.includes(entry)) {
2288
+ entries.push(entry);
2289
+ }
2290
+ }
2291
+
2292
+ function summarizeDocument(document) {
2293
+ return {
2294
+ elementCount: Array.isArray(document.elements) ? document.elements.length : 0,
2295
+ relationshipCount: Array.isArray(document.relationships) ? document.relationships.length : 0,
2296
+ viewCount: Array.isArray(document.views) ? document.views.length : 0,
2297
+ };
2298
+ }
2299
+
2300
+ // --- WP2791: post-canonical-write .qea projection (parallel to Neo4j sync, non-fatal) ---
2301
+ // Target resolution (decision qea-full-wholefile-argo-scripts-no-config): env ARGO_EA_QEA >
2302
+ // the single *.qea at the workspace root (0/many -> no-op with an explicit log). NO config file.
2303
+ // Projection script runs from argo/scripts (same package as the MCP runtime), so a workspace
2304
+ // does not need to ship its own projection script (bundled argo/scripts module).
2305
+ function resolveQeaProjectionTarget(context) {
2306
+ const none = (reason, hasEaSignals) => ({ target: null, reason, hasEaSignals: !!hasEaSignals });
2307
+ try {
2308
+ const workspaceRoot = String(context && context.workspaceRoot ? context.workspaceRoot : '');
2309
+ if (!workspaceRoot || !fs.existsSync(workspaceRoot)) { return none('workspace root unavailable: ' + workspaceRoot, true); }
2310
+ const graphAbsolute = context.graphPath && context.graphPath.absolutePath ? context.graphPath.absolutePath : null;
2311
+ if (!graphAbsolute || !fs.existsSync(graphAbsolute)) { return none('canonical graph not found under ' + workspaceRoot, false); }
2312
+ const pick = (p) => (p && fs.existsSync(p) ? path.resolve(p) : null);
2313
+ const envTarget = process.env.ARGO_EA_QEA;
2314
+ let qeaPath = pick(envTarget);
2315
+ if (qeaPath) { return { target: { qeaPath, graphPath: graphAbsolute, workspaceRoot } }; }
2316
+ let qeas = [];
2317
+ try { qeas = fs.readdirSync(workspaceRoot).filter((n) => n.toLowerCase().endsWith('.qea')).sort(); } catch { /* ignore */ }
2318
+ if (qeas.length === 1) {
2319
+ return { target: { qeaPath: path.resolve(workspaceRoot, qeas[0]), graphPath: graphAbsolute, workspaceRoot } };
2320
+ }
2321
+ let eaFiles = [];
2322
+ try { eaFiles = fs.readdirSync(workspaceRoot).filter((n) => /\.(qea|feap|eap)$/i.test(n)).sort(); } catch { /* ignore */ }
2323
+ if (qeas.length > 1) {
2324
+ const reason = `${qeas.length} *.qea files found at the workspace root (${qeas.join(', ')}); expected exactly one or set ARGO_EA_QEA`;
2325
+ console.log('[ea-qea] projection target: none (' + reason + ') in ' + workspaceRoot);
2326
+ return none(reason, true);
2327
+ }
2328
+ const legacy = eaFiles.filter((n) => /\.(feap|eap)$/i.test(n));
2329
+ if (legacy.length > 0) {
2330
+ const reason = `EA model is a legacy ${legacy.join(', ')} (Firebird/Jet); the direct .qea projection cannot write it — convert to .qea (EA 17.2+) or set ARGO_EA_QEA to a .qea target`;
2331
+ console.log('[ea-qea] projection target: none (' + reason + ') in ' + workspaceRoot);
2332
+ return none(reason, true);
2333
+ }
2334
+ if (envTarget) {
2335
+ const reason = 'ARGO_EA_QEA points to a missing .qea file: ' + envTarget;
2336
+ console.log('[ea-qea] projection target: none (' + reason + ')');
2337
+ return none(reason, true);
2338
+ }
2339
+ console.log('[ea-qea] projection target: none in ' + workspaceRoot);
2340
+ return none('no .qea target found (set ARGO_EA_QEA or place exactly one *.qea at the workspace root)', false);
2341
+ } catch (error) {
2342
+ console.log('[ea-qea] projection target resolution failed: ' + String(error && error.message ? error.message : error));
2343
+ return none('EA .qea target resolution failed: ' + String(error && error.message ? error.message : error), true);
2344
+ }
2345
+ }
2346
+
2347
+ function runQeaProjection(target) {
2348
+ // Synchronous child: this runs right before the async Neo4j sync + embedding
2349
+ // lifecycle. An async child leaves a libuv handle closing while subsequent
2350
+ // async I/O (fetch / neo4j-driver) proceeds, which on Windows can trip a
2351
+ // native `UV_HANDLE_CLOSING` assertion and abort the whole MCP. spawnSync has
2352
+ // no lingering handle (~150ms, bounded); the caller's `await` still applies.
2353
+ const script = path.join(__dirname, 'ea-qea-sync.js');
2354
+ const started = Date.now();
2355
+ if (!fs.existsSync(script)) {
2356
+ return { ok: false, error: 'argo/scripts/ea-qea-sync.js missing', ms: 0 };
2357
+ }
2358
+ const snapshotDir = path.join(target.workspaceRoot, '.argo', 'temp', 'qea-backups');
2359
+ // -y enables the projection-owned delete reconcile: objects that carry a schema anchor
2360
+ // (t_object.Alias / t_connectortag schema_id) but are no longer in canonical are removed
2361
+ // from the .qea, so a graph-side deletion actually disappears from EA on the next
2362
+ // projection. Human-drawn (un-anchored) content is never a delete candidate.
2363
+ const args = [script, '--mode', 'sync', '--graph', target.graphPath, '--qea', target.qeaPath, '--snapshot-dir', snapshotDir, '-y'];
2364
+ try {
2365
+ const res = spawnSync(process.execPath, args, { cwd: target.workspaceRoot, windowsHide: true, encoding: 'utf8', timeout: 120000 });
2366
+ const ok = res.status === 0;
2367
+ return {
2368
+ ok,
2369
+ code: res.status,
2370
+ ms: Date.now() - started,
2371
+ stderr: String(res.stderr || '').slice(0, 600),
2372
+ ...(ok ? {} : { error: String((res.stderr || '').slice(0, 600) || ('exit ' + res.status)) }),
2373
+ };
2374
+ } catch (error) {
2375
+ return { ok: false, error: String(error && error.message ? error.message : error), ms: Date.now() - started };
2376
+ }
2377
+ }
2378
+
2379
+ function writeGraph(graphPath, document) {
2380
+ const tempPath = `${graphPath}.${process.pid}.${Date.now()}.tmp`;
2381
+ fs.writeFileSync(tempPath, `${JSON.stringify(document, null, 2)}\n`, 'utf8');
2382
+ fs.renameSync(tempPath, graphPath);
2383
+ }
2384
+
2385
+ function validateAgainstSchema(value, schemaNode, pointer, errors, rootSchema) {
2386
+ if (!schemaNode || typeof schemaNode !== 'object') {
2387
+ return;
2388
+ }
2389
+
2390
+ const resolvedSchema = schemaNode.$ref ? resolveRef(schemaNode.$ref, rootSchema, errors, pointer) : schemaNode;
2391
+ if (!resolvedSchema) {
2392
+ return;
2393
+ }
2394
+
2395
+ if (resolvedSchema.const !== undefined && !isDeepStrictEqual(value, resolvedSchema.const)) {
2396
+ errors.push(`${pointer} must equal ${JSON.stringify(resolvedSchema.const)}`);
2397
+ return;
2398
+ }
2399
+
2400
+ if (resolvedSchema.enum && !resolvedSchema.enum.some(option => isDeepStrictEqual(option, value))) {
2401
+ errors.push(`${pointer} must be one of: ${resolvedSchema.enum.map(option => JSON.stringify(option)).join(', ')}`);
2402
+ return;
2403
+ }
2404
+
2405
+ if (resolvedSchema.type !== undefined) {
2406
+ validateType(value, resolvedSchema.type, pointer, errors);
2407
+ if (!typeMatches(value, resolvedSchema.type)) {
2408
+ return;
2409
+ }
2410
+ }
2411
+
2412
+ if (typeof resolvedSchema.minLength === 'number' && (typeof value !== 'string' || value.length < resolvedSchema.minLength)) {
2413
+ errors.push(`${pointer} must be at least ${resolvedSchema.minLength} character(s) long`);
2414
+ }
2415
+
2416
+ if (resolvedSchema.pattern) {
2417
+ const matcher = new RegExp(resolvedSchema.pattern);
2418
+ if (typeof value !== 'string' || !matcher.test(value)) {
2419
+ errors.push(`${pointer} must match pattern ${JSON.stringify(resolvedSchema.pattern)}`);
2420
+ }
2421
+ }
2422
+
2423
+ if (typeof resolvedSchema.minItems === 'number' && (!Array.isArray(value) || value.length < resolvedSchema.minItems)) {
2424
+ errors.push(`${pointer} must contain at least ${resolvedSchema.minItems} item(s)`);
2425
+ }
2426
+
2427
+ if (resolvedSchema.type === 'object') {
2428
+ validateObject(value, resolvedSchema, pointer, errors, rootSchema);
2429
+ return;
2430
+ }
2431
+
2432
+ if (resolvedSchema.type === 'array') {
2433
+ validateArray(value, resolvedSchema, pointer, errors, rootSchema);
2434
+ }
2435
+ }
2436
+
2437
+ function validateObject(value, schemaNode, pointer, errors, rootSchema) {
2438
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
2439
+ return;
2440
+ }
2441
+
2442
+ const properties = schemaNode.properties || {};
2443
+ const required = Array.isArray(schemaNode.required) ? schemaNode.required : [];
2444
+ for (const key of required) {
2445
+ if (!(key in value)) {
2446
+ errors.push(`${pointer} is missing required property '${key}'`);
2447
+ }
2448
+ }
2449
+
2450
+ if (schemaNode.additionalProperties === false) {
2451
+ for (const key of Object.keys(value)) {
2452
+ if (!(key in properties)) {
2453
+ errors.push(`${pointer} contains unsupported property '${key}'`);
2454
+ }
2455
+ }
2456
+ }
2457
+
2458
+ for (const [key, propertySchema] of Object.entries(properties)) {
2459
+ if (key in value) {
2460
+ validateAgainstSchema(value[key], propertySchema, `${pointer}.${key}`, errors, rootSchema);
2461
+ }
2462
+ }
2463
+ }
2464
+
2465
+ function validateArray(value, schemaNode, pointer, errors, rootSchema) {
2466
+ if (!Array.isArray(value)) {
2467
+ return;
2468
+ }
2469
+
2470
+ if (schemaNode.items) {
2471
+ value.forEach((entry, index) => {
2472
+ validateAgainstSchema(entry, schemaNode.items, `${pointer}[${index}]`, errors, rootSchema);
2473
+ });
2474
+ }
2475
+ }
2476
+
2477
+ function validateType(value, expectedType, pointer, errors) {
2478
+ if (!typeMatches(value, expectedType)) {
2479
+ const printableType = Array.isArray(expectedType) ? expectedType.join(' or ') : expectedType;
2480
+ errors.push(`${pointer} must be of type ${printableType}`);
2481
+ }
2482
+ }
2483
+
2484
+ function typeMatches(value, expectedType) {
2485
+ if (Array.isArray(expectedType)) {
2486
+ return expectedType.some(candidate => typeMatches(value, candidate));
2487
+ }
2488
+ switch (expectedType) {
2489
+ case 'object':
2490
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
2491
+ case 'array':
2492
+ return Array.isArray(value);
2493
+ case 'string':
2494
+ return typeof value === 'string';
2495
+ case 'number':
2496
+ return typeof value === 'number' && Number.isFinite(value);
2497
+ case 'integer':
2498
+ return typeof value === 'number' && Number.isInteger(value);
2499
+ case 'boolean':
2500
+ return typeof value === 'boolean';
2501
+ case 'null':
2502
+ return value === null;
2503
+ default:
2504
+ return true;
2505
+ }
2506
+ }
2507
+
2508
+ function resolveRef(ref, rootSchema, errors, pointer) {
2509
+ if (!ref.startsWith('#/')) {
2510
+ errors.push(`${pointer} uses unsupported $ref '${ref}'`);
2511
+ return undefined;
2512
+ }
2513
+
2514
+ const segments = ref.slice(2).split('/');
2515
+ let current = rootSchema;
2516
+ for (const segment of segments) {
2517
+ if (!current || typeof current !== 'object' || !(segment in current)) {
2518
+ errors.push(`${pointer} references missing schema path '${ref}'`);
2519
+ return undefined;
2520
+ }
2521
+ current = current[segment];
2522
+ }
2523
+ return current;
2524
+ }
2525
+
2526
+ function isDeepStrictEqual(left, right) {
2527
+ return JSON.stringify(left) === JSON.stringify(right);
2528
+ }
2529
+
2530
+ function clone(value) {
2531
+ return JSON.parse(JSON.stringify(value));
2532
+ }
2533
+
2534
+ function validateExplicitQuery(query) {
2535
+ if (!query || typeof query !== 'object' || Array.isArray(query) || !query.purpose) {
2536
+ return queryError('QUERY_PURPOSE_REQUIRED', 'Explicit queries require a purpose');
2537
+ }
2538
+ if (!LEGAL_QUERY_PURPOSES.has(query.purpose)) {
2539
+ return queryError('QUERY_PURPOSE_INVALID', `Unsupported query purpose: ${query.purpose}`);
2540
+ }
2541
+ if (typeof query.intent !== 'string' || query.intent.trim().length === 0) {
2542
+ return queryError('QUERY_INTENT_REQUIRED', 'Explicit queries require a non-blank intent');
2543
+ }
2544
+ if (
2545
+ query.purpose === 'audit'
2546
+ && (typeof query.subject !== 'string' || query.subject.trim().length === 0)
2547
+ ) {
2548
+ return queryError('AUDIT_SUBJECT_REQUIRED', 'Audit queries require a non-blank subject');
2549
+ }
2550
+
2551
+ return {
2552
+ status: 'passed',
2553
+ query: {
2554
+ ...query,
2555
+ intent: query.intent.trim(),
2556
+ ...(query.subject === undefined ? {} : { subject: query.subject.trim() }),
2557
+ },
2558
+ };
2559
+ }
2560
+
2561
+ function validateSemanticQueryResponseShapeControls(query) {
2562
+ for (const field of FORBIDDEN_RESPONSE_SHAPE_CONTROL_FIELDS) {
2563
+ if (!Object.prototype.hasOwnProperty.call(query, field)) {
2564
+ continue;
2565
+ }
2566
+ if (FORBIDDEN_RESPONSE_SHAPE_CONTROL_VALUES.has(String(query[field]).trim().toLowerCase())) {
2567
+ return queryError(
2568
+ 'QUERY_RESPONSE_SHAPE_CONTROL_FORBIDDEN',
2569
+ `Semantic query response-shape control '${field}' is forbidden`,
2570
+ );
2571
+ }
2572
+ }
2573
+ for (const flag of FORBIDDEN_RESPONSE_SHAPE_CONTROL_FLAGS) {
2574
+ if (
2575
+ Object.prototype.hasOwnProperty.call(query, flag)
2576
+ && query[flag] !== false
2577
+ && query[flag] !== null
2578
+ && query[flag] !== undefined
2579
+ ) {
2580
+ return queryError(
2581
+ 'QUERY_RESPONSE_SHAPE_CONTROL_FORBIDDEN',
2582
+ `Semantic query response-shape control '${flag}' is forbidden`,
2583
+ );
2584
+ }
2585
+ }
2586
+ return { status: 'passed' };
2587
+ }
2588
+
2589
+ function isOrdinarySemanticQuery(query) {
2590
+ return !!query
2591
+ && typeof query === 'object'
2592
+ && !Array.isArray(query);
2593
+ }
2594
+
2595
+ function isCanonicalSubsetSemanticContract(query, options = {}) {
2596
+ if (!isOrdinarySemanticQuery(query)) {
2597
+ return false;
2598
+ }
2599
+ if (!Array.isArray(query.anchors) || query.anchors.length === 0) {
2600
+ return !!(
2601
+ options.defaultNoAnchorSubset
2602
+ || options.architecturePath
2603
+ );
2604
+ }
2605
+ return query.anchors.some(anchor => !/^grag-[a-z0-9-]+$/.test(String(anchor)));
2606
+ }
2607
+
2608
+ function semanticContractOptions(args = {}, dependencies = undefined) {
2609
+ return {
2610
+ architecturePath: args.architecturePath,
2611
+ canonicalDocument: args.canonicalDocument,
2612
+ defaultNoAnchorSubset: !dependencies
2613
+ || !!dependencies.canonicalSubsetForNoAnchor
2614
+ || !!(
2615
+ dependencies.semanticOperatorJourney
2616
+ && dependencies.semanticOperatorJourney.canonicalSubsetForNoAnchor
2617
+ ),
2618
+ };
2619
+ }
2620
+
2621
+ function queryError(category, message, extras = {}) {
2622
+ return {
2623
+ status: 'failed',
2624
+ error: { category, message, ...extras },
2625
+ };
2626
+ }
2627
+
2628
+ function toolResult(payload, structuredContent = undefined) {
2629
+ return {
2630
+ ...payload,
2631
+ content: [
2632
+ {
2633
+ type: 'text',
2634
+ text: JSON.stringify(payload, null, 2),
2635
+ },
2636
+ ],
2637
+ ...(structuredContent === undefined ? {} : { structuredContent }),
2638
+ isError: payload.status === 'failed',
2639
+ };
2640
+ }
2641
+
2642
+ function mutationToolResult(payload, write) {
2643
+ if (write !== true || isMutationResponseDebugEnabled()) {
2644
+ return toolResult(payload);
2645
+ }
2646
+ return toolResult(compactMutationResponse(payload));
2647
+ }
2648
+
2649
+ function isMutationResponseDebugEnabled() {
2650
+ return process.env.ARGO_MCP_MUTATION_RESPONSE_DEBUG === '1';
2651
+ }
2652
+
2653
+ function compactMutationResponse(payload) {
2654
+ const compact = {
2655
+ status: payload && payload.status,
2656
+ written: Boolean(payload && payload.written),
2657
+ };
2658
+ if (payload && payload.embeddingLifecycle && payload.embeddingLifecycle.state) {
2659
+ compact.embeddingLifecycle = { state: payload.embeddingLifecycle.state };
2660
+ }
2661
+ // Successful writes stay compact but downstream projection side effects (EA .qea,
2662
+ // Neo4j) and non-fatal warnings must stay observable — a caller deciding whether
2663
+ // "the EA file reflects this write" relies on qeaProjection.status (passed /
2664
+ // failed / noop + reason), never on silence.
2665
+ if (payload && payload.qeaProjection) {
2666
+ const q = payload.qeaProjection;
2667
+ if (q.status === 'passed') {
2668
+ compact.qeaProjection = { status: 'passed', ms: q.ms };
2669
+ } else if (q.status === 'noop') {
2670
+ compact.qeaProjection = { status: 'noop', reason: q.reason };
2671
+ } else {
2672
+ compact.qeaProjection = { status: q.status, error: q.error || q.reason };
2673
+ }
2674
+ }
2675
+ if (payload && payload.neo4jSync) {
2676
+ compact.neo4jSync = { status: payload.neo4jSync.status };
2677
+ }
2678
+ // L1 dedup advisory must survive the compact successful-write response: it is
2679
+ // the whole point of surfacing (advisory) semantic near-duplicates to the caller.
2680
+ if (payload && payload.semanticDedup) {
2681
+ compact.semanticDedup = payload.semanticDedup;
2682
+ }
2683
+ if (Array.isArray(payload && payload.warnings) && payload.warnings.length > 0) {
2684
+ compact.warnings = payload.warnings;
2685
+ }
2686
+ // Failed actual writes must retain business diagnostics (e.g. View15 maximum/observed)
2687
+ // so callers can distinguish reject reasons; successful writes stay compact.
2688
+ if (payload && payload.status === 'failed') {
2689
+ if (Array.isArray(payload.errors)) {
2690
+ compact.errors = payload.errors;
2691
+ }
2692
+ if (Array.isArray(payload.guidance)) {
2693
+ compact.guidance = payload.guidance;
2694
+ }
2695
+ if (Array.isArray(payload.semanticConflicts)) {
2696
+ compact.semanticConflicts = payload.semanticConflicts;
2697
+ }
2698
+ }
2699
+ return compact;
2700
+ }
2701
+
2702
+ function getSystemArchitectureResult(payload) {
2703
+ const failed = payload.status === 'failed';
2704
+ return toolResult(payload, {
2705
+ version: '1.0',
2706
+ mode: failed ? 'error' : 'semantic-query',
2707
+ document: failed ? null : (payload.document === undefined ? null : payload.document),
2708
+ query: failed ? null : (payload.query || null),
2709
+ error: failed ? payload.error : null,
2710
+ });
2711
+ }
2712
+
2713
+ async function callTool(name, args = {}, dependencies = undefined) {
2714
+ if (name === 'getSystemArchitecture') {
2715
+ if (Object.prototype.hasOwnProperty.call(args, 'query')) {
2716
+ const validation = validateExplicitQuery(args.query);
2717
+ if (validation.status === 'failed') {
2718
+ return getSystemArchitectureResult(validation);
2719
+ }
2720
+
2721
+ const query = validation.query;
2722
+ const context = await loadContext(args);
2723
+ const contractOptions = semanticContractOptions({
2724
+ ...args,
2725
+ canonicalDocument: context.document,
2726
+ }, dependencies);
2727
+ if (isCanonicalSubsetSemanticContract(query, contractOptions)) {
2728
+ const responseShapeValidation = validateSemanticQueryResponseShapeControls(query);
2729
+ if (responseShapeValidation.status === 'failed') {
2730
+ return getSystemArchitectureResult(responseShapeValidation);
2731
+ }
2732
+ }
2733
+
2734
+ const journey = await resolveSemanticOperatorJourney(dependencies, {
2735
+ repositoryRoot: context.workspaceRoot,
2736
+ });
2737
+ return applySemanticResponseProfile(await journey.query(query), query, contractOptions);
2738
+ }
2739
+
2740
+ return getSystemArchitectureResult(queryError(
2741
+ 'QUERY_REQUIRED',
2742
+ 'getSystemArchitecture requires an explicit query (query.purpose + query.intent); full-graph snapshot access has been removed.',
2743
+ ));
2744
+ }
2745
+
2746
+ if (name === 'getIntentElementContext') {
2747
+ const context = await loadContext(args);
2748
+ return toolResult(attachContextWarnings(buildIntentElementContext(context, args), context));
2749
+ }
2750
+
2751
+ if (name === 'getArchitectureViewContext') {
2752
+ const context = await loadContext(args);
2753
+ return toolResult(attachContextWarnings(buildViewContext(context, args), context));
2754
+ }
2755
+
2756
+ if (name === 'previewSystemArchitectureMutation') {
2757
+ const context = await loadContext(args);
2758
+ return toolResult(attachContextWarnings(await buildMutationResult(context, args.mutations, false, dependencies, { acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }), context));
2759
+ }
2760
+
2761
+ if (name === 'applySystemArchitectureMutation') {
2762
+ const context = await loadContext(args);
2763
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, args.mutations, true, dependencies, { acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }), context), true);
2764
+ }
2765
+
2766
+ if (name === 'addArchitectureElement') {
2767
+ const context = await loadContext(args);
2768
+ const write = !args.dryRun;
2769
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'addElement', element: args.element, view_ids: args.view_ids, onConflict: args.onConflict, justification: args.justification }], write, dependencies), context), write);
2770
+ }
2771
+
2772
+ if (name === 'updateArchitectureElement') {
2773
+ const context = await loadContext(args);
2774
+ const write = !args.dryRun;
2775
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'updateElement', id: args.id, patch: args.patch, acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }], write), context), write);
2776
+ }
2777
+
2778
+ if (name === 'removeArchitectureElement') {
2779
+ const context = await loadContext(args);
2780
+ const write = !args.dryRun;
2781
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'removeElement', id: args.id, view_ids: args.view_ids, acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }], write), context), write);
2782
+ }
2783
+
2784
+ if (name === 'addArchitectureRelationship') {
2785
+ const context = await loadContext(args);
2786
+ const write = !args.dryRun;
2787
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'addRelationship', relationship: args.relationship, view_ids: args.view_ids, onConflict: args.onConflict, justification: args.justification }], write), context), write);
2788
+ }
2789
+
2790
+ if (name === 'updateArchitectureRelationship') {
2791
+ const context = await loadContext(args);
2792
+ const write = !args.dryRun;
2793
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'updateRelationship', id: args.id, patch: args.patch, acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }], write), context), write);
2794
+ }
2795
+
2796
+ if (name === 'removeArchitectureRelationship') {
2797
+ const context = await loadContext(args);
2798
+ const write = !args.dryRun;
2799
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'removeRelationship', id: args.id, view_ids: args.view_ids, acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }], write), context), write);
2800
+ }
2801
+
2802
+ if (name === 'addArchitectureView') {
2803
+ const context = await loadContext(args);
2804
+ const write = !args.dryRun;
2805
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'addView', view: args.view, onConflict: args.onConflict, justification: args.justification }], write), context), write);
2806
+ }
2807
+
2808
+ if (name === 'updateArchitectureView') {
2809
+ const context = await loadContext(args);
2810
+ const write = !args.dryRun;
2811
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'updateView', view_id: args.view_id, patch: args.patch, acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }], write), context), write);
2812
+ }
2813
+
2814
+ if (name === 'removeArchitectureView') {
2815
+ const context = await loadContext(args);
2816
+ const write = !args.dryRun;
2817
+ return mutationToolResult(attachContextWarnings(await buildMutationResult(context, [{ type: 'removeView', view_id: args.view_id, acknowledgeLoss: args.acknowledgeLoss, lossJustification: args.lossJustification }], write), context), write);
2818
+ }
2819
+
2820
+ if (name === 'queryNeo4jGraph') {
2821
+ return queryNeo4jGraphTool(args);
2822
+ }
2823
+
2824
+ if (name === 'memory_search') {
2825
+ return toolResult(await memorySearchTool(args, dependencies));
2826
+ }
2827
+
2828
+ throw new Error(`Unknown tool: ${name}`);
2829
+ }
2830
+
2831
+ // memory_search: natural-language semantic memory retrieval. Uses the
2832
+ // agent-facing 'general' purpose of the semantic journey (same path as
2833
+ // getSystemArchitecture, so readiness/closure behave identically) and reshapes
2834
+ // the retrieved elements into a memory-oriented hit list with content +
2835
+ // similarity score, so an agent can look up the user's memory in one call.
2836
+ async function memorySearchTool(args = {}, dependencies = undefined) {
2837
+ const query = typeof args.query === 'string' ? args.query.trim() : '';
2838
+ if (!query) {
2839
+ return { status: 'failed', error: { category: 'MEMORY_QUERY_REQUIRED', message: 'query is required' } };
2840
+ }
2841
+ const topK = Number.isInteger(args.top_k) && args.top_k > 0 ? args.top_k : 8;
2842
+ // max_desc_len: default 800 (compact excerpt). 0 = full description;
2843
+ // -1 = omit description entirely and return only the length. Keeps the tool
2844
+ // result compact (production memory cards, not full session dumps).
2845
+ let maxDescLen = 800;
2846
+ if (Number.isInteger(args.max_desc_len) && args.max_desc_len !== 800) {
2847
+ maxDescLen = args.max_desc_len;
2848
+ }
2849
+ const context = await loadContext(args);
2850
+ let retrieved;
2851
+ try {
2852
+ const journey = await resolveSemanticOperatorJourney(dependencies, {
2853
+ repositoryRoot: context.workspaceRoot,
2854
+ });
2855
+ retrieved = await journey.query({ purpose: 'general', intent: query });
2856
+ } catch (error) {
2857
+ return {
2858
+ status: 'failed',
2859
+ error: {
2860
+ category: error && error.category ? error.category : 'MEMORY_RETRIEVAL_FAILED',
2861
+ message: error && error.message ? error.message : 'Memory retrieval failed',
2862
+ },
2863
+ };
2864
+ }
2865
+ const source = retrieved && (retrieved.result || retrieved.document) || retrieved;
2866
+ const subset = buildCanonicalSemanticDocumentSubset(source, context.document);
2867
+ if (subset.status !== 'passed') {
2868
+ return { status: 'failed', error: subset.error || { category: 'MEMORY_RETRIEVAL_FAILED' } };
2869
+ }
2870
+ const hits = (Array.isArray(subset.document && subset.document.elements) ? subset.document.elements : [])
2871
+ .filter(element => element && typeof element.semanticScore === 'number')
2872
+ .sort((left, right) => right.semanticScore - left.semanticScore)
2873
+ .slice(0, topK)
2874
+ .map(element => Object.freeze(memoryHitCard(element, maxDescLen, query)));
2875
+ return {
2876
+ status: 'passed',
2877
+ query,
2878
+ max_desc_len: maxDescLen,
2879
+ fullTextHint: 'To read the full text of a hit, call getIntentElementContext with its id (elementId).',
2880
+ hits: Object.freeze(hits),
2881
+ };
2882
+ }
2883
+
2884
+ // Build one compact memory hit: id/name/type/score + an excerpt of the
2885
+ // description bounded by maxDescLen, plus the full text length so the caller
2886
+ // knows how much content exists and can decide whether to expand.
2887
+ function memoryHitCard(element, maxDescLen, query) {
2888
+ const description = typeof element.description === 'string' ? element.description : '';
2889
+ const descriptionLength = description.length;
2890
+ let excerpt = '';
2891
+ if (maxDescLen !== -1) {
2892
+ excerpt = maxDescLen === 0 ? description : description.slice(0, maxDescLen);
2893
+ }
2894
+ const card = {
2895
+ id: element.id,
2896
+ name: element.name,
2897
+ type: element.type,
2898
+ score: element.semanticScore,
2899
+ description_length: descriptionLength,
2900
+ };
2901
+ if (maxDescLen !== -1) {
2902
+ card.description = excerpt;
2903
+ if (maxDescLen > 0 && descriptionLength > maxDescLen) {
2904
+ card.truncated = true;
2905
+ }
2906
+ }
2907
+ // A memory match may be driven by an attribute/testcase (both are embedded);
2908
+ // surface the matching bookkeeping text so the agent sees WHY it hit without
2909
+ // a second call.
2910
+ const snippet = bookkeepingSnippet(element, 'Element', query);
2911
+ if (snippet) {
2912
+ card.matchedSnippet = snippet;
2913
+ }
2914
+ return card;
2915
+ }
2916
+
2917
+ // Semantic dedup gate (GraphDeduplication): for each element that would be
2918
+ // CREATED, search the WHOLE graph for same-type semantically near elements (a
2919
+ // large candidate window, strict threshold). A hit blocks the default create —
2920
+ // the caller must reuse an existing candidate or explicitly pass
2921
+ // onConflict:'allowDuplicate' with a justification. A missing/unavailable
2922
+ // semantic backend degrades to an explicit status, never an error.
2923
+ const DEFAULT_SEMANTIC_DEDUP_THRESHOLD = 0.85;
2924
+ const SEMANTIC_DEDUP_MAX_QUERIES = 3;
2925
+ const SEMANTIC_DEDUP_MAX_MATCHES = 10;
2926
+ const SEMANTIC_DEDUP_TOP_K = 25;
2927
+
2928
+ function semanticDedupThreshold() {
2929
+ const raw = process.env.ARGO_SEMANTIC_DEDUP_THRESHOLD
2930
+ ?? process.env.ARGO_MCP_SEMANTIC_DEDUP_THRESHOLD;
2931
+ const value = Number(raw);
2932
+ return Number.isFinite(value) && value > 0 && value <= 1 ? value : DEFAULT_SEMANTIC_DEDUP_THRESHOLD;
2933
+ }
2934
+
2935
+ function collectViewMemberElementIds(document, viewIds) {
2936
+ const ids = new Set();
2937
+ if (!Array.isArray(viewIds) || viewIds.length === 0) {
2938
+ return ids;
2939
+ }
2940
+ const wanted = new Set(viewIds);
2941
+ for (const view of Array.isArray(document && document.views) ? document.views : []) {
2942
+ if (!view || !wanted.has(view.view_id)) {
2943
+ continue;
2944
+ }
2945
+ for (const elementId of Array.isArray(view.included_elements) ? view.included_elements : []) {
2946
+ ids.add(elementId);
2947
+ }
2948
+ }
2949
+ return ids;
2950
+ }
2951
+
2952
+ // Only element adds that the applied mutation actually CREATED are subject to
2953
+ // the L1 advisory. A reuse that found an exact natural-key match creates nothing
2954
+ // (created:false) and is skipped; a reuse that fell through to creation
2955
+ // (created:true, id === requested id) is advised like any other new element.
2956
+ function selectCreatedElementAdds(mutations, mutationSummaries) {
2957
+ const createdIds = new Set(
2958
+ (Array.isArray(mutationSummaries) ? mutationSummaries : [])
2959
+ .filter(summary => summary && summary.type === 'addElement' && summary.created === true)
2960
+ .map(summary => summary.id),
2961
+ );
2962
+ return (Array.isArray(mutations) ? mutations : []).filter(mutation => (
2963
+ mutation
2964
+ && mutation.type === 'addElement'
2965
+ && mutation.element
2966
+ && createdIds.has(mutation.element.id)
2967
+ ));
2968
+ }
2969
+
2970
+ // Decide whether the semantic candidates block the create. A create is blocked
2971
+ // unless the caller explicitly opted into allowDuplicate (with justification).
2972
+ function evaluateSemanticDedupGate(advisory, mutations) {
2973
+ if (!advisory || advisory.status !== 'passed' || !Array.isArray(advisory.candidates)) {
2974
+ return { blocked: false, conflicts: [] };
2975
+ }
2976
+ const byId = new Map((Array.isArray(mutations) ? mutations : [])
2977
+ .filter(mutation => mutation && mutation.type === 'addElement' && mutation.element)
2978
+ .map(mutation => [mutation.element.id, mutation]));
2979
+ const conflicts = [];
2980
+ for (const entry of advisory.candidates) {
2981
+ if (!entry || !Array.isArray(entry.matches) || entry.matches.length === 0) {
2982
+ continue;
2983
+ }
2984
+ const mutation = byId.get(entry.requested && entry.requested.id);
2985
+ const overridden = mutation && mutation.onConflict === 'allowDuplicate';
2986
+ if (!overridden) {
2987
+ conflicts.push(entry);
2988
+ }
2989
+ }
2990
+ return { blocked: conflicts.length > 0, conflicts };
2991
+ }
2992
+
2993
+ async function buildSemanticDedupAdvisory(context, mutations, dependencies) {
2994
+ markPhase('mutation:semanticDedup');
2995
+ if (process.env.ARGO_MCP_SEMANTIC_DEDUP === '0') {
2996
+ return undefined;
2997
+ }
2998
+ const addedElements = (Array.isArray(mutations) ? mutations : []).filter(mutation => (
2999
+ mutation
3000
+ && mutation.type === 'addElement'
3001
+ && mutation.element
3002
+ && typeof mutation.element.name === 'string'
3003
+ && mutation.element.name.trim() !== ''
3004
+ ));
3005
+ if (addedElements.length === 0) {
3006
+ return undefined;
3007
+ }
3008
+ const threshold = semanticDedupThreshold();
3009
+ let journey;
3010
+ try {
3011
+ journey = await resolveSemanticOperatorJourney(dependencies, {
3012
+ repositoryRoot: context.workspaceRoot,
3013
+ });
3014
+ } catch (error) {
3015
+ return {
3016
+ status: 'unavailable',
3017
+ advisoryOnly: true,
3018
+ threshold,
3019
+ reason: String(error && error.category ? error.category : 'SEMANTIC_DEDUP_UNAVAILABLE'),
3020
+ candidates: [],
3021
+ };
3022
+ }
3023
+ const candidates = [];
3024
+ for (const mutation of addedElements.slice(0, SEMANTIC_DEDUP_MAX_QUERIES)) {
3025
+ const element = mutation.element;
3026
+ const targetMemberIds = collectViewMemberElementIds(context.document, mutation.view_ids);
3027
+ const requested = { id: element.id, name: element.name, type: element.type };
3028
+ try {
3029
+ const intent = [element.type, element.name, element.description]
3030
+ .filter(part => typeof part === 'string' && part.trim() !== '')
3031
+ .join(' ');
3032
+ const retrieved = await journey.query({ purpose: 'general', intent, topK: SEMANTIC_DEDUP_TOP_K, rerank: false, hybrid: false, scoreMode: 'similarity' });
3033
+ const source = retrieved && (retrieved.result || retrieved.document) || retrieved;
3034
+ const subset = buildCanonicalSemanticDocumentSubset(source, context.document);
3035
+ const elements = subset && subset.status === 'passed' && subset.document
3036
+ ? (Array.isArray(subset.document.elements) ? subset.document.elements : [])
3037
+ : [];
3038
+ const matches = elements
3039
+ .filter(candidate => candidate && candidate.id !== element.id && typeof candidate.semanticScore === 'number')
3040
+ .filter(candidate => !element.type || candidate.type === element.type)
3041
+ .filter(candidate => candidate.semanticScore >= threshold)
3042
+ .sort((left, right) => right.semanticScore - left.semanticScore)
3043
+ .slice(0, SEMANTIC_DEDUP_MAX_MATCHES)
3044
+ .map(candidate => ({
3045
+ id: candidate.id,
3046
+ name: candidate.name,
3047
+ type: candidate.type,
3048
+ score: Number(candidate.semanticScore.toFixed(4)),
3049
+ in_target_views: targetMemberIds.has(candidate.id),
3050
+ }));
3051
+ candidates.push({ requested, matches });
3052
+ } catch (error) {
3053
+ candidates.push({
3054
+ requested,
3055
+ matches: [],
3056
+ status: 'unavailable',
3057
+ reason: String(error && error.category ? error.category : 'SEMANTIC_DEDUP_QUERY_FAILED'),
3058
+ });
3059
+ }
3060
+ }
3061
+ return {
3062
+ status: 'passed',
3063
+ advisoryOnly: true,
3064
+ threshold,
3065
+ scope: 'whole graph, same type',
3066
+ candidates,
3067
+ has_suggestions: candidates.some(entry => entry.matches.length > 0),
3068
+ };
3069
+ }
3070
+
3071
+ async function queryNeo4jGraphTool(args = {}) {
3072
+ const architecturePath = args.architecturePath || DEFAULT_GRAPH_PATH;
3073
+ const workspaceRoot = resolveWorkspaceRoot(args);
3074
+
3075
+ if (args.schema === true) {
3076
+ return queryNeo4jGraphSchemaResult(architecturePath, workspaceRoot);
3077
+ }
3078
+
3079
+ let recovery = null;
3080
+ try {
3081
+ // Reject invalid/write queries before any side effect.
3082
+ assertReadOnlyCypher(args.cypher);
3083
+
3084
+ // Same projection-recovery mechanism as the loadContext-based tools
3085
+ // (e.g. getSystemArchitecture): when the sync state is dirty or the
3086
+ // recorded canonicalDigest no longer matches the canonical JSON, rebuild
3087
+ // the Neo4j projection before servicing the read-only query.
3088
+ recovery = await recoverNeo4jSyncIfNeeded({
3089
+ architecturePath,
3090
+ workspaceRoot,
3091
+ });
3092
+
3093
+ const result = await runNeo4jCypherQuery({
3094
+ architecturePath,
3095
+ cypher: args.cypher,
3096
+ workspaceRoot,
3097
+ });
3098
+ const payload = {
3099
+ status: 'passed',
3100
+ architecturePath: result.architecturePath,
3101
+ graphKey: result.graphKey,
3102
+ database: result.database,
3103
+ records: result.records,
3104
+ summary: result.summary,
3105
+ };
3106
+ if (recovery.attempted) {
3107
+ payload.neo4jRecovery = recovery;
3108
+ if (recovery.status === 'failed') {
3109
+ payload.warnings = [
3110
+ `Neo4j automatic resync failed before servicing ${architecturePath}: ${recovery.error}`,
3111
+ 'The read-only query still ran against the current projection. Neo4j will be retried on the next canonical read or write, or you can run node .argo/scripts/syncSystemArchitectureToNeo4j.js manually.',
3112
+ ];
3113
+ }
3114
+ }
3115
+ return toolResult(payload);
3116
+ } catch (error) {
3117
+ return toolResult(queryError(
3118
+ error && error.category ? error.category : 'NEO4J_QUERY_FAILED',
3119
+ String(error && error.message ? error.message : error),
3120
+ {
3121
+ architecturePath,
3122
+ graphKey: buildGraphKey(architecturePath),
3123
+ ...(error && error.clause ? { clause: error.clause } : {}),
3124
+ ...(error && error.queriedDatabase ? { queriedDatabase: error.queriedDatabase } : {}),
3125
+ ...(error && error.expectedDatabase ? { expectedDatabase: error.expectedDatabase } : {}),
3126
+ ...(recovery && recovery.attempted ? { neo4jRecovery: recovery } : {}),
3127
+ },
3128
+ ));
3129
+ }
3130
+ }
3131
+
3132
+ function queryNeo4jGraphSchemaResult(architecturePath, workspaceRoot) {
3133
+ const schema = buildNeo4jGraphSchema(architecturePath);
3134
+ let typeEnums = {};
3135
+ let schemaBundleInfo = {};
3136
+ try {
3137
+ const resolvedRoot = workspaceRoot || resolveWorkspaceRoot({ architecturePath });
3138
+ const { bundle, ontology } = loadSchemaBundleAndOntology(resolvedRoot);
3139
+ const enums = resolveTypeEnums(bundle);
3140
+ typeEnums = {
3141
+ archimateElementTypes: enums.elementTypes,
3142
+ archimateRelationshipTypes: enums.relationshipTypes,
3143
+ schemaLanguage: (bundle.config && bundle.config.language) || null,
3144
+ schemaKind: bundle.kind,
3145
+ schemaDialect: ontology.dialect,
3146
+ actorElementType: ontology.actorElementType,
3147
+ bundleValidation: ontology.bundleValidation,
3148
+ };
3149
+ schemaBundleInfo = {
3150
+ schemaPath: bundle.schema.relativePath,
3151
+ schemaKind: bundle.kind,
3152
+ schemaDir: bundle.relativeDir,
3153
+ guidePath: bundle.guidePath ? bundle.guidePath.relativePath : null,
3154
+ };
3155
+ } catch (error) {
3156
+ typeEnums = {
3157
+ archimateElementTypes: [],
3158
+ archimateRelationshipTypes: [],
3159
+ schemaEnumError: String(error && error.message ? error.message : error),
3160
+ };
3161
+ }
3162
+
3163
+ return toolResult({
3164
+ status: 'passed',
3165
+ architecturePath,
3166
+ graphKey: buildGraphKey(architecturePath),
3167
+ schema: {
3168
+ ...schema,
3169
+ ...typeEnums,
3170
+ ...schemaBundleInfo,
3171
+ },
3172
+ usage: {
3173
+ scopeGraph: 'MATCH (e:Element {graphKey: $graphKey}) ...',
3174
+ exampleAllBusinessActors: "MATCH (e:Element {graphKey: $graphKey}) WHERE e.type = 'Business Actor' RETURN e.id, e.name, e.description",
3175
+ exampleAssignments: "MATCH (a:Element {graphKey: $graphKey, type: 'Business Actor'})-[r:ARCHIMATE_RELATES]->(b:Element {graphKey: $graphKey}) WHERE r.relationship_id IS NOT NULL RETURN a.name, type(r), b.name, r.relationship_id",
3176
+ },
3177
+ });
3178
+ }
3179
+
3180
+ async function resolveSemanticOperatorJourney(dependencies, options = {}) {
3181
+ if (dependencies && dependencies.semanticOperatorJourney) {
3182
+ return dependencies.semanticOperatorJourney;
3183
+ }
3184
+ // Thread the caller's already-resolved workspace root into the journey: the
3185
+ // no-arg resolveWorkspaceRoot() fallback is process.cwd(), i.e. whatever
3186
+ // directory the host launched this server from (a global ~/.argo installation
3187
+ // started by the host process resolves to that host's cwd, e.g.
3188
+ // C:\Windows\System32), never the workspace the caller asked for.
3189
+ const repositoryRoot = options && typeof options.repositoryRoot === 'string'
3190
+ ? options.repositoryRoot
3191
+ : '';
3192
+ return createDefaultProductionSemanticOperatorJourney(
3193
+ repositoryRoot ? { repositoryRoot } : {},
3194
+ );
3195
+ }
3196
+
3197
+ async function executeSemanticSystemArchitectureQuery(args, dependencies) {
3198
+ const context = await loadContext({
3199
+ ...(args || {}),
3200
+ ...(dependencies && dependencies.repositoryRoot
3201
+ ? { workspaceRoot: dependencies.repositoryRoot }
3202
+ : {}),
3203
+ });
3204
+ const query = args.query;
3205
+ const scopeResolution = resolveSemanticScope(context.document, query && query.scope);
3206
+ if (scopeResolution.status === 'failed') {
3207
+ return getSystemArchitectureResult(queryError(
3208
+ scopeResolution.error.category,
3209
+ scopeResolution.error.message,
3210
+ ));
3211
+ }
3212
+ const queryForRetrieval = Array.isArray(scopeResolution.identities) && scopeResolution.identities.length > 0
3213
+ ? { ...(query || {}), canonicalIdentities: scopeResolution.identities }
3214
+ : query;
3215
+ const contractOptions = semanticContractOptions(args, dependencies);
3216
+ const canonicalSubsetContract = isCanonicalSubsetSemanticContract(query, contractOptions);
3217
+ if (canonicalSubsetContract) {
3218
+ const responseShapeValidation = validateSemanticQueryResponseShapeControls(query);
3219
+ if (responseShapeValidation.status === 'failed') {
3220
+ return getSystemArchitectureResult(responseShapeValidation);
3221
+ }
3222
+ }
3223
+ const semanticRetrievalBoundary = resolveSemanticRetrievalBoundary(dependencies, {
3224
+ canonicalGraph: context.document,
3225
+ });
3226
+ if (!semanticRetrievalBoundary || typeof semanticRetrievalBoundary.retrieve !== 'function') {
3227
+ return getSystemArchitectureResult(queryError(
3228
+ 'SEMANTIC_RETRIEVAL_UNAVAILABLE',
3229
+ 'Semantic retrieval boundary is unavailable',
3230
+ ));
3231
+ }
3232
+ let document;
3233
+ try {
3234
+ const retrieved = await semanticRetrievalBoundary.retrieve(queryForRetrieval);
3235
+ if (canonicalSubsetContract) {
3236
+ // scoreMode:'similarity' (used by the write-path dedup gate) returns the
3237
+ // true vector similarity instead of the closure rank-derived score.
3238
+ const subset = buildCanonicalSemanticDocumentSubset(retrieved, context.document, {
3239
+ preferSeedSimilarity: !!(query && query.scoreMode === 'similarity'),
3240
+ });
3241
+ if (subset.status === 'failed') {
3242
+ return getSystemArchitectureResult(subset);
3243
+ }
3244
+ document = subset.document;
3245
+ } else {
3246
+ document = shouldReturnDebugSemanticResult(query)
3247
+ ? retrieved
3248
+ : buildBusinessSemanticSummary(retrieved, query);
3249
+ }
3250
+ } catch (error) {
3251
+ const semanticErrorEvidence = {};
3252
+ for (const field of [
3253
+ 'action',
3254
+ 'fullSnapshotFallback',
3255
+ 'state',
3256
+ 'canonicalVersion',
3257
+ 'contentVersion',
3258
+ 'indexVersion',
3259
+ 'completedChannels',
3260
+ 'missingChannels',
3261
+ 'mismatchedChannels',
3262
+ ]) {
3263
+ if (error && Object.prototype.hasOwnProperty.call(error, field)) {
3264
+ semanticErrorEvidence[field] = error[field];
3265
+ }
3266
+ }
3267
+ if (
3268
+ error
3269
+ && error.category === 'SEMANTIC_AUTO_ALIGNMENT_FAILED'
3270
+ && typeof semanticErrorEvidence.action !== 'string'
3271
+ ) {
3272
+ semanticErrorEvidence.action = 'Repair semantic lifecycle alignment, then retry the original query.';
3273
+ }
3274
+ return getSystemArchitectureResult(queryError(
3275
+ error && error.category ? error.category : 'SEMANTIC_RETRIEVAL_FAILED',
3276
+ error && error.message ? error.message : 'Semantic retrieval failed',
3277
+ semanticErrorEvidence,
3278
+ ));
3279
+ }
3280
+ if (
3281
+ Array.isArray(scopeResolution.identities)
3282
+ && scopeResolution.identities.length > 0
3283
+ && document
3284
+ && typeof document === 'object'
3285
+ ) {
3286
+ document = applySemanticScopeFilter(document, scopeResolution.identities);
3287
+ }
3288
+ const semanticPayload = {
3289
+ status: 'passed',
3290
+ graphPath: context.graphPath.relativePath,
3291
+ query: {
3292
+ ...query,
3293
+ mode: 'semantic-query',
3294
+ semanticRetrieval: 'invoked',
3295
+ ...(canonicalSubsetContract
3296
+ ? {}
3297
+ : { responseProfile: shouldReturnDebugSemanticResult(query) ? 'debug' : 'business-summary' }),
3298
+ },
3299
+ };
3300
+ return getSystemArchitectureResult({
3301
+ ...semanticPayload,
3302
+ ...(canonicalSubsetContract
3303
+ ? { document }
3304
+ : (document && Object.prototype.hasOwnProperty.call(document, 'result')
3305
+ ? { result: document.result }
3306
+ : { result: document })),
3307
+ ...(canonicalSubsetContract || !shouldReturnDebugSemanticResult(query) ? {} : { document }),
3308
+ });
3309
+ }
3310
+
3311
+ function shouldReturnDebugSemanticResult(query) {
3312
+ return ['debug', 'full', 'evidence'].includes(String(
3313
+ query && (query.responseProfile || query.detail || query.outputMode) || '',
3314
+ ).toLowerCase());
3315
+ }
3316
+
3317
+ function resolveSemanticScope(document, scope) {
3318
+ if (!scope || typeof scope !== 'object') {
3319
+ return { identities: undefined };
3320
+ }
3321
+ const elements = new Set();
3322
+ const relationships = new Set();
3323
+ const views = new Set();
3324
+
3325
+ if (typeof scope.view_id === 'string' && scope.view_id) {
3326
+ const view = (document.views || []).find(item => item && item.view_id === scope.view_id);
3327
+ if (!view) {
3328
+ return {
3329
+ status: 'failed',
3330
+ error: {
3331
+ category: 'SCOPE_VIEW_NOT_FOUND',
3332
+ message: `Scope view '${scope.view_id}' does not exist in the canonical graph`,
3333
+ },
3334
+ };
3335
+ }
3336
+ (view.included_elements || []).forEach(id => elements.add(String(id)));
3337
+ (view.included_relationships || []).forEach(id => relationships.add(String(id)));
3338
+ views.add(String(scope.view_id));
3339
+ return { identities: scopeIdentitiesOf(elements, relationships, views) };
3340
+ }
3341
+
3342
+ if (typeof scope.element_id === 'string' && scope.element_id) {
3343
+ const root = (document.elements || []).find(item => item && item.id === scope.element_id);
3344
+ if (!root) {
3345
+ return {
3346
+ status: 'failed',
3347
+ error: {
3348
+ category: 'SCOPE_ELEMENT_NOT_FOUND',
3349
+ message: `Scope element '${scope.element_id}' does not exist in the canonical graph`,
3350
+ },
3351
+ };
3352
+ }
3353
+ const depth = Number.isInteger(scope.depth) && scope.depth > 0 ? scope.depth : 2;
3354
+ elements.add(String(scope.element_id));
3355
+ const queue = [{ elementId: scope.element_id, level: 0 }];
3356
+ const visited = new Set();
3357
+ while (queue.length > 0) {
3358
+ const { elementId, level } = queue.shift();
3359
+ if (visited.has(elementId)) continue;
3360
+ visited.add(elementId);
3361
+ const element = (document.elements || []).find(item => item && item.id === elementId);
3362
+ const subViews = Array.isArray(element && element.subdiagram_views)
3363
+ ? element.subdiagram_views
3364
+ : [];
3365
+ for (const subView of subViews) {
3366
+ const view = (document.views || []).find(item => item && item.view_id === subView.view_id);
3367
+ if (!view) continue;
3368
+ views.add(String(view.view_id));
3369
+ (view.included_relationships || []).forEach(id => relationships.add(String(id)));
3370
+ for (const childId of (view.included_elements || [])) {
3371
+ elements.add(String(childId));
3372
+ if (level < depth - 1) {
3373
+ queue.push({ elementId: childId, level: level + 1 });
3374
+ }
3375
+ }
3376
+ }
3377
+ }
3378
+ return { identities: scopeIdentitiesOf(elements, relationships, views) };
3379
+ }
3380
+
3381
+ return { identities: undefined };
3382
+ }
3383
+
3384
+ function scopeIdentitiesOf(elements, relationships, views) {
3385
+ return [...elements, ...relationships, ...views];
3386
+ }
3387
+
3388
+ function applySemanticScopeFilter(document, identities) {
3389
+ if (!document || typeof document !== 'object' || !Array.isArray(identities)) {
3390
+ return document;
3391
+ }
3392
+ const allowed = new Set(identities.map(id => String(id)));
3393
+ if (
3394
+ Array.isArray(document.elements)
3395
+ || Array.isArray(document.relationships)
3396
+ || Array.isArray(document.views)
3397
+ ) {
3398
+ return Object.freeze({
3399
+ ...document,
3400
+ elements: Object.freeze((document.elements || []).filter(item => item && allowed.has(String(item.id)))),
3401
+ relationships: Object.freeze((document.relationships || []).filter(item => item && allowed.has(String(item.id)))),
3402
+ views: Object.freeze((document.views || []).filter(item => item && allowed.has(String(item.view_id)))),
3403
+ });
3404
+ }
3405
+ if (document.businessObjects) {
3406
+ return Object.freeze({
3407
+ ...document,
3408
+ businessObjects: Object.freeze({
3409
+ elements: Object.freeze((document.businessObjects.elements || []).filter(item => item && allowed.has(String(item.id)))),
3410
+ relationships: Object.freeze((document.businessObjects.relationships || []).filter(item => item && allowed.has(String(item.id)))),
3411
+ views: Object.freeze((document.businessObjects.views || []).filter(item => item && allowed.has(String(item.view_id)))),
3412
+ }),
3413
+ semanticSeeds: Object.freeze((document.semanticSeeds || []).filter(seed => seed && allowed.has(String(seed.objectId)))),
3414
+ hitReasons: Object.freeze((document.hitReasons || []).filter(reason => reason && allowed.has(String(reason.objectId)))),
3415
+ });
3416
+ }
3417
+ return document;
3418
+ }
3419
+
3420
+ function buildBusinessSemanticSummary(retrieved, query = {}) {
3421
+ if (retrieved && retrieved.responseProfile === 'business-summary') return retrieved;
3422
+ if (retrieved && retrieved.result && retrieved.result.responseProfile === 'business-summary') return retrieved.result;
3423
+ const source = retrieved && typeof retrieved === 'object' ? retrieved : {};
3424
+ const provenanceObjects = Array.isArray(source.provenance && source.provenance.objects)
3425
+ ? source.provenance.objects
3426
+ : [];
3427
+ const hitReasonByKey = new Map(provenanceObjects.map(item => [
3428
+ `${item.objectType}:${item.objectId}`,
3429
+ {
3430
+ firstInclusionReason: item.firstInclusionReason,
3431
+ supplementaryReasons: Array.isArray(item.supplementaryReasons) ? [...item.supplementaryReasons] : [],
3432
+ },
3433
+ ]));
3434
+ const recordById = new Map();
3435
+ const putRecord = (objectType, record, id) => { if (record && id) recordById.set(`${objectType}:${id}`, record); };
3436
+ for (const element of (source.closure && source.closure.elements) || []) putRecord('Element', element, element.id);
3437
+ for (const view of (source.viewClosure && source.viewClosure.views) || []) {
3438
+ putRecord('View', view, view.view_id);
3439
+ for (const member of view.memberElements || []) putRecord('Element', member, member.id);
3440
+ for (const member of view.memberRelationships || []) putRecord('ArchitectureRelationship', member, member.id);
3441
+ }
3442
+ for (const relationship of (source.endpointClosure && source.endpointClosure.relationships) || []) {
3443
+ putRecord('ArchitectureRelationship', relationship, relationship.id);
3444
+ if (relationship.source) putRecord('Element', relationship.source, relationship.source.id);
3445
+ if (relationship.target) putRecord('Element', relationship.target, relationship.target.id);
3446
+ }
3447
+ const ctx = {
3448
+ query,
3449
+ recordById,
3450
+ hitElementIds: buildHitIdSet(source, 'elements'),
3451
+ hitRelationshipIds: buildHitIdSet(source, 'relationships'),
3452
+ hitViewIds: buildHitIdSet(source, 'views'),
3453
+ };
3454
+ const seedLimit = businessSummaryLimit(query);
3455
+ const semanticSeeds = summarizeSeeds(source.seedsByType, hitReasonByKey, seedLimit, ctx);
3456
+ const elements = summarizeElements(source, hitReasonByKey, seedLimit * 2, ctx);
3457
+ const relationships = summarizeRelationships(source, hitReasonByKey, seedLimit * 2, ctx);
3458
+ const views = summarizeViews(source, hitReasonByKey, seedLimit, ctx);
3459
+ const includedObjectIds = Object.freeze([
3460
+ ...elements.map(item => item.id),
3461
+ ...relationships.map(item => item.id),
3462
+ ...views.map(item => item.id),
3463
+ ]);
3464
+ return Object.freeze({
3465
+ responseProfile: 'business-summary',
3466
+ purpose: query.purpose,
3467
+ intent: query.intent,
3468
+ semanticSeeds,
3469
+ businessObjects: Object.freeze({
3470
+ elements: Object.freeze(elements),
3471
+ relationships: Object.freeze(relationships),
3472
+ views: Object.freeze(views),
3473
+ }),
3474
+ hitReasons: Object.freeze(provenanceObjects.map(item => Object.freeze({
3475
+ objectType: item.objectType,
3476
+ objectId: item.objectId,
3477
+ firstInclusionReason: item.firstInclusionReason,
3478
+ supplementaryReasons: Object.freeze(Array.isArray(item.supplementaryReasons) ? item.supplementaryReasons : []),
3479
+ }))),
3480
+ policySummary: Object.freeze({
3481
+ policyId: source.closurePolicy && source.closurePolicy.policyId,
3482
+ purpose: source.closurePolicy && source.closurePolicy.category,
3483
+ boundaryRationale: source.boundary && source.boundary.rationale,
3484
+ }),
3485
+ boundarySummary: Object.freeze({
3486
+ includedObjectIds,
3487
+ includedCount: includedObjectIds.length,
3488
+ excluded: Object.freeze(Array.isArray(source.boundary && source.boundary.excluded) ? source.boundary.excluded : []),
3489
+ }),
3490
+ semanticIndex: Object.freeze({
3491
+ canonicalVersion: source.canonicalVersion,
3492
+ contentVersion: source.contentVersion,
3493
+ indexVersion: source.indexVersion,
3494
+ alignment: source.provenance && source.provenance.alignment && source.provenance.alignment.state,
3495
+ }),
3496
+ omittedByDefault: Object.freeze([
3497
+ 'embedding vectors',
3498
+ 'full provenance version evidence per object',
3499
+ 'queryTemplate',
3500
+ 'parameterContract',
3501
+ 'archimateSemantics',
3502
+ 'full element descriptions',
3503
+ 'full testcase bodies',
3504
+ ]),
3505
+ expandWith: 'Set query.responseProfile to "debug" to return the full semantic evidence payload.',
3506
+ });
3507
+ }
3508
+
3509
+ function applySemanticResponseProfile(response, query, options = {}) {
3510
+ if (!isCanonicalSubsetSemanticContract(query, options)) {
3511
+ if (shouldReturnDebugSemanticResult(query)) return normalizeSemanticToolResponse(response);
3512
+ const payload = parseToolResponsePayload(response);
3513
+ if (!payload) return response;
3514
+ if (payload.status === 'failed') {
3515
+ return normalizeFailedSemanticResponse(payload, response);
3516
+ }
3517
+ const source = payload.result || payload.document;
3518
+ const summary = buildBusinessSemanticSummary(source, query);
3519
+ const { document: _omittedDocument, ...payloadWithoutDocument } = payload;
3520
+ return getSystemArchitectureResult({
3521
+ ...payloadWithoutDocument,
3522
+ query: {
3523
+ ...(payload.query || query),
3524
+ responseProfile: 'business-summary',
3525
+ },
3526
+ result: summary,
3527
+ });
3528
+ }
3529
+ const payload = parseToolResponsePayload(response);
3530
+ if (!payload) return response;
3531
+ if (payload.status === 'failed') {
3532
+ return normalizeFailedSemanticResponse(payload, response);
3533
+ }
3534
+ const source = payload.result || payload.document;
3535
+ const subset = buildCanonicalSemanticDocumentSubset(source, options.canonicalDocument);
3536
+ if (subset.status === 'failed') {
3537
+ return getSystemArchitectureResult(subset);
3538
+ }
3539
+ const { document: _omittedDocument, result: _omittedResult, ...payloadWithoutDocument } = payload;
3540
+ return getSystemArchitectureResult({
3541
+ ...payloadWithoutDocument,
3542
+ query: {
3543
+ ...(payload.query || query),
3544
+ mode: 'semantic-query',
3545
+ semanticRetrieval: 'invoked',
3546
+ },
3547
+ document: subset.document,
3548
+ });
3549
+ }
3550
+
3551
+ function normalizeFailedSemanticResponse(payload, fallbackResponse) {
3552
+ const error = payload && payload.error;
3553
+ if (!error || error.category !== 'SEMANTIC_AUTO_ALIGNMENT_FAILED' || typeof error.action === 'string') {
3554
+ return fallbackResponse;
3555
+ }
3556
+ return getSystemArchitectureResult({
3557
+ ...payload,
3558
+ error: {
3559
+ ...error,
3560
+ action: 'Repair semantic lifecycle alignment, then retry the original query.',
3561
+ },
3562
+ });
3563
+ }
3564
+
3565
+ function buildCanonicalSemanticDocumentSubset(source, canonicalDocument = undefined, options = {}) {
3566
+ const evidence = source && typeof source === 'object' ? source : {};
3567
+ const endpointClosureRelationships = arrayAt(evidence, ['endpointClosure', 'relationships']);
3568
+ const viewClosureViews = arrayAt(evidence, ['viewClosure', 'views']);
3569
+ const viewMemberRelationships = viewClosureViews.flatMap(view => (
3570
+ Array.isArray(view && view.memberRelationships) ? view.memberRelationships : []
3571
+ ));
3572
+ const evidenceElements = uniqueById([
3573
+ ...arrayAt(evidence, ['closure', 'elements']),
3574
+ ...arrayAt(evidence, ['elements']),
3575
+ ...endpointClosureRelationships.flatMap(relationship => [relationship && relationship.source, relationship && relationship.target]),
3576
+ ...viewClosureViews.flatMap(view => (
3577
+ Array.isArray(view && view.memberElements) ? view.memberElements : []
3578
+ )),
3579
+ ...viewMemberRelationships.flatMap(relationship => [relationship && relationship.source, relationship && relationship.target]),
3580
+ ], 'id');
3581
+ const evidenceRelationships = uniqueById([
3582
+ ...endpointClosureRelationships,
3583
+ ...arrayAt(evidence, ['relationships']),
3584
+ ...viewMemberRelationships,
3585
+ ], 'id');
3586
+ const evidenceViews = uniqueById([
3587
+ ...viewClosureViews,
3588
+ ...arrayAt(evidence, ['views']),
3589
+ ], 'view_id');
3590
+
3591
+ const canonicalElements = Array.isArray(canonicalDocument && canonicalDocument.elements)
3592
+ ? canonicalDocument.elements
3593
+ : [];
3594
+ const canonicalRelationships = Array.isArray(canonicalDocument && canonicalDocument.relationships)
3595
+ ? canonicalDocument.relationships
3596
+ : [];
3597
+ const canonicalViews = Array.isArray(canonicalDocument && canonicalDocument.views)
3598
+ ? canonicalDocument.views
3599
+ : [];
3600
+
3601
+ const canonicalElementById = new Map(canonicalElements.map(element => [element && element.id, element]));
3602
+ const canonicalRelationshipById = new Map(canonicalRelationships.map(relationship => [relationship && relationship.id, relationship]));
3603
+ const canonicalViewById = new Map(canonicalViews.map(view => [view && view.view_id, view]));
3604
+ const evidenceElementCandidates = evidenceElements
3605
+ .map(item => classifyCanonicalSubsetCandidate(item, 'Element'))
3606
+ .filter(candidate => candidate && candidate.kind === 'Element');
3607
+ const evidenceRelationshipCandidates = evidenceRelationships
3608
+ .map(item => classifyCanonicalSubsetCandidate(item, 'ArchitectureRelationship'))
3609
+ .filter(candidate => candidate && candidate.kind === 'ArchitectureRelationship');
3610
+ const evidenceViewCandidates = evidenceViews
3611
+ .map(item => classifyCanonicalSubsetCandidate(item, 'View'))
3612
+ .filter(candidate => candidate && candidate.kind === 'View');
3613
+ const evidenceElementById = new Map(evidenceElementCandidates
3614
+ .map(candidate => [candidate.id, candidate.item]));
3615
+ const evidenceRelationshipById = new Map(evidenceRelationshipCandidates
3616
+ .map(candidate => [candidate.id, candidate.item]));
3617
+ const evidenceViewById = new Map(evidenceViewCandidates
3618
+ .map(candidate => [candidate.id, candidate.item]));
3619
+
3620
+ const elementIds = new Set([...evidenceElementById.keys()].filter(id => canonicalElementById.has(id)));
3621
+ const relationshipIds = new Set([...evidenceRelationshipById.keys()]);
3622
+ const viewIds = new Set([...evidenceViewById.keys()]);
3623
+
3624
+ const selectElement = (elementId, category, message) => {
3625
+ if (!evidenceElementById.has(elementId)) {
3626
+ return semanticSubsetError(category, message);
3627
+ }
3628
+ const element = canonicalElementById.get(elementId);
3629
+ if (!element) {
3630
+ return semanticSubsetError(category, message);
3631
+ }
3632
+ elementIds.add(elementId);
3633
+ return undefined;
3634
+ };
3635
+ const selectRelationship = (relationshipId, category, message) => {
3636
+ if (!evidenceRelationshipById.has(relationshipId)) {
3637
+ return { error: semanticSubsetError(category, message) };
3638
+ }
3639
+ const relationship = canonicalRelationshipById.get(relationshipId);
3640
+ if (!relationship) {
3641
+ return { error: semanticSubsetError(category, message) };
3642
+ }
3643
+ relationshipIds.add(relationshipId);
3644
+ return { relationship };
3645
+ };
3646
+
3647
+ for (const viewId of [...viewIds]) {
3648
+ const view = canonicalViewById.get(viewId);
3649
+ if (!view) {
3650
+ viewIds.delete(viewId);
3651
+ continue;
3652
+ }
3653
+ for (const elementId of view && Array.isArray(view.included_elements) ? view.included_elements : []) {
3654
+ const error = selectElement(
3655
+ elementId,
3656
+ 'SEMANTIC_SUBSET_VIEW_MISSING',
3657
+ `Semantic View subset is missing included Element '${elementId}'`,
3658
+ );
3659
+ if (error) {
3660
+ return error;
3661
+ }
3662
+ }
3663
+ for (const relationshipId of view && Array.isArray(view.included_relationships) ? view.included_relationships : []) {
3664
+ const selected = selectRelationship(
3665
+ relationshipId,
3666
+ 'SEMANTIC_SUBSET_VIEW_MISSING',
3667
+ `Semantic View subset is missing included Relationship '${relationshipId}'`,
3668
+ );
3669
+ if (selected.error) {
3670
+ return selected.error;
3671
+ }
3672
+ const { relationship } = selected;
3673
+ for (const endpointId of [relationship.source_id, relationship.target_id]) {
3674
+ const error = selectElement(
3675
+ endpointId,
3676
+ 'SEMANTIC_SUBSET_VIEW_MISSING',
3677
+ `Semantic View subset is missing endpoint Elements for Relationship '${relationship.id}'`,
3678
+ );
3679
+ if (error) {
3680
+ return error;
3681
+ }
3682
+ }
3683
+ }
3684
+ }
3685
+
3686
+ for (const relationshipId of [...relationshipIds]) {
3687
+ const selected = selectRelationship(
3688
+ relationshipId,
3689
+ 'SEMANTIC_SUBSET_RELATIONSHIP_MISSING',
3690
+ `Semantic Relationship subset is missing canonical Relationship '${relationshipId}'`,
3691
+ );
3692
+ if (selected.error) {
3693
+ return selected.error;
3694
+ }
3695
+ const { relationship } = selected;
3696
+ for (const endpointId of [relationship && relationship.source_id, relationship && relationship.target_id]) {
3697
+ const error = selectElement(
3698
+ endpointId,
3699
+ 'SEMANTIC_SUBSET_RELATIONSHIP_MISSING',
3700
+ `Semantic Relationship subset is missing endpoint Elements for Relationship '${relationship && relationship.id}'`,
3701
+ );
3702
+ if (error) {
3703
+ return error;
3704
+ }
3705
+ }
3706
+ }
3707
+
3708
+ // Attach the semantic similarity score to each retrieved object so callers can
3709
+ // judge relevance (top-K bounded recall may include borderline neighbours).
3710
+ const semanticScoreById = new Map();
3711
+ const seedsByType = evidence.seedsByType || {};
3712
+ for (const channelSeeds of Object.values(seedsByType)) {
3713
+ for (const seed of Array.isArray(channelSeeds) ? channelSeeds : []) {
3714
+ if (!seed || !seed.id) continue;
3715
+ const numericScore = Number(seed.score);
3716
+ if (!Number.isFinite(numericScore)) continue;
3717
+ const bareId = String(seed.id).replace(/^[^:]*:/, '');
3718
+ if (bareId && (!semanticScoreById.has(bareId) || numericScore > semanticScoreById.get(bareId))) {
3719
+ semanticScoreById.set(bareId, numericScore);
3720
+ }
3721
+ }
3722
+ }
3723
+ // The closure's rank-derived score (0.99..0.8, by closure rank) must NOT
3724
+ // overwrite a seed's TRUE similarity: when preferSeedSimilarity is set the
3725
+ // caller needs the cosine, so this override is skipped (otherwise the dedup
3726
+ // gate would flag every same-type seed in the top window regardless of actual
3727
+ // similarity -- the false-positive defect).
3728
+ if (!options.preferSeedSimilarity) for (const item of evidenceElements) {
3729
+ if (!item) continue;
3730
+ const numericScore = Number(item.semanticScore);
3731
+ if (!Number.isFinite(numericScore)) continue;
3732
+ // Evidence ids may still carry the channel prefix (real Neo4j shape); the
3733
+ // seed-score map and canonical lookups are keyed on the bare canonical id,
3734
+ // so normalize before comparing (otherwise the rank-derived score lands on
3735
+ // a phantom prefixed key and the tiny fused RRF score wins for the element).
3736
+ const key = String(item.id !== undefined ? item.id : item.view_id).replace(/^[^:]*:/, '');
3737
+ if (key && (!semanticScoreById.has(key) || numericScore > semanticScoreById.get(key))) {
3738
+ semanticScoreById.set(key, numericScore);
3739
+ }
3740
+ }
3741
+ const withSemanticScore = item => {
3742
+ if (!item) return item;
3743
+ const score = item.id !== undefined
3744
+ ? semanticScoreById.get(String(item.id))
3745
+ : semanticScoreById.get(String(item.view_id));
3746
+ return typeof score === 'number' ? Object.freeze({ ...item, semanticScore: score }) : item;
3747
+ };
3748
+ const elements = [...elementIds]
3749
+ .map(id => canonicalElementById.get(id))
3750
+ .filter(Boolean)
3751
+ .map(withSemanticScore);
3752
+ const relationships = [...relationshipIds]
3753
+ .map(id => canonicalRelationshipById.get(id))
3754
+ .filter(Boolean)
3755
+ .map(withSemanticScore);
3756
+ const views = [...viewIds]
3757
+ .map(id => canonicalViewById.get(id))
3758
+ .filter(Boolean)
3759
+ .map(withSemanticScore);
3760
+
3761
+ return {
3762
+ status: 'passed',
3763
+ document: {
3764
+ elements: elements.map(clone),
3765
+ relationships: relationships.map(clone),
3766
+ views: views.map(clone),
3767
+ },
3768
+ };
3769
+ }
3770
+
3771
+ function classifyCanonicalSubsetCandidate(item, fallbackKind) {
3772
+ if (!item || typeof item !== 'object') return undefined;
3773
+ const rawId = item.id || item.view_id || item.objectId || item.canonicalIdentity;
3774
+ if (!rawId) return undefined;
3775
+ const qualified = parseSemanticQualifiedId(rawId);
3776
+ if (qualified) {
3777
+ return { ...qualified, item };
3778
+ }
3779
+ return {
3780
+ kind: normalizeSemanticObjectKind(item.objectType || item.channel || fallbackKind),
3781
+ id: String(rawId),
3782
+ item,
3783
+ };
3784
+ }
3785
+
3786
+ function parseSemanticQualifiedId(rawId) {
3787
+ const text = String(rawId);
3788
+ for (const [prefix, kind] of [
3789
+ ['ArchitectureRelationship:', 'ArchitectureRelationship'],
3790
+ ['Relationship:', 'ArchitectureRelationship'],
3791
+ ['View:', 'View'],
3792
+ ['Element:', 'Element'],
3793
+ ]) {
3794
+ if (text.startsWith(prefix)) {
3795
+ return {
3796
+ kind,
3797
+ id: text.slice(prefix.length),
3798
+ };
3799
+ }
3800
+ }
3801
+ return undefined;
3802
+ }
3803
+
3804
+ function normalizeSemanticObjectKind(value) {
3805
+ const kind = String(value || '').toLowerCase();
3806
+ if (kind === 'architecturerelationship' || kind === 'relationship' || kind === 'relationships') {
3807
+ return 'ArchitectureRelationship';
3808
+ }
3809
+ if (kind === 'view' || kind === 'views') {
3810
+ return 'View';
3811
+ }
3812
+ return 'Element';
3813
+ }
3814
+
3815
+ function arrayAt(value, pathSegments) {
3816
+ let current = value;
3817
+ for (const segment of pathSegments) {
3818
+ current = current && current[segment];
3819
+ }
3820
+ return Array.isArray(current) ? current : [];
3821
+ }
3822
+
3823
+ function semanticSubsetError(category, message) {
3824
+ return queryError(category, message, { fullSnapshotFallback: false });
3825
+ }
3826
+
3827
+ function parseToolResponsePayload(response) {
3828
+ if (!response || typeof response !== 'object') return undefined;
3829
+ if (response.content && Array.isArray(response.content) && response.content[0] && typeof response.content[0].text === 'string') {
3830
+ try {
3831
+ return JSON.parse(response.content[0].text);
3832
+ } catch (_error) {
3833
+ return undefined;
3834
+ }
3835
+ }
3836
+ return response;
3837
+ }
3838
+
3839
+ function normalizeSemanticToolResponse(response) {
3840
+ if (response && response.content && Array.isArray(response.content)) return response;
3841
+ const payload = response && typeof response === 'object'
3842
+ ? response
3843
+ : { status: 'failed', error: { category: 'SEMANTIC_RETRIEVAL_FAILED', message: 'Semantic retrieval failed' } };
3844
+ return getSystemArchitectureResult(payload);
3845
+ }
3846
+
3847
+ function businessSummaryLimit(query) {
3848
+ const supplied = Number(query && (query.topN || query.limit || query.maxResults));
3849
+ return Number.isInteger(supplied) && supplied > 0 ? Math.min(supplied, 50) : 8;
3850
+ }
3851
+
3852
+ // A hit may be driven by an attribute/testcase (both are embedded), so surface
3853
+ // the matching bookkeeping text on HIT records only — so the agent sees WHY it
3854
+ // matched without a second lookup. Never attached to pruned neighbours.
3855
+ function tokenizeForMatch(text) {
3856
+ const tokens = new Set();
3857
+ const s = String(text || '');
3858
+ for (const word of s.toLowerCase().match(/[a-z0-9]{3,}/g) || []) tokens.add(word);
3859
+ for (const run of s.match(/[\u4e00-\u9fff]{2,}/g) || []) {
3860
+ tokens.add(run);
3861
+ for (let i = 0; i + 2 <= run.length; i += 1) tokens.add(run.slice(i, i + 2));
3862
+ }
3863
+ return [...tokens];
3864
+ }
3865
+
3866
+ function bookkeepingSnippet(record, objectType, query, maxLen = 240) {
3867
+ if (!record || typeof record !== 'object') return null;
3868
+ const candidates = [];
3869
+ if (objectType === 'ArchitectureRelationship' || objectType === 'Relationship') {
3870
+ if (typeof record.statement === 'string' && record.statement.trim()) candidates.push(record.statement.trim());
3871
+ if (typeof record.description === 'string' && record.description.trim()) candidates.push(record.description.trim());
3872
+ }
3873
+ for (const attribute of Array.isArray(record.attributes) ? record.attributes : []) {
3874
+ if (!attribute || typeof attribute.name !== 'string') continue;
3875
+ const text = (typeof attribute.value === 'string' && attribute.value.trim())
3876
+ || (typeof attribute.description === 'string' && attribute.description.trim()) || '';
3877
+ if (text) candidates.push(`${attribute.name}: ${text}`);
3878
+ }
3879
+ for (const testcase of Array.isArray(record.testcases) ? record.testcases : []) {
3880
+ if (!testcase) continue;
3881
+ const text = typeof testcase === 'string'
3882
+ ? testcase
3883
+ : (testcase.description || testcase.coverage || testcase.name || '');
3884
+ if (typeof text === 'string' && text.trim()) candidates.push(`AT ${testcase.name || ''}: ${text.trim()}`.trim());
3885
+ }
3886
+ if (!candidates.length) return null;
3887
+ const q = typeof query === 'string' ? query : (query && query.intent) || '';
3888
+ const tokens = tokenizeForMatch(q);
3889
+ const scored = candidates.map((text, index) => {
3890
+ const lower = text.toLowerCase();
3891
+ let overlap = 0;
3892
+ for (const token of tokens) if (lower.includes(token)) overlap += 1;
3893
+ return { text, overlap, index };
3894
+ }).sort((a, b) => (b.overlap - a.overlap) || (b.text.length - a.text.length) || (a.index - b.index));
3895
+ let out = '';
3896
+ for (const entry of scored) {
3897
+ if (out && out.length + entry.text.length + 2 > maxLen) break;
3898
+ out = out ? `${out} | ${entry.text}` : entry.text;
3899
+ if (out.length >= maxLen) break;
3900
+ }
3901
+ if (!out) return null;
3902
+ return out.length > maxLen ? `${out.slice(0, maxLen - 3)}...` : out;
3903
+ }
3904
+
3905
+ function buildHitIdSet(source, typeKey) {
3906
+ const set = new Set();
3907
+ const seeds = (source && source.seedsByType && source.seedsByType[typeKey]) || [];
3908
+ for (const seed of Array.isArray(seeds) ? seeds : []) {
3909
+ const raw = seed && (seed.id || seed.objectId || seed.canonicalIdentity);
3910
+ if (typeof raw === 'string' && raw) set.add(raw.includes(':') ? raw.split(':').pop() : raw);
3911
+ }
3912
+ return set;
3913
+ }
3914
+
3915
+ function summarizeSeeds(seedsByType = {}, hitReasonByKey, limit, ctx = {}) {
3916
+ return Object.freeze(Object.fromEntries(Object.entries(seedsByType).map(([type, seeds]) => [
3917
+ type,
3918
+ Object.freeze((Array.isArray(seeds) ? seeds : [])
3919
+ .slice()
3920
+ .sort((left, right) => Number(right.score || 0) - Number(left.score || 0))
3921
+ .slice(0, limit)
3922
+ .map(seed => {
3923
+ const objectType = seed.objectType || seed.channel || inferObjectTypeFromSeedType(type);
3924
+ const rawId = seed.id || seed.objectId || seed.canonicalIdentity;
3925
+ const objectId = typeof rawId === 'string' && rawId.includes(':') ? rawId.split(':').pop() : rawId;
3926
+ const reasons = hitReasonByKey.get(`${objectType}:${objectId}`) || {};
3927
+ const record = ctx.recordById ? ctx.recordById.get(`${objectType}:${objectId}`) : null;
3928
+ const snippet = record ? bookkeepingSnippet(record, objectType, ctx.query) : null;
3929
+ return Object.freeze({
3930
+ objectId,
3931
+ objectType,
3932
+ score: typeof seed.score === 'number' ? seed.score : undefined,
3933
+ hitReason: reasons.firstInclusionReason || 'semantic-seed',
3934
+ supplementaryReasons: Object.freeze(reasons.supplementaryReasons || []),
3935
+ ...(snippet ? { matchedSnippet: snippet } : {}),
3936
+ });
3937
+ })),
3938
+ ])));
3939
+ }
3940
+
3941
+ function inferObjectTypeFromSeedType(type) {
3942
+ if (type === 'relationships') return 'ArchitectureRelationship';
3943
+ if (type === 'views') return 'View';
3944
+ return 'Element';
3945
+ }
3946
+
3947
+ function summarizeElements(source, hitReasonByKey, limit, ctx = {}) {
3948
+ // Semantic subgraph rule: the attribute/testcase-DERIVED fields (status /
3949
+ // functionalPoints / testCoverage) and the matchedSnippet are the match
3950
+ // surface for the HIT elements only; closure neighbours drop them
3951
+ // (bookkeepingOmitted) — mirroring the structural-read projection.
3952
+ const hitIds = ctx.hitElementIds || buildHitIdSet(source, 'elements');
3953
+ return uniqueById([
3954
+ ...(((source.closure && source.closure.elements) || [])),
3955
+ ...((((source.viewClosure && source.viewClosure.views) || []).flatMap(view => view.memberElements || []))),
3956
+ ...((((source.endpointClosure && source.endpointClosure.relationships) || []).flatMap(relationship => [relationship.source, relationship.target]).filter(Boolean))),
3957
+ ], 'id').slice(0, limit).map(element => summarizeElement(element, hitReasonByKey, hitIds, ctx));
3958
+ }
3959
+
3960
+ function summarizeRelationships(source, hitReasonByKey, limit, ctx = {}) {
3961
+ const hitIds = ctx.hitRelationshipIds || buildHitIdSet(source, 'relationships');
3962
+ return uniqueById([
3963
+ ...(((source.endpointClosure && source.endpointClosure.relationships) || [])),
3964
+ ...((((source.viewClosure && source.viewClosure.views) || []).flatMap(view => view.memberRelationships || []))),
3965
+ ], 'id').slice(0, limit).map(relationship => summarizeRelationship(relationship, hitReasonByKey, hitIds, ctx));
3966
+ }
3967
+
3968
+ function summarizeViews(source, hitReasonByKey, limit) {
3969
+ return uniqueById(((source.viewClosure && source.viewClosure.views) || []), 'view_id')
3970
+ .slice(0, limit)
3971
+ .map(view => summarizeView(view, hitReasonByKey));
3972
+ }
3973
+
3974
+ function summarizeElement(element, hitReasonByKey, hitIds = null, ctx = {}) {
3975
+ const attributes = attributesMap(element);
3976
+ const reasons = hitReasonByKey.get(`Element:${element.id}`) || {};
3977
+ const isHit = !hitIds || hitIds.size === 0 || hitIds.has(element.id);
3978
+ const base = {
3979
+ id: element.id,
3980
+ name: element.name,
3981
+ type: element.type,
3982
+ descriptionSummary: summarizeText(element.description),
3983
+ hitReason: reasons.firstInclusionReason,
3984
+ supplementaryReasons: Object.freeze(reasons.supplementaryReasons || []),
3985
+ };
3986
+ if (isHit) {
3987
+ const snippet = bookkeepingSnippet(element, 'Element', ctx.query);
3988
+ return Object.freeze({
3989
+ ...base,
3990
+ status: attributes.deliveryStatus || attributes.status,
3991
+ functionalPoints: Object.freeze(Object.entries(attributes)
3992
+ .filter(([name]) => name.startsWith('functionalPoint'))
3993
+ .map(([, value]) => value)),
3994
+ testCoverage: summarizeTestcases(element.testcases),
3995
+ ...(snippet ? { matchedSnippet: snippet } : {}),
3996
+ });
3997
+ }
3998
+ const hasBookkeeping = Object.keys(attributes).length > 0
3999
+ || (Array.isArray(element.testcases) && element.testcases.length > 0);
4000
+ return Object.freeze({ ...base, ...(hasBookkeeping ? { bookkeepingOmitted: true } : {}) });
4001
+ }
4002
+
4003
+ function summarizeRelationship(relationship, hitReasonByKey, hitIds = null, ctx = {}) {
4004
+ const reasons = hitReasonByKey.get(`ArchitectureRelationship:${relationship.id}`) || {};
4005
+ const base = {
4006
+ id: relationship.id,
4007
+ name: relationship.name,
4008
+ type: relationship.type,
4009
+ source_id: relationship.source_id,
4010
+ target_id: relationship.target_id,
4011
+ hitReason: reasons.firstInclusionReason,
4012
+ supplementaryReasons: Object.freeze(reasons.supplementaryReasons || []),
4013
+ };
4014
+ const isHit = !hitIds || hitIds.size === 0 || hitIds.has(relationship.id);
4015
+ if (!isHit) {
4016
+ return Object.freeze(base);
4017
+ }
4018
+ const snippet = bookkeepingSnippet(relationship, 'ArchitectureRelationship', ctx.query);
4019
+ return Object.freeze({ ...base, ...(snippet ? { matchedSnippet: snippet } : {}) });
4020
+ }
4021
+
4022
+ function summarizeView(view, hitReasonByKey) {
4023
+ const reasons = hitReasonByKey.get(`View:${view.view_id}`) || {};
4024
+ return Object.freeze({
4025
+ view_id: view.view_id,
4026
+ view_name: view.view_name || view.name,
4027
+ descriptionSummary: summarizeText(view.description),
4028
+ elementCount: Array.isArray(view.included_elements) ? view.included_elements.length : undefined,
4029
+ relationshipCount: Array.isArray(view.included_relationships) ? view.included_relationships.length : undefined,
4030
+ hitReason: reasons.firstInclusionReason,
4031
+ supplementaryReasons: Object.freeze(reasons.supplementaryReasons || []),
4032
+ });
4033
+ }
4034
+
4035
+ function attributesMap(value = {}) {
4036
+ const result = {};
4037
+ for (const attribute of Array.isArray(value.attributes) ? value.attributes : []) {
4038
+ if (attribute && typeof attribute.name === 'string') result[attribute.name] = attribute.value;
4039
+ }
4040
+ return result;
4041
+ }
4042
+
4043
+ function summarizeTestcases(testcases) {
4044
+ return Object.freeze((Array.isArray(testcases) ? testcases : []).map(testcase => {
4045
+ if (typeof testcase === 'string') return { name: testcase };
4046
+ return {
4047
+ name: testcase.name || testcase.id || testcase.testcasename,
4048
+ status: testcase.status,
4049
+ coverage: testcase.coverage || testcase.coveragePoint || testcase.description,
4050
+ };
4051
+ }));
4052
+ }
4053
+
4054
+ function summarizeText(text) {
4055
+ if (typeof text !== 'string') return undefined;
4056
+ const compact = text.replace(/\s+/g, ' ').trim();
4057
+ return compact.length <= 180 ? compact : `${compact.slice(0, 177)}...`;
4058
+ }
4059
+
4060
+ function uniqueById(items, idField) {
4061
+ const seen = new Set();
4062
+ const result = [];
4063
+ for (const item of items) {
4064
+ const id = item && item[idField];
4065
+ if (!id || seen.has(id)) continue;
4066
+ seen.add(id);
4067
+ result.push(item);
4068
+ }
4069
+ return result;
4070
+ }
4071
+
4072
+ async function createDefaultProductionSemanticOperatorJourney(options = {}) {
4073
+ const workspaceRoot = options.repositoryRoot || resolveWorkspaceRoot();
4074
+ const graphPath = resolveWorkspacePath(workspaceRoot, DEFAULT_GRAPH_PATH);
4075
+ const canonicalGraph = readJson(graphPath.absolutePath, graphPath.relativePath);
4076
+ const readinessStore = createProductionSemanticReadinessStore({
4077
+ repositoryRoot: workspaceRoot,
4078
+ });
4079
+ const retrieval = createDefaultSemanticRetrieval({
4080
+ canonicalGraph,
4081
+ repositoryRoot: workspaceRoot,
4082
+ readinessBoundary: readinessStore,
4083
+ });
4084
+ const runtime = createProductionGraphRagRuntime({
4085
+ canonicalGraph,
4086
+ neo4jRetrievalBoundary: retrieval,
4087
+ });
4088
+ const journey = createProductionSemanticOperatorJourney({
4089
+ initializeWorkspace: request => initializeWorkspace(request),
4090
+ syncCanonicalStructuralProjection: request => syncCanonicalStructuralProjection(request),
4091
+ resolveApprovedConfiguration: request => resolveApprovedLiveConfiguration(request),
4092
+ runSemanticBackfill: request => runtime.runSemanticBackfill(request),
4093
+ readSemanticReadiness: () => retrieval.readReadiness(),
4094
+ querySystemArchitecture: request => executeSemanticSystemArchitectureQuery(request, {
4095
+ semanticRetrievalBoundary: retrieval,
4096
+ canonicalSubsetForNoAnchor: true,
4097
+ repositoryRoot: workspaceRoot,
4098
+ }),
4099
+ });
4100
+ return Object.freeze({
4101
+ ...journey,
4102
+ canonicalSubsetForNoAnchor: true,
4103
+ });
4104
+ }
4105
+
4106
+ function createDefaultCanonicalSemanticInitComposition(options = {}) {
4107
+ const repositoryRoot = options.repositoryRoot || resolveWorkspaceRoot();
4108
+ const readinessStore = createProductionSemanticReadinessStore({ repositoryRoot });
4109
+ const graphPath = resolveWorkspacePath(repositoryRoot, DEFAULT_GRAPH_PATH);
4110
+ const canonicalGraph = readJson(graphPath.absolutePath, graphPath.relativePath);
4111
+ let configurationEvidence;
4112
+ return Object.freeze({
4113
+ configurationBehavior: Object.freeze({
4114
+ readGate(name) {
4115
+ return process.env[name];
4116
+ },
4117
+ async resolve() {
4118
+ configurationEvidence = await resolveApprovedLiveConfiguration({
4119
+ repositoryRoot,
4120
+ requiredOptIns: [LIVE_PROVIDER_OPT_IN, W31_LIVE_OPT_IN],
4121
+ });
4122
+ return configurationEvidence;
4123
+ },
4124
+ }),
4125
+ productionGraphRagRuntime: Object.freeze({
4126
+ async runSemanticBackfill(request) {
4127
+ const runtime = await createDefaultProductionSemanticRuntime({ repositoryRoot });
4128
+ try {
4129
+ return await runtime.runSemanticBackfill(request);
4130
+ } finally {
4131
+ if (runtime && typeof runtime.close === 'function') {
4132
+ await runtime.close();
4133
+ }
4134
+ }
4135
+ },
4136
+ }),
4137
+ finalReadiness: Object.freeze({
4138
+ async invalidate(evidence) {
4139
+ return readinessStore.invalidate(evidence);
4140
+ },
4141
+ async recordFailure(evidence) {
4142
+ return readinessStore.recordFailure(evidence);
4143
+ },
4144
+ async verifyQueryability(backfill) {
4145
+ if (!backfill || backfill.alignmentState !== 'Aligned') return false;
4146
+ const contentVersion = backfill.contentVersion || backfill.canonicalVersion;
4147
+ const indexVersion = backfill.indexVersion || backfill.canonicalVersion;
4148
+ const retrieval = createDefaultSemanticRetrieval({
4149
+ canonicalGraph,
4150
+ repositoryRoot,
4151
+ });
4152
+ await retrieval.probeQueryability(Object.freeze({
4153
+ purpose: 'implementation-design',
4154
+ intent: 'verify system architecture semantic queryability',
4155
+ }), Object.freeze({
4156
+ state: 'QueryabilityProbe',
4157
+ canonicalVersion: backfill.canonicalVersion,
4158
+ contentVersion,
4159
+ indexVersion,
4160
+ }));
4161
+ return true;
4162
+ },
4163
+ async verifyGlobalCoherence(backfill) {
4164
+ return Boolean(
4165
+ backfill
4166
+ && backfill.alignmentState === 'Aligned'
4167
+ && ['Element', 'ArchitectureRelationship', 'View'].every(channel => (
4168
+ backfill.channels
4169
+ && backfill.channels[channel]
4170
+ && backfill.channels[channel].status === 'complete'
4171
+ && backfill.channels[channel].canonicalVersion === backfill.canonicalVersion
4172
+ )),
4173
+ );
4174
+ },
4175
+ async recordAligned(evidence) {
4176
+ const profile = configurationEvidence && configurationEvidence.configuration;
4177
+ return readinessStore.recordAligned(Object.freeze({
4178
+ ...evidence,
4179
+ channels: Object.freeze((evidence.channels || []).map(channel => Object.freeze({
4180
+ ...channel,
4181
+ state: 'Aligned',
4182
+ provider: profile.embeddingProvider,
4183
+ model: profile.embeddingModel,
4184
+ modelVersion: profile.embeddingModelVersion,
4185
+ dimensions: profile.embeddingDimensions,
4186
+ queryable: true,
4187
+ coherent: true,
4188
+ }))),
4189
+ }));
4190
+ },
4191
+ }),
4192
+ });
4193
+ }
4194
+
4195
+ async function createDefaultProductionSemanticRuntime(options = {}) {
4196
+ const workspaceRoot = options.repositoryRoot || resolveWorkspaceRoot();
4197
+ const configuration = await resolveDefaultSemanticConfiguration(workspaceRoot);
4198
+ const neo4j = require('neo4j-driver');
4199
+ const driver = neo4j.driver(
4200
+ configuration.neo4jDatabaseUrl,
4201
+ neo4j.auth.basic(
4202
+ configuration.neo4jDatabaseUsername,
4203
+ configuration.neo4jDatabasePassword,
4204
+ ),
4205
+ );
4206
+ const graphPath = resolveWorkspacePath(workspaceRoot, DEFAULT_GRAPH_PATH);
4207
+ const canonicalDocument = readJson(graphPath.absolutePath, graphPath.relativePath);
4208
+ const canonicalVersion = deriveSemanticCanonicalVersion(canonicalDocument);
4209
+ const canonicalSnapshot = Object.freeze({
4210
+ ...canonicalDocument,
4211
+ version: canonicalVersion,
4212
+ });
4213
+ const qualification = Object.freeze({
4214
+ approvedByHuman: true,
4215
+ provider: configuration.embeddingProvider,
4216
+ model: configuration.embeddingModel,
4217
+ version: configuration.embeddingModelVersion,
4218
+ dimensions: configuration.embeddingDimensions,
4219
+ source: 'explicit-human-approval',
4220
+ });
4221
+ const providerClient = createLiveEmbeddingProviderClient({
4222
+ configuration,
4223
+ transport: Object.freeze({
4224
+ request(url, options) {
4225
+ if (typeof global.fetch !== 'function') {
4226
+ const error = new Error('LIVE_PROVIDER_TRANSPORT_UNAVAILABLE');
4227
+ error.category = 'LIVE_PROVIDER_TRANSPORT_UNAVAILABLE';
4228
+ throw error;
4229
+ }
4230
+ return global.fetch(url, options);
4231
+ },
4232
+ }),
4233
+ });
4234
+
4235
+ const runtime = createProductionGraphRagRuntime({
4236
+ canonicalGraph: canonicalSnapshot,
4237
+ neo4jRetrievalBoundary: Object.freeze({
4238
+ async retrieve() {
4239
+ const error = new Error('SEMANTIC_RETRIEVAL_REQUEST_REQUIRED');
4240
+ error.category = 'SEMANTIC_RETRIEVAL_REQUEST_REQUIRED';
4241
+ throw error;
4242
+ },
4243
+ }),
4244
+ embeddingQualification: qualification,
4245
+ semanticPersistence: Object.freeze({
4246
+ canonicalSource: Object.freeze({
4247
+ async readSnapshot() {
4248
+ return canonicalSnapshot;
4249
+ },
4250
+ }),
4251
+ structuralProjection: Object.freeze({
4252
+ async requireComplete() {
4253
+ await verifyArchitectureSync({
4254
+ architecturePath: graphPath.relativePath,
4255
+ document: canonicalDocument,
4256
+ driver,
4257
+ database: configuration.neo4jDatabase,
4258
+ });
4259
+ return Object.freeze({
4260
+ status: 'complete',
4261
+ canonicalVersion,
4262
+ });
4263
+ },
4264
+ }),
4265
+ embeddingProvider: Object.freeze({
4266
+ async embedBatch(batch) {
4267
+ const vectors = [];
4268
+ const failures = [];
4269
+ for (const record of batch) {
4270
+ try {
4271
+ vectors.push(Object.freeze({
4272
+ canonicalIdentity: record.canonicalIdentity,
4273
+ vector: Object.freeze(await providerClient.embed(buildSemanticRecordText(record.channel, record.canonicalObject))),
4274
+ }));
4275
+ } catch (error) {
4276
+ failures.push(Object.freeze({
4277
+ canonicalIdentity: record.canonicalIdentity,
4278
+ category: error && error.category ? error.category : 'LIVE_PROVIDER_REQUEST_FAILED',
4279
+ }));
4280
+ }
4281
+ }
4282
+ return Object.freeze({
4283
+ vectors: Object.freeze(vectors),
4284
+ failures: Object.freeze(failures),
4285
+ });
4286
+ },
4287
+ }),
4288
+ neo4jDriver: driver,
4289
+ canonicalAuthority: Object.freeze({
4290
+ assertProjectionOnly() {
4291
+ return Object.freeze({
4292
+ authority: 'canonical-json',
4293
+ projectionRole: 'subordinate-projection-index',
4294
+ });
4295
+ },
4296
+ }),
4297
+ configuration,
4298
+ qualification,
4299
+ batchSize: 100,
4300
+ }),
4301
+ });
4302
+ return Object.freeze({
4303
+ ...runtime,
4304
+ async close() {
4305
+ await driver.close();
4306
+ },
4307
+ });
4308
+ }
4309
+
4310
+ // Resolve the canonical semantic-init/backfill configuration through the SAME
4311
+ // profile-aware resolver the retrieval path uses, so argo init embeds via the
4312
+ // configured provider (ARGO_EMBEDDING_PROFILE) instead of a hardcoded cloud
4313
+ // profile. `resolveApprovedLiveConfiguration` still fails closed when a required
4314
+ // key is missing or an unknown key is present in the .env file.
4315
+ async function resolveDefaultSemanticConfiguration(repositoryRoot) {
4316
+ const evidence = await resolveApprovedLiveConfiguration({
4317
+ repositoryRoot,
4318
+ requiredOptIns: [LIVE_PROVIDER_OPT_IN, W31_LIVE_OPT_IN],
4319
+ });
4320
+ return buildDefaultSemanticConfiguration(evidence);
4321
+ }
4322
+
4323
+ function deriveSemanticCanonicalVersion(document) {
4324
+ return `canonical:${crypto.createHash('sha256').update(JSON.stringify({
4325
+ name: document.name || 'System',
4326
+ elements: (document.elements || []).map(element => element.id).sort(),
4327
+ relationships: (document.relationships || []).map(relationship => relationship.id).sort(),
4328
+ views: (document.views || []).map(view => view.view_id).sort(),
4329
+ })).digest('hex')}`;
4330
+ }
4331
+
4332
+ function resolveSemanticRetrievalBoundary(dependencies, context = {}) {
4333
+ if (!dependencies) {
4334
+ return createDefaultSemanticRetrievalBoundary(context);
4335
+ }
4336
+ if (
4337
+ dependencies.semanticRetrievalBoundary
4338
+ && typeof dependencies.semanticRetrievalBoundary.retrieve === 'function'
4339
+ ) {
4340
+ return dependencies.semanticRetrievalBoundary;
4341
+ }
4342
+
4343
+ const runtime = dependencies.productionGraphRagRuntime
4344
+ || (dependencies.productionGraphRagDependencies
4345
+ ? createProductionGraphRagRuntime(dependencies.productionGraphRagDependencies)
4346
+ : undefined);
4347
+ if (!runtime || typeof runtime.querySemantic !== 'function') {
4348
+ return undefined;
4349
+ }
4350
+ return {
4351
+ retrieve(request) {
4352
+ return runtime.querySemantic(request);
4353
+ },
4354
+ };
4355
+ }
4356
+
4357
+ function createDefaultSemanticRetrievalBoundary(context = {}) {
4358
+ return createDefaultSemanticRetrieval({
4359
+ canonicalGraph: context.canonicalGraph,
4360
+ });
4361
+ }
4362
+
4363
+ function attachContextWarnings(payload, context) {
4364
+ const recovery = context && context.neo4jSyncRecovery;
4365
+ if (!recovery || !recovery.attempted) {
4366
+ return payload;
4367
+ }
4368
+
4369
+ payload.neo4jRecovery = recovery;
4370
+ if (recovery.status === 'failed') {
4371
+ payload.warnings = addUnique(payload.warnings || [], [
4372
+ `Neo4j automatic resync failed before servicing ${context.graphPath.relativePath}: ${recovery.error}`,
4373
+ 'The canonical JSON graph is still being served and written. Neo4j will be retried again on the next canonical read or write, or you can run node .argo/scripts/syncSystemArchitectureToNeo4j.js manually.',
4374
+ ]);
4375
+ }
4376
+ return payload;
4377
+ }
4378
+
4379
+ function send(message) {
4380
+ process.stdout.write(`${JSON.stringify(message)}\n`);
4381
+ }
4382
+
4383
+ async function handleRequest(request, dependencies = undefined) {
4384
+ const { id, method, params } = request;
4385
+
4386
+ if (method === 'initialize') {
4387
+ return {
4388
+ jsonrpc: '2.0',
4389
+ id,
4390
+ result: {
4391
+ protocolVersion: '2024-11-05',
4392
+ capabilities: { tools: {} },
4393
+ serverInfo: {
4394
+ name: 'argo',
4395
+ version: '1.0.0',
4396
+ },
4397
+ },
4398
+ };
4399
+ }
4400
+
4401
+ if (method === 'notifications/initialized') {
4402
+ return null;
4403
+ }
4404
+
4405
+ if (method === 'tools/list') {
4406
+ return {
4407
+ jsonrpc: '2.0',
4408
+ id,
4409
+ result: { tools: TOOLS },
4410
+ };
4411
+ }
4412
+
4413
+ if (method === 'tools/call') {
4414
+ try {
4415
+ let activeDependencies = dependencies;
4416
+ if (
4417
+ !activeDependencies
4418
+ && params.name === 'getSystemArchitecture'
4419
+ && params.arguments
4420
+ && Object.prototype.hasOwnProperty.call(params.arguments, 'query')
4421
+ && params.arguments.query
4422
+ ) {
4423
+ activeDependencies = {
4424
+ semanticOperatorJourney: await createDefaultProductionSemanticOperatorJourney({
4425
+ repositoryRoot: resolveWorkspaceRoot(params.arguments),
4426
+ }),
4427
+ canonicalSubsetForNoAnchor: true,
4428
+ };
4429
+ }
4430
+ const result = await callTool(
4431
+ params.name,
4432
+ params.arguments || {},
4433
+ activeDependencies,
4434
+ );
4435
+ return { jsonrpc: '2.0', id, result };
4436
+ } catch (error) {
4437
+ return {
4438
+ jsonrpc: '2.0',
4439
+ id,
4440
+ result: semanticOperatorErrorResult(error),
4441
+ };
4442
+ }
4443
+ }
4444
+
4445
+ if (method === 'ping') {
4446
+ return { jsonrpc: '2.0', id, result: {} };
4447
+ }
4448
+
4449
+ return {
4450
+ jsonrpc: '2.0',
4451
+ id,
4452
+ error: {
4453
+ code: -32601,
4454
+ message: `Method not found: ${method}`,
4455
+ },
4456
+ };
4457
+ }
4458
+
4459
+ async function main() {
4460
+ const rl = readline.createInterface({
4461
+ input: process.stdin,
4462
+ crlfDelay: Infinity,
4463
+ });
4464
+
4465
+ for await (const line of rl) {
4466
+ if (!line.trim()) {
4467
+ continue;
4468
+ }
4469
+ let request;
4470
+ try {
4471
+ request = JSON.parse(line);
4472
+ } catch {
4473
+ continue;
4474
+ }
4475
+ const response = await handleRequest(request);
4476
+ if (response) {
4477
+ send(response);
4478
+ }
4479
+ }
4480
+ }
4481
+
4482
+ if (require.main === module) {
4483
+ main().catch((error) => {
4484
+ console.error(error);
4485
+ process.exit(1);
4486
+ });
4487
+ }
4488
+
4489
+ module.exports = {
4490
+ GET_SYSTEM_ARCHITECTURE_OUTPUT_SCHEMA,
4491
+ TOOLS,
4492
+ applyMutations,
4493
+ buildBusinessSemanticSummary,
4494
+ buildSemanticDedupAdvisory,
4495
+ selectCreatedElementAdds,
4496
+ evaluateSemanticDedupGate,
4497
+ callTool,
4498
+ compactMutationResponse,
4499
+ createDefaultCanonicalSemanticInitComposition,
4500
+ createDefaultProductionSemanticOperatorJourney,
4501
+ applySemanticScopeFilter,
4502
+ handleRequest,
4503
+ loadContext,
4504
+ main,
4505
+ memoryHitCard,
4506
+ resolveSemanticScope,
4507
+ validateDocument,
4508
+ };