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,269 @@
1
+ const { spawnSync } = require('node:child_process');
2
+ const path = require('node:path');
3
+
4
+ const {
5
+ getArgoEnvPath,
6
+ } = require('../argo-paths.js');
7
+
8
+ const CAPABILITY_NAMES = Object.freeze([
9
+ 'isSecretFileIgnored',
10
+ 'isSecretFileTracked',
11
+ 'isSecretFileInsideGitRepository',
12
+ 'readCurrentIdentity',
13
+ 'readSecretFileAcl',
14
+ ]);
15
+
16
+ function createSystemMetadataCommandAdapter(options = {}) {
17
+ requireExactKeys(options, ['repositoryRoot']);
18
+ const repositoryRoot = requireRepositoryRoot(options.repositoryRoot);
19
+ return createAdapter({
20
+ repositoryRoot,
21
+ executeMetadataCommand: spawnSync,
22
+ mutateInvocation: undefined,
23
+ forbiddenValues: [],
24
+ }).adapter;
25
+ }
26
+
27
+ function createReadinessAttestationMetadataAdapter(options = {}) {
28
+ requireExactKeys(options, ['repositoryRoot']);
29
+ const repositoryRoot = requireRepositoryRoot(options.repositoryRoot);
30
+ const file = path.join(
31
+ options.repositoryRoot,
32
+ '.argo',
33
+ 'temp',
34
+ 'semantic-readiness-attestation.json',
35
+ );
36
+ const directory = path.dirname(file);
37
+ const environment = sanitizedEnvironment();
38
+
39
+ function spawnExact(executable, args) {
40
+ return spawnSync(executable, args, {
41
+ cwd: repositoryRoot,
42
+ encoding: 'utf8',
43
+ env: { ...environment },
44
+ shell: false,
45
+ windowsHide: true,
46
+ });
47
+ }
48
+
49
+ return Object.freeze({
50
+ readCurrentIdentity: () => spawnExact('whoami', []),
51
+ readReadinessAttestationDirectoryAcl: () => spawnExact('icacls', [directory]),
52
+ readReadinessAttestationAcl: () => spawnExact('icacls', [file]),
53
+ readReadinessAttestationOwner: () => spawnExact('powershell.exe', [
54
+ '-NoProfile',
55
+ '-NonInteractive',
56
+ '-Command',
57
+ exactOwnerScript(file),
58
+ ]),
59
+ });
60
+ }
61
+
62
+ function exactOwnerScript(file) {
63
+ const literalPath = String(file).replace(/'/g, "''");
64
+ return `(Get-Acl -LiteralPath '${literalPath}').Owner`;
65
+ }
66
+
67
+ function sanitizedEnvironment() {
68
+ return Object.freeze(Object.fromEntries(
69
+ ['PATH', 'Path', 'PATHEXT', 'SystemRoot', 'WINDIR']
70
+ .filter(key => typeof process.env[key] === 'string')
71
+ .map(key => [key, process.env[key]]),
72
+ ));
73
+ }
74
+
75
+ function withSystemMetadataCommandTestComposition(options = {}, callback) {
76
+ requireExactKeys(options, [
77
+ 'executeMetadataCommand',
78
+ 'forbiddenValues',
79
+ 'mutateInvocation',
80
+ 'repositoryRoot',
81
+ ], true);
82
+ if (typeof options.executeMetadataCommand !== 'function' || typeof callback !== 'function') {
83
+ throw prohibited();
84
+ }
85
+ const composition = createAdapter({
86
+ repositoryRoot: requireRepositoryRoot(options.repositoryRoot),
87
+ executeMetadataCommand: options.executeMetadataCommand,
88
+ mutateInvocation: options.mutateInvocation,
89
+ forbiddenValues: Array.isArray(options.forbiddenValues) ? [...options.forbiddenValues] : [],
90
+ });
91
+ let result;
92
+ let then;
93
+ let asyncRevocationOwner = false;
94
+ try {
95
+ result = callback(composition.adapter);
96
+ if (
97
+ result !== null
98
+ && (typeof result === 'object' || typeof result === 'function')
99
+ ) {
100
+ then = result.then;
101
+ }
102
+ if (typeof then === 'function') {
103
+ asyncRevocationOwner = true;
104
+ return assimilateThenable(result, then, composition.revoke);
105
+ }
106
+ return undefined;
107
+ } finally {
108
+ if (!asyncRevocationOwner) composition.revoke();
109
+ }
110
+ }
111
+
112
+ async function assimilateThenable(value, then, revoke) {
113
+ try {
114
+ await new Promise((resolve, reject) => {
115
+ then.call(value, resolve, reject);
116
+ });
117
+ return undefined;
118
+ } finally {
119
+ revoke();
120
+ }
121
+ }
122
+
123
+ function createAdapter({
124
+ repositoryRoot,
125
+ executeMetadataCommand,
126
+ mutateInvocation,
127
+ forbiddenValues,
128
+ }) {
129
+ const canonicalPath = getArgoEnvPath();
130
+ const gitDirectory = path.dirname(canonicalPath);
131
+ const sanitizedEnvironment = Object.freeze(Object.fromEntries(
132
+ ['PATH', 'PATHEXT', 'SystemRoot', 'WINDIR']
133
+ .filter(key => typeof process.env[key] === 'string')
134
+ .map(key => [key, process.env[key]]),
135
+ ));
136
+ let revoked = false;
137
+
138
+ function invoke(capabilityName, receivedArguments) {
139
+ if (revoked) {
140
+ const error = new Error('TEST_SYSTEM_METADATA_ADAPTER_REVOKED');
141
+ error.category = 'TEST_SYSTEM_METADATA_ADAPTER_REVOKED';
142
+ throw error;
143
+ }
144
+ if (receivedArguments.length !== 0) throw prohibited();
145
+ const expected = buildInvocation(
146
+ capabilityName,
147
+ gitDirectory,
148
+ canonicalPath,
149
+ sanitizedEnvironment,
150
+ );
151
+ const candidate = typeof mutateInvocation === 'function'
152
+ ? mutateInvocation(cloneInvocation(expected))
153
+ : expected;
154
+ validateInvocation(candidate, expected, forbiddenValues);
155
+ return executeMetadataCommand(
156
+ candidate.executable,
157
+ [...candidate.args],
158
+ cloneOptions(candidate.options),
159
+ );
160
+ }
161
+
162
+ const adapter = Object.create(null);
163
+ for (const capabilityName of CAPABILITY_NAMES) {
164
+ const capability = capabilityName === 'isSecretFileIgnored'
165
+ ? (...args) => invoke(capabilityName, args).status === 0
166
+ : capabilityName === 'isSecretFileTracked'
167
+ ? (...args) => invoke(capabilityName, args).status === 0
168
+ : (...args) => {
169
+ const result = invoke(capabilityName, args);
170
+ return {
171
+ status: result.status,
172
+ stdout: typeof result.stdout === 'string' ? result.stdout : '',
173
+ };
174
+ };
175
+ Object.freeze(capability);
176
+ Object.defineProperty(adapter, capabilityName, {
177
+ value: capability,
178
+ enumerable: true,
179
+ writable: false,
180
+ configurable: false,
181
+ });
182
+ }
183
+ Object.freeze(adapter);
184
+ return {
185
+ adapter,
186
+ revoke() {
187
+ revoked = true;
188
+ },
189
+ };
190
+ }
191
+
192
+ function buildInvocation(capabilityName, gitDirectory, canonicalPath, environment) {
193
+ const templates = {
194
+ isSecretFileInsideGitRepository: ['git', ['rev-parse', '--is-inside-work-tree']],
195
+ isSecretFileIgnored: ['git', ['check-ignore', '--quiet', '--', '.env']],
196
+ isSecretFileTracked: ['git', ['ls-files', '--error-unmatch', '--', '.env']],
197
+ readCurrentIdentity: ['whoami', []],
198
+ readSecretFileAcl: ['icacls', [canonicalPath]],
199
+ };
200
+ const template = templates[capabilityName];
201
+ if (!template) throw prohibited();
202
+ return {
203
+ executable: template[0],
204
+ args: [...template[1]],
205
+ options: {
206
+ cwd: gitDirectory,
207
+ encoding: 'utf8',
208
+ env: { ...environment },
209
+ shell: false,
210
+ windowsHide: true,
211
+ },
212
+ };
213
+ }
214
+
215
+ function validateInvocation(candidate, expected, forbiddenValues) {
216
+ if (!candidate || typeof candidate !== 'object') throw prohibited();
217
+ if (JSON.stringify(candidate) !== JSON.stringify(expected)) throw prohibited();
218
+ const serialized = JSON.stringify(candidate);
219
+ for (const forbiddenValue of forbiddenValues) {
220
+ if (typeof forbiddenValue === 'string' && forbiddenValue && serialized.includes(forbiddenValue)) {
221
+ throw prohibited();
222
+ }
223
+ }
224
+ }
225
+
226
+ function cloneInvocation(invocation) {
227
+ return {
228
+ executable: invocation.executable,
229
+ args: [...invocation.args],
230
+ options: cloneOptions(invocation.options),
231
+ };
232
+ }
233
+
234
+ function cloneOptions(options) {
235
+ return {
236
+ cwd: options.cwd,
237
+ encoding: options.encoding,
238
+ env: { ...options.env },
239
+ shell: options.shell,
240
+ windowsHide: options.windowsHide,
241
+ };
242
+ }
243
+
244
+ function requireExactKeys(value, allowedKeys, optional = false) {
245
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw prohibited();
246
+ const actual = Object.keys(value).sort();
247
+ const allowed = [...allowedKeys].sort();
248
+ if (actual.some(key => !allowed.includes(key))) throw prohibited();
249
+ if (!optional && (actual.length !== allowed.length || actual.some((key, index) => key !== allowed[index]))) {
250
+ throw prohibited();
251
+ }
252
+ }
253
+
254
+ function requireRepositoryRoot(value) {
255
+ if (typeof value !== 'string' || value.trim() === '') throw prohibited();
256
+ return path.resolve(value);
257
+ }
258
+
259
+ function prohibited() {
260
+ const error = new Error('SYSTEM_METADATA_COMMAND_PROHIBITED');
261
+ error.category = 'SYSTEM_METADATA_COMMAND_PROHIBITED';
262
+ return error;
263
+ }
264
+
265
+ module.exports = {
266
+ createReadinessAttestationMetadataAdapter,
267
+ createSystemMetadataCommandAdapter,
268
+ withSystemMetadataCommandTestComposition,
269
+ };
@@ -0,0 +1,266 @@
1
+ // Shared graph-semantics validation for SystemArchitecture.
2
+ // Used by both validateSystemArchitecture.js (full validation) and
3
+ // systemarchitecture-mcp-server.js (mutation-path validation).
4
+ //
5
+ // This module eliminates the duplicate validateGraphSemantics implementations.
6
+ // All callers get identical core checks; the modeling language (element types,
7
+ // relationship types, endpoint matrix, statement grammar, root-view name and
8
+ // view element limit) is supplied by an *ontology* so a repository that ships
9
+ // its own schema under .argo/schema is validated against its own language.
10
+ //
11
+ // The ontology argument is optional: when omitted, the default ArgoBument
12
+ // (ArchiMate 3.2 + ARGO) ontology is used, preserving historical behaviour.
13
+
14
+ const { loadSchemaBundleAndOntology } = require('./argob-schema.js');
15
+
16
+ let defaultOntology = null;
17
+
18
+ function resolveOntology(ontology) {
19
+ if (ontology) {
20
+ return ontology;
21
+ }
22
+ if (!defaultOntology) {
23
+ defaultOntology = loadSchemaBundleAndOntology(process.cwd()).ontology;
24
+ }
25
+ return defaultOntology;
26
+ }
27
+
28
+ /**
29
+ * Core graph-semantics checks that are always identical for all callers.
30
+ *
31
+ * @param {object} document - parsed SystemArchitecture JSON
32
+ * @param {string[]} errors - error accumulator
33
+ * @param {object} [ontology] - resolved modeling language (defaults to ArgoBument)
34
+ */
35
+ function validateGraphSemantics(document, errors, ontology) {
36
+ if (!document || typeof document !== 'object') {
37
+ return;
38
+ }
39
+ const language = resolveOntology(ontology);
40
+ const invariants = language.invariants || {};
41
+ const elementTypeLabel = language.elementTypeErrorLabel || language.language || 'the';
42
+ const relationshipTypeLabel = language.relationshipTypeErrorLabel || language.language || 'the';
43
+ const rootViewName = invariants.rootViewName === undefined ? 'SystemArchitecture' : invariants.rootViewName;
44
+
45
+ const elements = Array.isArray(document.elements) ? document.elements : [];
46
+ const relationships = Array.isArray(document.relationships) ? document.relationships : [];
47
+ const views = Array.isArray(document.views) ? document.views : [];
48
+ const elementById = new Map();
49
+ const relationshipById = new Map();
50
+
51
+ // --- elements: identity, type, parent ---
52
+ for (const element of elements) {
53
+ if (!element || typeof element !== 'object') {
54
+ continue;
55
+ }
56
+ if (elementById.has(element.id)) {
57
+ errors.push(`elements contains duplicate id '${element.id}'`);
58
+ continue;
59
+ }
60
+ elementById.set(element.id, element);
61
+ if (!language.isSupportedElementType(element.type)) {
62
+ errors.push(`elements '${element.id}' uses unsupported ${elementTypeLabel} element type '${element.type}'`);
63
+ }
64
+ }
65
+
66
+ for (const element of elements) {
67
+ if (!element || typeof element !== 'object' || !element.parent) {
68
+ continue;
69
+ }
70
+ if (!elementById.has(element.parent)) {
71
+ errors.push(`elements '${element.id}' references missing parent '${element.parent}'`);
72
+ }
73
+ }
74
+
75
+ // --- relationships: identity, type, endpoints, statement ---
76
+ for (const relationship of relationships) {
77
+ if (!relationship || typeof relationship !== 'object') {
78
+ continue;
79
+ }
80
+ if (relationshipById.has(relationship.id)) {
81
+ errors.push(`relationships contains duplicate id '${relationship.id}'`);
82
+ continue;
83
+ }
84
+ relationshipById.set(relationship.id, relationship);
85
+ if (!language.isSupportedRelationshipType(relationship.type)) {
86
+ errors.push(`relationships '${relationship.id}' uses unsupported ${relationshipTypeLabel} relationship type '${relationship.type}'`);
87
+ }
88
+
89
+ const source = elementById.get(relationship.source_id);
90
+ if (!source) {
91
+ errors.push(`relationships '${relationship.id}' references missing source_id '${relationship.source_id}'`);
92
+ } else if (relationship.source_name !== source.name) {
93
+ errors.push(`relationships '${relationship.id}' source_name '${relationship.source_name}' does not match element '${relationship.source_id}' name '${source.name}'`);
94
+ }
95
+
96
+ const target = elementById.get(relationship.target_id);
97
+ if (!target) {
98
+ errors.push(`relationships '${relationship.id}' references missing target_id '${relationship.target_id}'`);
99
+ } else if (relationship.target_name !== target.name) {
100
+ errors.push(`relationships '${relationship.id}' target_name '${relationship.target_name}' does not match element '${relationship.target_id}' name '${target.name}'`);
101
+ }
102
+
103
+ if (invariants.statementGrammar === false) {
104
+ continue;
105
+ }
106
+ const expectedStatement = source && target
107
+ ? `${source.name} --(${relationship.type})--> ${target.name}`
108
+ : undefined;
109
+ if (expectedStatement && relationship.statement !== expectedStatement) {
110
+ errors.push(`relationships '${relationship.id}' statement must be '${expectedStatement}'`);
111
+ }
112
+ }
113
+
114
+ // --- views: topology, membership, endpoint co-occurrence ---
115
+ const topLevelViews = views.filter(view => view && typeof view === 'object' && !view.parent_element_id);
116
+ if (topLevelViews.length !== 1) {
117
+ errors.push(
118
+ rootViewName
119
+ ? `views must contain exactly one top-level view named '${rootViewName}'; found ${topLevelViews.length}`
120
+ : `views must contain exactly one top-level view; found ${topLevelViews.length}`,
121
+ );
122
+ } else if (rootViewName && topLevelViews[0].view_name !== rootViewName) {
123
+ errors.push(`top-level view '${topLevelViews[0].view_id}' view_name must be '${rootViewName}'`);
124
+ }
125
+
126
+ const elementIdsIncludedInViews = new Set();
127
+ const relationshipIdsIncludedInViews = new Set();
128
+ for (const view of views) {
129
+ if (!view || typeof view !== 'object') {
130
+ continue;
131
+ }
132
+ if (!view.parent_element_id && rootViewName && view.view_name !== rootViewName) {
133
+ errors.push(`views '${view.view_id}' must declare parent_element_id unless it is the top-level ${rootViewName} view`);
134
+ }
135
+ if (view.parent_element_id) {
136
+ const parent = elementById.get(view.parent_element_id);
137
+ if (!parent) {
138
+ errors.push(`views '${view.view_id}' references missing parent_element_id '${view.parent_element_id}'`);
139
+ } else if (view.parent_element_name && view.parent_element_name !== parent.name) {
140
+ errors.push(`views '${view.view_id}' parent_element_name '${view.parent_element_name}' does not match element '${view.parent_element_id}' name '${parent.name}'`);
141
+ }
142
+ }
143
+ const includedElementIds = new Set(view.included_elements || []);
144
+ if (includedElementIds.size !== (view.included_elements || []).length) {
145
+ errors.push(`views '${view.view_id}' must not contain duplicate included_elements`);
146
+ }
147
+ for (const elementId of view.included_elements || []) {
148
+ elementIdsIncludedInViews.add(elementId);
149
+ if (!elementById.has(elementId)) {
150
+ errors.push(`views '${view.view_id}' references missing included element '${elementId}'`);
151
+ }
152
+ }
153
+ const includedRelationshipIds = new Set(view.included_relationships || []);
154
+ if (includedRelationshipIds.size !== (view.included_relationships || []).length) {
155
+ errors.push(`views '${view.view_id}' must not contain duplicate included_relationships`);
156
+ }
157
+ for (const relationshipId of view.included_relationships || []) {
158
+ relationshipIdsIncludedInViews.add(relationshipId);
159
+ const rel = relationshipById.get(relationshipId);
160
+ if (!rel) {
161
+ errors.push(`views '${view.view_id}' references missing included relationship '${relationshipId}'`);
162
+ continue;
163
+ }
164
+ if (!includedElementIds.has(rel.source_id)) {
165
+ errors.push(`views '${view.view_id}' includes relationship '${relationshipId}' but not source element '${rel.source_id}'`);
166
+ }
167
+ if (!includedElementIds.has(rel.target_id)) {
168
+ errors.push(`views '${view.view_id}' includes relationship '${relationshipId}' but not target element '${rel.target_id}'`);
169
+ }
170
+ }
171
+ }
172
+
173
+ for (const element of elements) {
174
+ if (element && typeof element === 'object' && !elementIdsIncludedInViews.has(element.id)) {
175
+ errors.push(`elements '${element.id}' must be included in at least one view`);
176
+ }
177
+ }
178
+
179
+ for (const relationship of relationships) {
180
+ if (relationship && typeof relationship === 'object' && !relationshipIdsIncludedInViews.has(relationship.id)) {
181
+ errors.push(`relationships '${relationship.id}' must be included in at least one view`);
182
+ }
183
+ }
184
+ }
185
+
186
+ /**
187
+ * Validate the modeling language's endpoint-type matrix for relationships.
188
+ * No-op when the ontology disables the endpoint matrix invariant.
189
+ *
190
+ * @param {object} document - parsed SystemArchitecture JSON
191
+ * @param {string[]} errors - error accumulator
192
+ * @param {object} [options]
193
+ * @param {string[]} [options.touchedRelationshipIds] - if provided, only these
194
+ * relationships are checked; if omitted/empty, ALL relationships are checked
195
+ * @param {object} [options.ontology] - resolved modeling language
196
+ */
197
+ function validateArchiMateEndpointMatrix(document, errors, options = {}) {
198
+ const ontology = resolveOntology(options.ontology);
199
+ if (ontology.invariants && ontology.invariants.endpointMatrix === false) {
200
+ return;
201
+ }
202
+ const elementById = new Map(
203
+ (document.elements || []).map(element => [element.id, element]),
204
+ );
205
+ const relationshipIdSet =
206
+ Array.isArray(options.touchedRelationshipIds) && options.touchedRelationshipIds.length > 0
207
+ ? new Set(options.touchedRelationshipIds)
208
+ : undefined;
209
+
210
+ for (const relationship of document.relationships || []) {
211
+ if (relationshipIdSet && !relationshipIdSet.has(relationship.id)) {
212
+ continue;
213
+ }
214
+ const source = elementById.get(relationship.source_id);
215
+ const target = elementById.get(relationship.target_id);
216
+ errors.push(...ontology.validateRelationshipEndpointTypes(relationship, source, target));
217
+ }
218
+ }
219
+
220
+ /**
221
+ * Validate the ontology's per-view element limit (default 15).
222
+ * `maxElementsPerView: null` disables the limit. included_relationships do not
223
+ * consume the quota.
224
+ *
225
+ * @param {object} document - parsed SystemArchitecture JSON
226
+ * @param {string[]} errors - error accumulator
227
+ * @param {object} [options]
228
+ * @param {string[]} [options.touchedViewIds] - if provided, only these views
229
+ * are checked; if omitted/empty, ALL views are checked
230
+ * @param {object} [options.ontology] - resolved modeling language
231
+ */
232
+ function validateViewElementLimits(document, errors, options = {}) {
233
+ const ontology = resolveOntology(options.ontology);
234
+ const maxIncludedElements = ontology.invariants && ontology.invariants.maxElementsPerView !== undefined
235
+ ? ontology.invariants.maxElementsPerView
236
+ : 15;
237
+ if (maxIncludedElements === null) {
238
+ return;
239
+ }
240
+ const touchedViewIdSet =
241
+ Array.isArray(options.touchedViewIds) && options.touchedViewIds.length > 0
242
+ ? new Set(options.touchedViewIds)
243
+ : undefined;
244
+
245
+ for (const view of document.views || []) {
246
+ if (!view) {
247
+ continue;
248
+ }
249
+ if (touchedViewIdSet && !touchedViewIdSet.has(view.view_id)) {
250
+ continue;
251
+ }
252
+ const elementCount = Array.isArray(view.included_elements) ? view.included_elements.length : 0;
253
+ if (elementCount > maxIncludedElements) {
254
+ errors.push(
255
+ `views '${view.view_id}' must contain at most ${maxIncludedElements} elements; found ${elementCount}. ` +
256
+ 'Split the content into layered sub-views before adding more elements.',
257
+ );
258
+ }
259
+ }
260
+ }
261
+
262
+ module.exports = {
263
+ validateGraphSemantics,
264
+ validateArchiMateEndpointMatrix,
265
+ validateViewElementLimits,
266
+ };