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,99 @@
1
+ const CHECKPOINT_LABEL = 'ArgoProductionSemanticCheckpoint';
2
+
3
+ function createProductionSemanticCheckpointStore(dependencies = {}) {
4
+ const { driver } = dependencies;
5
+ if (!driver || (typeof driver.execute !== 'function' && typeof driver.session !== 'function')) {
6
+ throw new TypeError('driver.execute or driver.session is required');
7
+ }
8
+
9
+ return Object.freeze({
10
+ async readCheckpoint(channel) {
11
+ if (typeof driver.execute === 'function') {
12
+ const result = await driver.execute(Object.freeze({
13
+ kind: 'semantic-checkpoint-read',
14
+ channel,
15
+ }));
16
+ return result && result.checkpoint ? cloneCheckpoint(result.checkpoint) : undefined;
17
+ }
18
+ return withSession(driver, dependencies.configuration, async session => {
19
+ const result = await executeRead(
20
+ session,
21
+ `MATCH (checkpoint:${CHECKPOINT_LABEL} {channel: $channel}) RETURN checkpoint.payload AS payload`,
22
+ { channel },
23
+ );
24
+ const record = result.records && result.records[0];
25
+ const payload = record && typeof record.get === 'function' ? record.get('payload') : record && record.payload;
26
+ return typeof payload === 'string' ? cloneCheckpoint(JSON.parse(payload)) : undefined;
27
+ });
28
+ },
29
+
30
+ async writeCheckpoint(checkpoint) {
31
+ const durableCheckpoint = cloneCheckpoint(checkpoint);
32
+ if (typeof driver.execute === 'function') {
33
+ const result = await driver.execute(Object.freeze({
34
+ kind: 'semantic-checkpoint-write',
35
+ checkpoint: durableCheckpoint,
36
+ }));
37
+ return result && result.checkpoint ? cloneCheckpoint(result.checkpoint) : durableCheckpoint;
38
+ }
39
+ await withSession(driver, dependencies.configuration, session => executeWrite(
40
+ session,
41
+ [
42
+ `MERGE (checkpoint:${CHECKPOINT_LABEL} {channel: $channel})`,
43
+ 'SET checkpoint.canonicalVersion = $canonicalVersion, checkpoint.payload = $payload',
44
+ 'RETURN checkpoint.payload AS payload',
45
+ ].join('\n'),
46
+ {
47
+ channel: durableCheckpoint.channel,
48
+ canonicalVersion: durableCheckpoint.canonicalVersion,
49
+ payload: JSON.stringify(durableCheckpoint),
50
+ },
51
+ ));
52
+ return durableCheckpoint;
53
+ },
54
+
55
+ async close() {
56
+ if (typeof driver.close === 'function') {
57
+ await driver.close();
58
+ }
59
+ },
60
+ });
61
+ }
62
+
63
+ async function withSession(driver, configuration, action) {
64
+ const database = configuration && configuration.neo4jDatabase;
65
+ const session = driver.session(database === undefined ? undefined : { database });
66
+ try {
67
+ return await action(session);
68
+ } finally {
69
+ if (session && typeof session.close === 'function') {
70
+ await session.close();
71
+ }
72
+ }
73
+ }
74
+
75
+ function executeWrite(session, query, parameters) {
76
+ if (typeof session.executeWrite === 'function') {
77
+ return session.executeWrite(transaction => transaction.run(query, parameters));
78
+ }
79
+ return session.run(query, parameters);
80
+ }
81
+
82
+ function executeRead(session, query, parameters) {
83
+ if (typeof session.executeRead === 'function') {
84
+ return session.executeRead(transaction => transaction.run(query, parameters));
85
+ }
86
+ return session.run(query, parameters);
87
+ }
88
+
89
+ function cloneCheckpoint(checkpoint) {
90
+ return Object.freeze({
91
+ ...checkpoint,
92
+ completedCanonicalIdentities: Object.freeze([...(checkpoint.completedCanonicalIdentities || [])]),
93
+ isolatedFailures: Object.freeze((checkpoint.isolatedFailures || []).map(failure => Object.freeze({ ...failure }))),
94
+ });
95
+ }
96
+
97
+ module.exports = {
98
+ createProductionSemanticCheckpointStore,
99
+ };
@@ -0,0 +1,186 @@
1
+ const SEMANTIC_LABEL = 'ArgoProductionSemanticRecord';
2
+ const CHANNEL_INDEXES = Object.freeze({
3
+ Element: Object.freeze({
4
+ label: 'ArgoProductionSemanticElement',
5
+ indexName: 'argo_production_semantic_element_vector',
6
+ }),
7
+ ArchitectureRelationship: Object.freeze({
8
+ label: 'ArgoProductionSemanticRelationship',
9
+ indexName: 'argo_production_semantic_relationship_vector',
10
+ }),
11
+ View: Object.freeze({
12
+ label: 'ArgoProductionSemanticView',
13
+ indexName: 'argo_production_semantic_view_vector',
14
+ }),
15
+ });
16
+
17
+ function createProductionSemanticNeo4jAdapter(dependencies = {}) {
18
+ const { driver } = dependencies;
19
+ if (!driver || (typeof driver.execute !== 'function' && typeof driver.session !== 'function')) {
20
+ throw new TypeError('driver.execute or driver.session is required');
21
+ }
22
+
23
+ return Object.freeze({
24
+ async upsertRecords(records) {
25
+ if (typeof driver.execute === 'function') {
26
+ return driver.execute(Object.freeze({
27
+ kind: 'semantic-record-upsert',
28
+ records: Object.freeze(records.map(cloneRecord)),
29
+ }));
30
+ }
31
+ return withSession(driver, dependencies.configuration, async session => {
32
+ await ensureVectorIndexes(session, resolveEmbeddingDimensions(dependencies.configuration));
33
+ await ensureFulltextIndexes(session);
34
+ const results = [];
35
+ for (const [channel, definition] of Object.entries(CHANNEL_INDEXES)) {
36
+ const channelRecords = records.filter(record => record.channel === channel).map(cloneRecord);
37
+ if (channelRecords.length === 0) continue;
38
+ const query = [
39
+ 'UNWIND $records AS record',
40
+ `MERGE (semantic:${SEMANTIC_LABEL} {canonicalIdentity: record.canonicalIdentity})`,
41
+ 'SET semantic = record',
42
+ `SET semantic:${definition.label}`,
43
+ 'RETURN count(semantic) AS count',
44
+ ].join('\n');
45
+ results.push(await executeWrite(session, query, { records: channelRecords }));
46
+ }
47
+ return results[results.length - 1] || { records: [] };
48
+ });
49
+ },
50
+
51
+ async deleteTombstones(tombstones) {
52
+ if (typeof driver.execute === 'function') {
53
+ return driver.execute(Object.freeze({
54
+ kind: 'semantic-record-delete-tombstones',
55
+ tombstones: Object.freeze(tombstones.map(cloneRecord)),
56
+ }));
57
+ }
58
+ return withSession(driver, dependencies.configuration, async session => {
59
+ const query = [
60
+ 'UNWIND $canonicalIdentities AS canonicalIdentity',
61
+ `MATCH (semantic:${SEMANTIC_LABEL} {canonicalIdentity: canonicalIdentity})`,
62
+ 'DETACH DELETE semantic',
63
+ 'RETURN count(*) AS count',
64
+ ].join('\n');
65
+ return executeWrite(session, query, {
66
+ canonicalIdentities: tombstones.map(item => item.canonicalIdentity),
67
+ });
68
+ });
69
+ },
70
+
71
+ async readRecords() {
72
+ if (typeof driver.execute === 'function') {
73
+ const result = await driver.execute(Object.freeze({ kind: 'semantic-record-read-all' }));
74
+ return Object.freeze((result && result.records ? result.records : []).map(cloneRecord));
75
+ }
76
+ return withSession(driver, dependencies.configuration, async session => {
77
+ const result = await executeRead(
78
+ session,
79
+ `MATCH (semantic:${SEMANTIC_LABEL}) RETURN properties(semantic) AS record ORDER BY semantic.canonicalIdentity`,
80
+ {},
81
+ );
82
+ return Object.freeze((result.records || []).map(resultRecord).map(cloneRecord));
83
+ });
84
+ },
85
+
86
+ async close() {
87
+ if (typeof driver.close === 'function') {
88
+ await driver.close();
89
+ }
90
+ },
91
+ });
92
+ }
93
+
94
+ const EMBEDDING_DIMENSIONS = 1536;
95
+
96
+ function resolveEmbeddingDimensions(configuration) {
97
+ const value = configuration && configuration.embeddingDimensions;
98
+ return Number.isInteger(value) && value > 0 ? value : EMBEDDING_DIMENSIONS;
99
+ }
100
+
101
+ async function ensureVectorIndexes(session, dimensions = EMBEDDING_DIMENSIONS) {
102
+ for (const definition of Object.values(CHANNEL_INDEXES)) {
103
+ // CREATE ... IF NOT EXISTS cannot change an existing index's dimensions, so
104
+ // when the configured embedding dimension changes (e.g. 1024 -> 1536) drop
105
+ // the stale index first and recreate it at the configured dimension.
106
+ const existing = await executeRead(
107
+ session,
108
+ 'SHOW INDEXES YIELD name, type, options WHERE type = \'VECTOR\' AND name = $name RETURN name, options',
109
+ { name: definition.indexName },
110
+ );
111
+ if (existing.records.length > 0) {
112
+ const options = existing.records[0].get('options');
113
+ const dim = options && options.indexConfig && options.indexConfig['vector.dimensions'];
114
+ if (dim !== dimensions) {
115
+ await executeWrite(session, `DROP INDEX ${definition.indexName} IF EXISTS`, {});
116
+ }
117
+ }
118
+ await executeWrite(
119
+ session,
120
+ [
121
+ `CREATE VECTOR INDEX ${definition.indexName} IF NOT EXISTS`,
122
+ `FOR (semantic:${definition.label}) ON (semantic.vector)`,
123
+ `OPTIONS { indexConfig: { \`vector.dimensions\`: ${dimensions}, \`vector.similarity_function\`: "cosine" } }`,
124
+ ].join('\n'),
125
+ {},
126
+ );
127
+ }
128
+ }
129
+
130
+ async function ensureFulltextIndexes(session) {
131
+ for (const definition of Object.values(CHANNEL_INDEXES)) {
132
+ await executeWrite(
133
+ session,
134
+ [
135
+ `CREATE FULLTEXT INDEX ${definition.indexName}_fulltext IF NOT EXISTS`,
136
+ `FOR (semantic:${definition.label}) ON EACH [semantic.searchText]`,
137
+ ].join('\n'),
138
+ {},
139
+ );
140
+ }
141
+ }
142
+
143
+ async function withSession(driver, configuration, action) {
144
+ const database = configuration && configuration.neo4jDatabase;
145
+ const session = driver.session(database === undefined ? undefined : { database });
146
+ try {
147
+ return await action(session);
148
+ } finally {
149
+ if (session && typeof session.close === 'function') {
150
+ await session.close();
151
+ }
152
+ }
153
+ }
154
+
155
+ function executeWrite(session, query, parameters) {
156
+ if (typeof session.executeWrite === 'function') {
157
+ return session.executeWrite(transaction => transaction.run(query, parameters));
158
+ }
159
+ return session.run(query, parameters);
160
+ }
161
+
162
+ function executeRead(session, query, parameters) {
163
+ if (typeof session.executeRead === 'function') {
164
+ return session.executeRead(transaction => transaction.run(query, parameters));
165
+ }
166
+ return session.run(query, parameters);
167
+ }
168
+
169
+ function resultRecord(record) {
170
+ if (record && typeof record.get === 'function') {
171
+ return record.get('record');
172
+ }
173
+ return record && record.record ? record.record : record;
174
+ }
175
+
176
+ function cloneRecord(record) {
177
+ return Object.freeze({
178
+ ...record,
179
+ ...(Array.isArray(record && record.vector) ? { vector: Object.freeze([...record.vector]) } : {}),
180
+ });
181
+ }
182
+
183
+ module.exports = {
184
+ createProductionSemanticNeo4jAdapter,
185
+ resolveEmbeddingDimensions,
186
+ };
@@ -0,0 +1,171 @@
1
+ const {
2
+ evaluateEmbeddingQualification,
3
+ } = require('../embeddingQualificationGate.js');
4
+
5
+ const CHANNELS = new Set(['Element', 'ArchitectureRelationship', 'View']);
6
+ const STRING_METADATA_FIELDS = Object.freeze([
7
+ 'canonicalIdentity',
8
+ 'canonicalVersion',
9
+ 'contentVersion',
10
+ 'indexVersion',
11
+ 'provider',
12
+ 'model',
13
+ 'modelVersion',
14
+ ]);
15
+
16
+ function createProductionSemanticProjectionStore(dependencies = {}) {
17
+ const {
18
+ persistenceAdapter,
19
+ canonicalAuthority,
20
+ configuration,
21
+ qualification,
22
+ } = dependencies;
23
+ requireAdapter(persistenceAdapter);
24
+ if (!canonicalAuthority || typeof canonicalAuthority.assertProjectionOnly !== 'function') {
25
+ throw new TypeError('canonicalAuthority.assertProjectionOnly is required');
26
+ }
27
+
28
+ function requireReleaseGates() {
29
+ requireExternalConfiguration(configuration);
30
+ const approved = evaluateEmbeddingQualification(qualification);
31
+ canonicalAuthority.assertProjectionOnly();
32
+ return approved;
33
+ }
34
+
35
+ return Object.freeze({
36
+ async upsertRecords(records) {
37
+ const supplied = requireArray(records, 'records');
38
+ rejectRunIds(supplied);
39
+ const approved = requireReleaseGates();
40
+ const validated = supplied.map(record => validateRecord(record, approved));
41
+ await persistenceAdapter.upsertRecords(validated);
42
+ return Object.freeze({ count: validated.length });
43
+ },
44
+
45
+ async deleteTombstones(tombstones) {
46
+ const supplied = requireArray(tombstones, 'tombstones');
47
+ rejectRunIds(supplied);
48
+ requireReleaseGates();
49
+ const validated = supplied.map(validateTombstone);
50
+ await persistenceAdapter.deleteTombstones(validated);
51
+ return Object.freeze({ count: validated.length });
52
+ },
53
+
54
+ async readRecords() {
55
+ requireReleaseGates();
56
+ const records = await persistenceAdapter.readRecords();
57
+ return Object.freeze((records || []).map(record => Object.freeze({
58
+ ...record,
59
+ ...(Array.isArray(record.vector) ? { vector: Object.freeze([...record.vector]) } : {}),
60
+ })));
61
+ },
62
+
63
+ async close() {
64
+ await persistenceAdapter.close();
65
+ },
66
+ });
67
+ }
68
+
69
+ function requireAdapter(adapter) {
70
+ for (const method of ['upsertRecords', 'deleteTombstones', 'readRecords', 'close']) {
71
+ if (!adapter || typeof adapter[method] !== 'function') {
72
+ throw new TypeError(`persistenceAdapter.${method} is required`);
73
+ }
74
+ }
75
+ }
76
+
77
+ function requireExternalConfiguration(configuration) {
78
+ const supplied = configuration && typeof configuration === 'object' ? configuration : {};
79
+ const required = [
80
+ ['neo4jDatabaseUrl', 'neo4jUri'],
81
+ ['neo4jDatabaseUsername', 'neo4jUsername'],
82
+ ['neo4jDatabasePassword', 'neo4jPassword'],
83
+ ['embeddingCredential'],
84
+ ];
85
+ for (const alternatives of required) {
86
+ const value = alternatives.map(field => supplied[field]).find(isNonBlankString);
87
+ if (value === undefined) {
88
+ throw categoryError('EXTERNAL_CREDENTIALS_REQUIRED', alternatives[0]);
89
+ }
90
+ }
91
+ }
92
+
93
+ function validateRecord(record, qualification) {
94
+ if (!record || typeof record !== 'object') {
95
+ throw categoryError('SP02_SEMANTIC_RECORD_METADATA_INVALID', 'record');
96
+ }
97
+ for (const field of STRING_METADATA_FIELDS) {
98
+ if (!isNonBlankString(record[field])) {
99
+ throw categoryError('SP02_SEMANTIC_RECORD_METADATA_INVALID', field);
100
+ }
101
+ }
102
+ if (!CHANNELS.has(record.channel)) {
103
+ throw categoryError('SP02_SEMANTIC_RECORD_METADATA_INVALID', 'channel');
104
+ }
105
+ if (!Number.isInteger(record.dimensions) || record.dimensions <= 0) {
106
+ throw categoryError('SP02_SEMANTIC_RECORD_METADATA_INVALID', 'dimensions');
107
+ }
108
+ if (
109
+ !Array.isArray(record.vector)
110
+ || record.vector.length !== record.dimensions
111
+ || record.vector.some(value => typeof value !== 'number' || !Number.isFinite(value))
112
+ ) {
113
+ throw categoryError('SP02_SEMANTIC_RECORD_METADATA_INVALID', 'vector');
114
+ }
115
+ if (
116
+ record.provider !== qualification.provider
117
+ || record.model !== qualification.model
118
+ || record.modelVersion !== qualification.version
119
+ || record.dimensions !== qualification.dimensions
120
+ ) {
121
+ throw categoryError('SP02_SEMANTIC_RECORD_QUALIFICATION_MISMATCH', 'qualification');
122
+ }
123
+ return Object.freeze({
124
+ ...record,
125
+ vector: Object.freeze([...record.vector]),
126
+ });
127
+ }
128
+
129
+ function validateTombstone(tombstone) {
130
+ if (
131
+ !tombstone
132
+ || !isNonBlankString(tombstone.canonicalIdentity)
133
+ || !CHANNELS.has(tombstone.channel)
134
+ || !isNonBlankString(tombstone.canonicalVersion)
135
+ ) {
136
+ throw categoryError('SP02_TOMBSTONE_METADATA_INVALID', 'tombstone');
137
+ }
138
+ return Object.freeze({
139
+ canonicalIdentity: tombstone.canonicalIdentity.trim(),
140
+ channel: tombstone.channel,
141
+ canonicalVersion: tombstone.canonicalVersion.trim(),
142
+ });
143
+ }
144
+
145
+ function rejectRunIds(records) {
146
+ if (records.some(record => record && Object.prototype.hasOwnProperty.call(record, 'runId'))) {
147
+ throw categoryError('SP02_PRODUCTION_RUNID_PROHIBITED', 'runId');
148
+ }
149
+ }
150
+
151
+ function requireArray(value, field) {
152
+ if (!Array.isArray(value)) {
153
+ throw categoryError('SP02_SEMANTIC_RECORD_METADATA_INVALID', field);
154
+ }
155
+ return value;
156
+ }
157
+
158
+ function isNonBlankString(value) {
159
+ return typeof value === 'string' && value.trim() !== '';
160
+ }
161
+
162
+ function categoryError(category, field) {
163
+ const error = new Error(category);
164
+ error.category = category;
165
+ error.field = field;
166
+ return error;
167
+ }
168
+
169
+ module.exports = {
170
+ createProductionSemanticProjectionStore,
171
+ };
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ // Cross-process, single-flight lock for the heavy semantic-index alignment
4
+ // (workspace bootstrap + semantic backfill + Neo4j sync + EA projection). Any
5
+ // invocation that can rebuild the index -- the MCP startup preheat, the
6
+ // query-path auto-alignment, and an explicit `argo init` (initializeWorkspace),
7
+ // in this process or another -- acquires this lock, so they serialize instead of
8
+ // racing (duplicate embeddings, concurrent Neo4j upserts, concurrent .qea
9
+ // rebuild, readiness/report races).
10
+ //
11
+ // The lock is a regular file created with `wx` under <workspace>/.argo/temp. A
12
+ // holder that crashes leaves a stale file; a lock older than `staleMs` is stolen.
13
+
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+
17
+ const LOCK_RELATIVE_PATH = path.join('.argo', 'temp', 'semantic-alignment.lock');
18
+ const DEFAULT_WAIT_MS = 10 * 60 * 1000;
19
+ const DEFAULT_STALE_MS = 15 * 60 * 1000;
20
+
21
+ function alignmentLockPath(repositoryRoot) {
22
+ return path.join(repositoryRoot, ...LOCK_RELATIVE_PATH.split(path.sep));
23
+ }
24
+
25
+ function sleep(ms) {
26
+ return new Promise(resolve => setTimeout(resolve, ms));
27
+ }
28
+
29
+ async function withAlignmentLock(repositoryRoot, action, options = {}) {
30
+ const waitMs = Number.isFinite(options.waitMs) && options.waitMs > 0 ? options.waitMs : DEFAULT_WAIT_MS;
31
+ const staleMs = Number.isFinite(options.staleMs) && options.staleMs > 0 ? options.staleMs : DEFAULT_STALE_MS;
32
+ const file = alignmentLockPath(repositoryRoot);
33
+ fs.mkdirSync(path.dirname(file), { recursive: true });
34
+ const deadline = Date.now() + waitMs;
35
+ let fd = null;
36
+ for (;;) {
37
+ try {
38
+ fd = fs.openSync(file, 'wx');
39
+ break;
40
+ } catch (error) {
41
+ if (!error || error.code !== 'EEXIST') {
42
+ throw error;
43
+ }
44
+ let stale = false;
45
+ try {
46
+ stale = (Date.now() - fs.statSync(file).mtimeMs) > staleMs;
47
+ } catch {
48
+ stale = true;
49
+ }
50
+ if (stale) {
51
+ try { fs.unlinkSync(file); } catch { /* raced with another stealer */ }
52
+ continue;
53
+ }
54
+ if (Date.now() >= deadline) {
55
+ const timeout = new Error('SEMANTIC_ALIGNMENT_LOCK_TIMEOUT');
56
+ timeout.category = 'SEMANTIC_ALIGNMENT_LOCK_TIMEOUT';
57
+ timeout.message = 'Another semantic alignment is already running and did not finish in time.';
58
+ timeout.action = 'Wait for the running alignment (argo init) to finish, then retry.';
59
+ throw timeout;
60
+ }
61
+ await sleep(250);
62
+ }
63
+ }
64
+ try {
65
+ try { fs.writeSync(fd, String(process.pid)); } catch { /* best-effort owner marker */ }
66
+ return await action();
67
+ } finally {
68
+ try { fs.closeSync(fd); } catch { /* ignore */ }
69
+ try { fs.unlinkSync(file); } catch { /* already gone */ }
70
+ }
71
+ }
72
+
73
+ module.exports = {
74
+ withAlignmentLock,
75
+ alignmentLockPath,
76
+ };
@@ -0,0 +1,131 @@
1
+ 'use strict';
2
+
3
+ // Owns the (expensive) semantic-index alignment child process. When readiness is
4
+ // NOT aligned, the index must be rebuilt to serve correct (full-recall) results;
5
+ // that rebuild can take seconds to ~90s. This module:
6
+ // - runs it ASYNCHRONOUSLY (child_process.spawn, not spawnSync) so the MCP
7
+ // event loop is never frozen while it runs;
8
+ // - de-duplicates concurrent requests (one rebuild shared by all waiters);
9
+ // - logs start/finish/failure for observability;
10
+ // - exposes preheatSemanticAlignment() for a background warm-up at startup.
11
+ // It never changes WHAT is retrieved (recall/precision), only how the rebuild is
12
+ // scheduled/observed.
13
+
14
+ const fs = require('node:fs');
15
+ const path = require('node:path');
16
+ const { spawn } = require('node:child_process');
17
+ const { getWorkspaceRoot, resolveArgoPath } = require('../argo-paths.js');
18
+
19
+ const READINESS_RELATIVE_PATH = path.join('.argo', 'temp', 'system-architecture-semantic-readiness.json');
20
+
21
+ let inFlight = null;
22
+ let preheated = false;
23
+
24
+ function readinessRecordPath(repositoryRoot) {
25
+ return path.join(repositoryRoot, ...READINESS_RELATIVE_PATH.split(path.sep));
26
+ }
27
+
28
+ function isSemanticReady(repositoryRoot) {
29
+ try {
30
+ const parsed = JSON.parse(fs.readFileSync(readinessRecordPath(repositoryRoot), 'utf8'));
31
+ return !!parsed && parsed.state === 'Aligned' && parsed.verified === true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ // A project is "initialized" once its canonical graph exists. The startup
38
+ // preheat must NEVER bootstrap a brand-new project: creating files / running a
39
+ // full backfill for an unknown workspace in the background is surprising and
40
+ // would race an explicit `argo init`. New projects initialize explicitly.
41
+ function isProjectInitialized(repositoryRoot) {
42
+ try {
43
+ return fs.existsSync(path.join(repositoryRoot, 'design', 'KG', 'SystemArchitecture.json'));
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ // A readiness record proves the workspace was initialized (argo init) before.
50
+ // The preheat only RECONCILES a previously-initialized-but-now-stale workspace;
51
+ // a never-aligned workspace (brand-new project, or a synthetic test copy) must
52
+ // be initialized explicitly, never rebuilt in the background.
53
+ function hasReadinessRecord(repositoryRoot) {
54
+ try {
55
+ return fs.existsSync(readinessRecordPath(repositoryRoot));
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ function alignmentError() {
62
+ const error = new Error('SEMANTIC_AUTO_ALIGNMENT_FAILED');
63
+ error.category = 'SEMANTIC_AUTO_ALIGNMENT_FAILED';
64
+ error.message = 'Semantic automatic alignment failed before retry.';
65
+ error.action = 'Repair semantic lifecycle alignment, then retry the original query.';
66
+ error.fullSnapshotFallback = false;
67
+ return error;
68
+ }
69
+
70
+ // Run the alignment (once). Returns a promise resolving to { status: 'aligned' }
71
+ // or rejecting with the SEMANTIC_AUTO_ALIGNMENT_FAILED envelope.
72
+ function runSemanticAlignment(repositoryRoot = getWorkspaceRoot(), options = {}) {
73
+ if (inFlight) {
74
+ return inFlight;
75
+ }
76
+ const scriptPath = resolveArgoPath('scripts', 'ensureArgoHarnessEnvironment.js');
77
+ const startedAt = Date.now();
78
+ console.error('[argo] semantic auto-alignment: index not aligned, rebuilding (recall-safe)…');
79
+ inFlight = new Promise((resolve, reject) => {
80
+ const child = spawn(process.execPath, [scriptPath], {
81
+ cwd: repositoryRoot,
82
+ env: process.env,
83
+ stdio: ['ignore', 'ignore', 'inherit'],
84
+ });
85
+ if (options.unref && typeof child.unref === 'function') {
86
+ // Background preheat must NOT keep the MCP process alive (a spawnSync-driven
87
+ // caller waits for the server to exit; an attached child would hang it).
88
+ child.unref();
89
+ }
90
+ const finish = (failed, cause) => {
91
+ inFlight = null;
92
+ const ms = Date.now() - startedAt;
93
+ if (failed) {
94
+ console.error(`[argo] semantic auto-alignment FAILED in ${ms}ms${cause ? ': ' + cause : ''}`);
95
+ reject(alignmentError());
96
+ } else {
97
+ console.error(`[argo] semantic auto-alignment done in ${ms}ms`);
98
+ resolve(Object.freeze({ status: 'aligned' }));
99
+ }
100
+ };
101
+ child.on('error', (error) => finish(true, error && error.message));
102
+ child.on('exit', (code, signal) => finish(code !== 0, `code=${code} signal=${signal || '-'}`));
103
+ });
104
+ return inFlight;
105
+ }
106
+
107
+ // Fire-and-forget warm-up: if readiness is already Aligned it does nothing;
108
+ // otherwise it starts the rebuild in the background so the first query rarely
109
+ // pays for it. Safe to call repeatedly (guarded + de-duplicated).
110
+ function preheatSemanticAlignment(repositoryRoot = getWorkspaceRoot()) {
111
+ if (preheated || !repositoryRoot || !isProjectInitialized(repositoryRoot) || isSemanticReady(repositoryRoot)) {
112
+ return;
113
+ }
114
+ // Only reconcile a workspace that was initialized before (a readiness record
115
+ // exists); never rebuild a never-aligned project in the background.
116
+ if (!hasReadinessRecord(repositoryRoot)) {
117
+ return;
118
+ }
119
+ preheated = true;
120
+ console.error('[argo] readiness not aligned at startup; preheating semantic alignment in background…');
121
+ runSemanticAlignment(repositoryRoot, { unref: true }).catch(() => {});
122
+ }
123
+
124
+ module.exports = {
125
+ runSemanticAlignment,
126
+ preheatSemanticAlignment,
127
+ isSemanticReady,
128
+ isProjectInitialized,
129
+ hasReadinessRecord,
130
+ readinessRecordPath,
131
+ };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // Maps profile-aware configuration evidence (from resolveApprovedLiveConfiguration)
4
+ // into the shape the canonical semantic-init / backfill runtime consumes.
5
+ //
6
+ // This is the single place that turns "which embedding profile" into the init
7
+ // backfill's configuration, so argo init embeds through the SAME provider the
8
+ // retrieval path uses (approved cloud by default, or a self-hosted endpoint via
9
+ // ARGO_EMBEDDING_PROFILE=openai-compatible) — instead of a hardcoded profile.
10
+
11
+ function buildDefaultSemanticConfiguration(evidence) {
12
+ const configuration = evidence && typeof evidence === 'object' && evidence.configuration
13
+ ? evidence.configuration
14
+ : evidence;
15
+ if (!configuration || typeof configuration !== 'object') {
16
+ throw new TypeError('resolved configuration evidence is required');
17
+ }
18
+ return Object.freeze({
19
+ ...configuration,
20
+ embeddingCredential: configuration.embeddingApiKey || configuration.qwenKey,
21
+ });
22
+ }
23
+
24
+ module.exports = { buildDefaultSemanticConfiguration };