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,110 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ // WP2791 Node direct .qea projection CLI (no EA, no third-party deps).
5
+ // node argo/scripts/ea-qea-sync.js --graph <json> --qea <file.qea> --mode import|sync|full|export|watch
6
+ // [--delete-confirm-file <f> | -y] [--dry-run] [--snapshot-dir <dir>] [--out <file>] [--no-backup]
7
+ //
8
+ // import/sync : project design/KG graph into the .qea (update-in-place, batch INSERT,
9
+ // full : clear projection-owned content (kg_sync_meta + ArchGraph Sync subtree) then
10
+ // unchanged fingerprint skip, opt-in EA-only delete with confirmation).
11
+ // export : read .qea back into graph-shaped JSON (roundtrip comparable).
12
+ // watch : on graph JSON change, run sync (fs.watch + polling fallback).
13
+ // Every write first snapshots the target as <file>_before_sync_<ts> unless --no-backup.
14
+
15
+ const path = require('node:path');
16
+ const fs = require('node:fs');
17
+ const lib = require(path.join(__dirname, 'ea-qea-sync-lib.js'));
18
+
19
+ function parseArgs(argv) {
20
+ const args = { mode: 'sync', graph: '', qea: '', allowDelete: false, deleteConfirmFile: '', dryRun: false, snapshotDir: '', out: '', noBackup: false, intervalMs: 2000, pruneMembership: true };
21
+ for (let i = 0; i < argv.length; i++) {
22
+ const a = argv[i];
23
+ const next = () => (i + 1 < argv.length ? argv[++i] : '');
24
+ if (a === '--graph') { args.graph = next(); }
25
+ else if (a === '--qea') { args.qea = next(); }
26
+ else if (a === '--mode') { args.mode = next(); }
27
+ else if (a === '--delete-confirm-file') { args.deleteConfirmFile = next(); args.allowDelete = true; }
28
+ else if (a === '-y' || a === '--yes') { args.allowDelete = true; }
29
+ else if (a === '--dry-run') { args.dryRun = true; }
30
+ else if (a === '--snapshot-dir') { args.snapshotDir = next(); }
31
+ else if (a === '--out') { args.out = next(); }
32
+ else if (a === '--no-backup') { args.noBackup = true; }
33
+ else if (a === '--no-prune') { args.pruneMembership = false; }
34
+ else if (a === '--interval') { args.intervalMs = Number(next()) || 2000; }
35
+ else if (a.startsWith('-')) { /* ignore unknown */ }
36
+ else if (args.modeSet === undefined) { /* positional not used */ }
37
+ }
38
+ return args;
39
+ }
40
+
41
+ function readGraph(jsonPath) {
42
+ const raw = fs.readFileSync(jsonPath, 'utf8').replace(/^\uFEFF/, '');
43
+ return JSON.parse(raw);
44
+ }
45
+ function confirmDelete(args) {
46
+ if (args.allowDelete) { return true; }
47
+ if (args.deleteConfirmFile) {
48
+ try {
49
+ const text = fs.readFileSync(args.deleteConfirmFile, 'utf8').trim().toLowerCase();
50
+ return text.indexOf('delete') >= 0;
51
+ } catch { return false; }
52
+ }
53
+ return false;
54
+ }
55
+
56
+ async function main() {
57
+ const args = parseArgs(process.argv.slice(2));
58
+ const cwd = process.cwd();
59
+ const graphPath = path.resolve(cwd, args.graph || 'design/KG/SystemArchitecture.json');
60
+ const qeaPath = path.resolve(cwd, args.qea || 'archgraph.qea');
61
+ if (!fs.existsSync(qeaPath)) {
62
+ console.error('qea not found: ' + qeaPath);
63
+ process.exit(2);
64
+ }
65
+ if (args.mode === 'export') {
66
+ const graph = lib.exportQeaToGraph(qeaPath);
67
+ const text = JSON.stringify(graph, null, 2);
68
+ if (args.out) { fs.writeFileSync(path.resolve(cwd, args.out), text, 'utf8'); console.log('export written to ' + args.out); }
69
+ else { console.log(text); }
70
+ return;
71
+ }
72
+ if (!fs.existsSync(graphPath)) {
73
+ console.error('graph not found: ' + graphPath);
74
+ process.exit(2);
75
+ }
76
+ const graph = readGraph(graphPath);
77
+ if (args.mode === 'watch') {
78
+ // eslint-disable-next-line no-constant-condition
79
+ while (true) {
80
+ runOnce(args, graphPath, qeaPath);
81
+ const m0 = statHash(graphPath);
82
+ await sleep(args.intervalMs);
83
+ const m1 = statHash(graphPath);
84
+ if (m0 !== m1) { continue; } // changed while waiting -> immediate re-sync
85
+ }
86
+ } else {
87
+ runOnce(args, graphPath, qeaPath);
88
+ }
89
+ }
90
+ function statHash(p) {
91
+ try { const st = fs.statSync(p); return st.size + ':' + st.mtimeMs; } catch { return 'gone'; }
92
+ }
93
+ function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
94
+ function runOnce(args, graphPath, qeaPath) {
95
+ const graph = readGraph(graphPath);
96
+ let snapshot = null;
97
+ if (!args.dryRun && !args.noBackup) {
98
+ snapshot = lib.snapshotQea(qeaPath, args.snapshotDir || undefined);
99
+ }
100
+ const res = args.mode === 'full'
101
+ ? lib.fullProjection(graph, qeaPath, { dryRun: args.dryRun })
102
+ : lib.syncGraphToQea(graph, qeaPath, { dryRun: args.dryRun, allowDelete: confirmDelete(args), pruneMembership: args.pruneMembership });
103
+ const mode = args.dryRun ? 'dry-run' : 'sync';
104
+ console.log(JSON.stringify({ mode, graph: graphPath, qea: qeaPath, snapshot, result: res }, null, 2));
105
+ }
106
+
107
+ main().catch((e) => {
108
+ console.error('ea-qea-sync failed: ' + (e && e.message));
109
+ process.exit(1);
110
+ });
@@ -0,0 +1,451 @@
1
+ const fs = require('node:fs');
2
+ const path = require('node:path');
3
+ const { spawnSync } = require('node:child_process');
4
+
5
+ const argoMcp = require('./argo-mcp-server.js');
6
+ const systemArchitectureMcp = require('./systemarchitecture-mcp-server.js');
7
+ const {
8
+ runCanonicalSemanticInit,
9
+ } = require('./graph-rag/semanticOperatorJourney.js');
10
+ const {
11
+ DEFAULT_GRAPH_PATH,
12
+ createDriver,
13
+ ensureDatabaseExists,
14
+ getNeo4jConfig,
15
+ getNeo4jGraphSyncState,
16
+ syncArchitectureToNeo4j,
17
+ verifyArchitectureSync,
18
+ } = require('./neo4j-system-architecture-store.js');
19
+ const {
20
+ loadRepositoryArgoEnvironment,
21
+ } = require('./repositoryArgoEnvironment.js');
22
+ const {
23
+ getWorkspaceRoot,
24
+ resolveArgoPath,
25
+ } = require('./argo-paths.js');
26
+ const {
27
+ repairSubdiagramViews,
28
+ } = require('./repair-subdiagram-views.js');
29
+
30
+ const REQUIRED_TOOL_NAMES = [
31
+ 'getSystemArchitecture',
32
+ 'applySystemArchitectureMutation',
33
+ 'validateSystemArchitecture',
34
+ ];
35
+
36
+ // Build the deterministic argo-init harness report (Neo4j structural sync,
37
+ // semantic lifecycle, canonical validation, subdiagram_views consistency).
38
+ // `includeBootstrap` is true for the standalone CLI (it calls initializeWorkspace
39
+ // to bootstrap the workspace); the initializeWorkspace MCP tool passes false
40
+ // because it already bootstrapped — avoids re-entrancy through ensureWorkspaceBootstrap.
41
+ async function buildHarnessReport(options = {}) {
42
+ const { checkOnly = false, workspaceRoot, includeBootstrap = true } = options;
43
+ const { withAlignmentLock } = require('./graph-rag/semanticAlignmentLock.js');
44
+ return withAlignmentLock(workspaceRoot, () => runHarnessReport({ checkOnly, workspaceRoot, includeBootstrap }));
45
+ }
46
+
47
+ async function runHarnessReport({ checkOnly, workspaceRoot, includeBootstrap }) {
48
+ const reportPath = path.join(workspaceRoot, '.argo', 'temp', 'argo-harness-init-report.json');
49
+ const report = {
50
+ status: 'ok',
51
+ workspaceRoot,
52
+ generatedAt: new Date().toISOString(),
53
+ mode: checkOnly ? 'check-only' : 'prepare-and-check',
54
+ reportPath: normalizeRelativePath(path.relative(workspaceRoot, reportPath)),
55
+ };
56
+
57
+ try {
58
+ report.harnessEnvironment = loadRepositoryArgoEnvironment(workspaceRoot);
59
+ try {
60
+ const { bundle, ontology } = require('./argob-schema.js').loadSchemaBundleAndOntology(workspaceRoot);
61
+ report.schemaBundle = {
62
+ kind: bundle.kind,
63
+ language: ontology.language,
64
+ dialect: ontology.dialect,
65
+ dir: bundle.relativeDir,
66
+ guide: bundle.guidePath ? bundle.guidePath.relativePath : null,
67
+ actorElementType: ontology.actorElementType,
68
+ bundleValidation: ontology.bundleValidation ? ontology.bundleValidation.status : null,
69
+ };
70
+ } catch (schemaError) {
71
+ report.schemaBundle = { kind: 'unknown', error: String(schemaError && schemaError.message ? schemaError.message : schemaError) };
72
+ }
73
+ if (includeBootstrap) {
74
+ report.workspaceBootstrap = await ensureWorkspaceBootstrap({ checkOnly, workspaceRoot });
75
+ }
76
+ report.mcp = verifyArgoMcpServer({ workspaceRoot });
77
+ report.systemArchitecture = await verifyCanonicalSystemArchitecture({ workspaceRoot });
78
+ report.subdiagramViews = report.systemArchitecture.status === 'ok'
79
+ ? await ensureSubdiagramViewsConsistency({ checkOnly, workspaceRoot })
80
+ : {
81
+ status: 'skipped',
82
+ mode: checkOnly ? 'check' : 'fix-direct',
83
+ reason: 'system architecture invalid; subdiagram_views repair skipped',
84
+ };
85
+ report.neo4j = await ensureNeo4jProjection({ checkOnly, workspaceRoot });
86
+ report.semanticLifecycle = await ensureCanonicalSemanticLifecycle({
87
+ checkOnly,
88
+ workspaceRoot,
89
+ neo4j: report.neo4j,
90
+ });
91
+ } catch (error) {
92
+ report.status = 'failed';
93
+ report.error = formatErrorForReport(error);
94
+ }
95
+
96
+ for (const section of ['workspaceBootstrap', 'mcp', 'systemArchitecture', 'neo4j', 'semanticLifecycle', 'subdiagramViews']) {
97
+ if (report[section] && report[section].status === 'failed') {
98
+ report.status = 'failed';
99
+ }
100
+ }
101
+
102
+ writeJson(reportPath, report);
103
+ return report;
104
+ }
105
+
106
+ async function main() {
107
+ const options = parseArgs(process.argv.slice(2));
108
+ const workspaceRoot = resolveWorkspaceRoot();
109
+ const report = await buildHarnessReport({
110
+ checkOnly: options.checkOnly,
111
+ workspaceRoot,
112
+ includeBootstrap: true,
113
+ });
114
+ const reportPath = path.join(workspaceRoot, '.argo', 'temp', 'argo-harness-init-report.json');
115
+ writeJson(reportPath, report);
116
+ console.log(JSON.stringify(report, null, 2));
117
+
118
+ if (report.status !== 'ok') {
119
+ process.exit(1);
120
+ }
121
+ }
122
+
123
+ module.exports = { buildHarnessReport, main };
124
+
125
+ function parseArgs(argv) {
126
+ const options = {
127
+ checkOnly: false,
128
+ };
129
+
130
+ for (const token of argv) {
131
+ if (token === '--check-only') {
132
+ options.checkOnly = true;
133
+ continue;
134
+ }
135
+ throw new Error(`Unsupported argument: ${token}`);
136
+ }
137
+
138
+ return options;
139
+ }
140
+
141
+ function resolveWorkspaceRoot() {
142
+ return getWorkspaceRoot();
143
+ }
144
+
145
+ async function ensureWorkspaceBootstrap({ checkOnly, workspaceRoot }) {
146
+ if (checkOnly) {
147
+ return {
148
+ status: 'skipped',
149
+ reason: 'check-only',
150
+ };
151
+ }
152
+
153
+ try {
154
+ const workspace = await argoMcp.initializeWorkspace(workspaceRoot);
155
+ return {
156
+ status: 'ok',
157
+ workspaceRoot: workspace.workspaceRoot,
158
+ targetEaName: workspace.targetEaName,
159
+ createdFiles: workspace.createdFiles,
160
+ updatedFiles: workspace.updatedFiles,
161
+ removedFiles: workspace.removedFiles,
162
+ skippedSteps: workspace.skippedSteps,
163
+ };
164
+ } catch (error) {
165
+ return {
166
+ status: 'failed',
167
+ error: String(error && error.message ? error.message : error),
168
+ };
169
+ }
170
+ }
171
+
172
+ async function ensureCanonicalSemanticLifecycle({ checkOnly, workspaceRoot, neo4j }) {
173
+ if (checkOnly) {
174
+ return {
175
+ status: 'skipped',
176
+ reason: 'check-only',
177
+ fullSnapshotFallback: false,
178
+ };
179
+ }
180
+
181
+ try {
182
+ const semanticLifecycle = await runCanonicalSemanticInit(
183
+ systemArchitectureMcp.createDefaultCanonicalSemanticInitComposition({ repositoryRoot: workspaceRoot }),
184
+ {
185
+ repositoryRoot: workspaceRoot,
186
+ neo4j,
187
+ },
188
+ );
189
+ return {
190
+ status: 'ok',
191
+ state: semanticLifecycle.state,
192
+ alignment: semanticLifecycle.alignment,
193
+ readiness: semanticLifecycle.readiness,
194
+ fullSnapshotFallback: semanticLifecycle.fullSnapshotFallback === true,
195
+ };
196
+ } catch (error) {
197
+ return {
198
+ status: 'failed',
199
+ ...formatSemanticLifecycleError(error),
200
+ };
201
+ }
202
+ }
203
+
204
+ function verifyArgoMcpServer({ workspaceRoot }) {
205
+ const serverPath = resolveArgoPath('scripts', 'argo-mcp-server.js');
206
+ const requests = [
207
+ { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'argo-init-skill', version: '1' } } },
208
+ { jsonrpc: '2.0', method: 'notifications/initialized', params: {} },
209
+ { jsonrpc: '2.0', id: 2, method: 'tools/list', params: {} },
210
+ { jsonrpc: '2.0', id: 3, method: 'ping', params: {} },
211
+ ];
212
+ const input = `${requests.map(entry => JSON.stringify(entry)).join('\n')}\n`;
213
+ const result = spawnSync(process.execPath, [serverPath], {
214
+ cwd: workspaceRoot,
215
+ input,
216
+ encoding: 'utf8',
217
+ });
218
+
219
+ if (result.error) {
220
+ return {
221
+ status: 'failed',
222
+ error: String(result.error),
223
+ };
224
+ }
225
+ if (result.status !== 0) {
226
+ return {
227
+ status: 'failed',
228
+ error: result.stderr || `argo MCP exited with code ${result.status}`,
229
+ };
230
+ }
231
+
232
+ const responses = String(result.stdout || '')
233
+ .split(/\r?\n/)
234
+ .filter(line => line.trim())
235
+ .map(line => JSON.parse(line));
236
+ const initializeResponse = responses.find(entry => entry.id === 1);
237
+ const toolsListResponse = responses.find(entry => entry.id === 2);
238
+ const pingResponse = responses.find(entry => entry.id === 3);
239
+
240
+ if (!initializeResponse || !toolsListResponse || !pingResponse) {
241
+ return {
242
+ status: 'failed',
243
+ error: 'argo MCP did not return initialize/tools-list/ping responses as expected.',
244
+ };
245
+ }
246
+
247
+ const toolNames = (toolsListResponse.result && toolsListResponse.result.tools ? toolsListResponse.result.tools : [])
248
+ .map(tool => tool.name)
249
+ .sort();
250
+ const missingTools = REQUIRED_TOOL_NAMES.filter(name => !toolNames.includes(name));
251
+ if (missingTools.length > 0) {
252
+ return {
253
+ status: 'failed',
254
+ error: `argo MCP is missing required tools: ${missingTools.join(', ')}`,
255
+ toolCount: toolNames.length,
256
+ };
257
+ }
258
+
259
+ return {
260
+ status: 'ok',
261
+ protocolVersion: initializeResponse.result && initializeResponse.result.protocolVersion,
262
+ serverName: initializeResponse.result && initializeResponse.result.serverInfo && initializeResponse.result.serverInfo.name,
263
+ toolCount: toolNames.length,
264
+ checkedTools: REQUIRED_TOOL_NAMES,
265
+ ping: 'ok',
266
+ };
267
+ }
268
+
269
+ async function verifyCanonicalSystemArchitecture({ workspaceRoot } = {}) {
270
+ const graphPath = DEFAULT_GRAPH_PATH;
271
+ let document = null;
272
+ try {
273
+ const raw = fs.readFileSync(path.resolve(workspaceRoot, graphPath), 'utf8');
274
+ document = JSON.parse(raw);
275
+ } catch (error) {
276
+ return {
277
+ status: 'failed',
278
+ error: `failed to read canonical graph ${graphPath}: ${error.message}`,
279
+ };
280
+ }
281
+
282
+ const validateResponse = await argoMcp.callTool('validateSystemArchitecture', {
283
+ workspaceRoot,
284
+ architecturePath: graphPath,
285
+ });
286
+ const validatePayload = parseToolPayload(validateResponse);
287
+ if (validatePayload.status !== 'passed') {
288
+ return {
289
+ status: 'failed',
290
+ graphPath,
291
+ error: 'validateSystemArchitecture reported errors.',
292
+ errors: validatePayload.errors || [],
293
+ };
294
+ }
295
+
296
+ return {
297
+ status: 'ok',
298
+ graphPath,
299
+ elementCount: Array.isArray(document.elements) ? document.elements.length : 0,
300
+ relationshipCount: Array.isArray(document.relationships) ? document.relationships.length : 0,
301
+ viewCount: Array.isArray(document.views) ? document.views.length : 0,
302
+ neo4jRecovery: null,
303
+ };
304
+ }
305
+
306
+ async function ensureSubdiagramViewsConsistency({ checkOnly, workspaceRoot }) {
307
+ const mode = checkOnly ? 'check' : 'fix-direct';
308
+ try {
309
+ const result = await repairSubdiagramViews({
310
+ workspaceRoot,
311
+ architecturePath: DEFAULT_GRAPH_PATH,
312
+ mode,
313
+ });
314
+ return {
315
+ status: result.status,
316
+ mode,
317
+ graphPath: result.graphPath,
318
+ driftCount: result.driftCount,
319
+ fixedCount: result.fixedCount,
320
+ written: Boolean(result.written),
321
+ backupPath: result.backupPath || null,
322
+ reports: result.reports || [],
323
+ ...(result.error === undefined ? {} : { error: result.error }),
324
+ };
325
+ } catch (error) {
326
+ return {
327
+ status: 'failed',
328
+ mode,
329
+ error: String(error && error.message ? error.message : error),
330
+ };
331
+ }
332
+ }
333
+
334
+ async function ensureNeo4jProjection({ checkOnly, workspaceRoot }) {
335
+ const config = getNeo4jConfig({ workspaceRoot });
336
+ const dirtyBefore = getNeo4jGraphSyncState(DEFAULT_GRAPH_PATH, workspaceRoot);
337
+ const driver = createDriver(config);
338
+ let databaseProvision = null;
339
+ try {
340
+ await driver.verifyConnectivity();
341
+ if (!checkOnly) {
342
+ databaseProvision = await ensureDatabaseExists(driver, config.database);
343
+ }
344
+ } catch (error) {
345
+ await driver.close();
346
+ return {
347
+ status: 'failed',
348
+ uri: config.uri,
349
+ database: config.database,
350
+ dirtyBefore,
351
+ error: String(error && error.message ? error.message : error),
352
+ };
353
+ }
354
+
355
+ await driver.close();
356
+
357
+ let syncResult = null;
358
+ if (!checkOnly) {
359
+ syncResult = await syncArchitectureToNeo4j({
360
+ architecturePath: DEFAULT_GRAPH_PATH,
361
+ workspaceRoot,
362
+ ...config,
363
+ });
364
+ databaseProvision = syncResult.databaseProvision;
365
+ }
366
+
367
+ const verification = await verifyArchitectureSync({
368
+ architecturePath: DEFAULT_GRAPH_PATH,
369
+ workspaceRoot,
370
+ ...config,
371
+ });
372
+ if (!verification.matches) {
373
+ return {
374
+ status: 'failed',
375
+ uri: config.uri,
376
+ database: config.database,
377
+ databaseProvision: verification.databaseProvision || databaseProvision,
378
+ dirtyBefore,
379
+ initialSync: syncResult ? syncResult.counts : null,
380
+ verification,
381
+ };
382
+ }
383
+
384
+ return {
385
+ status: 'ok',
386
+ uri: config.uri,
387
+ database: config.database,
388
+ databaseProvision: verification.databaseProvision || databaseProvision,
389
+ dirtyBefore,
390
+ initialSync: syncResult ? {
391
+ graphKey: syncResult.graphKey,
392
+ counts: syncResult.counts,
393
+ } : null,
394
+ verification,
395
+ };
396
+ }
397
+
398
+ function formatSemanticLifecycleError(error) {
399
+ const payload = error && typeof error === 'object' ? error : {};
400
+ const category = typeof payload.category === 'string'
401
+ ? payload.category
402
+ : 'SEMANTIC_LIFECYCLE_INIT_FAILED';
403
+ const action = typeof payload.action === 'string'
404
+ ? payload.action
405
+ : 'Repair semantic lifecycle initialization, then run argo init again.';
406
+ const message = payload.safeSemanticLifecycleMessage === true && typeof payload.message === 'string'
407
+ ? payload.message
408
+ : (typeof payload.publicMessage === 'string'
409
+ ? payload.publicMessage
410
+ : 'Semantic lifecycle initialization failed.');
411
+ return {
412
+ category,
413
+ action,
414
+ message,
415
+ ...(typeof payload.field === 'string' ? { field: payload.field } : {}),
416
+ };
417
+ }
418
+
419
+ function parseToolPayload(result) {
420
+ if (!result || !Array.isArray(result.content) || result.content.length === 0) {
421
+ throw new Error('Unexpected MCP tool result shape.');
422
+ }
423
+ return JSON.parse(result.content[0].text);
424
+ }
425
+
426
+ function normalizeRelativePath(value) {
427
+ return String(value).replace(/\\/g, '/');
428
+ }
429
+
430
+ function writeJson(filePath, payload) {
431
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
432
+ fs.writeFileSync(filePath, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
433
+ }
434
+
435
+ function formatErrorForReport(error) {
436
+ let message = String(error && error.stack ? error.stack : error);
437
+ for (const key of ['QWEN_KEY', 'ARGO_NEO4J_DATABASE_PASSWORD']) {
438
+ const value = process.env[key];
439
+ if (typeof value === 'string' && value.length > 0) {
440
+ message = message.split(value).join(`[REDACTED:${key}]`);
441
+ }
442
+ }
443
+ return message;
444
+ }
445
+
446
+ if (require.main === module) {
447
+ main().catch(error => {
448
+ console.error(formatErrorForReport(error));
449
+ process.exit(1);
450
+ });
451
+ }