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,201 @@
1
+ 'use strict';
2
+
3
+ // Two-stage rerank (P3): after the (vector, or hybrid) candidate pool is
4
+ // retrieved, an LLM listwise reranker reorders it by relevance to the query.
5
+ // Additive and fail-open: when disabled nothing runs; any error returns null so
6
+ // the caller keeps the original ordering. Pure helpers are exported for tests.
7
+
8
+ const DEFAULT_RERANK_MODEL = 'qwen-turbo';
9
+ // Candidate pool size. The pool is the recall CEILING: a target the seed stage
10
+ // ranks outside the pool can never be recovered by rerank, so it must NOT be
11
+ // shrunk for speed. Keep the original 20. With DeepSeek thinking disabled a
12
+ // single rerank call is ~flat across candidate counts (8-40 all ~1s), so a
13
+ // larger pool costs ~nothing -- never trade recall for latency here.
14
+ const DEFAULT_RERANK_POOL = 20;
15
+ const DEFAULT_RERANK_RETURN = 8;
16
+ // Per-call timeout. Channel reranks run concurrently, so the end-to-end rerank
17
+ // cost is ~one timeout, not N. 3.5s keeps the whole semantic query under ~5s
18
+ // while still letting typical calls (1-4s) complete; slower calls fail open to
19
+ // the pre-rerank (fused) order. Overridable via ARGO_SEMANTIC_RERANK_TIMEOUT_MS.
20
+ const DEFAULT_RERANK_TIMEOUT_MS = 3500;
21
+
22
+ function rerankTimeoutMs(env = process.env) {
23
+ const value = Number(env && env.ARGO_SEMANTIC_RERANK_TIMEOUT_MS);
24
+ return Number.isFinite(value) && value > 0 ? value : DEFAULT_RERANK_TIMEOUT_MS;
25
+ }
26
+
27
+ function isRerankEnabled(env = process.env) {
28
+ return String((env && env.ARGO_SEMANTIC_RERANK) || '') === '1';
29
+ }
30
+
31
+ function firstNonEmpty(...values) {
32
+ for (const value of values) {
33
+ if (typeof value === 'string' && value.trim() !== '') return value.trim();
34
+ }
35
+ return '';
36
+ }
37
+
38
+ // Rerank provider resolution, DECOUPLED from the embedding provider:
39
+ // - dedicated keys (ARGO_RERANK_BASE_URL / ARGO_RERANK_API_KEY / ARGO_RERANK_PROVIDER
40
+ // / ARGO_RERANK_MODEL) win when set, so a different provider/model can be used;
41
+ // - otherwise it falls back to the embedding configuration (qwen by default).
42
+ function resolveRerankProvider(configuration = {}, env = process.env) {
43
+ const baseUrl = firstNonEmpty(env.ARGO_RERANK_BASE_URL, configuration.embeddingBaseUrl);
44
+ const apiKey = firstNonEmpty(env.ARGO_RERANK_API_KEY, configuration.qwenKey);
45
+ const model = firstNonEmpty(env.ARGO_RERANK_MODEL, env.ARGO_SEMANTIC_RERANK_MODEL, DEFAULT_RERANK_MODEL);
46
+ const provider = firstNonEmpty(env.ARGO_RERANK_PROVIDER, configuration.embeddingProvider, 'qwen');
47
+ return { baseUrl, apiKey, model, provider };
48
+ }
49
+
50
+ function rerankConfig(env = process.env) {
51
+ const model = (env && typeof env.ARGO_SEMANTIC_RERANK_MODEL === 'string' && env.ARGO_SEMANTIC_RERANK_MODEL.trim())
52
+ ? env.ARGO_SEMANTIC_RERANK_MODEL.trim()
53
+ : DEFAULT_RERANK_MODEL;
54
+ const pool = Number(env && env.ARGO_SEMANTIC_RERANK_POOL);
55
+ const maxReturn = Number(env && env.ARGO_SEMANTIC_RERANK_RETURN);
56
+ return {
57
+ model,
58
+ poolSize: Number.isInteger(pool) && pool > 0 ? pool : DEFAULT_RERANK_POOL,
59
+ maxReturn: Number.isInteger(maxReturn) && maxReturn > 0 ? maxReturn : DEFAULT_RERANK_RETURN,
60
+ };
61
+ }
62
+
63
+ // Model-agnostic "disable thinking/reasoning" body fragment. Reasoning models
64
+ // spend seconds on hidden reasoning tokens for a simple listwise ranking with no
65
+ // accuracy gain, so disable it by default for EVERY rerank provider (not just
66
+ // deepseek), so switching models keeps the same behaviour. Providers use
67
+ // different field names, so it is fully overridable:
68
+ // ARGO_RERANK_DISABLE_THINKING=0 -> send nothing
69
+ // ARGO_RERANK_THINKING_PARAM='{...}' -> send this exact JSON fragment
70
+ // rerankCandidates retries WITHOUT the fragment if the provider rejects it, so an
71
+ // unsupported field can never break rerank (recall-first: never lose rerank to a
72
+ // 400).
73
+ const DEFAULT_RERANK_THINKING_OFF = Object.freeze({ thinking: { type: 'disabled' } });
74
+
75
+ function resolveRerankThinkingOff(env = process.env) {
76
+ if (String((env && env.ARGO_RERANK_DISABLE_THINKING) || '') === '0') return null;
77
+ const raw = env && env.ARGO_RERANK_THINKING_PARAM;
78
+ if (typeof raw === 'string' && raw.trim() !== '') {
79
+ try {
80
+ const parsed = JSON.parse(raw);
81
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+ return DEFAULT_RERANK_THINKING_OFF;
87
+ }
88
+
89
+ function candidateText(record) {
90
+ const raw = record && (record.searchText || record.description || record.name || '');
91
+ return String(raw).replace(/\s+/g, ' ').slice(0, 160);
92
+ }
93
+
94
+ // Accept the canonical id or its bare/suffix form (models often drop the
95
+ // channel prefix), dedupe, ignore anything not in the candidate set.
96
+ function parseRerankOrder(content, candidateIds) {
97
+ let parsed;
98
+ try { parsed = JSON.parse(content); } catch { return []; }
99
+ const raw = Array.isArray(parsed && parsed.order) ? parsed.order : [];
100
+ const byKey = new Map();
101
+ for (const id of candidateIds) {
102
+ const text = String(id);
103
+ byKey.set(text, id);
104
+ byKey.set(text.split(':').slice(1).join(':'), id);
105
+ byKey.set(text.split(':').pop(), id);
106
+ }
107
+ const seen = new Set();
108
+ const order = [];
109
+ for (const value of raw) {
110
+ const canonical = byKey.get(String(value));
111
+ if (canonical && !seen.has(canonical)) {
112
+ seen.add(canonical);
113
+ order.push(canonical);
114
+ }
115
+ }
116
+ return order;
117
+ }
118
+
119
+ // Reorder seeds by the model's order, then append any seeds the model omitted
120
+ // (nothing is lost), bounded by `limit`.
121
+ function applyRerankOrder(seeds, orderedIds, limit) {
122
+ const list = Array.isArray(seeds) ? seeds.filter(Boolean) : [];
123
+ const byId = new Map(list.map(seed => [seed.id, seed]));
124
+ const out = [];
125
+ const seen = new Set();
126
+ for (const id of (Array.isArray(orderedIds) ? orderedIds : [])) {
127
+ const seed = byId.get(id);
128
+ if (seed && !seen.has(id)) { seen.add(id); out.push(seed); }
129
+ }
130
+ for (const seed of list) {
131
+ if (!seen.has(seed.id)) { seen.add(seed.id); out.push(seed); }
132
+ }
133
+ return Number.isInteger(limit) && limit > 0 ? out.slice(0, limit) : out;
134
+ }
135
+
136
+ async function rerankCandidates({ query, candidates, provider, transport, maxReturn, timeoutMs } = {}) {
137
+ const list = Array.isArray(candidates) ? candidates.filter(candidate => candidate && candidate.id) : [];
138
+ if (list.length < 2 || typeof query !== 'string' || query.trim() === '') return null;
139
+ if (!provider || !transport || typeof transport.request !== 'function') return null;
140
+ const baseUrl = typeof provider.baseUrl === 'string' ? provider.baseUrl : '';
141
+ const apiKey = typeof provider.apiKey === 'string' ? provider.apiKey : '';
142
+ if (baseUrl === '' || apiKey === '') return null;
143
+ const model = provider.model || DEFAULT_RERANK_MODEL;
144
+ const thinkingOff = resolveRerankThinkingOff();
145
+ const baseBody = {
146
+ model,
147
+ temperature: 0,
148
+ response_format: { type: 'json_object' },
149
+ messages: [
150
+ { role: 'system', content: 'You rank architecture elements by relevance to a query. Return ONLY JSON {"order":[ids best-first]} using only the candidate ids.' },
151
+ { role: 'user', content: `Query: ${query}\n\nCandidates (id\\ttext):\n${list.map(candidate => `${candidate.id}\t${candidateText(candidate)}`).join('\n')}\n\nReturn up to ${Math.min(maxReturn || DEFAULT_RERANK_RETURN, list.length)} ids best-first.` },
152
+ ],
153
+ };
154
+ const timeout = timeoutMs || rerankTimeoutMs();
155
+ const send = async (extra) => {
156
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
157
+ const timer = controller ? setTimeout(() => controller.abort(), timeout) : null;
158
+ try {
159
+ return await transport.request(`${baseUrl}/chat/completions`, {
160
+ method: 'POST',
161
+ headers: { Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json' },
162
+ body: JSON.stringify({ ...baseBody, ...extra }),
163
+ ...(controller ? { signal: controller.signal } : {}),
164
+ });
165
+ } catch {
166
+ return null;
167
+ } finally {
168
+ if (timer) clearTimeout(timer);
169
+ }
170
+ };
171
+ try {
172
+ let response = await send(thinkingOff || {});
173
+ // A provider may reject the thinking-off fragment (unknown field -> 400).
174
+ // Retry WITHOUT it so rerank still works: never lose rerank/recall to a 400.
175
+ if ((!response || response.ok !== true) && thinkingOff) {
176
+ response = await send({});
177
+ }
178
+ if (!response || response.ok !== true || typeof response.json !== 'function') return null;
179
+ const payload = await response.json();
180
+ const content = payload && payload.choices && payload.choices[0] && payload.choices[0].message && payload.choices[0].message.content;
181
+ return parseRerankOrder(content, list.map(candidate => candidate.id));
182
+ } catch {
183
+ return null;
184
+ }
185
+ }
186
+
187
+ module.exports = {
188
+ DEFAULT_RERANK_MODEL,
189
+ DEFAULT_RERANK_POOL,
190
+ DEFAULT_RERANK_RETURN,
191
+ DEFAULT_RERANK_TIMEOUT_MS,
192
+ isRerankEnabled,
193
+ rerankConfig,
194
+ rerankTimeoutMs,
195
+ resolveRerankProvider,
196
+ resolveRerankThinkingOff,
197
+ DEFAULT_RERANK_THINKING_OFF,
198
+ parseRerankOrder,
199
+ applyRerankOrder,
200
+ rerankCandidates,
201
+ };
@@ -0,0 +1,51 @@
1
+ # Production Semantic Persistence Contract
2
+
3
+ This local contract refines `OVERALL_ARCHITECTURE.md` and the parent `.argo/scripts/graph-rag/ARCHITECTURE.md`.
4
+
5
+ ## Responsibilities
6
+
7
+ - `productionSemanticBackfill.js` owns the explicit WP-P1 backfill use case through `createProductionSemanticBackfill(dependencies).execute({ explicitOptIn })`.
8
+ - Backfill begins only after the injected structural-projection boundary proves the same canonical version complete. Structural projection is a prerequisite, not semantic readiness.
9
+ - Backfill reads one immutable canonical snapshot and independently enumerates every Element, ArchitectureRelationship, and View. It never fabricates a canonical mutation to trigger embedding generation.
10
+ - Work is bounded by an explicit positive batch size. Every channel has durable totals, completed counts, cursor, canonical version, retry, and isolated-failure checkpoints.
11
+ - Resume starts from durable channel checkpoints and does not repeat completed work. Acceptance independently compares provider and durable-upsert canonical identities before and after interruption; an implementation-reported resume flag is not evidence. Rerun performs stable-identity upserts and is idempotent for unchanged canonical/content/index/provider/model/version/dimensions/vector evidence.
12
+ - A record failure is observable and isolated from other records. Partial or failed channels remain non-Aligned. Alignment may become `Aligned` only after Element, ArchitectureRelationship, and View channels all report complete for the same canonical version.
13
+ - `productionSemanticProjectionStore.js` owns `createProductionSemanticProjectionStore(dependencies)` and exposes only `upsertRecords(records)`, `deleteTombstones(tombstones)`, `readRecords()`, and `close()`.
14
+ - `productionSemanticNeo4jAdapter.js` owns `createProductionSemanticNeo4jAdapter(dependencies)` as the concrete durable production projection adapter. `productionSemanticCheckpointStore.js` owns `createProductionSemanticCheckpointStore(dependencies)` as the concrete durable per-channel checkpoint adapter. Deterministic tests inject only a recording raw Neo4j driver beneath these production factories; they do not substitute an in-memory projection or checkpoint implementation.
15
+ - The production store validates stable canonical identity and complete channel, canonical/content/index, provider/model/model-version/dimensions, and vector metadata before persistence.
16
+ - The production store depends inward on a durable Neo4j persistence adapter. It must MERGE/upsert changed records by stable canonical identity and delete tombstones by that identity.
17
+ - Production records have no `runId`; a `runId`-bearing record is rejected before persistence. The store's complete callable public surface is exactly `upsertRecords`, `deleteTombstones`, `readRecords`, and `close`: no cleanup, runId-delete, truncate, clear, or reset API is permitted. Production never imports or delegates to `liveEmbeddingNeo4jBoundary.js`.
18
+ - Existing live E2E runId cleanup remains test-only and unchanged. It cannot select or delete production semantic projection labels or identities.
19
+ - The same four-method production store is the only durable target for automatic incremental indexing. Successful batch and focused Element, ArchitectureRelationship, and View add/update/remove writes provide exact touched identities: add/update records use `upsertRecords`, removed identities use `deleteTombstones`, and unrelated records remain unchanged across restart. Incremental records carry the same complete canonical/content/index/provider/model/model-version/dimensions/vector contract as full reconciliation.
20
+ - Readiness invalidation belongs to the canonical-write orchestration boundary and occurs before this store or provider is called. This directory may report persistence success/failure but cannot mark Aligned; queryability and global coherence are later outer checks.
21
+ - External Neo4j and provider credentials use the existing approved external configuration and qualification boundaries. Missing configuration or provider qualification blocks before provider, projection, checkpoint, or index side effects. Missing `neo4jUri` blocks startup; tests never invent synchronization evidence.
22
+ - Canonical JSON remains authority at `design/KG/SystemArchitecture.json`. The durable Neo4j records are subordinate projection/index state and have no API that writes canonical JSON.
23
+
24
+ ## Public interface
25
+
26
+ - `createProductionSemanticBackfill(dependencies)` requires canonical-source, structural-projection, qualified-provider, durable projection-store, checkpoint-store, external configuration, qualification, and bounded-batch dependencies; it returns `execute({ explicitOptIn })`.
27
+ - `createProductionSemanticProjectionStore(dependencies)` requires the concrete durable adapter, canonical-authority policy, external configuration, and qualified-provider evidence; it returns exactly the four store methods listed above.
28
+ - `createProductionSemanticNeo4jAdapter(dependencies)` and `createProductionSemanticCheckpointStore(dependencies)` translate store/checkpoint operations to the configured durable Neo4j driver boundary.
29
+ - The parent runtime exposes `runSemanticBackfill(request)` and composes the concrete adapter, store, checkpoint store, and backfill from `semanticPersistence` production dependencies.
30
+ - The parent durable incremental lifecycle composes the existing projection store directly for exact touched upsert/tombstone operations. It does not reuse live-E2E `writeEvidence(runId, ...)` or cleanup APIs.
31
+ - Canonical argo init privately delegates to `runtime.runSemanticBackfill(request)` after its exact enabled/valid gate decision. No standalone MCP backfill route is exposed. The private composition must exist without Harness injection; missing internal consent fails `SP01_EXPLICIT_OPT_IN_REQUIRED`, and structural/canonical mismatch fails `SP01_STRUCTURAL_VERSION_MISMATCH`, both before provider or durable effects. Structural mutation uses the incremental lifecycle and never fakes a full-backfill trigger.
32
+
33
+ ## Local dependencies
34
+
35
+ - MCP gateway → production Graph RAG composition → semantic backfill → canonical/structural/provider/store/checkpoint ports.
36
+ - Semantic backfill may depend on provider and projection interfaces; provider and store adapters must not depend outward on backfill orchestration.
37
+ - Production semantic persistence may depend on the approved Neo4j JavaScript driver adapter and existing external configuration/qualification modules.
38
+ - No file in this directory may depend on `tests/`, Python, Neo4j GenAI procedures, the live-E2E evidence boundary, or mutable canonical-write internals.
39
+ - Checkpoint persistence and semantic projection persistence are durable production state. Neither is a process-local map in production composition.
40
+
41
+ ## Owned tests
42
+
43
+ - `tests/harness/productionSemanticPersistenceHarness.js`
44
+ - `tests/explicit/entries/runProductionSemanticBackfill.js` — SP-01 control point: shipped non-injected JSON-RPC `tools/call` plus explicit backfill after structural projection. Observation: the default MCP path owns production composition and fails closed before secrets/Neo4j, while the deterministic injected raw-driver scenario proves independent complete channels, bounded checkpoints, interruption/resume, isolated failure, idempotent rerun, complete metadata, no fake mutation, and alignment only after all channels complete.
45
+ - `tests/explicit/entries/runPersistentSemanticProjectionLifecycle.js` — SP-02 control point: durable projection across restart, changed-record upsert, tombstone deletion, and unrelated live-E2E cleanup. Observation: stable identity and metadata survive, production has no runId cleanup, canonical authority remains intact, and Neo4j remains subordinate.
46
+ - `tests/architecture/production-semantic-persistence/architecture-boundary.guard.js` — `ArchitectureBoundaryGuard`.
47
+ - `tests/architecture/production-semantic-persistence/dependency-direction.guard.js` — `DependencyDirectionGuard`.
48
+ - `tests/architecture/production-semantic-persistence/explicit-entrypoint-correctness.guard.js` — `ExplicitEntrypointCorrectnessGuard`.
49
+ - `tests/architecture/production-semantic-persistence/implementation-traceability.guard.js` — `KeyImplementationTraceabilityGuard`.
50
+
51
+ All owned Harness, explicit entrypoints, guards, this contract, the root and parent contracts, incoming intent handoff, runner failure records, and canonical graph are frozen during Coding/Repair. The protected fixture is `canonicalThreeChannelFixture`; the protected baseline is the committed WP-P1 pre-coding full-run result in `design/KG/test-failure-records.json`.
@@ -0,0 +1,342 @@
1
+ const crypto = require('node:crypto');
2
+ const {
3
+ evaluateEmbeddingQualification,
4
+ } = require('../embeddingQualificationGate.js');
5
+ const {
6
+ buildSemanticRecordText,
7
+ } = require('../semanticRecordText.js');
8
+
9
+ const CHANNELS = Object.freeze(['Element', 'ArchitectureRelationship', 'View']);
10
+ const CHANNEL_SOURCES = Object.freeze({
11
+ Element: Object.freeze({ property: 'elements', identity: record => record.id }),
12
+ ArchitectureRelationship: Object.freeze({ property: 'relationships', identity: record => record.id }),
13
+ View: Object.freeze({ property: 'views', identity: record => record.view_id }),
14
+ });
15
+
16
+ function createProductionSemanticBackfill(dependencies = {}) {
17
+ requireBoundary(dependencies.canonicalSource, 'readSnapshot', 'canonicalSource');
18
+ requireBoundary(dependencies.structuralProjection, 'requireComplete', 'structuralProjection');
19
+ requireBoundary(dependencies.embeddingProvider, 'embedBatch', 'embeddingProvider');
20
+ requireBoundary(dependencies.projectionStore, 'upsertRecords', 'projectionStore');
21
+ requireBoundary(dependencies.projectionStore, 'readRecords', 'projectionStore');
22
+ requireBoundary(dependencies.projectionStore, 'deleteTombstones', 'projectionStore');
23
+ requireBoundary(dependencies.checkpointStore, 'readCheckpoint', 'checkpointStore');
24
+ requireBoundary(dependencies.checkpointStore, 'writeCheckpoint', 'checkpointStore');
25
+ const batchSize = dependencies.batchSize;
26
+ if (!Number.isInteger(batchSize) || batchSize <= 0) {
27
+ throw categoryError('SP01_POSITIVE_BATCH_SIZE_REQUIRED', 'batchSize');
28
+ }
29
+
30
+ return Object.freeze({
31
+ async execute(request = {}) {
32
+ if (request.explicitOptIn !== true) {
33
+ throw categoryError('SP01_EXPLICIT_OPT_IN_REQUIRED', 'explicitOptIn');
34
+ }
35
+ requireExternalConfiguration(dependencies.configuration);
36
+ const qualification = evaluateEmbeddingQualification(dependencies.qualification);
37
+
38
+ const structural = await dependencies.structuralProjection.requireComplete();
39
+ const snapshot = await dependencies.canonicalSource.readSnapshot();
40
+ const canonicalVersion = snapshot && snapshot.version;
41
+ if (
42
+ !structural
43
+ || structural.status !== 'complete'
44
+ || !isNonBlankString(structural.canonicalVersion)
45
+ || structural.canonicalVersion !== canonicalVersion
46
+ ) {
47
+ throw categoryError('SP01_STRUCTURAL_VERSION_MISMATCH', 'canonicalVersion');
48
+ }
49
+
50
+ const channels = {};
51
+ for (const channel of CHANNELS) {
52
+ channels[channel] = await processChannel({
53
+ channel,
54
+ snapshot,
55
+ canonicalVersion,
56
+ qualification,
57
+ batchSize,
58
+ embeddingProvider: dependencies.embeddingProvider,
59
+ projectionStore: dependencies.projectionStore,
60
+ checkpointStore: dependencies.checkpointStore,
61
+ });
62
+ }
63
+ const reconciled = await reconcileRemovals({
64
+ snapshot,
65
+ canonicalVersion,
66
+ projectionStore: dependencies.projectionStore,
67
+ });
68
+ const aligned = CHANNELS.every(channel => (
69
+ channels[channel].status === 'complete'
70
+ && channels[channel].canonicalVersion === canonicalVersion
71
+ ));
72
+ return Object.freeze({
73
+ status: aligned ? 'passed' : 'partial',
74
+ canonicalVersion,
75
+ alignmentState: aligned ? 'Aligned' : 'Updating',
76
+ channels: Object.freeze(channels),
77
+ reconciled,
78
+ });
79
+ },
80
+ });
81
+ }
82
+
83
+ async function processChannel(options) {
84
+ const source = CHANNEL_SOURCES[options.channel];
85
+ const canonicalRecords = (options.snapshot[source.property] || []).map(record => Object.freeze({
86
+ canonicalIdentity: `${options.channel}:${source.identity(record)}`,
87
+ channel: options.channel,
88
+ canonicalObject: record,
89
+ }));
90
+ const stored = await options.checkpointStore.readCheckpoint(options.channel);
91
+ const checkpoint = stored && stored.canonicalVersion === options.canonicalVersion
92
+ ? mutableCheckpoint(stored, canonicalRecords.length)
93
+ : await resumeCheckpointByContent(options, canonicalRecords);
94
+ const attempts = new Map();
95
+
96
+ while (checkpoint.completedCanonicalIdentities.length < canonicalRecords.length) {
97
+ const completed = new Set(checkpoint.completedCanonicalIdentities);
98
+ const pending = canonicalRecords.filter(record => (
99
+ !completed.has(record.canonicalIdentity)
100
+ && (attempts.get(record.canonicalIdentity) || 0) < 2
101
+ ));
102
+ if (pending.length === 0) {
103
+ break;
104
+ }
105
+ const batch = pending.slice(0, options.batchSize);
106
+ for (const record of batch) {
107
+ attempts.set(record.canonicalIdentity, (attempts.get(record.canonicalIdentity) || 0) + 1);
108
+ }
109
+
110
+ const providerResult = await options.embeddingProvider.embedBatch(Object.freeze(batch));
111
+ const vectors = new Map((providerResult && providerResult.vectors ? providerResult.vectors : [])
112
+ .map(result => [result.canonicalIdentity, result.vector]));
113
+ const providerFailures = providerResult && Array.isArray(providerResult.failures)
114
+ ? providerResult.failures
115
+ : [];
116
+ const successfulRecords = [];
117
+ const currentFailures = [];
118
+
119
+ for (const record of batch) {
120
+ const vector = vectors.get(record.canonicalIdentity);
121
+ if (Array.isArray(vector)) {
122
+ successfulRecords.push(buildSemanticRecord(record, vector, options));
123
+ completed.add(record.canonicalIdentity);
124
+ continue;
125
+ }
126
+ const observed = providerFailures.find(failure => failure.canonicalIdentity === record.canonicalIdentity);
127
+ currentFailures.push(Object.freeze({
128
+ canonicalIdentity: record.canonicalIdentity,
129
+ category: observed && observed.category ? observed.category : 'PROVIDER_RECORD_FAILED',
130
+ }));
131
+ }
132
+
133
+ if (successfulRecords.length > 0) {
134
+ await options.projectionStore.upsertRecords(successfulRecords);
135
+ }
136
+ checkpoint.completedCanonicalIdentities = [...completed];
137
+ checkpoint.completedCount = completed.size;
138
+ checkpoint.cursor = completed.size;
139
+ checkpoint.retries += currentFailures.length;
140
+ checkpoint.isolatedFailures = mergeFailures(checkpoint.isolatedFailures, currentFailures);
141
+ checkpoint.status = completed.size === canonicalRecords.length ? 'complete' : 'partial';
142
+ await options.checkpointStore.writeCheckpoint(freezeCheckpoint(checkpoint));
143
+ }
144
+
145
+ return Object.freeze({
146
+ status: checkpoint.completedCanonicalIdentities.length === canonicalRecords.length ? 'complete' : 'partial',
147
+ canonicalVersion: options.canonicalVersion,
148
+ total: canonicalRecords.length,
149
+ completedCount: checkpoint.completedCanonicalIdentities.length,
150
+ cursor: checkpoint.cursor,
151
+ retries: checkpoint.retries,
152
+ isolatedFailures: Object.freeze(checkpoint.isolatedFailures.map(failure => Object.freeze({ ...failure }))),
153
+ });
154
+ }
155
+
156
+ // Cross-version incremental resume. The resume checkpoint is keyed by
157
+ // canonicalVersion, but ANY add/remove of an element/relationship/view changes
158
+ // that version. Re-embedding every record on every such change is wasteful and
159
+ // slow (~hundreds of provider calls: measured ~174s). Instead, when the stored
160
+ // checkpoint is for a different version, seed the completed set from the
161
+ // persisted records whose curated semantic text (contentHash) AND embedding
162
+ // provider/model/dimensions already match the current graph; only changed/new
163
+ // records get embedded. Recall is unchanged: changed content is ALWAYS
164
+ // re-embedded, only byte-identical text is skipped.
165
+ async function resumeCheckpointByContent(options, canonicalRecords) {
166
+ const checkpoint = emptyCheckpoint(options.channel, options.canonicalVersion, canonicalRecords.length);
167
+ let persisted = [];
168
+ try {
169
+ const stored = await options.projectionStore.readRecords();
170
+ persisted = Array.isArray(stored) ? stored : [];
171
+ } catch {
172
+ persisted = [];
173
+ }
174
+ const byIdentity = new Map();
175
+ for (const record of persisted) {
176
+ if (record && record.channel === options.channel && isNonBlankString(record.canonicalIdentity)) {
177
+ byIdentity.set(record.canonicalIdentity, record);
178
+ }
179
+ }
180
+ const completed = [];
181
+ for (const record of canonicalRecords) {
182
+ const existing = byIdentity.get(record.canonicalIdentity);
183
+ if (existing && persistedRecordMatches(existing, record, options.qualification)) {
184
+ completed.push(record.canonicalIdentity);
185
+ }
186
+ }
187
+ checkpoint.completedCanonicalIdentities = completed;
188
+ checkpoint.completedCount = completed.length;
189
+ checkpoint.cursor = completed.length;
190
+ checkpoint.status = completed.length === canonicalRecords.length ? 'complete' : 'pending';
191
+ return checkpoint;
192
+ }
193
+
194
+ function persistedRecordMatches(existing, canonicalRecord, qualification) {
195
+ if (!Array.isArray(existing.vector)) {
196
+ return false;
197
+ }
198
+ const searchText = buildSemanticRecordText(canonicalRecord.channel, canonicalRecord.canonicalObject);
199
+ const contentHash = crypto.createHash('sha256').update(searchText).digest('hex');
200
+ return existing.contentVersion === `content:${contentHash}`
201
+ && existing.provider === qualification.provider
202
+ && existing.model === qualification.model
203
+ && existing.modelVersion === qualification.version
204
+ && toNumber(existing.dimensions) === toNumber(qualification.dimensions);
205
+ }
206
+
207
+ function toNumber(value) {
208
+ return value && typeof value.toNumber === 'function' ? value.toNumber() : Number(value);
209
+ }
210
+
211
+ function buildSemanticRecord(record, vector, options) {
212
+ const searchText = buildSemanticRecordText(record.channel, record.canonicalObject);
213
+ const contentHash = crypto.createHash('sha256')
214
+ .update(searchText)
215
+ .digest('hex');
216
+ return Object.freeze({
217
+ canonicalIdentity: record.canonicalIdentity,
218
+ channel: record.channel,
219
+ canonicalVersion: options.canonicalVersion,
220
+ contentVersion: `content:${contentHash}`,
221
+ indexVersion: `index:${contentHash}`,
222
+ provider: options.qualification.provider,
223
+ model: options.qualification.model,
224
+ modelVersion: options.qualification.version,
225
+ dimensions: options.qualification.dimensions,
226
+ searchText,
227
+ vector: Object.freeze([...vector]),
228
+ });
229
+ }
230
+
231
+ function emptyCheckpoint(channel, canonicalVersion, total) {
232
+ return {
233
+ channel,
234
+ canonicalVersion,
235
+ total,
236
+ completedCount: 0,
237
+ cursor: 0,
238
+ retries: 0,
239
+ completedCanonicalIdentities: [],
240
+ isolatedFailures: [],
241
+ status: total === 0 ? 'complete' : 'pending',
242
+ };
243
+ }
244
+
245
+ function mutableCheckpoint(checkpoint, total) {
246
+ return {
247
+ channel: checkpoint.channel,
248
+ canonicalVersion: checkpoint.canonicalVersion,
249
+ total,
250
+ completedCount: checkpoint.completedCount || 0,
251
+ cursor: checkpoint.cursor || 0,
252
+ retries: checkpoint.retries || 0,
253
+ completedCanonicalIdentities: [...(checkpoint.completedCanonicalIdentities || [])],
254
+ isolatedFailures: [...(checkpoint.isolatedFailures || [])],
255
+ status: checkpoint.status || 'pending',
256
+ };
257
+ }
258
+
259
+ function freezeCheckpoint(checkpoint) {
260
+ return Object.freeze({
261
+ ...checkpoint,
262
+ completedCanonicalIdentities: Object.freeze([...checkpoint.completedCanonicalIdentities]),
263
+ isolatedFailures: Object.freeze(checkpoint.isolatedFailures.map(failure => Object.freeze({ ...failure }))),
264
+ });
265
+ }
266
+
267
+ function mergeFailures(existing, current) {
268
+ const merged = new Map(existing.map(failure => [failure.canonicalIdentity, failure]));
269
+ for (const failure of current) {
270
+ merged.set(failure.canonicalIdentity, failure);
271
+ }
272
+ return [...merged.values()];
273
+ }
274
+
275
+ // Full-reconciliation removal pass: after all channels are upserted, delete any
276
+ // persisted semantic record whose canonical identity no longer exists in the
277
+ // local JSON snapshot. This guarantees argo-init rebuilds a semantic projection
278
+ // that is exactly consistent with the canonical graph (no stale vectors).
279
+ async function reconcileRemovals({ snapshot, canonicalVersion, projectionStore }) {
280
+ const currentByChannel = new Map();
281
+ for (const channel of CHANNELS) {
282
+ const source = CHANNEL_SOURCES[channel];
283
+ const identities = new Set(
284
+ (snapshot[source.property] || []).map(record => `${channel}:${source.identity(record)}`),
285
+ );
286
+ currentByChannel.set(channel, identities);
287
+ }
288
+ const stored = await projectionStore.readRecords();
289
+ const allStored = Array.isArray(stored) ? stored : [];
290
+ const stale = allStored.filter(record => {
291
+ const identities = currentByChannel.get(record.channel);
292
+ return identities && !identities.has(record.canonicalIdentity);
293
+ });
294
+ const tombstones = stale.map(record => Object.freeze({
295
+ canonicalIdentity: record.canonicalIdentity,
296
+ channel: record.channel,
297
+ canonicalVersion: record.canonicalVersion || canonicalVersion,
298
+ }));
299
+ if (tombstones.length > 0) {
300
+ await projectionStore.deleteTombstones(tombstones);
301
+ }
302
+ return Object.freeze({
303
+ scanned: allStored.length,
304
+ tombstoned: tombstones.length,
305
+ });
306
+ }
307
+
308
+ function requireBoundary(boundary, method, name) {
309
+ if (!boundary || typeof boundary[method] !== 'function') {
310
+ throw new TypeError(`${name}.${method} is required`);
311
+ }
312
+ }
313
+
314
+ function requireExternalConfiguration(configuration) {
315
+ const supplied = configuration && typeof configuration === 'object' ? configuration : {};
316
+ const required = [
317
+ ['neo4jDatabaseUrl', 'neo4jUri'],
318
+ ['neo4jDatabaseUsername', 'neo4jUsername'],
319
+ ['neo4jDatabasePassword', 'neo4jPassword'],
320
+ ['embeddingCredential'],
321
+ ];
322
+ for (const alternatives of required) {
323
+ if (alternatives.map(field => supplied[field]).find(isNonBlankString) === undefined) {
324
+ throw categoryError('EXTERNAL_CREDENTIALS_REQUIRED', alternatives[0]);
325
+ }
326
+ }
327
+ }
328
+
329
+ function isNonBlankString(value) {
330
+ return typeof value === 'string' && value.trim() !== '';
331
+ }
332
+
333
+ function categoryError(category, field) {
334
+ const error = new Error(category);
335
+ error.category = category;
336
+ error.field = field;
337
+ return error;
338
+ }
339
+
340
+ module.exports = {
341
+ createProductionSemanticBackfill,
342
+ };