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,1014 @@
1
+ 'use strict';
2
+
3
+ // EA .qea (SQLite) direct projection library — WP2791.
4
+ // Zero third-party deps: node:sqlite (DatabaseSync, Node >=22/24), node:crypto, node:fs.
5
+ // Mirrors the ArchiMate->EA mapping conventions of eatool/EA-jsscript/import-from-kg.js
6
+ // (Object_Type base + Stereotype archimate name + Alias/ea_guid anchors + schema_view_id
7
+ // StyleEx token) while writing through SQLite directly (no EA COM required).
8
+ //
9
+ // Concurrency model:
10
+ // - PRAGMA busy_timeout = 15000 set on every connection; write phases wrapped in short
11
+ // transactions with a bounded busy retry. Keep EA's own SQLite handle open is fine —
12
+ // SQLite only locks during active transactions, an idle open connection does not block.
13
+ // - Rows are matched by Alias (schema id) / deterministic ea_guid, update-in-place only;
14
+ // existing t_diagramobjects/t_diagramlinks geometry of STILL-VISIBLE members is never
15
+ // rewritten; the membership reconcile only INSERTs missing members and PRUNES stale
16
+ // schema-anchored members whose element/relationship is no longer in the view
17
+ // (pruneMembership, default true). Human-drawn (un-anchored) shapes are never pruned.
18
+
19
+ const { DatabaseSync } = require('node:sqlite');
20
+ const DEBUG = !!process.env.EA_QEA_DEBUG;
21
+ const crypto = require('node:crypto');
22
+
23
+ const SYNC_PACKAGE_NAME = 'ArchGraph Sync';
24
+ const DIAGRAM_TYPE = 'Logical';
25
+ // Attributes/Operations "Show Compartments" (Elements tab) default unchecked: EA stores
26
+ // these in t_diagram.PDATA as HideAtts / HideOps (hide compartment = 1). Projected
27
+ // diagrams hide both compartments by default while preserving EA's other PDATA tokens.
28
+ const DIAGRAM_DISPLAY_DEFAULT = 'HideAtts=1;HideOps=1;';
29
+ const META_TABLE = 'kg_sync_meta'; // {kind,key,sha,payload} — Node export/reconcile store
30
+ const BUSY_TIMEOUT_MS = 15000;
31
+ const CHUNK = 200;
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // ArchiMate -> EA mapping (mirrors import-from-kg.js)
35
+ // ---------------------------------------------------------------------------
36
+ function normalizeName(value) {
37
+ const text = String(value === null || value === undefined ? '' : value);
38
+ return text.replace(/^ArchiMate[_\s-]*/i, '');
39
+ }
40
+ function alnum(value) {
41
+ return String(value === null || value === undefined ? '' : value)
42
+ .replace(/&/g, '')
43
+ .replace(/[^A-Za-z0-9]/g, '');
44
+ }
45
+ function elementStereotype(type) {
46
+ const norm = alnum(normalizeName(type));
47
+ if (norm === '') { return ''; }
48
+ if (norm === 'SystemSoftware') { return 'ArchiMate_SystemSoftware'; }
49
+ if (norm === 'Constraint') { return 'ArchiMate_Constraint'; }
50
+ return norm;
51
+ }
52
+ const ACTIVITY_ALNUM = new Set([
53
+ 'BusinessEvent', 'BusinessProcess', 'BusinessFunction', 'BusinessInteraction',
54
+ 'BusinessService', 'ApplicationEvent', 'ApplicationProcess', 'ApplicationFunction',
55
+ 'ApplicationInteraction', 'ApplicationService', 'TechnologyEvent',
56
+ 'TechnologyProcess', 'TechnologyFunction', 'TechnologyInteraction',
57
+ 'TechnologyService', 'ValueStream',
58
+ ]);
59
+ function elementObjectType(type) {
60
+ const norm = alnum(normalizeName(type));
61
+ if (norm === 'ApplicationComponent') { return 'Component'; }
62
+ if (ACTIVITY_ALNUM.has(norm)) { return 'Activity'; }
63
+ if (norm === 'Junction' || norm === 'AndJunction' || norm === 'OrJunction') { return 'StateNode'; }
64
+ return 'Class';
65
+ }
66
+ function canonicalArchimateType(type) {
67
+ const norm = alnum(normalizeName(type));
68
+ return norm; // full ArchiMate name e.g. BusinessActor is carried by Stereotype column
69
+ }
70
+ function relStereotype(type) {
71
+ return alnum(normalizeName(type));
72
+ }
73
+ function relationshipMap(type) {
74
+ const norm = alnum(normalizeName(type));
75
+ const meta = { connectorType: 'Association', directed: false };
76
+ switch (norm) {
77
+ case 'Composition':
78
+ case 'Aggregation':
79
+ meta.connectorType = 'Association';
80
+ break;
81
+ case 'Specialization':
82
+ meta.connectorType = 'Generalization';
83
+ meta.directed = true;
84
+ break;
85
+ case 'Realization':
86
+ case 'Access':
87
+ meta.connectorType = 'Dependency';
88
+ meta.directed = true;
89
+ break;
90
+ case 'Serving':
91
+ case 'Assignment':
92
+ meta.connectorType = 'Association';
93
+ meta.directed = true;
94
+ break;
95
+ case 'Association':
96
+ meta.connectorType = 'Association';
97
+ break;
98
+ case 'Triggering':
99
+ case 'Flow':
100
+ case 'Influence':
101
+ meta.connectorType = 'ControlFlow';
102
+ meta.directed = true;
103
+ break;
104
+ default:
105
+ meta.connectorType = 'Association';
106
+ break;
107
+ }
108
+ return meta;
109
+ }
110
+ function safeName(name, fallbackId) {
111
+ const n = String(name === null || name === undefined ? '' : name).trim();
112
+ return n !== '' ? n : String(fallbackId === null || fallbackId === undefined ? '' : fallbackId);
113
+ }
114
+ function deterministicGuid(seed) {
115
+ const h = crypto.createHash('sha1').update(String(seed)).digest('hex');
116
+ return '{' + h.slice(0, 8) + '-' + h.slice(8, 12) + '-' + h.slice(12, 16) + '-' + h.slice(16, 20) + '-' + h.slice(20, 32) + '}';
117
+ }
118
+ function sha1(text) {
119
+ return crypto.createHash('sha1').update(String(text)).digest('hex');
120
+ }
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Element child mirror (attributes -> t_attribute, testcases -> t_objecttests)
124
+ // Mirrors the legacy object-model import (import-from-kg.js applyElementAttributes /
125
+ // applyTestcases) so canonical attributes and acceptance tests are visible in EA
126
+ // under the element's Attributes / Testing tabs. Canonical-owned fields only:
127
+ // run status/results on tests are left untouched on update (EA-side state).
128
+ // ---------------------------------------------------------------------------
129
+ const MAX_ATTRIBUTE_DEFAULT_LENGTH = 250;
130
+ const TEST_CLASS_ACCEPTANCE = 4; // mirrors import-from-kg mapTestTypeToEaClass('Acceptance Test')
131
+
132
+ function attrRowGuid(elementAlias, name, occurrence) {
133
+ return deterministicGuid('attr:' + elementAlias + ':' + name + '#' + occurrence);
134
+ }
135
+ function attributeDefaultValue(attr) {
136
+ const value = attr.value === undefined || attr.value === null ? '' : String(attr.value);
137
+ return value.length > MAX_ATTRIBUTE_DEFAULT_LENGTH ? '' : value;
138
+ }
139
+ function attributeNoteText(attr) {
140
+ const parts = [];
141
+ const value = attr.value === undefined || attr.value === null ? '' : String(attr.value);
142
+ if (value.length > MAX_ATTRIBUTE_DEFAULT_LENGTH) { parts.push(value); }
143
+ if (attr.description !== undefined && attr.description !== null && String(attr.description) !== '') { parts.push(String(attr.description)); }
144
+ if (attr.content !== undefined && attr.content !== null && String(attr.content) !== '') { parts.push(String(attr.content)); }
145
+ return parts.join('\r\n\r\n');
146
+ }
147
+ function isPersistedAttribute(attr) {
148
+ return !!(attr && typeof attr === 'object' && typeof attr.name === 'string' && attr.name.trim() !== '' && attr.op !== 'remove');
149
+ }
150
+ function mirrorElementChildren(db, objectId, element, stats) {
151
+ const alias = String(element.id);
152
+ const attrs = (Array.isArray(element.attributes) ? element.attributes : []).filter(isPersistedAttribute);
153
+ if (attrs.length > 0) {
154
+ const existing = db.prepare('SELECT ID, Name, "Default", Notes, ea_guid, Pos FROM t_attribute WHERE Object_ID=?').all(objectId);
155
+ const available = existing.map((r) => ({ ...r }));
156
+ let maxPos = 0;
157
+ for (const r of existing) { const p = Number(r.Pos); if (!Number.isNaN(p) && p > maxPos) { maxPos = p; } }
158
+ const occurrence = {};
159
+ for (const a of attrs) {
160
+ occurrence[a.name] = (occurrence[a.name] || 0) + 1;
161
+ const guid = attrRowGuid(alias, a.name, occurrence[a.name]);
162
+ const notes = attributeNoteText(a);
163
+ const def = attributeDefaultValue(a);
164
+ const idx = available.findIndex((r) => String(r.ea_guid || '') === guid);
165
+ if (idx >= 0) {
166
+ db.prepare('UPDATE t_attribute SET Name=?, Type=?, "Default"=?, Notes=? WHERE ID=?')
167
+ .run(a.name, 'String', def, notes, Number(available[idx].ID));
168
+ available.splice(idx, 1);
169
+ stats.attributesUpdated++;
170
+ } else {
171
+ maxPos += 16;
172
+ db.prepare('INSERT INTO t_attribute (Object_ID, Name, Scope, Type, "Default", Notes, Pos, ea_guid) VALUES (?,?,?,?,?,?,?,?)')
173
+ .run(objectId, a.name, 'Public', 'String', def, notes, maxPos, guid);
174
+ stats.attributesAdded++;
175
+ }
176
+ }
177
+ }
178
+ const tests = Array.isArray(element.testcases) ? element.testcases : [];
179
+ for (const tc of tests) {
180
+ if (!tc || typeof tc.name !== 'string' || tc.name.trim() === '') { continue; }
181
+ const name = tc.name.trim();
182
+ const type = (tc.type !== undefined && tc.type !== null && String(tc.type) !== '') ? String(tc.type) : 'Acceptance Test';
183
+ const notes = tc.description === undefined || tc.description === null ? '' : String(tc.description);
184
+ const input = tc.Input === undefined || tc.Input === null ? '' : String(tc.Input);
185
+ const criteria = tc.acceptanceCriteria === undefined || tc.acceptanceCriteria === null ? '' : String(tc.acceptanceCriteria);
186
+ const existing = db.prepare('SELECT Test FROM t_objecttests WHERE Object_ID=? AND Test=? AND TestClass=?')
187
+ .get(objectId, name, TEST_CLASS_ACCEPTANCE);
188
+ if (existing) {
189
+ db.prepare('UPDATE t_objecttests SET TestType=?, Notes=?, InputData=?, AcceptanceCriteria=? WHERE Object_ID=? AND Test=? AND TestClass=?')
190
+ .run(type, notes, input, criteria, objectId, name, TEST_CLASS_ACCEPTANCE);
191
+ stats.testsUpdated++;
192
+ } else {
193
+ db.prepare('INSERT INTO t_objecttests (Object_ID, Test, TestClass, TestType, Notes, InputData, AcceptanceCriteria, Status, Results) VALUES (?,?,?,?,?,?,?,?,?)')
194
+ .run(objectId, name, TEST_CLASS_ACCEPTANCE, type, notes, input, criteria, 'Proposed', '');
195
+ stats.testsAdded++;
196
+ }
197
+ }
198
+ }
199
+
200
+ // ---------------------------------------------------------------------------
201
+ // sqlite helpers
202
+ // ---------------------------------------------------------------------------
203
+ function openQea(file) {
204
+ const db = new DatabaseSync(file);
205
+ db.exec('PRAGMA busy_timeout=' + BUSY_TIMEOUT_MS);
206
+ db.exec('PRAGMA foreign_keys=OFF');
207
+ return db;
208
+ }
209
+ function columnNames(db, table) {
210
+ const rows = db.prepare('PRAGMA table_info(' + table + ')').all();
211
+ return rows.map((r) => r.name);
212
+ }
213
+ function ensureMetaTable(db) {
214
+ db.exec('CREATE TABLE IF NOT EXISTS ' + META_TABLE + ' (kind TEXT NOT NULL, key TEXT NOT NULL, sha TEXT, payload TEXT, PRIMARY KEY(kind,key))');
215
+ }
216
+ // multi-row INSERT with positional placeholders, chunked
217
+ function insertMany(db, table, columns, rows) {
218
+ let inserted = 0;
219
+ if (!rows || rows.length === 0) { return 0; }
220
+ for (let i = 0; i < rows.length; i += CHUNK) {
221
+ const chunk = rows.slice(i, i + CHUNK);
222
+ const colSql = columns.join(', ');
223
+ const valueSql = chunk.map(() => '(' + columns.map(() => '?').join(', ') + ')').join(', ');
224
+ const sql = 'INSERT INTO ' + table + ' (' + colSql + ') VALUES ' + valueSql;
225
+ const params = [];
226
+ for (const r of chunk) { for (const c of columns) { params.push(r[c]); } }
227
+ db.prepare(sql).run(...params);
228
+ inserted += chunk.length;
229
+ }
230
+ return inserted;
231
+ }
232
+ function updateRow(db, table, setColumns, whereColumn, id, values) {
233
+ const setSql = setColumns.map((c) => c + '=?').join(', ');
234
+ db.prepare('UPDATE ' + table + ' SET ' + setSql + ' WHERE ' + whereColumn + '=?')
235
+ .run(...setColumns.map((c) => values[c]), id);
236
+ }
237
+ function upsertMeta(db, kind, key, node) {
238
+ const payload = JSON.stringify(node);
239
+ const sh = sha1(payload);
240
+ db.prepare('INSERT INTO ' + META_TABLE + ' (kind,key,sha,payload) VALUES (?,?,?,?) ON CONFLICT(kind,key) DO UPDATE SET sha=excluded.sha, payload=excluded.payload')
241
+ .run(kind, String(key), sh, payload);
242
+ return sh;
243
+ }
244
+ function readMetaKind(db, kind) {
245
+ const rows = db.prepare('SELECT key, payload FROM ' + META_TABLE + ' WHERE kind=? ORDER BY key').all(kind);
246
+ const out = [];
247
+ for (const r of rows) { try { out.push(JSON.parse(r.payload)); } catch { /* skip corrupt */ } }
248
+ return out;
249
+ }
250
+ // mark checkpoints
251
+ function nowMs() { return Date.now(); }
252
+
253
+ // ---------------------------------------------------------------------------
254
+ // Package anchoring
255
+ // ---------------------------------------------------------------------------
256
+ function resolveSyncPackage(db, dryRun) {
257
+ let roots = db.prepare('SELECT Package_ID FROM t_package WHERE Parent_ID=0 ORDER BY Package_ID').all();
258
+ if (roots.length === 0) { roots = db.prepare('SELECT Package_ID FROM t_package ORDER BY Package_ID LIMIT 1').all(); }
259
+ const rootId = Number(roots[0].Package_ID);
260
+ let existing = db.prepare('SELECT Package_ID, Name FROM t_package WHERE Parent_ID=? AND Name=?').get(rootId, SYNC_PACKAGE_NAME);
261
+ if (existing) { return { rootId, packageId: Number(existing.Package_ID), created: false }; }
262
+ if (dryRun) { return { rootId, packageId: 0, created: true }; }
263
+ const guid = deterministicGuid('pkg:' + SYNC_PACKAGE_NAME);
264
+ const r = db.prepare('INSERT INTO t_package (Name, Parent_ID, ea_guid, Notes) VALUES (?,?,?,?)').run(SYNC_PACKAGE_NAME, rootId, guid, '');
265
+ return { rootId, packageId: Number(r.lastInsertRowid), created: true };
266
+ }
267
+ function parseStyleToken(styleEx, key) {
268
+ const text = String(styleEx === null || styleEx === undefined ? '' : styleEx);
269
+ const re = new RegExp('(^|;|\\s)' + key + '=([^;]*)', 'i');
270
+ const m = re.exec(text);
271
+ return m ? m[2] : '';
272
+ }
273
+ function ensureStyleToken(styleEx, keyValue) {
274
+ // EA rewrites StyleEx with its own tokens and drops unknown ones (e.g. schema_view_id).
275
+ // Re-inject our anchor while preserving EA's formatting tokens so diagram identity
276
+ // stays discoverable on the next sync.
277
+ const text = String(styleEx === null || styleEx === undefined ? '' : styleEx);
278
+ const key = String(keyValue).split('=')[0];
279
+ const existing = parseStyleToken(text, key);
280
+ if (existing !== '') { return text; }
281
+ const token = String(keyValue).indexOf('=') >= 0 ? String(keyValue) + ';' : String(keyValue) + '=;';
282
+ return text ? token + text : token;
283
+ }
284
+ // Force a StyleEx token to a value (replaces an existing one, else prepends).
285
+ // Used for DLKO=1 (the "Freeze Visible" connector-display flag EA persists in the
286
+ // diagram's StyleEx): every projected diagram must default to Freeze Visible ON, even
287
+ // if EA previously stored DLKO=0 / dropped it after a human unchecked the box.
288
+ function setStyleToken(styleEx, key, value) {
289
+ const text = String(styleEx === null || styleEx === undefined ? '' : styleEx);
290
+ const re = new RegExp('(^|;|\\s)' + key + '=[^;]*', 'i');
291
+ if (re.test(text)) { return text.replace(re, (m, pre) => pre + key + '=' + value); }
292
+ const token = key + '=' + value + ';';
293
+ return text ? token + text : token;
294
+ }
295
+
296
+ // ---------------------------------------------------------------------------
297
+ // Core sync
298
+ // ---------------------------------------------------------------------------
299
+ // opts: { dryRun, allowDelete, snapshotDir, pruneMembership }
300
+ // pruneMembership (default true): the incremental membership reconcile is
301
+ // authoritative for schema-anchored members — a shape/connector whose canonical
302
+ // element/relationship is no longer in the view's included_elements/included_relationships
303
+ // is pruned from that diagram. Human-drawn shapes (no schema_id anchor) are never
304
+ // pruned, and still-in-view members keep their geometry untouched.
305
+ function syncGraphToQea(graph, qeaPath, opts) {
306
+ const o = opts || {};
307
+ const pruneMembership = o.pruneMembership !== false;
308
+ const stages = {};
309
+ const stats = {
310
+ added: { elements: 0, relationships: 0, diagrams: 0, diagramObjects: 0, diagramLinks: 0 },
311
+ updated: { elements: 0, relationships: 0, diagrams: 0 },
312
+ skipped: { elements: 0, relationships: 0, diagrams: 0 },
313
+ removed: { diagramObjects: 0, diagramLinks: 0 },
314
+ deleteCandidates: 0, deleted: 0,
315
+ };
316
+ const t0 = nowMs();
317
+ const db = openQea(qeaPath);
318
+ try {
319
+ ensureMetaTable(db);
320
+ if (!o.dryRun) { db.exec('BEGIN IMMEDIATE'); }
321
+ stages.package = nowMs();
322
+
323
+ const syncPkg = resolveSyncPackage(db, o.dryRun);
324
+ const syncId = syncPkg.packageId;
325
+ stats.syncPackageId = syncId;
326
+
327
+ // --- elements ---------------------------------------------------------
328
+ const elemById = new Map();
329
+ for (const e of graph.elements || []) { if (e && e.id !== undefined && e.id !== null) { elemById.set(String(e.id), e); } }
330
+ const existingElems = db.prepare(
331
+ 'SELECT Object_ID, Alias, ea_guid, Object_Type, Name, Stereotype, Note, Status, Package_ID, ParentID FROM t_object WHERE Package_ID=?').all(syncId);
332
+ const elemByAlias = new Map();
333
+ const elemByGuid = new Map();
334
+ for (const row of existingElems) {
335
+ if (row.Alias) { elemByAlias.set(String(row.Alias), row); }
336
+ if (row.ea_guid) { elemByGuid.set(String(row.ea_guid), row); }
337
+ }
338
+ const newElems = [];
339
+ const parentOf = {};
340
+ for (const e of graph.elements || []) {
341
+ if (!e || e.id === undefined || e.id === null) { continue; }
342
+ const alias = String(e.id);
343
+ const guid = deterministicGuid('el:' + alias);
344
+ const existing = elemByAlias.get(alias) || elemByGuid.get(guid) || null;
345
+ const parentId = e.parent !== undefined && e.parent !== null && String(e.parent) !== '0' && elemById.has(String(e.parent)) ? parentOf[String(e.parent)] || 0 : 0;
346
+ const intended = {
347
+ Object_Type: elementObjectType(e.type),
348
+ Name: safeName(e.name, alias),
349
+ Stereotype: elementStereotype(e.type),
350
+ Note: String(e.description === null || e.description === undefined ? '' : e.description),
351
+ Status: String(e.status === null || e.status === undefined ? 'Proposed' : e.status),
352
+ ParentID: parentId || 0,
353
+ };
354
+ if (existing) {
355
+ const changed = intended.Object_Type !== existing.Object_Type || intended.Name !== existing.Name ||
356
+ (intended.Stereotype || '') !== (existing.Stereotype || '') || intended.Note !== (existing.Note || '') ||
357
+ (intended.Status || '') !== (existing.Status || '') || Number(intended.ParentID) !== Number(existing.ParentID || 0);
358
+ if (changed && !o.dryRun) {
359
+ updateRow(db, 't_object', ['Name', 'Stereotype', 'Note', 'Status', 'ParentID'], 'Object_ID', Number(existing.Object_ID), intended);
360
+ }
361
+ stats[changed ? 'updated' : 'skipped'].elements++;
362
+ parentOf[alias] = Number(existing.Object_ID);
363
+ } else {
364
+ newElems.push({ ...intended, Alias: alias, ea_guid: guid, Package_ID: syncId });
365
+ stats.added.elements++;
366
+ }
367
+ }
368
+ // batch insert new elements (ParentID refined below) then read ids
369
+ if (newElems.length > 0) {
370
+ if (!o.dryRun) {
371
+ insertMany(db, 't_object', ['Object_Type', 'Name', 'Stereotype', 'Note', 'Status', 'Alias', 'ea_guid', 'Package_ID', 'ParentID'], newElems);
372
+ }
373
+ for (const row of newElems) { parentOf[row.Alias] = row.Alias; } // placeholder; resolved by readback
374
+ }
375
+ // resolve real Object_ID for new elements + parents
376
+ const aliasToId = new Map();
377
+ if (!o.dryRun) {
378
+ const aliases = newElems.map((r) => r.Alias);
379
+ const readback = [];
380
+ for (let i = 0; i < aliases.length; i += 200) {
381
+ const part = aliases.slice(i, i + 200);
382
+ const marks = part.map(() => '?').join(',');
383
+ const rows = db.prepare('SELECT Object_ID, Alias FROM t_object WHERE Alias IN (' + marks + ')').all(...part);
384
+ readback.push(...rows);
385
+ }
386
+ for (const r of readback) { aliasToId.set(String(r.Alias), Number(r.Object_ID)); }
387
+ } else {
388
+ for (const r of newElems) { aliasToId.set(r.Alias, -1); }
389
+ }
390
+ // second pass: set ParentID where the parent is a new element
391
+ if (newElems.length > 0 && !o.dryRun) {
392
+ for (const e of graph.elements || []) {
393
+ if (!e || e.id === undefined || e.id === null) { continue; }
394
+ const alias = String(e.id);
395
+ const pid = aliasToId.get(alias);
396
+ if (pid === undefined) { continue; }
397
+ const parentNode = e.parent !== undefined && e.parent !== null && elemById.get(String(e.parent)) ? elemById.get(String(e.parent)) : null;
398
+ if (!parentNode) { continue; }
399
+ const parentRowId = (function () {
400
+ const a = String(e.parent);
401
+ const ex = elemByAlias.get(a) || elemByGuid.get(deterministicGuid('el:' + a));
402
+ if (ex) { return Number(ex.Object_ID); }
403
+ return aliasToId.get(a);
404
+ })();
405
+ if (parentRowId && Number(parentRowId) !== pid) {
406
+ db.prepare('UPDATE t_object SET ParentID=? WHERE Object_ID=?').run(Number(parentRowId), pid);
407
+ }
408
+ }
409
+ }
410
+ stages.elements = nowMs();
411
+
412
+ // element anchors + meta (idempotent, fingerprint-skipped)
413
+ let tagStats = { propsNew: 0, propsSkip: 0, attributesUpdated: 0, attributesAdded: 0, testsUpdated: 0, testsAdded: 0, relationshipAttributesUpdated: 0, relationshipAttributesAdded: 0 };
414
+ if (!o.dryRun) {
415
+ // minimal EA-facing anchors for compatibility with the legacy object-model exporter
416
+ const anchorRows = [];
417
+ const elemIdByAliasFinal = new Map();
418
+ for (const ex of existingElems) { elemIdByAliasFinal.set(String(ex.Alias), Number(ex.Object_ID)); }
419
+ for (const [a, id] of aliasToId) { elemIdByAliasFinal.set(a, id); }
420
+ const toTag = [];
421
+ for (const e of graph.elements || []) {
422
+ if (!e || e.id === undefined || e.id === null) { continue; }
423
+ const id = elemIdByAliasFinal.get(String(e.id));
424
+ if (id === undefined) { continue; }
425
+ toTag.push({ id: Number(id), e });
426
+ }
427
+ const metaNew = [];
428
+ const propsToWrite = [];
429
+ for (const t of toTag) {
430
+ const sh = upsertMeta(db, 'element', t.e.id, t.e);
431
+ metaNew.push(1);
432
+ propsToWrite.push([t.id, 'schema_id', t.e.id]);
433
+ propsToWrite.push([t.id, 'archimate_type', canonicalArchimateType(t.e.type)]);
434
+ }
435
+ if (propsToWrite.length > 0) {
436
+ const existingProps = new Set();
437
+ for (let i = 0; i < propsToWrite.length; i += 200) {
438
+ const part = propsToWrite.slice(i, i + 200);
439
+ const ids = new Set(part.map((p) => p[0]));
440
+ const marks = Array.from(ids).map(() => '?').join(',');
441
+ const rows = db.prepare('SELECT Object_ID, Property FROM t_objectproperties WHERE Object_ID IN (' + marks + ')').all(...Array.from(ids));
442
+ for (const r of rows) { existingProps.add(Number(r.Object_ID) + '|' + r.Property); }
443
+ }
444
+ const newProps = propsToWrite.filter((p) => !existingProps.has(p[0] + '|' + p[1]));
445
+ if (newProps.length > 0) {
446
+ insertMany(db, 't_objectproperties', ['Object_ID', 'Property', 'Value', 'Notes'], newProps.map((p) => ({ Object_ID: p[0], Property: p[1], Value: p[2], Notes: '' })));
447
+ tagStats.propsNew += newProps.length;
448
+ }
449
+ tagStats.propsSkip = propsToWrite.length - newProps.length;
450
+ }
451
+ // canonical attributes -> t_attribute, canonical testcases -> t_objecttests
452
+ for (const t of toTag) {
453
+ mirrorElementChildren(db, t.id, t.e, tagStats);
454
+ }
455
+ }
456
+ stages.elemTags = nowMs();
457
+
458
+ // --- relationships -----------------------------------------------------
459
+ const elemIdByAliasAll = new Map();
460
+ for (const ex of existingElems) { if (ex.Alias) { elemIdByAliasAll.set(String(ex.Alias), Number(ex.Object_ID)); } }
461
+ if (!o.dryRun) { for (const [a, id] of aliasToId) { elemIdByAliasAll.set(a, id); } }
462
+ const relByGuid = new Map();
463
+ const existingRels = db.prepare('SELECT Connector_ID, ea_guid, Name, Connector_Type, Stereotype, Notes, Direction, Start_Object_ID, End_Object_ID FROM t_connector').all();
464
+ for (const r of existingRels) { if (r.ea_guid) { relByGuid.set(String(r.ea_guid), r); } }
465
+ const newRels = [];
466
+ const relAliasToId = new Map();
467
+ for (const rel of graph.relationships || []) {
468
+ if (!rel || rel.id === undefined || rel.id === null) { continue; }
469
+ const alias = String(rel.id);
470
+ const guid = deterministicGuid('rel:' + alias);
471
+ const start = elemIdByAliasAll.get(String(rel.source_id));
472
+ const end = elemIdByAliasAll.get(String(rel.target_id));
473
+ if (start === undefined || end === undefined) { continue; }
474
+ const map = relationshipMap(rel.type);
475
+ // Every ArchiMate relationship in the graph carries an explicit source->target
476
+ // orientation. Write an EA Direction unconditionally so the projected VIEW renders
477
+ // each relationship's arrowhead and the source/target orientation is never lost —
478
+ // an empty/Unspecified Direction renders Association-mapped connectors as arrowless
479
+ // lines (Serving/Assignment/Composition/Aggregation) which hides their direction.
480
+ const direction = 'Source -> Destination';
481
+ const existing = relByGuid.get(guid);
482
+ const intended = {
483
+ Name: safeName(rel.name, alias),
484
+ Connector_Type: map.connectorType,
485
+ Stereotype: relStereotype(rel.type),
486
+ Notes: String(rel.description === null || rel.description === undefined ? '' : rel.description),
487
+ Direction: direction,
488
+ Start_Object_ID: Number(start),
489
+ End_Object_ID: Number(end),
490
+ };
491
+ if (existing) {
492
+ relAliasToId.set(alias, Number(existing.Connector_ID));
493
+ const changed = intended.Name !== (existing.Name || '') || (intended.Connector_Type || '') !== (existing.Connector_Type || '') ||
494
+ (intended.Stereotype || '') !== (existing.Stereotype || '') || intended.Notes !== (existing.Notes || '') ||
495
+ intended.Direction !== (existing.Direction || '') || Number(intended.Start_Object_ID) !== Number(existing.Start_Object_ID || 0) ||
496
+ Number(intended.End_Object_ID) !== Number(existing.End_Object_ID || 0);
497
+ if (changed && !o.dryRun) {
498
+ updateRow(db, 't_connector', ['Name', 'Connector_Type', 'Stereotype', 'Notes', 'Direction', 'Start_Object_ID', 'End_Object_ID'], 'Connector_ID', Number(existing.Connector_ID), intended);
499
+ }
500
+ stats[changed ? 'updated' : 'skipped'].relationships++;
501
+ } else {
502
+ newRels.push({ ...intended, ea_guid: guid, _alias: alias });
503
+ stats.added.relationships++;
504
+ }
505
+ }
506
+ if (!o.dryRun) {
507
+ if (newRels.length > 0) {
508
+ insertMany(db, 't_connector', ['Name', 'Connector_Type', 'Stereotype', 'Notes', 'Direction', 'Start_Object_ID', 'End_Object_ID', 'ea_guid'], newRels);
509
+ }
510
+ for (let i = 0; i < newRels.length; i += 200) {
511
+ const part = newRels.slice(i, i + 200);
512
+ const marks = part.map(() => '?').join(',');
513
+ const rows = db.prepare('SELECT Connector_ID, ea_guid FROM t_connector WHERE ea_guid IN (' + marks + ')').all(...part.map((r) => r.ea_guid));
514
+ for (const r of rows) { const pr = part.find((x) => x.ea_guid === r.ea_guid); if (pr) { relAliasToId.set(pr._alias, Number(r.Connector_ID)); } }
515
+ }
516
+ } else {
517
+ for (const r of newRels) { relAliasToId.set(r._alias, -1); }
518
+ }
519
+ stages.relationships = nowMs();
520
+
521
+ // connector anchors + meta
522
+ if (!o.dryRun) {
523
+ for (const rel of graph.relationships || []) {
524
+ if (!rel || rel.id === undefined || rel.id === null) { continue; }
525
+ const id = relAliasToId.get(String(rel.id));
526
+ if (id === undefined || id < 0) { continue; }
527
+ upsertMeta(db, 'relationship', rel.id, rel);
528
+ const existingCt = db.prepare('SELECT PropertyID FROM t_connectortag WHERE ElementID=? AND Property=?').get(Number(id), 'schema_id');
529
+ if (!existingCt) {
530
+ db.prepare('INSERT INTO t_connectortag (ElementID, Property, VALUE, NOTES) VALUES (?,?,?,?)')
531
+ .run(Number(id), 'schema_id', rel.id, '');
532
+ db.prepare('INSERT INTO t_connectortag (ElementID, Property, VALUE, NOTES) VALUES (?,?,?,?)')
533
+ .run(Number(id), 'archimate_relationship_type', canonicalArchimateType(rel.type), '');
534
+ }
535
+ // Mirror relationship attributes into the connector's relationship_attributes_json
536
+ // tag so the human-edited EA model surfaces them (the EA-internal draft extractor
537
+ // diffs this visible field). Idempotent: update-in-place on the canonical value.
538
+ const relAttrs = (Array.isArray(rel.attributes) ? rel.attributes : []).filter(isPersistedAttribute);
539
+ const attrsJson = relAttrs.length > 0 ? JSON.stringify(relAttrs) : '';
540
+ const tagCt = db.prepare('SELECT PropertyID FROM t_connectortag WHERE ElementID=? AND Property=?').get(Number(id), 'relationship_attributes_json');
541
+ if (tagCt) {
542
+ const cur = db.prepare('SELECT VALUE AS v FROM t_connectortag WHERE PropertyID=?').get(Number(tagCt.PropertyID));
543
+ const curV = (cur && cur.v) || '';
544
+ if (curV !== attrsJson) {
545
+ db.prepare('UPDATE t_connectortag SET VALUE=?, NOTES=? WHERE PropertyID=?')
546
+ .run(attrsJson, '', Number(tagCt.PropertyID));
547
+ tagStats.relationshipAttributesUpdated++;
548
+ }
549
+ } else if (relAttrs.length > 0) {
550
+ db.prepare('INSERT INTO t_connectortag (ElementID, Property, VALUE, NOTES) VALUES (?,?,?,?)')
551
+ .run(Number(id), 'relationship_attributes_json', attrsJson, '');
552
+ tagStats.relationshipAttributesAdded++;
553
+ }
554
+ }
555
+ }
556
+ stages.relTags = nowMs();
557
+
558
+ // --- views/diagrams ----------------------------------------------------
559
+ // Diagram identity is matched by BOTH the schema_view_id StyleEx token AND the
560
+ // deterministic ea_guid. EA rewrites StyleEx (its own formatting tokens) whenever
561
+ // it touches an open project and DROPS unknown tokens like schema_view_id — if we
562
+ // only matched by the token we would re-INSERT the same deterministic ea_guid and
563
+ // crash on t_diagram's UNIQUE(ea_guid) (projection failure: Neo4j ok, EA stale).
564
+ const existingDiags = db.prepare('SELECT Diagram_ID, Package_ID, Name, StyleEx, PDATA, ea_guid FROM t_diagram WHERE Package_ID=?').all(syncId);
565
+ const diagByView = new Map();
566
+ const diagByGuid = new Map();
567
+ for (const d of existingDiags) {
568
+ if (d.ea_guid) { diagByGuid.set(String(d.ea_guid), d); }
569
+ const v = parseStyleToken(d.StyleEx, 'schema_view_id');
570
+ if (v) { diagByView.set(v, d); }
571
+ }
572
+ const diagViewRows = new Map(); // view_id -> matched existing row (token OR guid)
573
+ const newDiags = [];
574
+ for (const view of graph.views || []) {
575
+ if (!view || view.view_id === undefined || view.view_id === null) { continue; }
576
+ const viewId = String(view.view_id);
577
+ const styleEx = 'schema_view_id=' + viewId + ';DLKO=1;';
578
+ const parentObjectId = (function () {
579
+ if (view.parent_element_id !== undefined && view.parent_element_id !== null && view.parent_element_id !== '') {
580
+ const pid = elemIdByAliasAll.get(String(view.parent_element_id));
581
+ if (pid !== undefined) { return pid; }
582
+ }
583
+ return 0;
584
+ })();
585
+ const existing = diagByView.get(viewId) || diagByGuid.get(deterministicGuid('diag:' + viewId)) || null;
586
+ const intended = {
587
+ Name: safeName(view.view_name, viewId),
588
+ Diagram_Type: DIAGRAM_TYPE,
589
+ Package_ID: syncId,
590
+ ParentID: parentObjectId,
591
+ Notes: '', // EA .qea 不保留多段 Notes;视图内容经 kg_sync_meta 保真
592
+ StyleEx: styleEx,
593
+ PDATA: DIAGRAM_DISPLAY_DEFAULT,
594
+ };
595
+ if (existing) {
596
+ diagViewRows.set(viewId, existing);
597
+ // EA may have rewritten StyleEx and dropped the anchor — re-inject it while
598
+ // preserving EA's own formatting tokens so identity stays discoverable. Also
599
+ // force DLKO=1 so every diagram defaults to "Freeze Visible" checked.
600
+ const anchoredStyleEx = ensureStyleToken(
601
+ setStyleToken(existing.StyleEx, 'DLKO', '1'),
602
+ 'schema_view_id=' + viewId
603
+ );
604
+ // Default Attributes/Operations compartments unchecked: force HideAtts=1 /
605
+ // HideOps=1 into PDATA while preserving EA's other display tokens.
606
+ const anchoredPdata = setStyleToken(
607
+ setStyleToken(existing.PDATA, 'HideAtts', '1'),
608
+ 'HideOps', '1'
609
+ );
610
+ const changed = intended.Name !== (existing.Name || '') || (existing.StyleEx || '') !== anchoredStyleEx || (existing.PDATA || '') !== anchoredPdata;
611
+ if (DEBUG && changed) { console.error('DEBUG diagram chg', viewId, JSON.stringify({n:[intended.Name,(existing.Name||'')], style: !!parseStyleToken(existing.StyleEx,'schema_view_id')})); }
612
+ if (changed && !o.dryRun) {
613
+ db.prepare('UPDATE t_diagram SET Name=?, StyleEx=?, PDATA=? WHERE Diagram_ID=?')
614
+ .run(intended.Name, anchoredStyleEx, anchoredPdata, Number(existing.Diagram_ID));
615
+ }
616
+ stats[changed ? 'updated' : 'skipped'].diagrams++;
617
+ } else {
618
+ newDiags.push({ ...intended, ea_guid: deterministicGuid('diag:' + viewId) });
619
+ stats.added.diagrams++;
620
+ }
621
+ }
622
+ const diagAliasToId = new Map();
623
+ if (!o.dryRun) {
624
+ if (newDiags.length > 0) {
625
+ insertMany(db, 't_diagram', ['Name', 'Diagram_Type', 'Package_ID', 'ParentID', 'StyleEx', 'PDATA', 'ea_guid'], newDiags);
626
+ }
627
+ for (let i = 0; i < newDiags.length; i += 200) {
628
+ const part = newDiags.slice(i, i + 200);
629
+ const marks = part.map(() => '?').join(',');
630
+ const rows = db.prepare('SELECT Diagram_ID, StyleEx FROM t_diagram WHERE StyleEx IN (' + marks + ')').all(...part.map((d) => d.StyleEx));
631
+ for (const r of rows) {
632
+ const v = parseStyleToken(r.StyleEx, 'schema_view_id');
633
+ if (v) { diagAliasToId.set(v, Number(r.Diagram_ID)); }
634
+ }
635
+ }
636
+ } else {
637
+ for (const d of newDiags) { diagAliasToId.set(parseStyleToken(d.StyleEx, 'schema_view_id'), -1); }
638
+ }
639
+ const diagIdForView = (viewId) => {
640
+ const row = diagViewRows.get(viewId) || diagByView.get(viewId);
641
+ if (row) { return Number(row.Diagram_ID !== undefined ? row.Diagram_ID : row); }
642
+ const planned = diagAliasToId.get(viewId);
643
+ return planned === undefined ? null : planned;
644
+ };
645
+ // view meta
646
+ if (!o.dryRun) {
647
+ for (const view of graph.views || []) {
648
+ if (view && view.view_id !== undefined && view.view_id !== null) { upsertMeta(db, 'view', view.view_id, view); }
649
+ }
650
+ }
651
+ // memberships: insert missing members, and prune stale schema-anchored members
652
+ // whose element/relationship is no longer in the view (authoritative canonical
653
+ // membership reconcile). Still-in-view members keep their geometry untouched;
654
+ // human-drawn shapes (no schema anchor) are never pruned.
655
+ const canonicalElemObjIds = new Set(
656
+ [...elemIdByAliasAll.values()].filter((v) => v >= 0).map((v) => Number(v))
657
+ );
658
+ const canonicalRelCids = new Set(
659
+ [...relAliasToId.values()].filter((v) => v >= 0).map((v) => Number(v))
660
+ );
661
+ for (const view of graph.views || []) {
662
+ if (!view || view.view_id === undefined || view.view_id === null) { continue; }
663
+ const viewId = String(view.view_id);
664
+ const diagramId = diagIdForView(viewId);
665
+ if (diagramId === null) { continue; }
666
+ const incl = view.included_elements || [];
667
+ const placedObjs = new Set();
668
+ const objs = db.prepare('SELECT Object_ID FROM t_diagramobjects WHERE Diagram_ID=?').all(diagramId);
669
+ for (const r of objs) { placedObjs.add(Number(r.Object_ID)); }
670
+
671
+ if (pruneMembership) {
672
+ const wantedObjs = new Set();
673
+ for (const elId of incl) {
674
+ const oid = elemIdByAliasAll.get(String(elId));
675
+ if (oid !== undefined) { wantedObjs.add(Number(oid)); }
676
+ }
677
+ const stale = [...placedObjs].filter((oid) => !wantedObjs.has(oid) && canonicalElemObjIds.has(oid));
678
+ if (stale.length > 0 && !o.dryRun) {
679
+ const del = db.prepare('DELETE FROM t_diagramobjects WHERE Diagram_ID=? AND Object_ID=?');
680
+ for (const oid of stale) { del.run(diagramId, oid); }
681
+ }
682
+ stats.removed.diagramObjects += stale.length;
683
+ for (const oid of stale) { placedObjs.delete(oid); }
684
+ }
685
+
686
+ const nextSeq = objs.length;
687
+ const newObjs = [];
688
+ let seq = nextSeq;
689
+ for (const elId of incl) {
690
+ const oid = elemIdByAliasAll.get(String(elId));
691
+ if (oid === undefined) { continue; }
692
+ if (placedObjs.has(Number(oid))) { continue; }
693
+ const col = seq % 6;
694
+ const row = Math.floor(seq / 6);
695
+ newObjs.push({
696
+ Diagram_ID: diagramId, Object_ID: Number(oid),
697
+ RectLeft: 40 + col * 260, RectTop: 40 + row * 160,
698
+ RectRight: 40 + col * 260 + 180, RectBottom: 40 + row * 160 + 90,
699
+ Sequence: seq,
700
+ });
701
+ placedObjs.add(Number(oid));
702
+ seq++;
703
+ }
704
+ if (newObjs.length > 0 && !o.dryRun) {
705
+ insertMany(db, 't_diagramobjects', ['Diagram_ID', 'Object_ID', 'RectLeft', 'RectTop', 'RectRight', 'RectBottom', 'Sequence'], newObjs);
706
+ }
707
+ stats.added.diagramObjects += newObjs.length;
708
+
709
+ const relIncl = view.included_relationships || [];
710
+ const placedLinks = new Set();
711
+ const links = db.prepare('SELECT ConnectorID FROM t_diagramlinks WHERE DiagramID=?').all(diagramId);
712
+ for (const r of links) { placedLinks.add(Number(r.ConnectorID)); }
713
+
714
+ if (pruneMembership) {
715
+ const wantedRelCids = new Set();
716
+ for (const relId of relIncl) {
717
+ const cid = relAliasToId.get(String(relId));
718
+ if (cid !== undefined && cid >= 0) { wantedRelCids.add(Number(cid)); }
719
+ }
720
+ const staleLinks = [...placedLinks].filter((cid) => !wantedRelCids.has(cid) && canonicalRelCids.has(cid));
721
+ if (staleLinks.length > 0 && !o.dryRun) {
722
+ const del = db.prepare('DELETE FROM t_diagramlinks WHERE DiagramID=? AND ConnectorID=?');
723
+ for (const cid of staleLinks) { del.run(diagramId, cid); }
724
+ }
725
+ stats.removed.diagramLinks += staleLinks.length;
726
+ for (const cid of staleLinks) { placedLinks.delete(cid); }
727
+ }
728
+
729
+ const newLinks = [];
730
+ for (const relId of relIncl) {
731
+ const cid = relAliasToId.get(String(relId));
732
+ if (cid === undefined || cid < 0) { continue; }
733
+ if (placedLinks.has(Number(cid))) { continue; }
734
+ newLinks.push({ DiagramID: diagramId, ConnectorID: Number(cid), Style: '', Geometry: '' });
735
+ placedLinks.add(Number(cid));
736
+ }
737
+ if (newLinks.length > 0 && !o.dryRun) {
738
+ insertMany(db, 't_diagramlinks', ['DiagramID', 'ConnectorID', 'Style', 'Geometry'], newLinks);
739
+ }
740
+ stats.added.diagramLinks += newLinks.length;
741
+ }
742
+ stages.members = nowMs();
743
+
744
+ // --- deletion reconcile (opt-in) ---------------------------------------
745
+ // Elements are anchored by t_object.Alias; relationships have NO Alias column — their
746
+ // canonical id lives in t_connectortag(schema_id). Using row.Alias for relationships made
747
+ // the candidate check always false, so deleted relationships were never projected out.
748
+ const keepAliases = new Set();
749
+ for (const e of graph.elements || []) { if (e && e.id !== undefined) { keepAliases.add(String(e.id)); } }
750
+ for (const rel of graph.relationships || []) { if (rel && rel.id !== undefined) { keepAliases.add(String(rel.id)); } }
751
+ // connector id -> canonical relationship id (schema_id tag)
752
+ const relSchemaById = new Map();
753
+ try {
754
+ const relTagRows = db.prepare("SELECT ElementID, VALUE FROM t_connectortag WHERE Property='schema_id'").all();
755
+ for (const t of relTagRows) { relSchemaById.set(Number(t.ElementID), String(t.VALUE)); }
756
+ } catch { /* table may be absent on a hand-drawn model */ }
757
+ const candidates = [];
758
+ for (const row of existingElems) {
759
+ if (row.Alias && !keepAliases.has(String(row.Alias))) { candidates.push({ type: 'element', id: Number(row.Object_ID), alias: row.Alias }); }
760
+ }
761
+ for (const row of existingRels) {
762
+ const relId = relSchemaById.get(Number(row.Connector_ID));
763
+ if (relId !== undefined && !keepAliases.has(relId)) { candidates.push({ type: 'relationship', id: Number(row.Connector_ID), alias: relId }); }
764
+ }
765
+ // views: a projected diagram is owned by the projector. Identify its canonical view id via
766
+ // the schema_view_id StyleEx token, or (when EA rewrote StyleEx and dropped the token) by
767
+ // matching the deterministic diagram ea_guid `diag:<viewId>` against the view-id catalog
768
+ // that kg_sync_meta retains. A view id no longer in canonical -> delete the diagram.
769
+ const canonicalViewIds = new Set();
770
+ for (const v of graph.views || []) { if (v && v.view_id !== undefined && v.view_id !== null) { canonicalViewIds.add(String(v.view_id)); } }
771
+ const guidToView = new Map();
772
+ try {
773
+ const viewMetaRows = db.prepare("SELECT key FROM kg_sync_meta WHERE kind='view'").all();
774
+ for (const r of viewMetaRows) { guidToView.set(deterministicGuid('diag:' + String(r.key)), String(r.key)); }
775
+ } catch { /* meta table may be absent */ }
776
+ for (const d of existingDiags) {
777
+ let vid = parseStyleToken(d.StyleEx, 'schema_view_id');
778
+ if (!vid && d.ea_guid) { vid = guidToView.get(String(d.ea_guid)) || ''; }
779
+ if (vid && !canonicalViewIds.has(String(vid))) { candidates.push({ type: 'diagram', id: Number(d.Diagram_ID), alias: String(vid) }); }
780
+ }
781
+ stats.deleteCandidates = candidates.length;
782
+ if (candidates.length > 0 && o.allowDelete && !o.dryRun) {
783
+ for (const c of candidates) {
784
+ if (c.type === 'relationship') {
785
+ // SQLite has no FK cascade: clear the connector's tag + diagram-link rows too.
786
+ db.prepare('DELETE FROM t_connectortag WHERE ElementID=?').run(c.id);
787
+ db.prepare('DELETE FROM t_diagramlinks WHERE ConnectorID=?').run(c.id);
788
+ db.prepare('DELETE FROM t_connector WHERE Connector_ID=?').run(c.id);
789
+ } else if (c.type === 'diagram') {
790
+ db.prepare('DELETE FROM t_diagramobjects WHERE Diagram_ID=?').run(c.id);
791
+ db.prepare('DELETE FROM t_diagramlinks WHERE DiagramID=?').run(c.id);
792
+ db.prepare('DELETE FROM t_diagram WHERE Diagram_ID=?').run(c.id);
793
+ } else {
794
+ // remove connectors attached to this element (start or end) and their children
795
+ const attached = db.prepare('SELECT Connector_ID FROM t_connector WHERE Start_Object_ID=? OR End_Object_ID=?').all(c.id, c.id);
796
+ for (const a of attached) {
797
+ db.prepare('DELETE FROM t_connectortag WHERE ElementID=?').run(Number(a.Connector_ID));
798
+ db.prepare('DELETE FROM t_diagramlinks WHERE ConnectorID=?').run(Number(a.Connector_ID));
799
+ db.prepare('DELETE FROM t_connector WHERE Connector_ID=?').run(Number(a.Connector_ID));
800
+ }
801
+ db.prepare('DELETE FROM t_diagramobjects WHERE Object_ID=?').run(c.id);
802
+ db.prepare('DELETE FROM t_objectproperties WHERE Object_ID=?').run(c.id);
803
+ db.prepare('DELETE FROM t_attribute WHERE Object_ID=?').run(c.id);
804
+ db.prepare('DELETE FROM t_objecttests WHERE Object_ID=?').run(c.id);
805
+ db.prepare('DELETE FROM t_object WHERE Object_ID=?').run(c.id);
806
+ }
807
+ stats.deleted++;
808
+ }
809
+ }
810
+ stages.deletes = nowMs();
811
+ if (!o.dryRun) { db.exec('COMMIT'); }
812
+ } finally {
813
+ try { db.close(); } catch { /* ignore */ }
814
+ }
815
+ stats.ms = {
816
+ total: nowMs() - t0,
817
+ package: stages.package - t0,
818
+ elements: stages.elements - stages.package,
819
+ elemTags: stages.elemTags - stages.elements,
820
+ relationships: stages.relationships - stages.elemTags,
821
+ relTags: stages.relTags - stages.relationships,
822
+ views: stages.members - stages.relTags,
823
+ members: stages.members - stages.relTags,
824
+ };
825
+ return { ok: true, syncPackageId: stats.syncPackageId, stats };
826
+ }
827
+
828
+ // ---------------------------------------------------------------------------
829
+ // ---------------------------------------------------------------------------
830
+ // Full projection (whole-file rebuild, decision qea-full-wholefile-argo-scripts-no-config):
831
+ // wipe ALL existing content in the target .qea (every user table row, incl. kg_sync_meta),
832
+ // re-seed the minimal root package, then rebuild the whole .qea purely from the canonical
833
+ // graph. EA is treated as a projection: after full there is nothing but canonical content.
834
+ // ---------------------------------------------------------------------------
835
+ function wipeAllContent(db) {
836
+ const rows = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'").all();
837
+ const cleared = {};
838
+ for (const r of rows) {
839
+ try {
840
+ const before = db.prepare('SELECT COUNT(*) AS c FROM "' + r.name + '"').get().c;
841
+ db.exec('DELETE FROM "' + r.name + '"');
842
+ cleared[r.name] = before;
843
+ } catch { /* skip locked/system tables */ }
844
+ }
845
+ try { db.exec('DELETE FROM sqlite_sequence'); } catch { /* ignore */ }
846
+ return cleared;
847
+ }
848
+ function ensureRootPackage(db) {
849
+ const roots = db.prepare('SELECT Package_ID FROM t_package WHERE Parent_ID=0 ORDER BY Package_ID').all();
850
+ if (roots.length > 0) { return Number(roots[0].Package_ID); }
851
+ const r = db.prepare('INSERT INTO t_package (Name, Parent_ID, ea_guid) VALUES (?,?,?)').run('Model', 0, deterministicGuid('pkg:Model'));
852
+ return Number(r.lastInsertRowid);
853
+ }
854
+ function verifyQeaCanonical(graph, qeaPath) {
855
+ let roundtrip = null;
856
+ try { roundtrip = require('../../tests/_ea-roundtrip-lib.js'); } catch { roundtrip = null; }
857
+ const exp = exportQeaToGraph(qeaPath);
858
+ const counts = {
859
+ elements: exp.elements.length, relationships: exp.relationships.length, views: exp.views.length,
860
+ sourceElements: (graph.elements || []).length,
861
+ sourceRelationships: (graph.relationships || []).length,
862
+ sourceViews: (graph.views || []).length,
863
+ };
864
+ let equal = counts.elements === counts.sourceElements && counts.relationships === counts.sourceRelationships && counts.views === counts.sourceViews;
865
+ let diffs = null;
866
+ if (roundtrip && typeof roundtrip.compareRoundtrip === 'function') {
867
+ const rep = roundtrip.compareRoundtrip(graph, exp, {});
868
+ equal = rep.equal;
869
+ diffs = { missing: rep.missingInExport.length, extra: rep.extraInExport.length, valueDiffs: rep.valueDiffs.length };
870
+ }
871
+ return { consistent: equal, diffs, counts };
872
+ }
873
+ function fullProjection(graph, qeaPath, opts) {
874
+ const o = opts || {};
875
+ const t0 = nowMs();
876
+ let wiped = null;
877
+ let db = null;
878
+ try {
879
+ db = openQea(qeaPath);
880
+ ensureMetaTable(db);
881
+ db.exec('BEGIN IMMEDIATE');
882
+ wiped = wipeAllContent(db);
883
+ ensureRootPackage(db);
884
+ db.exec('COMMIT');
885
+ } finally {
886
+ if (db) { try { db.close(); } catch { /* ignore */ } }
887
+ }
888
+ const sync = syncGraphToQea(graph, qeaPath, { dryRun: o.dryRun, allowDelete: false });
889
+ const verification = o.verify === false ? null : verifyQeaCanonical(graph, qeaPath);
890
+ return { ok: true, wiped, sync: sync.stats, verification, ms: { total: nowMs() - t0 } };
891
+ }
892
+
893
+ // ---------------------------------------------------------------------------
894
+ // Export
895
+ // ---------------------------------------------------------------------------
896
+ // EA stores connector layout in two distinct t_diagramlinks columns, and they mean
897
+ // different things:
898
+ // - Path = the connector ROUTE: user-adjusted bend points as "x:y;x:y;" in diagram
899
+ // coordinates (empty when EA auto-routes a straight/orthogonal line).
900
+ // - Geometry = the non-route OVERRIDE tokens (SX/SY/EX/EY dock offsets, EDGE route
901
+ // style and label positions). It never contains bend points.
902
+ // Reading Geometry as if it were the line was the original defect: callers got the
903
+ // override string and could not rebuild the connector. We expose the route under `path`
904
+ // (+ parsed `points`), the route style as `edge`, and keep the override as `geometry`.
905
+ function parseRoutePoints(raw) {
906
+ const s = String(raw === null || raw === undefined ? '' : raw).trim();
907
+ if (s === '') { return []; }
908
+ const points = [];
909
+ for (const seg of s.split(';')) {
910
+ const t = seg.trim();
911
+ if (t === '') { continue; }
912
+ const parts = t.split(':');
913
+ if (parts.length < 2) { continue; }
914
+ const x = Number(parts[0]);
915
+ const y = Number(parts[1]);
916
+ if (!Number.isFinite(x) || !Number.isFinite(y)) { continue; }
917
+ points.push({ x, y });
918
+ }
919
+ return points;
920
+ }
921
+ function parseEdgeToken(geometry) {
922
+ const m = /(?:^|;)EDGE=(-?\d+)(?:;|$)/.exec(String(geometry === null || geometry === undefined ? '' : geometry));
923
+ return m ? Number(m[1]) : null;
924
+ }
925
+
926
+ // Read the EA diagram GEOMETRY for one KG view from a .qea model (read-only).
927
+ // The view maps to the diagram anchored by the deterministic ea_guid (diag:<viewId>)
928
+ // or the schema_view_id StyleEx token written by the sync. Returns:
929
+ // - element boxes = t_diagramobjects rects joined to t_object.Alias (schema id)
930
+ // - connector lines = t_diagramlinks rows joined to the connector's schema_id tag,
931
+ // with the ROUTE (t_diagramlinks.Path) parsed into `points`
932
+ // Returns null when the view has no matching EA diagram. Never writes EA geometry.
933
+ function readViewDiagramGeometry(qeaPath, viewId) {
934
+ const v = String(viewId === null || viewId === undefined ? '' : viewId).trim();
935
+ if (v === '') { return null; }
936
+ const db = openQea(qeaPath);
937
+ try {
938
+ ensureMetaTable(db);
939
+ const guid = deterministicGuid('diag:' + v);
940
+ const diag = db.prepare('SELECT Diagram_ID FROM t_diagram WHERE ea_guid = ? OR StyleEx LIKE ?')
941
+ .get(guid, '%schema_view_id=' + v + ';%');
942
+ if (!diag) { return null; }
943
+ const diagramId = Number(diag.Diagram_ID);
944
+ const elements = db.prepare(
945
+ 'SELECT o.Alias AS id, d.RectLeft AS left, d.RectTop AS top, d.RectRight AS right, d.RectBottom AS bottom ' +
946
+ 'FROM t_diagramobjects d JOIN t_object o ON o.Object_ID = d.Object_ID ' +
947
+ 'WHERE d.Diagram_ID = ? AND o.Alias IS NOT NULL AND o.Alias <> ? ' +
948
+ 'ORDER BY d.Sequence'
949
+ ).all(diagramId, '').map((r) => ({
950
+ id: String(r.id),
951
+ left: Number(r.left), top: Number(r.top), right: Number(r.right), bottom: Number(r.bottom),
952
+ }));
953
+ const relationships = db.prepare(
954
+ 'SELECT t.VALUE AS id, dl.Path AS path, dl.Geometry AS geometry ' +
955
+ 'FROM t_diagramlinks dl JOIN t_connectortag t ON t.ElementID = dl.ConnectorID AND t.Property = ? ' +
956
+ 'WHERE dl.DiagramID = ? ORDER BY dl.ConnectorID'
957
+ ).all('schema_id', diagramId).map((r) => {
958
+ const path = String(r.path === null || r.path === undefined ? '' : r.path);
959
+ const geometry = String(r.geometry === null || r.geometry === undefined ? '' : r.geometry);
960
+ return { id: String(r.id), path, points: parseRoutePoints(path), edge: parseEdgeToken(geometry), geometry };
961
+ });
962
+ return { diagramId, elements, relationships };
963
+ } finally {
964
+ try { db.close(); } catch { /* ignore */ }
965
+ }
966
+ }
967
+
968
+ function exportQeaToGraph(qeaPath) {
969
+ const db = openQea(qeaPath);
970
+ try {
971
+ ensureMetaTable(db);
972
+ const elements = readMetaKind(db, 'element').filter((e) => e && e.id !== undefined);
973
+ const relationships = readMetaKind(db, 'relationship').filter((r) => r && r.id !== undefined);
974
+ const views = readMetaKind(db, 'view').filter((v) => v && v.view_id !== undefined);
975
+ return { name: 'ArchGraph (from archgraph.qea)', description: '', elements, relationships, views };
976
+ } finally {
977
+ db.close();
978
+ }
979
+ }
980
+
981
+ // ---------------------------------------------------------------------------
982
+ // snapshot
983
+ // ---------------------------------------------------------------------------
984
+ function snapshotQea(qeaPath, snapshotDir) {
985
+ const fs = require('node:fs');
986
+ const path = require('node:path');
987
+ if (!fs.existsSync(qeaPath)) { return null; }
988
+ const dir = snapshotDir || path.dirname(qeaPath);
989
+ fs.mkdirSync(dir, { recursive: true });
990
+ const ts = new Date().toISOString().replace(/[:.]/g, '-');
991
+ const target = path.join(dir, path.basename(qeaPath).replace(/(\.qea)$/i, '_before_sync_' + ts + '$1'));
992
+ fs.copyFileSync(qeaPath, target);
993
+ return target;
994
+ }
995
+
996
+ module.exports = {
997
+ SYNC_PACKAGE_NAME,
998
+ META_TABLE,
999
+ openQea,
1000
+ deterministicGuid,
1001
+ elementObjectType,
1002
+ elementStereotype,
1003
+ relationshipMap,
1004
+ canonicalArchimateType,
1005
+ syncGraphToQea,
1006
+ exportQeaToGraph,
1007
+ readViewDiagramGeometry,
1008
+ snapshotQea,
1009
+ readMetaKind,
1010
+ fullProjection,
1011
+ wipeAllContent,
1012
+ ensureRootPackage,
1013
+ verifyQeaCanonical,
1014
+ };