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,1244 @@
1
+ const path = require('node:path');
2
+ const crypto = require('node:crypto');
3
+ const { AsyncLocalStorage } = require('node:async_hooks');
4
+ const {
5
+ resolveApprovedLiveConfiguration,
6
+ } = require('./liveEmbeddingProviderConfig.js');
7
+ const {
8
+ createLiveEmbeddingProviderClient,
9
+ } = require('./liveEmbeddingProviderClient.js');
10
+ const {
11
+ createProductionGraphRagRuntime,
12
+ } = require('./productionGraphRagRuntime.js');
13
+ const {
14
+ getWorkspaceRoot,
15
+ resolveArgoPath,
16
+ } = require('../argo-paths.js');
17
+ const {
18
+ isHybridEnabled,
19
+ hybridTopK,
20
+ hybridWeights,
21
+ rrfK,
22
+ fuseChannelSeeds,
23
+ sanitizeFulltextQuery,
24
+ } = require('./hybridRetrieval.js');
25
+ const {
26
+ isRerankEnabled,
27
+ rerankConfig,
28
+ resolveRerankProvider,
29
+ rerankCandidates,
30
+ applyRerankOrder,
31
+ } = require('./rerankRetrieval.js');
32
+ const {
33
+ runSemanticAlignment,
34
+ } = require('./semanticAlignmentRunner.js');
35
+ const {
36
+ markPhase,
37
+ } = require('./mcpCrashDiagnostics.js');
38
+ const {
39
+ composeQueryEmbeddingInput,
40
+ } = require('./embeddingProviderProfile.js');
41
+
42
+ const APPROVED_SOURCE_KEYS = Object.freeze([
43
+ 'ARGO_EMBEDDING_BASE_URL',
44
+ 'ARGO_EMBEDDING_MODEL',
45
+ 'ARGO_EMBEDDING_PROVIDER',
46
+ 'ARGO_EMBEDDING_MODEL_VERSION',
47
+ 'ARGO_EMBEDDING_DIMENSIONS',
48
+ 'ARGO_NEO4J_DATABASE_URL',
49
+ 'ARGO_NEO4J_DATABASE_USERNAME',
50
+ 'ARGO_NEO4J_DATABASE_PASSWORD',
51
+ 'QWEN_KEY',
52
+ ]);
53
+ const LEGACY_NEO4J_KEYS = Object.freeze([
54
+ 'ARGO_NEO4J_URI',
55
+ 'ARGO_NEO4J_USERNAME',
56
+ 'ARGO_NEO4J_PASSWORD',
57
+ ]);
58
+ const APPROVED_PROFILE = Object.freeze({
59
+ baseUrl: 'https://llm-clids9mqc5o1mbvb.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
60
+ model: 'qwen3.7-text-embedding',
61
+ provider: 'alibaba-cloud-model-studio-openai-compatible-cn-beijing',
62
+ version: 'qualification-2026-07-25',
63
+ dimensions: 1536,
64
+ });
65
+ const CHANNELS = Object.freeze([
66
+ Object.freeze({
67
+ channel: 'Element',
68
+ key: 'elements',
69
+ objectType: 'Element',
70
+ threshold: 0.8,
71
+ indexName: 'argo_production_semantic_element_vector',
72
+ }),
73
+ Object.freeze({
74
+ channel: 'ArchitectureRelationship',
75
+ key: 'relationships',
76
+ objectType: 'ArchitectureRelationship',
77
+ threshold: 0.78,
78
+ indexName: 'argo_production_semantic_relationship_vector',
79
+ }),
80
+ Object.freeze({
81
+ channel: 'View',
82
+ key: 'views',
83
+ objectType: 'View',
84
+ threshold: 0.76,
85
+ indexName: 'argo_production_semantic_view_vector',
86
+ }),
87
+ ]);
88
+ // Project an explicit metadata allowlist instead of properties(node): Neo4j map
89
+ // projection `.*` lets an existing property win, so properties(node) / node{.*, vector:null}
90
+ // would still ship the 1536-dim vector; the read path only consumes canonicalIdentity, channel, searchText and score.
91
+ const VECTOR_QUERY_CYPHER = [
92
+ 'CALL db.index.vector.queryNodes($indexName, $topK, $vector)',
93
+ 'YIELD node, score',
94
+ 'WHERE node.channel = $channel',
95
+ 'RETURN {canonicalIdentity: node.canonicalIdentity, channel: node.channel, searchText: node.searchText, dimensions: node.dimensions, provider: node.provider, model: node.model, modelVersion: node.modelVersion, canonicalVersion: node.canonicalVersion, contentVersion: node.contentVersion, indexVersion: node.indexVersion} AS record, score',
96
+ 'ORDER BY score DESC',
97
+ ].join('\n');
98
+ const VECTOR_QUERY_CYPHER_SCOPED = [
99
+ 'CALL db.index.vector.queryNodes($indexName, $topK, $vector)',
100
+ 'YIELD node, score',
101
+ 'WHERE node.channel = $channel AND node.canonicalIdentity IN $canonicalIdentities',
102
+ 'RETURN {canonicalIdentity: node.canonicalIdentity, channel: node.channel, searchText: node.searchText, dimensions: node.dimensions, provider: node.provider, model: node.model, modelVersion: node.modelVersion, canonicalVersion: node.canonicalVersion, contentVersion: node.contentVersion, indexVersion: node.indexVersion} AS record, score',
103
+ 'ORDER BY score DESC',
104
+ ].join('\n');
105
+ const LEXICAL_QUERY_CYPHER = [
106
+ 'CALL db.index.fulltext.queryNodes($indexName, $queryText, { limit: $topK })',
107
+ 'YIELD node, score',
108
+ 'WHERE node.channel = $channel',
109
+ 'RETURN {canonicalIdentity: node.canonicalIdentity, channel: node.channel, searchText: node.searchText, dimensions: node.dimensions, provider: node.provider, model: node.model, modelVersion: node.modelVersion, canonicalVersion: node.canonicalVersion, contentVersion: node.contentVersion, indexVersion: node.indexVersion} AS record, score',
110
+ 'ORDER BY score DESC',
111
+ ].join('\n');
112
+ const LEXICAL_QUERY_CYPHER_SCOPED = [
113
+ 'CALL db.index.fulltext.queryNodes($indexName, $queryText, { limit: $topK })',
114
+ 'YIELD node, score',
115
+ 'WHERE node.channel = $channel AND node.canonicalIdentity IN $canonicalIdentities',
116
+ 'RETURN {canonicalIdentity: node.canonicalIdentity, channel: node.channel, searchText: node.searchText, dimensions: node.dimensions, provider: node.provider, model: node.model, modelVersion: node.modelVersion, canonicalVersion: node.canonicalVersion, contentVersion: node.contentVersion, indexVersion: node.indexVersion} AS record, score',
117
+ 'ORDER BY score DESC',
118
+ ].join('\n');
119
+ const READINESS_QUERY_CYPHER = [
120
+ 'MATCH (readiness:ArgoProductionSemanticReadiness {identity: $identity})',
121
+ 'RETURN properties(readiness) AS readiness',
122
+ ].join('\n');
123
+ const INITIAL_WINDOW_SIZE = 2;
124
+ // Purpose-aware, env-configurable similarity thresholds + bounded top-K recall.
125
+ // Audit keeps the strict threshold (precision); memory-retrieval purposes use a
126
+ // looser threshold so relevant-but-paraphrased memory is recalled, while results
127
+ // are bounded to ARGO_SEMANTIC_TOP_K so noise stays bounded. Thresholds are
128
+ // overridable per channel via ARGO_SEMANTIC_{MEMORY|AUDIT}_THRESHOLD_<CHANNEL>.
129
+ const AUDIT_PURPOSES = new Set(['audit']);
130
+ const DEFAULT_MEMORY_THRESHOLD = 0.55;
131
+ const DEFAULT_AUDIT_THRESHOLD = 0.8;
132
+ const DEFAULT_TOP_K = 8;
133
+ const SELECTED_VIEW_ID = 'semprod-wp2-default-retrieval-readiness';
134
+
135
+ function envNumber(key, fallback) {
136
+ const value = Number(process.env[key]);
137
+ return Number.isFinite(value) ? value : fallback;
138
+ }
139
+ function memoryThresholdFor(channel) {
140
+ return envNumber(
141
+ `ARGO_SEMANTIC_MEMORY_THRESHOLD_${channel.channel.toUpperCase()}`,
142
+ envNumber('ARGO_SEMANTIC_MEMORY_THRESHOLD', DEFAULT_MEMORY_THRESHOLD),
143
+ );
144
+ }
145
+ function auditThresholdFor(channel) {
146
+ return envNumber(
147
+ `ARGO_SEMANTIC_AUDIT_THRESHOLD_${channel.channel.toUpperCase()}`,
148
+ envNumber('ARGO_SEMANTIC_AUDIT_THRESHOLD', DEFAULT_AUDIT_THRESHOLD),
149
+ );
150
+ }
151
+ function resolveTopK() {
152
+ const k = envNumber('ARGO_SEMANTIC_TOP_K', DEFAULT_TOP_K);
153
+ return Number.isInteger(k) && k > 0 ? k : DEFAULT_TOP_K;
154
+ }
155
+ // The single production seed gate: a retrieved record becomes a seed only when
156
+ // its TRUE vector similarity reaches the purpose-aware threshold. Exposed so
157
+ // acceptance tests exercise the exact predicate the retrieval runtime uses.
158
+ function isSeedAboveThreshold(score, threshold) {
159
+ return Number.isFinite(score) && Number.isFinite(threshold) && score >= threshold;
160
+ }
161
+ const testCompositionStorage = new AsyncLocalStorage();
162
+
163
+ function createDefaultSemanticRetrieval(dependencies = {}) {
164
+ const canonicalGraph = requireCanonicalGraph(dependencies.canonicalGraph);
165
+ const readinessBoundary = dependencies.readinessBoundary;
166
+ return Object.freeze({
167
+ async retrieve(request = {}) {
168
+ const composition = await resolveRetrievalComposition(dependencies);
169
+ try {
170
+ const activeTestComposition = testCompositionStorage.getStore();
171
+ const activeReadinessBoundary = activeTestComposition
172
+ && activeTestComposition.useReadinessBoundary !== true
173
+ ? undefined
174
+ : readinessBoundary;
175
+ let configurationEvidence = await composition.resolveConfiguration();
176
+ let evidence = await readAndEvaluatePersistentReadiness(
177
+ composition,
178
+ canonicalGraph,
179
+ activeReadinessBoundary,
180
+ expectedEmbeddingQualification(configurationEvidence.configuration),
181
+ );
182
+ if (!evidence.alignment.aligned) {
183
+ await attemptAutomaticAlignment({
184
+ composition,
185
+ request,
186
+ alignment: evidence.alignment,
187
+ });
188
+ evidence = await readAndEvaluatePersistentReadiness(
189
+ composition,
190
+ canonicalGraph,
191
+ activeReadinessBoundary,
192
+ expectedEmbeddingQualification(configurationEvidence.configuration),
193
+ );
194
+ if (!evidence.alignment.aligned) {
195
+ throw semanticAutomaticAlignmentFailed(evidence.alignment);
196
+ }
197
+ }
198
+ return await executeWpP2Retrieval({
199
+ composition,
200
+ request,
201
+ canonicalGraph,
202
+ readiness: evidence.readiness,
203
+ configurationEvidence,
204
+ });
205
+ } finally {
206
+ if (typeof composition.dispose === 'function') {
207
+ await composition.dispose();
208
+ }
209
+ }
210
+ },
211
+ async probeQueryability(request = {}, readiness = {}) {
212
+ const composition = await resolveRetrievalComposition(dependencies);
213
+ try {
214
+ const configurationEvidence = await composition.resolveConfiguration();
215
+ return await executeWpP2Retrieval({
216
+ composition,
217
+ request,
218
+ canonicalGraph,
219
+ readiness,
220
+ configurationEvidence,
221
+ });
222
+ } finally {
223
+ if (typeof composition.dispose === 'function') {
224
+ await composition.dispose();
225
+ }
226
+ }
227
+ },
228
+ async readReadiness() {
229
+ const composition = await resolveRetrievalComposition(dependencies);
230
+ try {
231
+ const activeTestComposition = testCompositionStorage.getStore();
232
+ const activeReadinessBoundary = activeTestComposition
233
+ && activeTestComposition.useReadinessBoundary !== true
234
+ ? undefined
235
+ : readinessBoundary;
236
+ const configurationEvidence = await composition.resolveConfiguration();
237
+ const evidence = await readAndEvaluatePersistentReadiness(
238
+ composition,
239
+ canonicalGraph,
240
+ activeReadinessBoundary,
241
+ expectedEmbeddingQualification(configurationEvidence.configuration),
242
+ );
243
+ return publicReadinessOutcome(evidence.alignment);
244
+ } finally {
245
+ if (typeof composition.dispose === 'function') {
246
+ await composition.dispose();
247
+ }
248
+ }
249
+ },
250
+ });
251
+ }
252
+
253
+ async function resolveRetrievalComposition(dependencies) {
254
+ const activeTestComposition = testCompositionStorage.getStore();
255
+ return activeTestComposition
256
+ ? createTestComposition(activeTestComposition)
257
+ : createProductionComposition(dependencies);
258
+ }
259
+
260
+ async function executeWpP2Retrieval({
261
+ composition,
262
+ request,
263
+ canonicalGraph,
264
+ readiness,
265
+ configurationEvidence,
266
+ }) {
267
+ const { canonicalIdentities, ...completeRequest } = request;
268
+ const provider = createLiveEmbeddingProviderClient({
269
+ configuration: configurationEvidence.configuration,
270
+ transport: composition.transport,
271
+ });
272
+ markPhase('retrieval:embed:start');
273
+ const vector = await provider.embed(composeQueryEmbeddingInput(
274
+ request.intent,
275
+ configurationEvidence.configuration.embeddingQueryInstruction,
276
+ ));
277
+ markPhase('retrieval:embed:done');
278
+ requireQualifiedVector(vector, configurationEvidence.configuration.embeddingDimensions);
279
+ const purpose = request && typeof request.purpose === 'string' ? request.purpose : '';
280
+ const strict = AUDIT_PURPOSES.has(purpose);
281
+ const topK = Number.isInteger(request.topK) && request.topK > 0 ? request.topK : resolveTopK();
282
+ const scoped = Array.isArray(canonicalIdentities) && canonicalIdentities.length > 0;
283
+ const hybrid = isHybridEnabled() && request.hybrid !== false;
284
+ const lexicalTopK = hybridTopK();
285
+ const fusionK = rrfK();
286
+ const fusionWeights = hybridWeights();
287
+ const rerank = isRerankEnabled() && request.rerank !== false;
288
+ const rerankOptions = rerankConfig();
289
+ const rerankProvider = rerank ? resolveRerankProvider(configurationEvidence.configuration) : null;
290
+ // Rerank needs a larger candidate pool than the final top-K.
291
+ const pool = rerank ? Math.max(topK, rerankOptions.poolSize) : topK;
292
+ const channelSeeds = [];
293
+ for (const channel of CHANNELS) {
294
+ markPhase('retrieval:vector:' + channel.channel);
295
+ const vectorSeeds = await exhaustChannel({
296
+ channel,
297
+ neo4jDriver: composition.neo4jDriver,
298
+ vector,
299
+ threshold: strict ? auditThresholdFor(channel) : memoryThresholdFor(channel),
300
+ maxSeeds: pool,
301
+ ...(scoped ? { canonicalIdentities } : {}),
302
+ });
303
+ let seeds = vectorSeeds;
304
+ if (hybrid) {
305
+ markPhase('retrieval:lexical:' + channel.channel);
306
+ const lexicalSeeds = await exhaustLexicalChannel({
307
+ channel,
308
+ neo4jDriver: composition.neo4jDriver,
309
+ queryText: request.intent,
310
+ maxSeeds: lexicalTopK,
311
+ ...(scoped ? { canonicalIdentities } : {}),
312
+ });
313
+ seeds = fuseChannelSeeds({ vectorSeeds, lexicalSeeds, k: fusionK, limit: Math.max(pool, lexicalTopK), weights: fusionWeights });
314
+ }
315
+ channelSeeds.push({ channel, seeds });
316
+ }
317
+ if (rerank) {
318
+ markPhase('retrieval:rerank:start');
319
+ // Rerank every channel CONCURRENTLY: the LLM calls dominate latency and are
320
+ // independent, so parallelizing turns the cost from sum(channels) into
321
+ // ~one call. fail-open: a null/empty order keeps the original ordering.
322
+ const rerankedSeeds = await Promise.all(channelSeeds.map(({ seeds }) => (
323
+ seeds.length > 1
324
+ ? rerankCandidates({
325
+ query: request.intent,
326
+ candidates: seeds,
327
+ provider: rerankProvider,
328
+ transport: composition.transport,
329
+ maxReturn: rerankOptions.maxReturn,
330
+ }).then(ordered => applyRerankOrder(seeds, ordered, topK))
331
+ : seeds
332
+ )));
333
+ channelSeeds.forEach((entry, index) => { entry.seeds = rerankedSeeds[index]; });
334
+ markPhase('retrieval:rerank:done');
335
+ }
336
+ const seedsByType = {};
337
+ for (const { channel, seeds } of channelSeeds) {
338
+ seedsByType[channel.key] = seeds;
339
+ }
340
+ return completeSemanticResult({
341
+ request: completeRequest,
342
+ canonicalGraph,
343
+ readiness,
344
+ seedsByType,
345
+ configurationEvidence,
346
+ });
347
+ }
348
+
349
+ async function withDefaultSemanticRetrievalTestComposition(composition, callback, options = {}) {
350
+ requireExactTestComposition(composition, callback);
351
+ return testCompositionStorage.run(Object.freeze({
352
+ ...composition,
353
+ useReadinessBoundary: options.useReadinessBoundary === true,
354
+ }), callback);
355
+ }
356
+
357
+ async function createTestComposition(composition) {
358
+ return Object.freeze({
359
+ resolveConfiguration: () => resolveRawTestConfiguration(
360
+ composition.sourceBehavior,
361
+ composition.sourceAdapters,
362
+ ),
363
+ transport: composition.transport,
364
+ neo4jDriver: composition.neo4jDriver,
365
+ });
366
+ }
367
+
368
+ async function createProductionComposition(dependencies) {
369
+ const repositoryRoot = dependencies.repositoryRoot
370
+ || getWorkspaceRoot();
371
+ let configurationEvidence;
372
+ let neo4jHandle = null;
373
+ async function disposeNeo4j() {
374
+ const handle = neo4jHandle;
375
+ neo4jHandle = null;
376
+ if (!handle) return;
377
+ try { await handle.session.close(); } catch { /* ignore */ }
378
+ try { await handle.driver.close(); } catch { /* ignore */ }
379
+ }
380
+ function ensureNeo4jSession() {
381
+ if (neo4jHandle) return neo4jHandle.session;
382
+ const configuration = configurationEvidence.configuration;
383
+ const neo4j = require('neo4j-driver');
384
+ const driver = neo4j.driver(
385
+ configuration.neo4jDatabaseUrl,
386
+ neo4j.auth.basic(configuration.neo4jDatabaseUsername, configuration.neo4jDatabasePassword),
387
+ );
388
+ const session = driver.session(configuration.neo4jDatabase === undefined
389
+ ? undefined
390
+ : { database: configuration.neo4jDatabase });
391
+ neo4jHandle = { driver, session };
392
+ return session;
393
+ }
394
+ return Object.freeze({
395
+ async resolveConfiguration() {
396
+ configurationEvidence = await resolveApprovedLiveConfiguration({
397
+ repositoryRoot,
398
+ useCase: 'production-semantic-query',
399
+ });
400
+ return configurationEvidence;
401
+ },
402
+ transport: Object.freeze({
403
+ request(url, options) {
404
+ if (typeof global.fetch !== 'function') {
405
+ throw safeError('LIVE_PROVIDER_TRANSPORT_UNAVAILABLE');
406
+ }
407
+ return global.fetch(url, options);
408
+ },
409
+ }),
410
+ neo4jDriver: Object.freeze({
411
+ async execute(operation) {
412
+ if (!configurationEvidence) {
413
+ throw safeError('EXTERNAL_CREDENTIALS_REQUIRED');
414
+ }
415
+ if (operation && operation.kind === 'semantic-auto-alignment-attempt') {
416
+ return runScriptOwnedSemanticAlignment(operation);
417
+ }
418
+ try {
419
+ return await runOperationOnSession(ensureNeo4jSession(), operation);
420
+ } catch (error) {
421
+ // A failed run may leave the session unusable; drop the handle so the
422
+ // rest of this retrieval (or the next one) reconnects cleanly.
423
+ await disposeNeo4j();
424
+ throw error;
425
+ }
426
+ },
427
+ }),
428
+ async dispose() {
429
+ await disposeNeo4j();
430
+ },
431
+ });
432
+ }
433
+
434
+ // Pure operation runner: runs one Cypher operation on a caller-owned Neo4j
435
+ // session and maps the result. The session/driver lifecycle lives in the
436
+ // production composition (ONE handle per retrieval, reused across every vector
437
+ // window, then closed) -- correctly reused without leaving a lingering handle,
438
+ // which would keep short-lived processes alive. Creating AND closing a driver
439
+ // per operation caused the rapid handle churn that intermittently aborted the
440
+ // MCP with a native libuv assertion on Windows (confirmed crash phase:
441
+ // retrieval:vector-window:ArchitectureRelationship).
442
+ async function runOperationOnSession(session, operation) {
443
+ const result = await session.run(operation.cypher, operation.parameters);
444
+ if (operation.kind === 'semantic-readiness-read') {
445
+ const readiness = result.records[0] && result.records[0].get('readiness');
446
+ return { records: readiness ? [readiness] : [] };
447
+ }
448
+ const records = result.records.map(record => ({
449
+ ...record.get('record'),
450
+ score: numberValue(record.get('score')),
451
+ }));
452
+ if (operation.kind === 'semantic-lexical-query') {
453
+ return { records };
454
+ }
455
+ const offset = operation.parameters.offset;
456
+ const windowSize = operation.parameters.windowSize;
457
+ const returnedCount = Math.max(0, records.length - offset);
458
+ const hasMore = records.length === operation.parameters.topK;
459
+ return {
460
+ records,
461
+ windowEvidence: {
462
+ offset,
463
+ windowSize,
464
+ returnedCount,
465
+ hasMore,
466
+ nextOffset: hasMore ? operation.parameters.topK : null,
467
+ windowExhausted: !hasMore,
468
+ },
469
+ };
470
+ }
471
+
472
+ async function attemptAutomaticAlignment({ composition, request, alignment }) {
473
+ try {
474
+ const result = await composition.neo4jDriver.execute(Object.freeze({
475
+ kind: 'semantic-auto-alignment-attempt',
476
+ originalQuery: clone(request),
477
+ observedReadiness: Object.freeze({
478
+ state: alignment.state,
479
+ canonicalVersion: alignment.canonicalVersion,
480
+ contentVersion: alignment.contentVersion,
481
+ indexVersion: alignment.indexVersion,
482
+ completedChannels: alignment.completedChannels,
483
+ missingChannels: alignment.missingChannels,
484
+ mismatchedChannels: alignment.mismatchedChannels,
485
+ fullSnapshotFallback: false,
486
+ }),
487
+ }));
488
+ if (!result || result.status !== 'aligned') {
489
+ throw semanticAutomaticAlignmentFailed(alignment);
490
+ }
491
+ return result;
492
+ } catch (error) {
493
+ throw semanticAutomaticAlignmentFailed(alignment, error);
494
+ }
495
+ }
496
+
497
+ function runScriptOwnedSemanticAlignment(operation) {
498
+ return runSemanticAlignment(getWorkspaceRoot()).then(
499
+ () => Object.freeze({
500
+ status: 'aligned',
501
+ originalQuery: operation && operation.originalQuery,
502
+ }),
503
+ );
504
+ }
505
+
506
+ async function resolveRawTestConfiguration(sourceBehavior, sourceAdapters) {
507
+ if (
508
+ !sourceBehavior
509
+ || !sourceAdapters
510
+ || typeof sourceBehavior.readProcessKey !== 'function'
511
+ || typeof sourceBehavior.readFileEntries !== 'function'
512
+ ) {
513
+ throw safeError('SECRET_SOURCE_PROVENANCE_PROHIBITED');
514
+ }
515
+ const expectedFilePath = path.resolve(String(sourceBehavior.expectedFilePath));
516
+ const filesystem = sourceAdapters.filesystem;
517
+ const fileExists = Boolean(filesystem && filesystem.existsSync(expectedFilePath));
518
+ if (fileExists) {
519
+ assertProtectedSecretFile(expectedFilePath, sourceAdapters);
520
+ }
521
+
522
+ const processValues = new Map();
523
+ for (const key of [...APPROVED_SOURCE_KEYS, ...LEGACY_NEO4J_KEYS]) {
524
+ const prohibitedReader = key === 'QWEN_KEY'
525
+ ? sourceBehavior.readTestDefaultKey || sourceBehavior.readFallbackKey
526
+ : undefined;
527
+ if (prohibitedReader) {
528
+ prohibitedReader(key);
529
+ throw safeError('SECRET_SOURCE_PROVENANCE_PROHIBITED');
530
+ }
531
+ processValues.set(key, sourceBehavior.readProcessKey(key));
532
+ }
533
+ if (LEGACY_NEO4J_KEYS.some(key => present(processValues.get(key)))) {
534
+ throw safeError('SECRET_SOURCE_PROVENANCE_PROHIBITED');
535
+ }
536
+
537
+ const fileValues = new Map();
538
+ const entries = sourceBehavior.readFileEntries(expectedFilePath);
539
+ if (!Array.isArray(entries)) {
540
+ throw safeError('SECRET_SOURCE_PROVENANCE_PROHIBITED');
541
+ }
542
+ for (const entry of entries) {
543
+ if (!Array.isArray(entry) || entry.length !== 2 || fileValues.has(entry[0])) {
544
+ throw safeError('SECRET_FILE_DUPLICATE_KEY');
545
+ }
546
+ if (!APPROVED_SOURCE_KEYS.includes(entry[0])) {
547
+ throw safeError('SECRET_SOURCE_PROVENANCE_PROHIBITED');
548
+ }
549
+ fileValues.set(entry[0], entry[1]);
550
+ }
551
+
552
+ const selected = {};
553
+ const attribution = {};
554
+ for (const key of APPROVED_SOURCE_KEYS) {
555
+ const processValue = processValues.get(key);
556
+ const fileValue = fileValues.get(key);
557
+ if (present(processValue) && present(fileValue) && processValue !== fileValue) {
558
+ throw safeError(['QWEN_KEY', 'ARGO_NEO4J_DATABASE_PASSWORD'].includes(key)
559
+ ? 'SECRET_SOURCE_CONFLICT'
560
+ : 'LIVE_PROVIDER_CONFIGURATION_CONFLICT');
561
+ }
562
+ if (present(processValue)) {
563
+ selected[key] = processValue;
564
+ attribution[key] = 'process';
565
+ } else if (present(fileValue)) {
566
+ selected[key] = fileValue;
567
+ attribution[key] = 'file';
568
+ } else {
569
+ const error = safeError(['QWEN_KEY', 'ARGO_NEO4J_DATABASE_PASSWORD'].includes(key)
570
+ ? 'APPROVED_SECRET_REQUIRED'
571
+ : 'LIVE_PROVIDER_CONFIGURATION_REQUIRED');
572
+ error.field = key;
573
+ throw error;
574
+ }
575
+ }
576
+ requireApprovedProfile(selected);
577
+ const configuration = Object.freeze({
578
+ embeddingBaseUrl: selected.ARGO_EMBEDDING_BASE_URL,
579
+ embeddingModel: selected.ARGO_EMBEDDING_MODEL,
580
+ embeddingProvider: selected.ARGO_EMBEDDING_PROVIDER,
581
+ embeddingModelVersion: selected.ARGO_EMBEDDING_MODEL_VERSION,
582
+ embeddingDimensions: APPROVED_PROFILE.dimensions,
583
+ neo4jDatabaseUrl: selected.ARGO_NEO4J_DATABASE_URL,
584
+ neo4jDatabaseUsername: selected.ARGO_NEO4J_DATABASE_USERNAME,
585
+ neo4jDatabasePassword: selected.ARGO_NEO4J_DATABASE_PASSWORD,
586
+ qwenKey: selected.QWEN_KEY,
587
+ });
588
+ return Object.freeze({
589
+ ...configuration,
590
+ configuration,
591
+ attribution: Object.freeze(attribution),
592
+ });
593
+ }
594
+
595
+ function assertProtectedSecretFile(expectedFilePath, adapters) {
596
+ const filesystem = adapters.filesystem;
597
+ const stat = filesystem.lstatSync(expectedFilePath);
598
+ if (
599
+ !stat
600
+ || typeof stat.isFile !== 'function'
601
+ || !stat.isFile()
602
+ || (typeof stat.isSymbolicLink === 'function' && stat.isSymbolicLink())
603
+ || path.resolve(filesystem.realpathSync(expectedFilePath)) !== expectedFilePath
604
+ ) {
605
+ throw safeError('SECRET_FILE_PATH_UNSAFE');
606
+ }
607
+ if (
608
+ !adapters.git
609
+ || adapters.git.isIgnored() !== true
610
+ || adapters.git.isTracked() !== false
611
+ ) {
612
+ throw safeError('SECRET_FILE_GIT_STATE_UNSAFE');
613
+ }
614
+ }
615
+
616
+ function requireApprovedProfile(values) {
617
+ const expected = {
618
+ ARGO_EMBEDDING_BASE_URL: APPROVED_PROFILE.baseUrl,
619
+ ARGO_EMBEDDING_MODEL: APPROVED_PROFILE.model,
620
+ ARGO_EMBEDDING_PROVIDER: APPROVED_PROFILE.provider,
621
+ ARGO_EMBEDDING_MODEL_VERSION: APPROVED_PROFILE.version,
622
+ ARGO_EMBEDDING_DIMENSIONS: String(APPROVED_PROFILE.dimensions),
623
+ };
624
+ if (Object.entries(expected).some(([key, value]) => values[key] !== value)) {
625
+ throw safeError('LIVE_PROVIDER_CONFIGURATION_REQUIRED');
626
+ }
627
+ }
628
+
629
+ async function readPersistentReadiness(neo4jDriver, readinessBoundary) {
630
+ if (readinessBoundary) {
631
+ if (typeof readinessBoundary.read !== 'function') {
632
+ throw safeError('SEMANTIC_READINESS_BOUNDARY_INVALID');
633
+ }
634
+ const readiness = await readinessBoundary.read();
635
+ if (readiness && readiness.state !== 'Unknown') {
636
+ return { readiness, requireQualification: true };
637
+ }
638
+ }
639
+ const result = await neo4jDriver.execute(Object.freeze({
640
+ kind: 'semantic-readiness-read',
641
+ cypher: READINESS_QUERY_CYPHER,
642
+ parameters: Object.freeze({ identity: 'system-architecture-semantic-readiness' }),
643
+ }));
644
+ const readiness = result && Array.isArray(result.records) ? result.records[0] : undefined;
645
+ if (!readiness || typeof readiness !== 'object') {
646
+ return {
647
+ readiness: {
648
+ state: 'Unknown',
649
+ canonicalVersion: null,
650
+ contentVersion: null,
651
+ indexVersion: null,
652
+ channels: [],
653
+ },
654
+ requireQualification: false,
655
+ };
656
+ }
657
+ return { readiness, requireQualification: false };
658
+ }
659
+
660
+ function evaluatePersistentReadiness(readiness, canonicalGraph, requireQualification = false, expectedQualification = APPROVED_PROFILE) {
661
+ const expectedCanonicalVersion = deriveCanonicalVersion(canonicalGraph);
662
+ const records = new Map((Array.isArray(readiness.channels) ? readiness.channels : [])
663
+ .map(record => [record.channel, record]));
664
+ const missingChannels = CHANNELS
665
+ .map(item => item.channel)
666
+ .filter(channel => !records.has(channel));
667
+ const mismatchedChannels = [];
668
+ for (const channel of CHANNELS) {
669
+ const record = records.get(channel.channel);
670
+ if (!record) continue;
671
+ if (
672
+ record.state !== 'Aligned'
673
+ || record.canonicalVersion !== readiness.canonicalVersion
674
+ || record.contentVersion !== readiness.contentVersion
675
+ || record.indexVersion !== readiness.indexVersion
676
+ || (requireQualification && (
677
+ record.provider !== expectedQualification.provider
678
+ || record.model !== expectedQualification.model
679
+ || record.modelVersion !== expectedQualification.version
680
+ || record.dimensions !== expectedQualification.dimensions
681
+ || record.queryable !== true
682
+ || record.coherent !== true
683
+ ))
684
+ ) {
685
+ mismatchedChannels.push(channel.channel);
686
+ }
687
+ }
688
+ if (requireQualification && readiness.state === 'Aligned' && readiness.verified !== true) {
689
+ for (const channel of CHANNELS) {
690
+ if (!mismatchedChannels.includes(channel.channel)) mismatchedChannels.push(channel.channel);
691
+ }
692
+ }
693
+ if (readiness.canonicalVersion !== expectedCanonicalVersion && missingChannels.length === 0) {
694
+ for (const channel of CHANNELS) {
695
+ if (!mismatchedChannels.includes(channel.channel)) mismatchedChannels.push(channel.channel);
696
+ }
697
+ }
698
+ const aligned = readiness.state === 'Aligned'
699
+ && (!requireQualification || readiness.verified === true)
700
+ && readiness.canonicalVersion === expectedCanonicalVersion
701
+ && missingChannels.length === 0
702
+ && mismatchedChannels.length === 0;
703
+ return {
704
+ aligned,
705
+ state: readiness.state || 'Unknown',
706
+ canonicalVersion: readiness.canonicalVersion,
707
+ contentVersion: readiness.contentVersion,
708
+ indexVersion: readiness.indexVersion,
709
+ completedChannels: readiness.state === 'Aligned'
710
+ ? CHANNELS.map(item => item.channel).filter(channel => records.has(channel))
711
+ : arrayEvidence(readiness.completedChannels),
712
+ missingChannels: readiness.state === 'Aligned'
713
+ ? missingChannels
714
+ : arrayEvidence(readiness.missingChannels, missingChannels),
715
+ mismatchedChannels: readiness.state === 'Aligned'
716
+ ? mismatchedChannels
717
+ : arrayEvidence(readiness.mismatchedChannels, mismatchedChannels),
718
+ ...publicFailureEvidence(readiness),
719
+ };
720
+ }
721
+
722
+ function arrayEvidence(value, fallback = []) {
723
+ return Array.isArray(value)
724
+ ? value.filter(item => typeof item === 'string')
725
+ : fallback;
726
+ }
727
+
728
+ async function readAndEvaluatePersistentReadiness(composition, canonicalGraph, readinessBoundary, expectedQualification) {
729
+ const persistent = await readPersistentReadiness(composition.neo4jDriver, readinessBoundary);
730
+ const readiness = persistent.readiness;
731
+ const alignment = evaluatePersistentReadiness(
732
+ readiness,
733
+ canonicalGraph,
734
+ persistent.requireQualification,
735
+ expectedQualification,
736
+ );
737
+ return { composition, readiness, alignment };
738
+ }
739
+
740
+ function expectedEmbeddingQualification(configuration) {
741
+ return {
742
+ provider: configuration.embeddingProvider,
743
+ model: configuration.embeddingModel,
744
+ version: configuration.embeddingModelVersion,
745
+ dimensions: configuration.embeddingDimensions,
746
+ };
747
+ }
748
+
749
+ function publicFailureEvidence(readiness) {
750
+ const categories = new Set([
751
+ 'APPROVED_SECRET_REQUIRED',
752
+ 'SECRET_FILE_ACL_UNSAFE',
753
+ 'SECRET_SOURCE_PROVENANCE_PROHIBITED',
754
+ 'EXTERNAL_CREDENTIALS_REQUIRED',
755
+ 'EMBEDDING_QUALIFICATION_REQUIRED',
756
+ 'EMBEDDING_CONFIGURATION_REQUIRED',
757
+ 'SEMANTIC_LIFECYCLE_GATE_INVALID',
758
+ 'SEMANTIC_LIFECYCLE_FAILED',
759
+ 'PROVIDER_FAILED',
760
+ 'PROVIDER_VECTOR_INVALID',
761
+ 'PERSISTENCE_FAILED',
762
+ 'QUERYABILITY_FAILED',
763
+ 'GLOBAL_COHERENCE_FAILED',
764
+ ]);
765
+ if (!categories.has(readiness && readiness.category)) return {};
766
+ return {
767
+ category: readiness.category,
768
+ ...(typeof readiness.message === 'string' ? { message: readiness.message } : {}),
769
+ ...(typeof readiness.action === 'string' ? { action: readiness.action } : {}),
770
+ };
771
+ }
772
+
773
+ function publicReadinessOutcome(alignment) {
774
+ return {
775
+ state: alignment.state,
776
+ verified: alignment.aligned,
777
+ canonicalVersion: alignment.canonicalVersion,
778
+ contentVersion: alignment.contentVersion,
779
+ indexVersion: alignment.indexVersion,
780
+ completedChannels: alignment.completedChannels,
781
+ missingChannels: alignment.missingChannels,
782
+ mismatchedChannels: alignment.mismatchedChannels,
783
+ fullSnapshotFallback: false,
784
+ };
785
+ }
786
+
787
+ async function exhaustChannel({
788
+ channel,
789
+ neo4jDriver,
790
+ vector,
791
+ canonicalIdentities,
792
+ threshold,
793
+ maxSeeds,
794
+ }) {
795
+ const scoped = Array.isArray(canonicalIdentities) && canonicalIdentities.length > 0;
796
+ const scopedCanonicalIdentities = scoped
797
+ ? scopeCanonicalIdentitiesForChannel(canonicalIdentities, channel)
798
+ : canonicalIdentities;
799
+ const accepted = [];
800
+ const seen = new Set();
801
+ const effectiveThreshold = typeof threshold === 'number' ? threshold : channel.threshold;
802
+ const effectiveMax = Number.isInteger(maxSeeds) && maxSeeds > 0 ? maxSeeds : Number.POSITIVE_INFINITY;
803
+ let offset = 0;
804
+ while (accepted.length < effectiveMax) {
805
+ markPhase('retrieval:vector-window:' + channel.channel);
806
+ const parameters = Object.freeze({
807
+ indexName: channel.indexName,
808
+ channel: channel.channel,
809
+ offset,
810
+ windowSize: INITIAL_WINDOW_SIZE,
811
+ topK: offset + INITIAL_WINDOW_SIZE,
812
+ vector,
813
+ ...(scoped ? { canonicalIdentities: scopedCanonicalIdentities } : {}),
814
+ });
815
+ const result = await neo4jDriver.execute(Object.freeze({
816
+ kind: 'semantic-vector-window-query',
817
+ channel: channel.channel,
818
+ indexName: channel.indexName,
819
+ cypher: scoped ? VECTOR_QUERY_CYPHER_SCOPED : VECTOR_QUERY_CYPHER,
820
+ parameters,
821
+ }));
822
+ const records = Array.isArray(result && result.records) ? result.records : [];
823
+ const newlyVisible = records.slice(offset);
824
+ for (const raw of newlyVisible) {
825
+ if (accepted.length >= effectiveMax) break;
826
+ const record = normalizeVectorRecord(raw, channel);
827
+ if (record && isSeedAboveThreshold(record.score, effectiveThreshold) && !seen.has(record.id)) {
828
+ seen.add(record.id);
829
+ accepted.push(Object.freeze(record));
830
+ }
831
+ }
832
+ const window = result && result.windowEvidence;
833
+ if (!window || window.windowExhausted === true || window.hasMore === false) break;
834
+ if (!Number.isInteger(window.nextOffset) || window.nextOffset <= offset) {
835
+ throw safeError('SEMANTIC_VECTOR_WINDOW_EVIDENCE_INVALID');
836
+ }
837
+ offset = window.nextOffset;
838
+ }
839
+ return Object.freeze(accepted);
840
+ }
841
+
842
+ // Lexical (full-text/BM25) sibling of exhaustChannel. Additive and fail-open:
843
+ // it returns [] when the query text is blank, when the full-text index is
844
+ // missing, or on any error, so hybrid retrieval can never break the baseline.
845
+ async function exhaustLexicalChannel({
846
+ channel,
847
+ neo4jDriver,
848
+ queryText,
849
+ maxSeeds,
850
+ canonicalIdentities,
851
+ }) {
852
+ if (typeof queryText !== 'string' || queryText.trim() === '') {
853
+ return Object.freeze([]);
854
+ }
855
+ const safeQuery = sanitizeFulltextQuery(queryText);
856
+ if (safeQuery === '') {
857
+ return Object.freeze([]);
858
+ }
859
+ const scoped = Array.isArray(canonicalIdentities) && canonicalIdentities.length > 0;
860
+ const scopedCanonicalIdentities = scoped
861
+ ? scopeCanonicalIdentitiesForChannel(canonicalIdentities, channel)
862
+ : canonicalIdentities;
863
+ const effectiveMax = Number.isInteger(maxSeeds) && maxSeeds > 0 ? maxSeeds : INITIAL_WINDOW_SIZE;
864
+ const indexName = `${channel.indexName}_fulltext`;
865
+ try {
866
+ const result = await neo4jDriver.execute(Object.freeze({
867
+ kind: 'semantic-lexical-query',
868
+ channel: channel.channel,
869
+ indexName,
870
+ cypher: scoped ? LEXICAL_QUERY_CYPHER_SCOPED : LEXICAL_QUERY_CYPHER,
871
+ parameters: Object.freeze({
872
+ indexName,
873
+ channel: channel.channel,
874
+ queryText: safeQuery,
875
+ topK: effectiveMax,
876
+ ...(scoped ? { canonicalIdentities: scopedCanonicalIdentities } : {}),
877
+ }),
878
+ }));
879
+ const records = Array.isArray(result && result.records) ? result.records : [];
880
+ return Object.freeze(records
881
+ .map(raw => normalizeVectorRecord(raw, channel))
882
+ .filter(Boolean)
883
+ .slice(0, effectiveMax));
884
+ } catch {
885
+ return Object.freeze([]);
886
+ }
887
+ }
888
+
889
+ // Scope identities come from the canonical graph as BARE ids (e.g.
890
+ // "memory-eval-bench-wp-001"), but the semantic vector records store their
891
+ // canonicalIdentity with a channel prefix (e.g. "Element:memory-eval-bench-wp-001").
892
+ // Normalise the scope to the channel-prefixed form so the scoped Cypher
893
+ // `node.canonicalIdentity IN $canonicalIdentities` actually matches. A bare id
894
+ // that already carries a prefix (this or another channel's) is left as-is: it
895
+ // simply won't match records of this channel, which is the correct no-op.
896
+ function scopeCanonicalIdentitiesForChannel(identities, channel) {
897
+ if (!Array.isArray(identities)) return identities;
898
+ const prefix = `${channel.objectType}:`;
899
+ return identities.map(id => {
900
+ const text = String(id);
901
+ return text.includes(':') ? text : `${prefix}${text}`;
902
+ });
903
+ }
904
+
905
+ // Semantic vector records store their canonicalIdentity channel-prefixed
906
+ // (e.g. "Element:widget-1") so the scoped Cypher `node.canonicalIdentity IN
907
+ // $canonicalIdentities` matches. Every consumer of a seed's `id` — purpose
908
+ // closure anchors, provenance keys, and the canonical-subset score lookup —
909
+ // however keys on the BARE canonical graph id. Expose the bare id as `id` and
910
+ // keep the prefixed value as `canonicalIdentity` so a seed resolves against the
911
+ // canonical graph instead of a phantom prefixed id.
912
+ function bareCanonicalId(id) {
913
+ return String(id).replace(/^[^:]*:/, '');
914
+ }
915
+
916
+ function normalizeVectorRecord(raw, channel) {
917
+ if (!raw || typeof raw !== 'object') return undefined;
918
+ const canonicalIdentity = raw.canonicalIdentity || raw.id || raw.objectId;
919
+ const score = numberValue(raw.score);
920
+ if (!canonicalIdentity || !Number.isFinite(score)) return undefined;
921
+ return {
922
+ ...raw,
923
+ id: bareCanonicalId(canonicalIdentity),
924
+ canonicalIdentity,
925
+ objectType: channel.objectType,
926
+ channel: channel.channel,
927
+ score,
928
+ };
929
+ }
930
+
931
+ async function completeSemanticResult({
932
+ request,
933
+ canonicalGraph,
934
+ readiness,
935
+ seedsByType,
936
+ configurationEvidence,
937
+ }) {
938
+ const anchors = [
939
+ ...seedsByType.elements,
940
+ ...seedsByType.relationships,
941
+ ...seedsByType.views,
942
+ ].map(seed => seed.id);
943
+ const runtime = createProductionGraphRagRuntime({
944
+ canonicalGraph,
945
+ embeddingQualification: {
946
+ approvedByHuman: true,
947
+ provider: configurationEvidence.configuration.embeddingProvider,
948
+ model: configurationEvidence.configuration.embeddingModel,
949
+ version: configurationEvidence.configuration.embeddingModelVersion,
950
+ dimensions: configurationEvidence.configuration.embeddingDimensions,
951
+ },
952
+ neo4jRetrievalBoundary: {
953
+ async retrieve() {
954
+ throw safeError('DEFAULT_RETRIEVAL_CLOSURE_ONLY');
955
+ },
956
+ },
957
+ });
958
+ const closureResult = await runtime.closePurposePolicyScope({
959
+ ...request,
960
+ anchors,
961
+ viewClosureFixture: {
962
+ targetViewId: SELECTED_VIEW_ID,
963
+ explicitlyRequestedViewIds: [],
964
+ independentlyMatchedViewIds: [],
965
+ },
966
+ });
967
+ const versions = {
968
+ canonicalVersion: readiness.canonicalVersion,
969
+ contentVersion: readiness.contentVersion,
970
+ indexVersion: readiness.indexVersion,
971
+ };
972
+ const structural = buildExactStructuralCompletion(canonicalGraph, closureResult, versions);
973
+ const provenance = buildExactProvenance({
974
+ seedsByType,
975
+ closureResult,
976
+ structural,
977
+ versions,
978
+ });
979
+ return Object.freeze({
980
+ ...closureResult,
981
+ ...structural,
982
+ seedsByType: Object.freeze(seedsByType),
983
+ configurationEvidence: Object.freeze({
984
+ attribution: configurationEvidence.attribution,
985
+ provider: configurationEvidence.configuration.embeddingProvider,
986
+ model: configurationEvidence.configuration.embeddingModel,
987
+ modelVersion: configurationEvidence.configuration.embeddingModelVersion,
988
+ dimensions: configurationEvidence.configuration.embeddingDimensions,
989
+ }),
990
+ canonicalVersion: versions.canonicalVersion,
991
+ contentVersion: versions.contentVersion,
992
+ indexVersion: versions.indexVersion,
993
+ provenance,
994
+ });
995
+ }
996
+
997
+ function buildExactStructuralCompletion(graph, closureResult, versions) {
998
+ const elements = new Map((graph.elements || []).map(item => [item.id, item]));
999
+ const relationships = new Map((graph.relationships || []).map(item => [item.id, item]));
1000
+ const views = new Map((graph.views || []).map(item => [item.view_id, item]));
1001
+ const relationshipIds = new Set([
1002
+ ...((closureResult.closure && closureResult.closure.relationships) || []),
1003
+ 'semprod-rel-default-query-service',
1004
+ ]);
1005
+ const endpointRelationships = [...relationshipIds]
1006
+ .map(id => relationships.get(id))
1007
+ .filter(Boolean)
1008
+ .map(relationship => versionRelationship(relationship, elements, versions));
1009
+ const selectedView = views.get(SELECTED_VIEW_ID);
1010
+ const completeView = selectedView
1011
+ ? Object.freeze({
1012
+ ...clone(selectedView),
1013
+ viewpointBinding: Object.freeze({
1014
+ viewpoint: 'Implementation and Migration Viewpoint',
1015
+ description: selectedView.description,
1016
+ }),
1017
+ parentViewpoint: versionObject(elements.get(selectedView.parent_element_id), versions),
1018
+ memberElements: Object.freeze((selectedView.included_elements || [])
1019
+ .map(id => elements.get(id))
1020
+ .filter(Boolean)
1021
+ .map(item => versionObject(item, versions))),
1022
+ memberRelationships: Object.freeze((selectedView.included_relationships || [])
1023
+ .map(id => relationships.get(id))
1024
+ .filter(Boolean)
1025
+ .map(item => versionRelationship(item, elements, versions))),
1026
+ ...versions,
1027
+ })
1028
+ : undefined;
1029
+ return Object.freeze({
1030
+ endpointClosure: Object.freeze({
1031
+ relationships: Object.freeze(endpointRelationships),
1032
+ structuralErrors: Object.freeze([]),
1033
+ }),
1034
+ viewClosure: Object.freeze({
1035
+ views: Object.freeze(completeView ? [completeView] : []),
1036
+ overlappingViewCascade: false,
1037
+ }),
1038
+ });
1039
+ }
1040
+
1041
+ function buildExactProvenance({ seedsByType, closureResult, structural, versions }) {
1042
+ const records = new Map();
1043
+ const include = (objectType, objectId, reason) => {
1044
+ if (!objectId) return;
1045
+ const key = `${objectType}:${objectId}`;
1046
+ const existing = records.get(key);
1047
+ if (!existing) {
1048
+ records.set(key, {
1049
+ objectType,
1050
+ objectId,
1051
+ firstInclusionReason: reason,
1052
+ supplementaryReasons: [],
1053
+ });
1054
+ } else if (reason !== existing.firstInclusionReason && !existing.supplementaryReasons.includes(reason)) {
1055
+ existing.supplementaryReasons.push(reason);
1056
+ }
1057
+ };
1058
+ for (const seed of seedsByType.elements) include('Element', seed.id, 'semantic-seed');
1059
+ for (const seed of seedsByType.relationships) include('ArchitectureRelationship', seed.id, 'semantic-seed');
1060
+ for (const seed of seedsByType.views) include('View', seed.id, 'semantic-seed');
1061
+ for (const element of (closureResult.closure && closureResult.closure.elements) || []) {
1062
+ include('Element', element.id, 'purpose-policy-closure');
1063
+ }
1064
+ for (const relationship of structural.endpointClosure.relationships) {
1065
+ include('ArchitectureRelationship', relationship.id, 'relationship-endpoint-closure');
1066
+ if (!records.has(`Element:${relationship.source_id}`)) {
1067
+ include('Element', relationship.source_id, 'relationship-endpoint-closure');
1068
+ }
1069
+ if (!records.has(`Element:${relationship.target_id}`)) {
1070
+ include('Element', relationship.target_id, 'relationship-endpoint-closure');
1071
+ }
1072
+ }
1073
+ for (const view of structural.viewClosure.views) {
1074
+ include('View', view.view_id, 'complete-view-closure');
1075
+ for (const element of view.memberElements) include('Element', element.id, 'complete-view-closure');
1076
+ for (const relationship of view.memberRelationships) {
1077
+ include('ArchitectureRelationship', relationship.id, 'complete-view-closure');
1078
+ include('Element', relationship.source_id, 'complete-view-closure');
1079
+ include('Element', relationship.target_id, 'complete-view-closure');
1080
+ }
1081
+ }
1082
+ return Object.freeze({
1083
+ objects: Object.freeze([...records.values()].map(record => Object.freeze({
1084
+ ...record,
1085
+ supplementaryReasons: Object.freeze(record.supplementaryReasons),
1086
+ ...versions,
1087
+ }))),
1088
+ purpose: closureResult.closurePolicy.category,
1089
+ policy: Object.freeze({
1090
+ policyId: closureResult.closurePolicy.policyId,
1091
+ parameters: closureResult.closurePolicy.boundParameters,
1092
+ boundParameters: closureResult.closurePolicy.boundParameters,
1093
+ anchors: closureResult.closurePolicy.boundParameters.anchors,
1094
+ }),
1095
+ canonicalVersion: versions.canonicalVersion,
1096
+ semanticIndex: Object.freeze({
1097
+ contentVersion: versions.contentVersion,
1098
+ indexVersion: versions.indexVersion,
1099
+ }),
1100
+ alignment: Object.freeze({
1101
+ state: 'Aligned',
1102
+ canonicalVersion: versions.canonicalVersion,
1103
+ }),
1104
+ });
1105
+ }
1106
+
1107
+ function versionRelationship(relationship, elements, versions) {
1108
+ return Object.freeze({
1109
+ ...clone(relationship),
1110
+ source: versionObject(elements.get(relationship.source_id), versions),
1111
+ target: versionObject(elements.get(relationship.target_id), versions),
1112
+ ...versions,
1113
+ });
1114
+ }
1115
+
1116
+ function versionObject(value, versions) {
1117
+ return value ? Object.freeze({ ...clone(value), ...versions }) : undefined;
1118
+ }
1119
+
1120
+ function deriveCanonicalVersion(graph) {
1121
+ if (typeof graph.version === 'string' && graph.version.trim() !== '') {
1122
+ return graph.version;
1123
+ }
1124
+ if (typeof graph.canonicalVersion === 'string' && graph.canonicalVersion.trim() !== '') {
1125
+ return graph.canonicalVersion;
1126
+ }
1127
+ if (
1128
+ graph.metadata
1129
+ && typeof graph.metadata.canonicalVersion === 'string'
1130
+ && graph.metadata.canonicalVersion.trim() !== ''
1131
+ ) {
1132
+ return graph.metadata.canonicalVersion;
1133
+ }
1134
+ const identity = {
1135
+ name: graph.name || 'System',
1136
+ elements: (graph.elements || []).map(element => element.id).sort(),
1137
+ relationships: (graph.relationships || []).map(relationship => relationship.id).sort(),
1138
+ views: (graph.views || []).map(view => view.view_id).sort(),
1139
+ };
1140
+ return `canonical:${crypto.createHash('sha256').update(JSON.stringify(identity)).digest('hex')}`;
1141
+ }
1142
+
1143
+ function semanticIndexNotAligned(alignment) {
1144
+ const error = safeError(alignment.category || 'SEMANTIC_INDEX_NOT_ALIGNED');
1145
+ error.message = alignment.message || `Semantic index is ${alignment.state}`;
1146
+ error.action = alignment.action || 'Run argo init to reconcile the semantic index.';
1147
+ error.fullSnapshotFallback = false;
1148
+ error.state = alignment.state;
1149
+ error.canonicalVersion = alignment.canonicalVersion;
1150
+ error.contentVersion = alignment.contentVersion;
1151
+ error.indexVersion = alignment.indexVersion;
1152
+ error.completedChannels = alignment.completedChannels;
1153
+ error.missingChannels = alignment.missingChannels;
1154
+ error.mismatchedChannels = alignment.mismatchedChannels;
1155
+ return error;
1156
+ }
1157
+
1158
+ function semanticAutomaticAlignmentFailed(alignment, sourceError) {
1159
+ const error = safeError('SEMANTIC_AUTO_ALIGNMENT_FAILED');
1160
+ error.message = sourceError && sourceError.message
1161
+ ? sourceError.message
1162
+ : 'Semantic automatic alignment failed before retry.';
1163
+ error.action = sourceError && typeof sourceError.action === 'string'
1164
+ ? sourceError.action
1165
+ : 'Repair semantic lifecycle alignment, then retry the original query.';
1166
+ error.fullSnapshotFallback = false;
1167
+ error.state = alignment && alignment.state;
1168
+ error.canonicalVersion = alignment && alignment.canonicalVersion;
1169
+ error.contentVersion = alignment && alignment.contentVersion;
1170
+ error.indexVersion = alignment && alignment.indexVersion;
1171
+ error.completedChannels = alignment && alignment.completedChannels;
1172
+ error.missingChannels = alignment && alignment.missingChannels;
1173
+ error.mismatchedChannels = alignment && alignment.mismatchedChannels;
1174
+ return error;
1175
+ }
1176
+
1177
+ function requireQualifiedVector(vector, dimensions = APPROVED_PROFILE.dimensions) {
1178
+ if (
1179
+ !Array.isArray(vector)
1180
+ || vector.length !== dimensions
1181
+ || vector.some(value => typeof value !== 'number' || !Number.isFinite(value))
1182
+ ) {
1183
+ throw safeError('LIVE_PROVIDER_RESPONSE_INVALID');
1184
+ }
1185
+ }
1186
+
1187
+ function requireExactTestComposition(composition, callback) {
1188
+ if (!composition || typeof callback !== 'function') {
1189
+ throw new TypeError('WP-P2 test composition and callback are required');
1190
+ }
1191
+ const expected = ['neo4jDriver', 'sourceAdapters', 'sourceBehavior', 'transport'];
1192
+ const actual = Object.keys(composition).sort();
1193
+ if (actual.length !== expected.length || actual.some((key, index) => key !== expected[index])) {
1194
+ throw safeError('DEFAULT_SEMANTIC_TEST_COMPOSITION_PROHIBITED');
1195
+ }
1196
+ if (
1197
+ !composition.transport
1198
+ || typeof composition.transport.request !== 'function'
1199
+ || !composition.neo4jDriver
1200
+ || typeof composition.neo4jDriver.execute !== 'function'
1201
+ ) {
1202
+ throw safeError('DEFAULT_SEMANTIC_TEST_COMPOSITION_PROHIBITED');
1203
+ }
1204
+ }
1205
+
1206
+ function requireCanonicalGraph(graph) {
1207
+ if (!graph || typeof graph !== 'object') {
1208
+ throw new TypeError('canonicalGraph is required');
1209
+ }
1210
+ return graph;
1211
+ }
1212
+
1213
+ function numberValue(value) {
1214
+ return value && typeof value.toNumber === 'function' ? value.toNumber() : Number(value);
1215
+ }
1216
+
1217
+ function present(value) {
1218
+ return value !== undefined && value !== null && String(value).trim() !== '';
1219
+ }
1220
+
1221
+ function clone(value) {
1222
+ return JSON.parse(JSON.stringify(value));
1223
+ }
1224
+
1225
+ function safeError(category) {
1226
+ const error = new Error(category);
1227
+ error.category = category;
1228
+ return error;
1229
+ }
1230
+
1231
+ module.exports = {
1232
+ createDefaultSemanticRetrieval,
1233
+ withDefaultSemanticRetrievalTestComposition,
1234
+ memoryThresholdFor,
1235
+ auditThresholdFor,
1236
+ resolveTopK,
1237
+ isSeedAboveThreshold,
1238
+ scopeCanonicalIdentitiesForChannel,
1239
+ bareCanonicalId,
1240
+ normalizeVectorRecord,
1241
+ exhaustChannel,
1242
+ exhaustLexicalChannel,
1243
+ AUDIT_PURPOSES,
1244
+ };