arkgate 2.13.0 → 3.0.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.
- package/CHANGELOG.md +39 -0
- package/README.md +37 -22
- package/bin/ark-check.mjs +62 -4
- package/bin/ark-mcp.mjs +108 -1
- package/bin/ark-shared.mjs +204 -149
- package/bin/ark.mjs +90 -25
- package/bin/lib/adapter-contract.mjs +93 -0
- package/bin/lib/agent-gates.mjs +1 -0
- package/bin/lib/analysis-engine.mjs +1171 -0
- package/bin/lib/architecture-scan.mjs +84 -135
- package/bin/lib/ci-and-commands.mjs +31 -0
- package/bin/lib/config-warnings.mjs +7 -205
- package/bin/lib/field-install.mjs +67 -10
- package/bin/lib/gate-files.mjs +42 -3
- package/bin/lib/graph-cycles.mjs +4 -54
- package/bin/lib/hook-templates.mjs +33 -1
- package/bin/lib/host-support-matrix.mjs +7 -1
- package/bin/lib/install-migrate.mjs +54 -16
- package/bin/lib/presets.mjs +42 -2
- package/bin/lib/safety-diagnostics.mjs +18 -17
- package/bin/lib/scan-files.mjs +12 -1
- package/bin/lib/skill-install.mjs +8 -1
- package/bin/lib/source-policy.mjs +36 -0
- package/bin/lib/start-preview.mjs +271 -0
- package/bin/lib/ts-resolve.mjs +11 -2
- package/bin/lib/write-path-capabilities.mjs +4 -0
- package/compat/nestjs.cjs +2 -0
- package/compat/nestjs.d.ts +2 -0
- package/compat/nestjs.js +1 -0
- package/compat/runtime.cjs +2 -0
- package/compat/runtime.d.ts +2 -0
- package/compat/runtime.js +1 -0
- package/dist/configContract-BxSIwVRo.d.cts +259 -0
- package/dist/configContract-BxSIwVRo.d.ts +259 -0
- package/dist/eslint/index.cjs +125 -48
- package/dist/eslint/index.d.cts +7 -1
- package/dist/eslint/index.d.ts +7 -1
- package/dist/eslint/index.js +125 -48
- package/dist/index.cjs +1248 -3302
- package/dist/index.d.cts +359 -483
- package/dist/index.d.ts +359 -483
- package/dist/index.js +1231 -3248
- package/docs/agent-guide.md +28 -16
- package/docs/ai-gates.md +30 -7
- package/docs/migrate-from-ark-runtime-kernel.md +2 -3
- package/docs/package-surface.md +8 -13
- package/docs/production-hardening.md +17 -4
- package/docs/typescript-support.md +27 -0
- package/package.json +33 -11
- package/schemas/ark.analysis-result.schema.json +91 -0
- package/server.json +2 -2
- package/templates/skills/ark-architect.md +3 -2
- package/dist/configContract-iBLxx5Tz.d.cts +0 -53
- package/dist/configContract-iBLxx5Tz.d.ts +0 -53
- package/dist/eslint/index.cjs.map +0 -1
- package/dist/eslint/index.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/nestjs/index.cjs +0 -2606
- package/dist/nestjs/index.cjs.map +0 -1
- package/dist/nestjs/index.d.cts +0 -23
- package/dist/nestjs/index.d.ts +0 -23
- package/dist/nestjs/index.js +0 -2582
- package/dist/nestjs/index.js.map +0 -1
- package/dist/runtime/index.cjs +0 -4014
- package/dist/runtime/index.cjs.map +0 -1
- package/dist/runtime/index.d.cts +0 -3
- package/dist/runtime/index.d.ts +0 -3
- package/dist/runtime/index.js +0 -3925
- package/dist/runtime/index.js.map +0 -1
- package/dist/types-BxBwnBpC.d.cts +0 -1041
- package/dist/types-Wcs_l1_J.d.ts +0 -1041
package/dist/index.cjs
CHANGED
|
@@ -17,738 +17,125 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
17
17
|
};
|
|
18
18
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
19
|
|
|
20
|
-
// src/
|
|
21
|
-
var
|
|
22
|
-
__export(
|
|
20
|
+
// src/gate.ts
|
|
21
|
+
var gate_exports = {};
|
|
22
|
+
__export(gate_exports, {
|
|
23
23
|
ANALYSIS_IR_SCHEMA_VERSION: () => ANALYSIS_IR_SCHEMA_VERSION,
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
InMemoryOutboxStore: () => InMemoryOutboxStore,
|
|
29
|
-
InMemoryReadModelStore: () => InMemoryReadModelStore,
|
|
30
|
-
InMemoryWorkflowStore: () => InMemoryWorkflowStore,
|
|
31
|
-
IntentRegistry: () => IntentRegistry,
|
|
32
|
-
InvalidIntentNameError: () => InvalidIntentNameError,
|
|
33
|
-
LayerPolicyContextError: () => LayerPolicyContextError,
|
|
34
|
-
MANIFEST_SCHEMA_VERSION: () => MANIFEST_SCHEMA_VERSION,
|
|
35
|
-
ObservedLayerFlowViolationError: () => ObservedLayerFlowViolationError,
|
|
36
|
-
PolicyEngine: () => PolicyEngine,
|
|
37
|
-
PolicyViolationError: () => PolicyViolationError,
|
|
38
|
-
SourceMetadataOverrideError: () => SourceMetadataOverrideError,
|
|
39
|
-
UnknownEventSourceError: () => UnknownEventSourceError,
|
|
40
|
-
UnregisteredIntentError: () => UnregisteredIntentError,
|
|
24
|
+
ARK_ANALYSIS_RESULT_SCHEMA: () => ARK_ANALYSIS_RESULT_SCHEMA,
|
|
25
|
+
ARK_ANALYSIS_RESULT_SCHEMA_VERSION: () => ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
|
|
26
|
+
ARK_CONFIG_SCHEMA: () => ARK_CONFIG_SCHEMA,
|
|
27
|
+
ARK_CONFIG_SCHEMA_VERSION: () => ARK_CONFIG_SCHEMA_VERSION,
|
|
41
28
|
analyzeChange: () => analyzeChange,
|
|
42
29
|
analyzeProject: () => analyzeProject,
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
checkAdapterGovernance: () => checkAdapterGovernance,
|
|
46
|
-
checkContract: () => checkContract,
|
|
30
|
+
collectAnalysisConfigWarnings: () => collectAnalysisConfigWarnings,
|
|
31
|
+
collectForbiddenCapabilityUses: () => collectForbiddenCapabilityUses,
|
|
47
32
|
createAICodeGate: () => createAICodeGate,
|
|
48
|
-
|
|
33
|
+
createAdapterResult: () => createAdapterResult,
|
|
49
34
|
createArchitectureProfile: () => createArchitectureProfile,
|
|
50
35
|
createArchitectureProfileFromArkConfig: () => createArchitectureProfileFromArkConfig,
|
|
51
|
-
createArkKernel: () => createArkKernel,
|
|
52
|
-
createArkKernelFromConfig: () => createArkKernelFromConfig,
|
|
53
|
-
createArkManifest: () => createArkManifest,
|
|
54
|
-
createArkTestHarness: () => createArkTestHarness,
|
|
55
|
-
createAuditTrail: () => createAuditTrail,
|
|
56
|
-
createDependencyGraph: () => createDependencyGraph,
|
|
57
36
|
createElevenLayerArkConfig: () => createElevenLayerArkConfig,
|
|
58
|
-
|
|
59
|
-
createEventContractRegistry: () => createEventContractRegistry,
|
|
60
|
-
createIntentRegistry: () => createIntentRegistry,
|
|
61
|
-
createLenientArkKernel: () => createLenientArkKernel,
|
|
62
|
-
createLenientArkKernelFromConfig: () => createLenientArkKernelFromConfig,
|
|
63
|
-
createMetadataRegistry: () => createMetadataRegistry,
|
|
64
|
-
createObservabilityReporter: () => createObservabilityReporter,
|
|
65
|
-
createProjectionRegistry: () => createProjectionRegistry,
|
|
66
|
-
createSaga: () => createSaga,
|
|
67
|
-
createStrictArkKernel: () => createStrictArkKernel,
|
|
68
|
-
createStrictArkKernelFromConfig: () => createStrictArkKernelFromConfig,
|
|
69
|
-
createWorkflowEngine: () => createWorkflowEngine,
|
|
70
|
-
defaultIntentRegistry: () => defaultIntentRegistry,
|
|
71
|
-
defineArchitectureProfilePolicy: () => defineArchitectureProfilePolicy,
|
|
72
|
-
defineIntent: () => defineIntent,
|
|
73
|
-
defineLayerPolicy: () => defineLayerPolicy,
|
|
74
|
-
definePolicy: () => definePolicy,
|
|
75
|
-
definePort: () => definePort,
|
|
76
|
-
definePublishPolicy: () => definePublishPolicy,
|
|
37
|
+
detectArchitectureCycles: () => detectArchitectureCycles,
|
|
77
38
|
deterministicHash: () => deterministicHash,
|
|
78
39
|
elevenLayerProfile: () => elevenLayerProfile,
|
|
40
|
+
evaluateArchitectureGraph: () => evaluateArchitectureGraph,
|
|
79
41
|
explainViolation: () => explainViolation,
|
|
80
|
-
|
|
42
|
+
extractSemanticDependencies: () => extractSemanticDependencies,
|
|
43
|
+
loadArkConfigContract: () => loadArkConfigContract,
|
|
81
44
|
loadContract: () => loadContract,
|
|
45
|
+
parseArkConfigJson: () => parseArkConfigJson,
|
|
82
46
|
stableSerialize: () => stableSerialize,
|
|
83
|
-
|
|
84
|
-
validateIntentName: () => validateIntentName,
|
|
47
|
+
toAdapterDiagnostic: () => toAdapterDiagnostic,
|
|
85
48
|
version: () => version
|
|
86
49
|
});
|
|
87
|
-
module.exports = __toCommonJS(
|
|
50
|
+
module.exports = __toCommonJS(gate_exports);
|
|
88
51
|
|
|
89
52
|
// src/version.ts
|
|
90
|
-
var version = "
|
|
53
|
+
var version = "3.0.0";
|
|
91
54
|
|
|
92
|
-
// src/
|
|
93
|
-
var
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
const fn = (payload) => ({
|
|
111
|
-
intent: name,
|
|
112
|
-
payload,
|
|
113
|
-
metadata: {
|
|
114
|
-
occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
115
|
-
source: "unknown"
|
|
116
|
-
}
|
|
117
|
-
});
|
|
118
|
-
Object.defineProperty(fn, "name", {
|
|
119
|
-
value: name,
|
|
120
|
-
enumerable: true,
|
|
121
|
-
configurable: false,
|
|
122
|
-
writable: false
|
|
123
|
-
});
|
|
124
|
-
const creator = fn;
|
|
125
|
-
this.intents.set(name, creator);
|
|
126
|
-
if (options?.dependsOn) {
|
|
127
|
-
for (const dep of options.dependsOn) {
|
|
128
|
-
this.declareDependency(name, dep);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
if (options?.produces) {
|
|
132
|
-
for (const prod of options.produces) {
|
|
133
|
-
this.declareProduction(name, prod);
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
return creator;
|
|
137
|
-
}
|
|
138
|
-
/**
|
|
139
|
-
* Declare that one intent depends on / relates to another.
|
|
140
|
-
* This information is used by the DependencyGraph (future iterations) and for policy checks.
|
|
141
|
-
*
|
|
142
|
-
* @param from - The source intent (e.g. an Application operation)
|
|
143
|
-
* @param to - The target intent it depends on (e.g. a Domain event or concept)
|
|
144
|
-
*/
|
|
145
|
-
declareDependency(from, to) {
|
|
146
|
-
if (!this.dependencies.has(from)) {
|
|
147
|
-
this.dependencies.set(from, /* @__PURE__ */ new Set());
|
|
148
|
-
}
|
|
149
|
-
this.dependencies.get(from).add(to);
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Declare that one intent produces / emits another (e.g. use case → domain event).
|
|
153
|
-
*/
|
|
154
|
-
declareProduction(from, to) {
|
|
155
|
-
if (!this.productions.has(from)) {
|
|
156
|
-
this.productions.set(from, /* @__PURE__ */ new Set());
|
|
157
|
-
}
|
|
158
|
-
this.productions.get(from).add(to);
|
|
159
|
-
}
|
|
160
|
-
/**
|
|
161
|
-
* Retrieve a previously defined intent creator by name.
|
|
162
|
-
*/
|
|
163
|
-
get(name) {
|
|
164
|
-
return this.intents.get(name);
|
|
165
|
-
}
|
|
166
|
-
/**
|
|
167
|
-
* List all registered intent creators.
|
|
168
|
-
*/
|
|
169
|
-
list() {
|
|
170
|
-
return Array.from(this.intents.values());
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Get all declared dependencies for a given intent.
|
|
174
|
-
*/
|
|
175
|
-
getDependencies(intentName) {
|
|
176
|
-
const deps = this.dependencies.get(intentName);
|
|
177
|
-
return deps ? Array.from(deps) : [];
|
|
178
|
-
}
|
|
179
|
-
/**
|
|
180
|
-
* Get all intents produced / emitted by a given intent.
|
|
181
|
-
*/
|
|
182
|
-
getProductions(intentName) {
|
|
183
|
-
const prods = this.productions.get(intentName);
|
|
184
|
-
return prods ? Array.from(prods) : [];
|
|
185
|
-
}
|
|
186
|
-
/**
|
|
187
|
-
* Get all declared relationships (useful for graph generation).
|
|
188
|
-
*/
|
|
189
|
-
getAllRelationships() {
|
|
190
|
-
const result = [];
|
|
191
|
-
for (const [from, tos] of this.dependencies.entries()) {
|
|
192
|
-
for (const to of tos) {
|
|
193
|
-
result.push({ from, to, kind: "dependsOn" });
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
for (const [from, tos] of this.productions.entries()) {
|
|
197
|
-
for (const to of tos) {
|
|
198
|
-
result.push({ from, to, kind: "produces" });
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
return result;
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Check if an intent name has been registered.
|
|
205
|
-
*/
|
|
206
|
-
has(name) {
|
|
207
|
-
return this.intents.has(name);
|
|
208
|
-
}
|
|
209
|
-
/**
|
|
210
|
-
* Clear the registry. Primarily useful for tests.
|
|
211
|
-
*/
|
|
212
|
-
clear() {
|
|
213
|
-
this.intents.clear();
|
|
214
|
-
this.dependencies.clear();
|
|
215
|
-
this.productions.clear();
|
|
216
|
-
}
|
|
217
|
-
};
|
|
218
|
-
|
|
219
|
-
// src/kernel/intent/defineIntent.ts
|
|
220
|
-
var defaultRegistry = new IntentRegistry();
|
|
221
|
-
function defineIntent(name, options) {
|
|
222
|
-
return defaultRegistry.define(name, options);
|
|
223
|
-
}
|
|
224
|
-
function createIntentRegistry() {
|
|
225
|
-
return new IntentRegistry();
|
|
226
|
-
}
|
|
227
|
-
var defaultIntentRegistry = defaultRegistry;
|
|
228
|
-
|
|
229
|
-
// src/kernel/intent/validateIntentName.ts
|
|
230
|
-
var ALLOWED_PREFIXES = [
|
|
231
|
-
"Domain.",
|
|
232
|
-
"Application.",
|
|
233
|
-
"Adapter.",
|
|
234
|
-
"Workflow.",
|
|
235
|
-
"Job.",
|
|
236
|
-
"Presentation.",
|
|
237
|
-
"Reporting.",
|
|
238
|
-
"Metadata.",
|
|
239
|
-
"Security.",
|
|
240
|
-
"Audit.",
|
|
241
|
-
"Observability.",
|
|
242
|
-
"Kernel."
|
|
243
|
-
];
|
|
244
|
-
function validateIntentName(name) {
|
|
245
|
-
if (!name || typeof name !== "string") {
|
|
246
|
-
return { valid: false, reason: "Intent name must be a non-empty string" };
|
|
247
|
-
}
|
|
248
|
-
if (!ALLOWED_PREFIXES.some((p) => name.startsWith(p))) {
|
|
249
|
-
return {
|
|
250
|
-
valid: false,
|
|
251
|
-
reason: `Intent "${name}" must start with one of: ${ALLOWED_PREFIXES.join(", ")}`
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
const rest = name.slice(name.indexOf(".") + 1);
|
|
255
|
-
if (!rest || !/^[A-Za-z][A-Za-z0-9_.]*$/.test(rest)) {
|
|
256
|
-
return {
|
|
257
|
-
valid: false,
|
|
258
|
-
reason: `Intent "${name}" has an invalid segment after the layer prefix`
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
return { valid: true };
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
// src/kernel/policy/PolicyViolationError.ts
|
|
265
|
-
var PolicyViolationError = class extends Error {
|
|
266
|
-
violations;
|
|
267
|
-
constructor(violations) {
|
|
268
|
-
const messages = violations.map((v) => `- ${v.policyName}: ${v.message}`).join("\n");
|
|
269
|
-
super(`Hard policy violation(s) detected:
|
|
270
|
-
${messages}`);
|
|
271
|
-
this.name = "PolicyViolationError";
|
|
272
|
-
this.violations = violations;
|
|
273
|
-
}
|
|
274
|
-
};
|
|
275
|
-
|
|
276
|
-
// src/kernel/policy/PolicyEngine.ts
|
|
277
|
-
var PolicyEngine = class {
|
|
278
|
-
policies = [];
|
|
279
|
-
constructor(initialPolicies = []) {
|
|
280
|
-
for (const policy of initialPolicies) {
|
|
281
|
-
this.add(policy);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
/**
|
|
285
|
-
* Adds a policy to the engine.
|
|
286
|
-
*/
|
|
287
|
-
add(policy) {
|
|
288
|
-
if (this.policies.some((p) => p.name === policy.name)) {
|
|
289
|
-
throw new Error(`Policy "${policy.name}" is already registered in this engine.`);
|
|
290
|
-
}
|
|
291
|
-
this.policies.push(policy);
|
|
292
|
-
}
|
|
293
|
-
/**
|
|
294
|
-
* Returns all registered policies.
|
|
295
|
-
*/
|
|
296
|
-
getPolicies() {
|
|
297
|
-
return [...this.policies];
|
|
298
|
-
}
|
|
299
|
-
/**
|
|
300
|
-
* Evaluates all policies against the provided context.
|
|
301
|
-
*/
|
|
302
|
-
evaluate(context) {
|
|
303
|
-
const violations = [];
|
|
304
|
-
for (const policy of this.policies) {
|
|
305
|
-
const result = policy.check(context);
|
|
306
|
-
if (result === true) {
|
|
307
|
-
continue;
|
|
308
|
-
}
|
|
309
|
-
if (result === false) {
|
|
310
|
-
violations.push({
|
|
311
|
-
policyName: policy.name,
|
|
312
|
-
severity: policy.severity,
|
|
313
|
-
message: `Policy "${policy.name}" was violated.`
|
|
314
|
-
});
|
|
315
|
-
continue;
|
|
316
|
-
}
|
|
317
|
-
if (Array.isArray(result)) {
|
|
318
|
-
for (const v of result) {
|
|
319
|
-
violations.push({
|
|
320
|
-
policyName: policy.name,
|
|
321
|
-
severity: policy.severity,
|
|
322
|
-
message: v.message,
|
|
323
|
-
details: v.details
|
|
324
|
-
});
|
|
325
|
-
}
|
|
326
|
-
} else {
|
|
327
|
-
violations.push({
|
|
328
|
-
policyName: policy.name,
|
|
329
|
-
severity: policy.severity,
|
|
330
|
-
message: result.message,
|
|
331
|
-
details: result.details
|
|
332
|
-
});
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
const hardViolations = violations.filter((v) => v.severity === "hard");
|
|
336
|
-
const softViolations = violations.filter((v) => v.severity === "soft");
|
|
337
|
-
return {
|
|
338
|
-
passed: violations.length === 0,
|
|
339
|
-
violations,
|
|
340
|
-
hardViolations,
|
|
341
|
-
softViolations
|
|
342
|
-
};
|
|
343
|
-
}
|
|
344
|
-
/**
|
|
345
|
-
* Enforces all policies.
|
|
346
|
-
*
|
|
347
|
-
* - Soft violations are collected and can be observed (returned or logged).
|
|
348
|
-
* - Hard violations cause an error to be thrown (by default).
|
|
349
|
-
*
|
|
350
|
-
* @returns Evaluation result (including any soft violations)
|
|
351
|
-
* @throws Error if any hard policy is violated
|
|
352
|
-
*/
|
|
353
|
-
enforce(context) {
|
|
354
|
-
const result = this.evaluate(context);
|
|
355
|
-
if (result.hardViolations.length > 0) {
|
|
356
|
-
throw new PolicyViolationError(result.hardViolations);
|
|
357
|
-
}
|
|
358
|
-
return result;
|
|
359
|
-
}
|
|
360
|
-
/**
|
|
361
|
-
* Clears all registered policies.
|
|
362
|
-
*/
|
|
363
|
-
clear() {
|
|
364
|
-
this.policies.length = 0;
|
|
365
|
-
}
|
|
366
|
-
};
|
|
367
|
-
|
|
368
|
-
// src/kernel/policy/definePolicy.ts
|
|
369
|
-
function definePolicy(options) {
|
|
370
|
-
const severity = options.severity ?? "soft";
|
|
371
|
-
const policy = {
|
|
372
|
-
name: options.name,
|
|
373
|
-
severity,
|
|
374
|
-
tags: options.tags,
|
|
375
|
-
owner: options.owner,
|
|
376
|
-
version: options.version,
|
|
377
|
-
rationale: options.rationale,
|
|
378
|
-
enforcementMode: options.enforcementMode,
|
|
379
|
-
deprecated: options.deprecated,
|
|
380
|
-
replacedBy: options.replacedBy,
|
|
381
|
-
check: options.check
|
|
55
|
+
// src/domain/adapterContract.ts
|
|
56
|
+
var ARK_ANALYSIS_RESULT_SCHEMA_VERSION = "1.0";
|
|
57
|
+
function text(value) {
|
|
58
|
+
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
59
|
+
}
|
|
60
|
+
function positiveInteger(value, fallback) {
|
|
61
|
+
return Number.isInteger(value) && Number(value) > 0 ? Number(value) : fallback;
|
|
62
|
+
}
|
|
63
|
+
function toAdapterDiagnostic(violation2, fallbackSeverity = "error") {
|
|
64
|
+
const ruleId = text(violation2.ruleId) ?? text(violation2.code) ?? "ARK_UNKNOWN";
|
|
65
|
+
const severity = violation2.severity === "warning" ? "warning" : fallbackSeverity;
|
|
66
|
+
const evidence = {
|
|
67
|
+
...text(violation2.target) ? { target: text(violation2.target) } : {},
|
|
68
|
+
...text(violation2.fromLayer) ? { fromLayer: text(violation2.fromLayer) } : {},
|
|
69
|
+
...text(violation2.toLayer) ? { toLayer: text(violation2.toLayer) } : {},
|
|
70
|
+
...typeof violation2.typeOnly === "boolean" ? { typeOnly: violation2.typeOnly } : {}
|
|
382
71
|
};
|
|
383
|
-
return
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
// src/kernel/policy/builtins.ts
|
|
387
|
-
function defaultLayerOf(name) {
|
|
388
|
-
const dot = name.indexOf(".");
|
|
389
|
-
return dot >= 0 ? name.slice(0, dot) : name;
|
|
390
|
-
}
|
|
391
|
-
function resolveLayer(name, options) {
|
|
392
|
-
return options.resolveLayer?.(name) ?? defaultLayerOf(name);
|
|
393
|
-
}
|
|
394
|
-
function matchesRule(fromLayer, toLayer, rule) {
|
|
395
|
-
return fromLayer === rule.from && toLayer === rule.to;
|
|
396
|
-
}
|
|
397
|
-
function defineLayerPolicy(options) {
|
|
398
|
-
const name = options.name ?? "Layer isolation";
|
|
399
|
-
const severity = options.severity ?? "hard";
|
|
400
|
-
return definePolicy({
|
|
401
|
-
name,
|
|
72
|
+
return {
|
|
73
|
+
ruleId,
|
|
402
74
|
severity,
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
const fromLayer = resolveLayer(edge.from, options);
|
|
412
|
-
const toLayer = resolveLayer(edge.to, options);
|
|
413
|
-
for (const rule of options.rules) {
|
|
414
|
-
if (!rule.allowed && matchesRule(fromLayer, toLayer, rule)) {
|
|
415
|
-
violations.push({
|
|
416
|
-
policyName: name,
|
|
417
|
-
severity,
|
|
418
|
-
message: rule.message ?? `Layer violation: ${edge.from} (${fromLayer}) must not relate to ${edge.to} (${toLayer})`
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
}
|
|
423
|
-
return violations.length > 0 ? violations : true;
|
|
424
|
-
}
|
|
425
|
-
});
|
|
426
|
-
}
|
|
427
|
-
function isLayerPolicy(policy) {
|
|
428
|
-
return policy.tags?.includes("layer") ?? false;
|
|
429
|
-
}
|
|
430
|
-
var architecturalPolicies = {
|
|
431
|
-
/**
|
|
432
|
-
* @deprecated Use cleanArchitectureMatrix() for full layer rules.
|
|
433
|
-
* Blocks Domain → Adapter declared dependencies only.
|
|
434
|
-
*/
|
|
435
|
-
layerIsolation() {
|
|
436
|
-
return architecturalPolicies.cleanArchitectureMatrix();
|
|
437
|
-
},
|
|
438
|
-
/**
|
|
439
|
-
* Clean-architecture dependency matrix (declared dependsOn / declared edges only).
|
|
440
|
-
* Does not block observed event flows (Domain events consumed by Application).
|
|
441
|
-
*/
|
|
442
|
-
cleanArchitectureMatrix() {
|
|
443
|
-
return defineLayerPolicy({
|
|
444
|
-
name: "Clean architecture matrix",
|
|
445
|
-
severity: "hard",
|
|
446
|
-
rules: [
|
|
447
|
-
{ from: "Domain", to: "Adapter", allowed: false },
|
|
448
|
-
{ from: "Domain", to: "Application", allowed: false },
|
|
449
|
-
{ from: "Adapter", to: "Application", allowed: false },
|
|
450
|
-
{ from: "Adapter", to: "Domain", allowed: false }
|
|
451
|
-
]
|
|
452
|
-
});
|
|
453
|
-
}
|
|
454
|
-
};
|
|
455
|
-
function defineArchitectureProfilePolicy(profile, options = {}) {
|
|
456
|
-
return defineLayerPolicy({
|
|
457
|
-
name: options.name ?? `${profile.name} layer policy`,
|
|
458
|
-
severity: options.severity ?? "hard",
|
|
459
|
-
rules: profile.rules,
|
|
460
|
-
resolveLayer: profile.resolveLayer
|
|
461
|
-
});
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
// src/kernel/event-bus/policyContext.ts
|
|
465
|
-
function buildPublishPolicyContext(options) {
|
|
466
|
-
return (event) => ({
|
|
467
|
-
event,
|
|
468
|
-
relationships: options.intentRegistry?.getAllRelationships(),
|
|
469
|
-
edges: options.dependencyGraph?.getEdges()
|
|
470
|
-
});
|
|
471
|
-
}
|
|
472
|
-
function definePublishPolicy(options) {
|
|
473
|
-
return definePolicy(options);
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// src/kernel/event-bus/errors.ts
|
|
477
|
-
var UnregisteredIntentError = class extends Error {
|
|
478
|
-
intentName;
|
|
479
|
-
constructor(intentName) {
|
|
480
|
-
super(
|
|
481
|
-
`Intent "${intentName}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`
|
|
482
|
-
);
|
|
483
|
-
this.name = "UnregisteredIntentError";
|
|
484
|
-
this.intentName = intentName;
|
|
485
|
-
}
|
|
486
|
-
};
|
|
487
|
-
var InvalidIntentNameError = class extends Error {
|
|
488
|
-
intentName;
|
|
489
|
-
reason;
|
|
490
|
-
constructor(intentName, reason) {
|
|
491
|
-
super(`Invalid intent name "${intentName}": ${reason}`);
|
|
492
|
-
this.name = "InvalidIntentNameError";
|
|
493
|
-
this.intentName = intentName;
|
|
494
|
-
this.reason = reason;
|
|
495
|
-
}
|
|
496
|
-
};
|
|
497
|
-
var LayerPolicyContextError = class extends Error {
|
|
498
|
-
constructor() {
|
|
499
|
-
super(
|
|
500
|
-
"Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."
|
|
501
|
-
);
|
|
502
|
-
this.name = "LayerPolicyContextError";
|
|
503
|
-
}
|
|
504
|
-
};
|
|
505
|
-
var EventContractViolationError = class extends Error {
|
|
506
|
-
intentName;
|
|
507
|
-
issues;
|
|
508
|
-
constructor(intentName, issues) {
|
|
509
|
-
super(
|
|
510
|
-
`Event contract violation for "${intentName}". Register a matching event contract/version or fix the payload before publishing.`
|
|
511
|
-
);
|
|
512
|
-
this.name = "EventContractViolationError";
|
|
513
|
-
this.intentName = intentName;
|
|
514
|
-
this.issues = issues;
|
|
515
|
-
}
|
|
516
|
-
};
|
|
517
|
-
var UnknownEventSourceError = class extends Error {
|
|
518
|
-
intentName;
|
|
519
|
-
source;
|
|
520
|
-
constructor(intentName, source) {
|
|
521
|
-
super(
|
|
522
|
-
source ? `Event "${intentName}" metadata.source "${source}" is not registered. Register the producer intent or publish from a known source.` : `Event "${intentName}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`
|
|
523
|
-
);
|
|
524
|
-
this.name = "UnknownEventSourceError";
|
|
525
|
-
this.intentName = intentName;
|
|
526
|
-
this.source = source;
|
|
527
|
-
}
|
|
528
|
-
};
|
|
529
|
-
var SourceMetadataOverrideError = class extends Error {
|
|
530
|
-
boundSource;
|
|
531
|
-
attemptedSource;
|
|
532
|
-
constructor(boundSource, attemptedSource) {
|
|
533
|
-
super(
|
|
534
|
-
`Source-bound publisher for "${boundSource}" cannot publish with metadata.source "${attemptedSource}". Create a publisher for the intended source instead.`
|
|
535
|
-
);
|
|
536
|
-
this.name = "SourceMetadataOverrideError";
|
|
537
|
-
this.boundSource = boundSource;
|
|
538
|
-
this.attemptedSource = attemptedSource;
|
|
539
|
-
}
|
|
540
|
-
};
|
|
541
|
-
var ObservedLayerFlowViolationError = class extends Error {
|
|
542
|
-
source;
|
|
543
|
-
intentName;
|
|
544
|
-
fromLayer;
|
|
545
|
-
toLayer;
|
|
546
|
-
constructor(source, intentName, fromLayer, toLayer, message) {
|
|
547
|
-
super(
|
|
548
|
-
message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${intentName}" (${toLayer}). Route this through an allowed layer or adjust the architecture profile rule.`
|
|
549
|
-
);
|
|
550
|
-
this.name = "ObservedLayerFlowViolationError";
|
|
551
|
-
this.source = source;
|
|
552
|
-
this.intentName = intentName;
|
|
553
|
-
this.fromLayer = fromLayer;
|
|
554
|
-
this.toLayer = toLayer;
|
|
555
|
-
}
|
|
556
|
-
};
|
|
557
|
-
|
|
558
|
-
// src/kernel/event-bus/publishGuards.ts
|
|
559
|
-
function assertIntentAllowed(intentName, options) {
|
|
560
|
-
if (!options.strictRegistry && !options.validateIntentNaming) {
|
|
561
|
-
return;
|
|
562
|
-
}
|
|
563
|
-
if (options.validateIntentNaming) {
|
|
564
|
-
const validation = validateIntentName(intentName);
|
|
565
|
-
if (!validation.valid) {
|
|
566
|
-
throw new InvalidIntentNameError(intentName, validation.reason);
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
if (options.strictRegistry && options.intentRegistry && !options.intentRegistry.has(intentName)) {
|
|
570
|
-
throw new UnregisteredIntentError(intentName);
|
|
571
|
-
}
|
|
572
|
-
}
|
|
573
|
-
function assertSourceAllowed(event, options) {
|
|
574
|
-
if (!options.requireKnownSource) return;
|
|
575
|
-
if (!event.metadata.source || event.metadata.source === "unknown") {
|
|
576
|
-
throw new UnknownEventSourceError(event.intent);
|
|
577
|
-
}
|
|
578
|
-
if (options.intentRegistry && !options.intentRegistry.has(event.metadata.source)) {
|
|
579
|
-
throw new UnknownEventSourceError(event.intent, event.metadata.source);
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
function assertContractAllowed(event, options) {
|
|
583
|
-
if (!options.eventContracts) return;
|
|
584
|
-
const result = options.eventContracts.validate(event);
|
|
585
|
-
if (!result.ok && (options.strictEventContracts || result.contract)) {
|
|
586
|
-
throw new EventContractViolationError(event.intent, result.issues);
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
|
|
590
|
-
// src/kernel/event-bus/payloadPatch.ts
|
|
591
|
-
function isPlainRecord(value) {
|
|
592
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
593
|
-
return false;
|
|
594
|
-
}
|
|
595
|
-
const proto = Object.getPrototypeOf(value);
|
|
596
|
-
return proto === Object.prototype || proto === null;
|
|
597
|
-
}
|
|
598
|
-
function clonePatchValue(value) {
|
|
599
|
-
if (Array.isArray(value)) return value.map(clonePatchValue);
|
|
600
|
-
if (isPlainRecord(value)) {
|
|
601
|
-
return Object.fromEntries(
|
|
602
|
-
Object.entries(value).map(([key, child]) => [key, clonePatchValue(child)])
|
|
603
|
-
);
|
|
604
|
-
}
|
|
605
|
-
return value;
|
|
606
|
-
}
|
|
607
|
-
function mergeRecordPatch(target, patch, path = "payload") {
|
|
608
|
-
const next = { ...target };
|
|
609
|
-
for (const [key, value] of Object.entries(patch)) {
|
|
610
|
-
const childPath = `${path}.${key}`;
|
|
611
|
-
if (!(key in next) || next[key] === void 0) {
|
|
612
|
-
next[key] = clonePatchValue(value);
|
|
613
|
-
continue;
|
|
614
|
-
}
|
|
615
|
-
if (isPlainRecord(next[key]) && isPlainRecord(value)) {
|
|
616
|
-
next[key] = mergeRecordPatch(next[key], value, childPath);
|
|
617
|
-
continue;
|
|
618
|
-
}
|
|
619
|
-
if (Array.isArray(next[key]) && Array.isArray(value)) {
|
|
620
|
-
next[key] = mergeArrayPatch(next[key], value, childPath);
|
|
621
|
-
continue;
|
|
622
|
-
}
|
|
623
|
-
throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
|
|
624
|
-
}
|
|
625
|
-
return next;
|
|
626
|
-
}
|
|
627
|
-
function mergeArrayPatch(target, patch, path = "payload") {
|
|
628
|
-
const next = [...target];
|
|
629
|
-
patch.forEach((value, index) => {
|
|
630
|
-
const childPath = `${path}[${index}]`;
|
|
631
|
-
if (index >= next.length || next[index] === void 0) {
|
|
632
|
-
next[index] = clonePatchValue(value);
|
|
633
|
-
return;
|
|
634
|
-
}
|
|
635
|
-
if (isPlainRecord(next[index]) && isPlainRecord(value)) {
|
|
636
|
-
next[index] = mergeRecordPatch(next[index], value, childPath);
|
|
637
|
-
return;
|
|
638
|
-
}
|
|
639
|
-
if (Array.isArray(next[index]) && Array.isArray(value)) {
|
|
640
|
-
next[index] = mergeArrayPatch(next[index], value, childPath);
|
|
641
|
-
return;
|
|
642
|
-
}
|
|
643
|
-
throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
|
|
644
|
-
});
|
|
645
|
-
return next;
|
|
75
|
+
message: text(violation2.message) ?? ruleId,
|
|
76
|
+
location: {
|
|
77
|
+
file: text(violation2.file) ?? "<unknown>",
|
|
78
|
+
line: positiveInteger(violation2.line, 1),
|
|
79
|
+
column: positiveInteger(violation2.column, 1)
|
|
80
|
+
},
|
|
81
|
+
evidence
|
|
82
|
+
};
|
|
646
83
|
}
|
|
647
|
-
function
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
if (!isPlainRecord(payload)) {
|
|
657
|
-
throw new Error("Object interceptor patch requires an object payload.");
|
|
658
|
-
}
|
|
659
|
-
return mergeRecordPatch(payload, patch);
|
|
84
|
+
function createAdapterResult(input) {
|
|
85
|
+
return {
|
|
86
|
+
schemaVersion: ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
|
|
87
|
+
valid: input.valid,
|
|
88
|
+
diagnostics: [
|
|
89
|
+
...(input.violations ?? []).map((item) => toAdapterDiagnostic(item, "error")),
|
|
90
|
+
...(input.warnings ?? []).map((item) => toAdapterDiagnostic(item, "warning"))
|
|
91
|
+
]
|
|
92
|
+
};
|
|
660
93
|
}
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
94
|
+
var ARK_ANALYSIS_RESULT_SCHEMA = {
|
|
95
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
96
|
+
$id: "https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",
|
|
97
|
+
title: "ArkGate analysis result",
|
|
98
|
+
type: "object",
|
|
99
|
+
additionalProperties: false,
|
|
100
|
+
required: ["schemaVersion", "valid", "diagnostics"],
|
|
101
|
+
properties: {
|
|
102
|
+
schemaVersion: { const: ARK_ANALYSIS_RESULT_SCHEMA_VERSION },
|
|
103
|
+
valid: { type: "boolean" },
|
|
104
|
+
diagnostics: {
|
|
105
|
+
type: "array",
|
|
106
|
+
items: {
|
|
107
|
+
type: "object",
|
|
108
|
+
additionalProperties: false,
|
|
109
|
+
required: ["ruleId", "severity", "message", "location", "evidence"],
|
|
110
|
+
properties: {
|
|
111
|
+
ruleId: { type: "string", minLength: 1 },
|
|
112
|
+
severity: { enum: ["error", "warning"] },
|
|
113
|
+
message: { type: "string", minLength: 1 },
|
|
114
|
+
location: {
|
|
115
|
+
type: "object",
|
|
116
|
+
additionalProperties: false,
|
|
117
|
+
required: ["file", "line", "column"],
|
|
118
|
+
properties: {
|
|
119
|
+
file: { type: "string", minLength: 1 },
|
|
120
|
+
line: { type: "integer", minimum: 1 },
|
|
121
|
+
column: { type: "integer", minimum: 1 }
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
evidence: {
|
|
125
|
+
type: "object",
|
|
126
|
+
additionalProperties: false,
|
|
127
|
+
properties: {
|
|
128
|
+
target: { type: "string" },
|
|
129
|
+
fromLayer: { type: "string" },
|
|
130
|
+
toLayer: { type: "string" },
|
|
131
|
+
typeOnly: { type: "boolean" }
|
|
132
|
+
}
|
|
677
133
|
}
|
|
678
|
-
})
|
|
679
|
-
);
|
|
680
|
-
if (patches.length === 0) {
|
|
681
|
-
continue;
|
|
682
|
-
}
|
|
683
|
-
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
684
|
-
let candidate = {
|
|
685
|
-
...current,
|
|
686
|
-
metadata: {
|
|
687
|
-
...current.metadata,
|
|
688
|
-
interceptions: [
|
|
689
|
-
...current.metadata.interceptions ?? [],
|
|
690
|
-
{ interceptorId: registration.interceptorId, timestamp }
|
|
691
|
-
]
|
|
692
134
|
}
|
|
693
|
-
};
|
|
694
|
-
for (const patch of patches) {
|
|
695
|
-
candidate = {
|
|
696
|
-
...candidate,
|
|
697
|
-
payload: applyPayloadPatch(candidate.payload, patch),
|
|
698
|
-
metadata: { ...candidate.metadata }
|
|
699
|
-
};
|
|
700
135
|
}
|
|
701
|
-
assertContractAllowed(candidate, {
|
|
702
|
-
eventContracts: deps.eventContracts,
|
|
703
|
-
strictEventContracts: deps.strictEventContracts
|
|
704
|
-
});
|
|
705
|
-
current = candidate;
|
|
706
|
-
registration.lastInterceptedAt = timestamp;
|
|
707
|
-
deps.appendTrace({
|
|
708
|
-
type: "event.intercepted",
|
|
709
|
-
timestamp,
|
|
710
|
-
intent: current.intent,
|
|
711
|
-
correlationId: current.metadata.correlationId,
|
|
712
|
-
traceId: current.metadata.traceId,
|
|
713
|
-
spanId: current.metadata.spanId,
|
|
714
|
-
details: {
|
|
715
|
-
registrationId: registration.registrationId,
|
|
716
|
-
interceptorId: registration.interceptorId,
|
|
717
|
-
patchesApplied: patches.length
|
|
718
|
-
}
|
|
719
|
-
});
|
|
720
|
-
await deps.recordAudit("event.intercepted", current, {
|
|
721
|
-
registrationId: registration.registrationId,
|
|
722
|
-
interceptorId: registration.interceptorId,
|
|
723
|
-
patchesApplied: patches.length
|
|
724
|
-
});
|
|
725
|
-
} catch (err) {
|
|
726
|
-
await recordInterceptorError(registration, current, err, deps);
|
|
727
136
|
}
|
|
728
137
|
}
|
|
729
|
-
|
|
730
|
-
}
|
|
731
|
-
async function recordInterceptorError(interceptor, event, error, deps) {
|
|
732
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
733
|
-
deps.appendTrace({
|
|
734
|
-
type: "interceptor.error",
|
|
735
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
736
|
-
intent: event.intent,
|
|
737
|
-
correlationId: event.metadata.correlationId,
|
|
738
|
-
traceId: event.metadata.traceId,
|
|
739
|
-
spanId: event.metadata.spanId,
|
|
740
|
-
details: {
|
|
741
|
-
registrationId: interceptor.registrationId,
|
|
742
|
-
interceptorId: interceptor.interceptorId,
|
|
743
|
-
error: message
|
|
744
|
-
}
|
|
745
|
-
});
|
|
746
|
-
await deps.recordAudit("interceptor.error", event, {
|
|
747
|
-
registrationId: interceptor.registrationId,
|
|
748
|
-
interceptorId: interceptor.interceptorId,
|
|
749
|
-
error: message
|
|
750
|
-
});
|
|
751
|
-
}
|
|
138
|
+
};
|
|
752
139
|
|
|
753
140
|
// src/domain/layerMatch.ts
|
|
754
141
|
var regexpCache = /* @__PURE__ */ new Map();
|
|
@@ -915,1897 +302,353 @@ function findDeniedEdgeRule(rules, from, to, options) {
|
|
|
915
302
|
return void 0;
|
|
916
303
|
}
|
|
917
304
|
|
|
918
|
-
// src/
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
const toLayer = profile.resolveLayer(event.intent);
|
|
928
|
-
if (!fromLayer || !toLayer) return;
|
|
929
|
-
const blocked = findDeniedEdgeRule(profile.rules, fromLayer, toLayer);
|
|
930
|
-
if (!blocked) return;
|
|
931
|
-
const severity = deps.mode;
|
|
932
|
-
const message = blocked.message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${event.intent}" (${toLayer}).`;
|
|
933
|
-
const details = {
|
|
934
|
-
source,
|
|
935
|
-
intent: event.intent,
|
|
936
|
-
fromLayer,
|
|
937
|
-
toLayer,
|
|
938
|
-
severity,
|
|
939
|
-
message,
|
|
940
|
-
rule: blocked
|
|
941
|
-
};
|
|
942
|
-
deps.appendTrace({
|
|
943
|
-
type: "layer.observedViolation",
|
|
944
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
945
|
-
intent: event.intent,
|
|
946
|
-
correlationId: event.metadata.correlationId,
|
|
947
|
-
traceId: event.metadata.traceId,
|
|
948
|
-
spanId: event.metadata.spanId,
|
|
949
|
-
details
|
|
950
|
-
});
|
|
951
|
-
await deps.recordAudit("layer.observedViolation", event, details);
|
|
952
|
-
if (severity === "hard") {
|
|
953
|
-
throw new ObservedLayerFlowViolationError(
|
|
954
|
-
source,
|
|
955
|
-
event.intent,
|
|
956
|
-
fromLayer,
|
|
957
|
-
toLayer,
|
|
958
|
-
message
|
|
959
|
-
);
|
|
960
|
-
}
|
|
305
|
+
// src/domain/sourcePolicy.ts
|
|
306
|
+
var SOURCE_POLICY_MESSAGES = {
|
|
307
|
+
RAW_EVENT_PUBLISH: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",
|
|
308
|
+
PUBLISH_MISSING_SOURCE: "Strict Ark publish calls must include metadata.source."
|
|
309
|
+
};
|
|
310
|
+
function looksLikeArkIntent(value) {
|
|
311
|
+
return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(
|
|
312
|
+
value
|
|
313
|
+
);
|
|
961
314
|
}
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
} catch (err) {
|
|
970
|
-
if (err instanceof PolicyViolationError) {
|
|
971
|
-
deps.appendTrace({
|
|
972
|
-
type: "policy.hardViolation",
|
|
973
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
974
|
-
intent: event.intent,
|
|
975
|
-
correlationId: event.metadata.correlationId,
|
|
976
|
-
traceId: event.metadata.traceId,
|
|
977
|
-
spanId: event.metadata.spanId,
|
|
978
|
-
details: { violations: err.violations }
|
|
979
|
-
});
|
|
980
|
-
await deps.recordAudit("policy.hardViolation", event, {
|
|
981
|
-
violations: err.violations
|
|
982
|
-
});
|
|
983
|
-
}
|
|
984
|
-
throw err;
|
|
985
|
-
}
|
|
986
|
-
if (policyResult.softViolations.length > 0) {
|
|
987
|
-
deps.appendTrace({
|
|
988
|
-
type: "policy.softViolation",
|
|
989
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
990
|
-
intent: event.intent,
|
|
991
|
-
correlationId: event.metadata.correlationId,
|
|
992
|
-
traceId: event.metadata.traceId,
|
|
993
|
-
spanId: event.metadata.spanId,
|
|
994
|
-
details: { violations: policyResult.softViolations }
|
|
315
|
+
function classifyPublishFacts(facts) {
|
|
316
|
+
if (!facts.publishCall) return [];
|
|
317
|
+
const findings = [];
|
|
318
|
+
if (facts.rawIntentName !== void 0 && looksLikeArkIntent(facts.rawIntentName) || facts.objectHasIntent) {
|
|
319
|
+
findings.push({
|
|
320
|
+
ruleId: "RAW_EVENT_PUBLISH",
|
|
321
|
+
message: SOURCE_POLICY_MESSAGES.RAW_EVENT_PUBLISH
|
|
995
322
|
});
|
|
996
|
-
|
|
997
|
-
|
|
323
|
+
}
|
|
324
|
+
if (facts.arkPublishCandidate && !facts.hasSource) {
|
|
325
|
+
findings.push({
|
|
326
|
+
ruleId: "PUBLISH_MISSING_SOURCE",
|
|
327
|
+
message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
|
|
998
328
|
});
|
|
999
|
-
if (deps.onSoftViolation) {
|
|
1000
|
-
await deps.safeHook(
|
|
1001
|
-
() => deps.onSoftViolation(policyResult, event),
|
|
1002
|
-
"onSoftViolation",
|
|
1003
|
-
event
|
|
1004
|
-
);
|
|
1005
|
-
}
|
|
1006
329
|
}
|
|
330
|
+
return findings;
|
|
1007
331
|
}
|
|
1008
332
|
|
|
1009
|
-
// src/kernel/
|
|
1010
|
-
function
|
|
1011
|
-
|
|
1012
|
-
if (buffers.maxHistorySize !== void 0 && buffers.history.length > buffers.maxHistorySize) {
|
|
1013
|
-
buffers.history.splice(0, buffers.history.length - buffers.maxHistorySize);
|
|
1014
|
-
}
|
|
333
|
+
// src/kernel/semanticAnalysis.ts
|
|
334
|
+
function literalText(ts, node) {
|
|
335
|
+
return node && ts.isStringLiteralLike(node) ? node.text : void 0;
|
|
1015
336
|
}
|
|
1016
|
-
function
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
337
|
+
function lineOf(sourceFile, node) {
|
|
338
|
+
return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
339
|
+
}
|
|
340
|
+
function isTypeOnlyReference(ts, node) {
|
|
341
|
+
if (ts.isImportDeclaration(node)) {
|
|
342
|
+
const clause = node.importClause;
|
|
343
|
+
if (!clause) return false;
|
|
344
|
+
if (clause.isTypeOnly) return true;
|
|
345
|
+
const named = clause.namedBindings;
|
|
346
|
+
return Boolean(
|
|
347
|
+
named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((element) => element.isTypeOnly)
|
|
348
|
+
);
|
|
1020
349
|
}
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
350
|
+
if (ts.isExportDeclaration(node)) {
|
|
351
|
+
if (node.isTypeOnly) return true;
|
|
352
|
+
const clause = node.exportClause;
|
|
353
|
+
return Boolean(
|
|
354
|
+
clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly)
|
|
355
|
+
);
|
|
1026
356
|
}
|
|
357
|
+
return false;
|
|
1027
358
|
}
|
|
1028
|
-
|
|
1029
|
-
|
|
359
|
+
function singleFileChecker(ts, sourceFile) {
|
|
360
|
+
const options = { noLib: true, noResolve: true, target: ts.ScriptTarget.Latest };
|
|
361
|
+
const host = ts.createCompilerHost(options, true);
|
|
362
|
+
host.getSourceFile = (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0;
|
|
363
|
+
host.fileExists = (fileName) => fileName === sourceFile.fileName;
|
|
364
|
+
host.readFile = (fileName) => fileName === sourceFile.fileName ? sourceFile.text : void 0;
|
|
365
|
+
return ts.createProgram([sourceFile.fileName], options, host).getTypeChecker();
|
|
366
|
+
}
|
|
367
|
+
function symbolAt(checker, node) {
|
|
1030
368
|
try {
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
intent: event.intent,
|
|
1035
|
-
correlationId: event.metadata.correlationId,
|
|
1036
|
-
causationId: event.metadata.causationId,
|
|
1037
|
-
subject: event.intent,
|
|
1038
|
-
details
|
|
1039
|
-
});
|
|
1040
|
-
} catch (err) {
|
|
1041
|
-
appendTrace(buffers, {
|
|
1042
|
-
type: "hook.error",
|
|
1043
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1044
|
-
intent: event.intent,
|
|
1045
|
-
correlationId: event.metadata.correlationId,
|
|
1046
|
-
traceId: event.metadata.traceId,
|
|
1047
|
-
spanId: event.metadata.spanId,
|
|
1048
|
-
details: {
|
|
1049
|
-
hook: "auditTrail",
|
|
1050
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1051
|
-
}
|
|
1052
|
-
});
|
|
369
|
+
return checker.getSymbolAtLocation(node);
|
|
370
|
+
} catch {
|
|
371
|
+
return void 0;
|
|
1053
372
|
}
|
|
1054
373
|
}
|
|
1055
|
-
|
|
1056
|
-
const
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
}
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
details
|
|
1069
|
-
});
|
|
1070
|
-
await recordAudit(buffers, "event.rawPublish", event, details);
|
|
374
|
+
function localDeclaration(ts, checker, sourceFile, node) {
|
|
375
|
+
const shorthand = node.parent && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
|
|
376
|
+
let symbol;
|
|
377
|
+
try {
|
|
378
|
+
symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(node.parent) : symbolAt(checker, node);
|
|
379
|
+
} catch {
|
|
380
|
+
symbol = void 0;
|
|
381
|
+
}
|
|
382
|
+
return Boolean(
|
|
383
|
+
symbol?.declarations?.some(
|
|
384
|
+
(declaration) => declaration.getSourceFile().fileName === sourceFile.fileName
|
|
385
|
+
)
|
|
386
|
+
);
|
|
1071
387
|
}
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
timestamp: record.publishedAt,
|
|
1083
|
-
intent: event.intent,
|
|
1084
|
-
correlationId: event.metadata.correlationId,
|
|
1085
|
-
traceId: event.metadata.traceId,
|
|
1086
|
-
spanId: event.metadata.spanId,
|
|
1087
|
-
details: { subscribersNotified }
|
|
388
|
+
function extractSemanticDependencies(ts, sourceFile) {
|
|
389
|
+
let checker;
|
|
390
|
+
const dependencies = [];
|
|
391
|
+
const add = (node, kind, specifier, typeOnly = false) => dependencies.push({
|
|
392
|
+
specifier,
|
|
393
|
+
kind,
|
|
394
|
+
line: lineOf(sourceFile, node),
|
|
395
|
+
typeOnly,
|
|
396
|
+
unresolved: specifier === void 0,
|
|
397
|
+
node
|
|
1088
398
|
});
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
399
|
+
const visit = (node) => {
|
|
400
|
+
if (ts.isImportDeclaration(node)) {
|
|
401
|
+
add(node, "import", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
|
|
402
|
+
} else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
|
|
403
|
+
add(node, "export", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
|
|
404
|
+
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
|
405
|
+
add(node, "require", literalText(ts, node.moduleReference.expression));
|
|
406
|
+
} else if (ts.isCallExpression(node)) {
|
|
407
|
+
const dynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
|
|
408
|
+
const requireCall = ts.isIdentifier(node.expression) && node.expression.text === "require";
|
|
409
|
+
const directRequire = requireCall && !localDeclaration(
|
|
410
|
+
ts,
|
|
411
|
+
checker ?? (checker = singleFileChecker(ts, sourceFile)),
|
|
412
|
+
sourceFile,
|
|
413
|
+
node.expression
|
|
414
|
+
);
|
|
415
|
+
if (dynamicImport || directRequire) {
|
|
416
|
+
add(node, directRequire ? "require" : "dynamic-import", literalText(ts, node.arguments[0]));
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
ts.forEachChild(node, visit);
|
|
1110
420
|
};
|
|
421
|
+
visit(sourceFile);
|
|
422
|
+
return dependencies;
|
|
1111
423
|
}
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
subscriptionsByIntent = /* @__PURE__ */ new Map();
|
|
1122
|
-
interceptors = [];
|
|
1123
|
-
interceptorsByIntent = /* @__PURE__ */ new Map();
|
|
1124
|
-
recording;
|
|
1125
|
-
onPublish;
|
|
1126
|
-
onSoftViolation;
|
|
1127
|
-
onHandlerError;
|
|
1128
|
-
eventContracts;
|
|
1129
|
-
strictEventContracts;
|
|
1130
|
-
requireKnownSource;
|
|
1131
|
-
architectureProfile;
|
|
1132
|
-
enforceObservedLayerFlowMode;
|
|
1133
|
-
rethrowHandlerErrors;
|
|
1134
|
-
policyEngine;
|
|
1135
|
-
getPolicyContext;
|
|
1136
|
-
intentRegistry;
|
|
1137
|
-
dependencyGraph;
|
|
1138
|
-
strictRegistry;
|
|
1139
|
-
validateIntentNaming;
|
|
1140
|
-
constructor(options = {}) {
|
|
1141
|
-
this.onPublish = options.onPublish;
|
|
1142
|
-
this.onSoftViolation = options.onSoftViolation;
|
|
1143
|
-
this.onHandlerError = options.onHandlerError;
|
|
1144
|
-
this.eventContracts = options.eventContracts;
|
|
1145
|
-
this.strictEventContracts = options.strictEventContracts ?? false;
|
|
1146
|
-
this.requireKnownSource = options.requireKnownSource ?? false;
|
|
1147
|
-
this.architectureProfile = options.architectureProfile;
|
|
1148
|
-
this.enforceObservedLayerFlowMode = options.enforceObservedLayerFlow ?? "off";
|
|
1149
|
-
this.rethrowHandlerErrors = options.rethrowHandlerErrors ?? false;
|
|
1150
|
-
this.intentRegistry = options.intentRegistry;
|
|
1151
|
-
this.dependencyGraph = options.dependencyGraph;
|
|
1152
|
-
this.strictRegistry = options.strictRegistry ?? options.intentRegistry !== void 0;
|
|
1153
|
-
this.validateIntentNaming = options.validateIntentNaming ?? this.strictRegistry;
|
|
1154
|
-
this.recording = {
|
|
1155
|
-
history: [],
|
|
1156
|
-
trace: [],
|
|
1157
|
-
maxHistorySize: options.maxHistorySize,
|
|
1158
|
-
traceSinks: [...options.traceSinks ?? []],
|
|
1159
|
-
auditTrail: options.auditTrail,
|
|
1160
|
-
outbox: options.outbox,
|
|
1161
|
-
instanceId: options.instanceId
|
|
1162
|
-
};
|
|
1163
|
-
if (options.policyEngine) {
|
|
1164
|
-
this.policyEngine = options.policyEngine;
|
|
1165
|
-
} else if (options.policies && options.policies.length > 0) {
|
|
1166
|
-
this.policyEngine = new PolicyEngine(options.policies);
|
|
1167
|
-
}
|
|
1168
|
-
const allPolicies = this.policyEngine?.getPolicies() ?? options.policies ?? [];
|
|
1169
|
-
if (allPolicies.some(isLayerPolicy) && !options.intentRegistry && !options.dependencyGraph && !options.getPolicyContext) {
|
|
1170
|
-
throw new LayerPolicyContextError();
|
|
1171
|
-
}
|
|
1172
|
-
if (options.getPolicyContext) {
|
|
1173
|
-
this.getPolicyContext = options.getPolicyContext;
|
|
1174
|
-
} else if (options.intentRegistry || options.dependencyGraph) {
|
|
1175
|
-
this.getPolicyContext = buildPublishPolicyContext({
|
|
1176
|
-
intentRegistry: options.intentRegistry,
|
|
1177
|
-
dependencyGraph: options.dependencyGraph
|
|
1178
|
-
});
|
|
1179
|
-
} else {
|
|
1180
|
-
this.getPolicyContext = (event) => ({ event });
|
|
424
|
+
function staticAccessPath(ts, node) {
|
|
425
|
+
const segments = [];
|
|
426
|
+
let current = node;
|
|
427
|
+
while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
|
|
428
|
+
if (ts.isPropertyAccessExpression(current)) segments.unshift(current.name.text);
|
|
429
|
+
else {
|
|
430
|
+
const property = literalText(ts, current.argumentExpression);
|
|
431
|
+
if (property === void 0) return void 0;
|
|
432
|
+
segments.unshift(property);
|
|
1181
433
|
}
|
|
434
|
+
current = current.expression;
|
|
1182
435
|
}
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
436
|
+
if (!ts.isIdentifier(current)) return void 0;
|
|
437
|
+
segments.unshift(current.text);
|
|
438
|
+
return { root: current, segments };
|
|
439
|
+
}
|
|
440
|
+
function runtimeIdentifierReference(ts, node) {
|
|
441
|
+
const parent = node.parent;
|
|
442
|
+
if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) return false;
|
|
443
|
+
return ts.isExpressionNode(node) && !ts.isInTypeQuery(node) || ts.isShorthandPropertyAssignment(parent) && parent.name === node;
|
|
444
|
+
}
|
|
445
|
+
function bestForbiddenMatch(entries, segments) {
|
|
446
|
+
const normalized = segments[0] === "globalThis" ? segments.slice(1) : segments;
|
|
447
|
+
for (let length = normalized.length; length >= 1; length -= 1) {
|
|
448
|
+
const candidate = normalized.slice(0, length).join(".");
|
|
449
|
+
if (entries.has(candidate)) return candidate;
|
|
450
|
+
}
|
|
451
|
+
return void 0;
|
|
452
|
+
}
|
|
453
|
+
function collectForbiddenCapabilityUses(ts, sourceFile, forbidden) {
|
|
454
|
+
if (forbidden.length === 0) return [];
|
|
455
|
+
const entries = new Set(forbidden);
|
|
456
|
+
const checker = singleFileChecker(ts, sourceFile);
|
|
457
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
458
|
+
const topLevelNames = /* @__PURE__ */ new Set();
|
|
459
|
+
for (const statement of sourceFile.statements) {
|
|
460
|
+
if (ts.isVariableStatement(statement)) {
|
|
461
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
462
|
+
if (ts.isIdentifier(declaration.name)) topLevelNames.add(declaration.name.text);
|
|
463
|
+
}
|
|
1210
464
|
}
|
|
1211
|
-
|
|
1212
|
-
|
|
465
|
+
}
|
|
466
|
+
const resolvePath = (node) => {
|
|
467
|
+
const path = staticAccessPath(ts, node);
|
|
468
|
+
if (!path) return void 0;
|
|
469
|
+
const symbol = symbolAt(checker, path.root);
|
|
470
|
+
const alias = symbol ? aliases.get(symbol) : void 0;
|
|
471
|
+
if (alias) return [...alias, ...path.segments.slice(1)];
|
|
472
|
+
return localDeclaration(ts, checker, sourceFile, path.root) || topLevelNames.has(path.root.text) ? void 0 : path.segments;
|
|
473
|
+
};
|
|
474
|
+
for (const statement of sourceFile.statements) {
|
|
475
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
476
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
477
|
+
if (!declaration.initializer || !ts.isIdentifier(declaration.name)) continue;
|
|
478
|
+
const path = resolvePath(declaration.initializer);
|
|
479
|
+
const symbol = symbolAt(checker, declaration.name);
|
|
480
|
+
if (!path || !symbol) continue;
|
|
481
|
+
aliases.set(symbol, path);
|
|
1213
482
|
}
|
|
1214
|
-
assertIntentAllowed(event.intent, {
|
|
1215
|
-
strictRegistry: this.strictRegistry,
|
|
1216
|
-
validateIntentNaming: this.validateIntentNaming,
|
|
1217
|
-
intentRegistry: this.intentRegistry
|
|
1218
|
-
});
|
|
1219
|
-
assertSourceAllowed(event, {
|
|
1220
|
-
requireKnownSource: this.requireKnownSource,
|
|
1221
|
-
intentRegistry: this.intentRegistry
|
|
1222
|
-
});
|
|
1223
|
-
assertContractAllowed(event, {
|
|
1224
|
-
eventContracts: this.eventContracts,
|
|
1225
|
-
strictEventContracts: this.strictEventContracts
|
|
1226
|
-
});
|
|
1227
|
-
event = await applyInterceptors(event, {
|
|
1228
|
-
interceptorsForIntent: (intent) => this.interceptorsByIntent.get(intent) ?? [],
|
|
1229
|
-
eventContracts: this.eventContracts,
|
|
1230
|
-
strictEventContracts: this.strictEventContracts,
|
|
1231
|
-
appendTrace: (r) => this.appendTrace(r),
|
|
1232
|
-
recordAudit: (type, e, details) => this.recordAudit(type, e, details)
|
|
1233
|
-
});
|
|
1234
|
-
assertContractAllowed(event, {
|
|
1235
|
-
eventContracts: this.eventContracts,
|
|
1236
|
-
strictEventContracts: this.strictEventContracts
|
|
1237
|
-
});
|
|
1238
|
-
await assertObservedLayerFlowAllowed(event, {
|
|
1239
|
-
mode: this.enforceObservedLayerFlowMode,
|
|
1240
|
-
architectureProfile: this.architectureProfile,
|
|
1241
|
-
appendTrace: (r) => this.appendTrace(r),
|
|
1242
|
-
recordAudit: (type, e, details) => this.recordAudit(type, e, details)
|
|
1243
|
-
});
|
|
1244
|
-
this.dependencyGraph?.registerEventFlow(event.metadata.source, event.intent);
|
|
1245
|
-
const matching = [...this.subscriptionsByIntent.get(event.intent) ?? []];
|
|
1246
|
-
if (this.policyEngine) {
|
|
1247
|
-
await enforcePublishPolicy(event, {
|
|
1248
|
-
policyEngine: this.policyEngine,
|
|
1249
|
-
getPolicyContext: this.getPolicyContext,
|
|
1250
|
-
appendTrace: (r) => this.appendTrace(r),
|
|
1251
|
-
recordAudit: (type, e, details) => this.recordAudit(type, e, details),
|
|
1252
|
-
onSoftViolation: this.onSoftViolation,
|
|
1253
|
-
safeHook: (fn, name, e) => this.safeHook(fn, name, e)
|
|
1254
|
-
});
|
|
1255
|
-
}
|
|
1256
|
-
await recordSuccessfulPublish(
|
|
1257
|
-
this.recording,
|
|
1258
|
-
event,
|
|
1259
|
-
matching.length
|
|
1260
|
-
);
|
|
1261
|
-
await Promise.all(
|
|
1262
|
-
matching.map((sub) => this.invokeHandler(sub, event))
|
|
1263
|
-
);
|
|
1264
|
-
if (this.onPublish) {
|
|
1265
|
-
await this.safeHook(
|
|
1266
|
-
() => this.onPublish(event),
|
|
1267
|
-
"onPublish",
|
|
1268
|
-
event
|
|
1269
|
-
);
|
|
1270
|
-
}
|
|
1271
|
-
}
|
|
1272
|
-
createPublisher(source) {
|
|
1273
|
-
const sourceName = typeof source === "string" ? source : source.name;
|
|
1274
|
-
assertIntentAllowed(sourceName, {
|
|
1275
|
-
strictRegistry: this.strictRegistry,
|
|
1276
|
-
validateIntentNaming: this.validateIntentNaming,
|
|
1277
|
-
intentRegistry: this.intentRegistry
|
|
1278
|
-
});
|
|
1279
|
-
return {
|
|
1280
|
-
source: sourceName,
|
|
1281
|
-
publish: async (intent, payload, metadata = {}) => {
|
|
1282
|
-
if (metadata.source && metadata.source !== sourceName) {
|
|
1283
|
-
throw new SourceMetadataOverrideError(sourceName, metadata.source);
|
|
1284
|
-
}
|
|
1285
|
-
await this.publish(intent, payload, {
|
|
1286
|
-
...metadata,
|
|
1287
|
-
source: sourceName
|
|
1288
|
-
});
|
|
1289
|
-
}
|
|
1290
|
-
};
|
|
1291
|
-
}
|
|
1292
|
-
subscribe(intent, handler) {
|
|
1293
|
-
const intentName = typeof intent === "string" ? intent : intent.name;
|
|
1294
|
-
assertIntentAllowed(intentName, {
|
|
1295
|
-
strictRegistry: this.strictRegistry,
|
|
1296
|
-
validateIntentNaming: this.validateIntentNaming,
|
|
1297
|
-
intentRegistry: this.intentRegistry
|
|
1298
|
-
});
|
|
1299
|
-
const sub = {
|
|
1300
|
-
intentName,
|
|
1301
|
-
handler
|
|
1302
|
-
};
|
|
1303
|
-
this.subscriptions.push(sub);
|
|
1304
|
-
const subscriptionsForIntent = this.subscriptionsByIntent.get(intentName) ?? [];
|
|
1305
|
-
subscriptionsForIntent.push(sub);
|
|
1306
|
-
this.subscriptionsByIntent.set(intentName, subscriptionsForIntent);
|
|
1307
|
-
return () => {
|
|
1308
|
-
const idx = this.subscriptions.indexOf(sub);
|
|
1309
|
-
if (idx >= 0) this.subscriptions.splice(idx, 1);
|
|
1310
|
-
const byIntent = this.subscriptionsByIntent.get(intentName);
|
|
1311
|
-
if (!byIntent) return;
|
|
1312
|
-
const intentIdx = byIntent.indexOf(sub);
|
|
1313
|
-
if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
|
|
1314
|
-
if (byIntent.length === 0) this.subscriptionsByIntent.delete(intentName);
|
|
1315
|
-
};
|
|
1316
|
-
}
|
|
1317
|
-
registerInterceptor(intent, interceptor, interceptorId) {
|
|
1318
|
-
const intentName = typeof intent === "string" ? intent : intent.name;
|
|
1319
|
-
assertIntentAllowed(intentName, {
|
|
1320
|
-
strictRegistry: this.strictRegistry,
|
|
1321
|
-
validateIntentNaming: this.validateIntentNaming,
|
|
1322
|
-
intentRegistry: this.intentRegistry
|
|
1323
|
-
});
|
|
1324
|
-
const registration = {
|
|
1325
|
-
registrationId: nextInterceptorRegistrationId(),
|
|
1326
|
-
interceptorId: interceptorId ?? intentName,
|
|
1327
|
-
intentName,
|
|
1328
|
-
interceptor,
|
|
1329
|
-
createdAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
1330
|
-
};
|
|
1331
|
-
this.interceptors.push(registration);
|
|
1332
|
-
const interceptorsForIntent = this.interceptorsByIntent.get(intentName) ?? [];
|
|
1333
|
-
interceptorsForIntent.push(registration);
|
|
1334
|
-
this.interceptorsByIntent.set(intentName, interceptorsForIntent);
|
|
1335
|
-
return registration.registrationId;
|
|
1336
|
-
}
|
|
1337
|
-
unregisterInterceptor(registrationId) {
|
|
1338
|
-
const interceptor = this.interceptors.find(
|
|
1339
|
-
(candidate) => candidate.registrationId === registrationId
|
|
1340
|
-
);
|
|
1341
|
-
if (!interceptor) return false;
|
|
1342
|
-
const idx = this.interceptors.indexOf(interceptor);
|
|
1343
|
-
if (idx >= 0) this.interceptors.splice(idx, 1);
|
|
1344
|
-
const byIntent = this.interceptorsByIntent.get(interceptor.intentName);
|
|
1345
|
-
if (byIntent) {
|
|
1346
|
-
const intentIdx = byIntent.indexOf(interceptor);
|
|
1347
|
-
if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
|
|
1348
|
-
if (byIntent.length === 0) this.interceptorsByIntent.delete(interceptor.intentName);
|
|
1349
|
-
}
|
|
1350
|
-
return true;
|
|
1351
483
|
}
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
})
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
}
|
|
1370
|
-
clearTrace() {
|
|
1371
|
-
this.recording.trace.length = 0;
|
|
1372
|
-
}
|
|
1373
|
-
appendTrace(record) {
|
|
1374
|
-
appendTrace(this.recording, record);
|
|
1375
|
-
}
|
|
1376
|
-
async recordAudit(type, event, details) {
|
|
1377
|
-
await recordAudit(this.recording, type, event, details);
|
|
1378
|
-
}
|
|
1379
|
-
async invokeHandler(sub, event) {
|
|
1380
|
-
try {
|
|
1381
|
-
await Promise.resolve(sub.handler(event));
|
|
1382
|
-
} catch (err) {
|
|
1383
|
-
this.appendTrace({
|
|
1384
|
-
type: "handler.error",
|
|
1385
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1386
|
-
intent: event.intent,
|
|
1387
|
-
correlationId: event.metadata.correlationId,
|
|
1388
|
-
traceId: event.metadata.traceId,
|
|
1389
|
-
spanId: event.metadata.spanId,
|
|
1390
|
-
details: { error: err instanceof Error ? err.message : String(err) }
|
|
1391
|
-
});
|
|
1392
|
-
await this.recordAudit("handler.error", event, {
|
|
1393
|
-
handlerIntent: sub.intentName,
|
|
1394
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1395
|
-
});
|
|
1396
|
-
if (this.onHandlerError) {
|
|
1397
|
-
await this.safeHook(
|
|
1398
|
-
() => this.onHandlerError(err, event, sub.intentName),
|
|
1399
|
-
"onHandlerError",
|
|
1400
|
-
event
|
|
1401
|
-
);
|
|
1402
|
-
}
|
|
1403
|
-
if (this.rethrowHandlerErrors) {
|
|
1404
|
-
throw err;
|
|
1405
|
-
}
|
|
484
|
+
const uses = [];
|
|
485
|
+
const seen = /* @__PURE__ */ new Set();
|
|
486
|
+
const flag = (name, node) => {
|
|
487
|
+
const line = lineOf(sourceFile, node);
|
|
488
|
+
const key = `${name}:${node.getStart(sourceFile)}`;
|
|
489
|
+
if (seen.has(key)) return;
|
|
490
|
+
seen.add(key);
|
|
491
|
+
uses.push({ name, line, node });
|
|
492
|
+
};
|
|
493
|
+
const visit = (node) => {
|
|
494
|
+
const parentContinuesPath = node.parent && (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node;
|
|
495
|
+
if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !parentContinuesPath) {
|
|
496
|
+
const path = resolvePath(node);
|
|
497
|
+
const match = path ? bestForbiddenMatch(entries, path) : void 0;
|
|
498
|
+
if (match) flag(match, node);
|
|
499
|
+
} else if (ts.isIdentifier(node) && entries.has(node.text) && runtimeIdentifierReference(ts, node) && !localDeclaration(ts, checker, sourceFile, node)) {
|
|
500
|
+
flag(node.text, node);
|
|
1406
501
|
}
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
intent: event.intent,
|
|
1416
|
-
correlationId: event.metadata.correlationId,
|
|
1417
|
-
traceId: event.metadata.traceId,
|
|
1418
|
-
spanId: event.metadata.spanId,
|
|
1419
|
-
details: {
|
|
1420
|
-
hook: hookName,
|
|
1421
|
-
error: err instanceof Error ? err.message : String(err)
|
|
502
|
+
if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer) {
|
|
503
|
+
const base = resolvePath(node.initializer);
|
|
504
|
+
if (base) {
|
|
505
|
+
for (const element of node.name.elements) {
|
|
506
|
+
if (!ts.isIdentifier(element.name)) continue;
|
|
507
|
+
const property = element.propertyName ? literalText(ts, element.propertyName) ?? element.propertyName.text : element.name.text;
|
|
508
|
+
const match = bestForbiddenMatch(entries, [...base, property]);
|
|
509
|
+
if (match) flag(match, node.initializer);
|
|
1422
510
|
}
|
|
1423
|
-
}
|
|
1424
|
-
await this.recordAudit("hook.error", event, {
|
|
1425
|
-
hook: hookName,
|
|
1426
|
-
error: err instanceof Error ? err.message : String(err)
|
|
1427
|
-
});
|
|
511
|
+
}
|
|
1428
512
|
}
|
|
1429
|
-
|
|
1430
|
-
};
|
|
1431
|
-
|
|
1432
|
-
return
|
|
513
|
+
ts.forEachChild(node, visit);
|
|
514
|
+
};
|
|
515
|
+
visit(sourceFile);
|
|
516
|
+
return uses;
|
|
1433
517
|
}
|
|
1434
518
|
|
|
1435
|
-
// src/kernel/
|
|
1436
|
-
function
|
|
1437
|
-
|
|
1438
|
-
return path.map(
|
|
1439
|
-
(segment) => typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment)
|
|
1440
|
-
).join(".");
|
|
1441
|
-
}
|
|
1442
|
-
function actualType(value) {
|
|
1443
|
-
if (Array.isArray(value)) return "array";
|
|
1444
|
-
if (value === null) return "object";
|
|
1445
|
-
const type = typeof value;
|
|
1446
|
-
if (type === "string" || type === "number" || type === "boolean" || type === "object") {
|
|
1447
|
-
return type;
|
|
1448
|
-
}
|
|
1449
|
-
return "unknown";
|
|
1450
|
-
}
|
|
1451
|
-
function formatPath(parent, field) {
|
|
1452
|
-
return parent ? `${parent}.${field}` : field;
|
|
1453
|
-
}
|
|
1454
|
-
function validateSchemaField(value, fieldSchema, path, contract, issues) {
|
|
1455
|
-
const valueType2 = actualType(value);
|
|
1456
|
-
if (fieldSchema.type !== "unknown" && valueType2 !== fieldSchema.type) {
|
|
1457
|
-
issues.push({
|
|
1458
|
-
intent: contract.intent,
|
|
1459
|
-
version: contract.version,
|
|
1460
|
-
field: path,
|
|
1461
|
-
message: `Expected ${fieldSchema.type}, received ${valueType2}.`
|
|
1462
|
-
});
|
|
1463
|
-
return;
|
|
1464
|
-
}
|
|
1465
|
-
if (fieldSchema.enum && !fieldSchema.enum.some((allowed) => Object.is(allowed, value))) {
|
|
1466
|
-
issues.push({
|
|
1467
|
-
intent: contract.intent,
|
|
1468
|
-
version: contract.version,
|
|
1469
|
-
field: path,
|
|
1470
|
-
message: "Value is not allowed by event contract enum."
|
|
1471
|
-
});
|
|
1472
|
-
}
|
|
1473
|
-
if (fieldSchema.type === "object" && fieldSchema.fields) {
|
|
1474
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
1475
|
-
issues.push({
|
|
1476
|
-
intent: contract.intent,
|
|
1477
|
-
version: contract.version,
|
|
1478
|
-
field: path,
|
|
1479
|
-
message: "Nested object field must be a non-array object."
|
|
1480
|
-
});
|
|
1481
|
-
return;
|
|
1482
|
-
}
|
|
1483
|
-
validateObjectSchema(
|
|
1484
|
-
value,
|
|
1485
|
-
fieldSchema.fields,
|
|
1486
|
-
contract,
|
|
1487
|
-
issues,
|
|
1488
|
-
path
|
|
1489
|
-
);
|
|
1490
|
-
}
|
|
1491
|
-
if (fieldSchema.type === "array" && fieldSchema.items && Array.isArray(value)) {
|
|
1492
|
-
value.forEach((item, index) => {
|
|
1493
|
-
validateSchemaField(
|
|
1494
|
-
item,
|
|
1495
|
-
fieldSchema.items,
|
|
1496
|
-
`${path}[${index}]`,
|
|
1497
|
-
contract,
|
|
1498
|
-
issues
|
|
1499
|
-
);
|
|
1500
|
-
});
|
|
1501
|
-
}
|
|
519
|
+
// src/kernel/ai-gate/AICodeGate.ts
|
|
520
|
+
function violation(ruleId, message, extra) {
|
|
521
|
+
return { ruleId, code: ruleId, message, ...extra };
|
|
1502
522
|
}
|
|
1503
|
-
function
|
|
1504
|
-
|
|
1505
|
-
const path = formatPath(parentPath, field);
|
|
1506
|
-
const value = payload[field];
|
|
1507
|
-
if (value === void 0) {
|
|
1508
|
-
if (fieldSchema.required) {
|
|
1509
|
-
issues.push({
|
|
1510
|
-
intent: contract.intent,
|
|
1511
|
-
version: contract.version,
|
|
1512
|
-
field: path,
|
|
1513
|
-
message: "Required field is missing."
|
|
1514
|
-
});
|
|
1515
|
-
}
|
|
1516
|
-
continue;
|
|
1517
|
-
}
|
|
1518
|
-
validateSchemaField(value, fieldSchema, path, contract, issues);
|
|
1519
|
-
}
|
|
523
|
+
function lineOf2(source, index) {
|
|
524
|
+
return source.slice(0, index).split("\n").length;
|
|
1520
525
|
}
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
}
|
|
1528
|
-
this.contracts.set(key, { allowAdditionalFields: true, ...contract });
|
|
1529
|
-
}
|
|
1530
|
-
get(intent, version2) {
|
|
1531
|
-
if (version2) return this.contracts.get(this.key(intent, version2));
|
|
1532
|
-
return this.list(intent).at(-1);
|
|
1533
|
-
}
|
|
1534
|
-
list(intent) {
|
|
1535
|
-
return Array.from(this.contracts.values()).filter(
|
|
1536
|
-
(contract) => !intent || contract.intent === intent
|
|
1537
|
-
);
|
|
526
|
+
function extractQuotedStrings(source) {
|
|
527
|
+
const matches = [];
|
|
528
|
+
const re = /['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g;
|
|
529
|
+
let m;
|
|
530
|
+
while ((m = re.exec(source)) !== null) {
|
|
531
|
+
matches.push({ value: m[1], index: m.index });
|
|
1538
532
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
message: typeof contract.deprecated === "string" ? contract.deprecated : "Event contract is deprecated."
|
|
1560
|
-
});
|
|
1561
|
-
}
|
|
1562
|
-
const payload = event.payload != null && typeof event.payload === "object" ? event.payload : void 0;
|
|
1563
|
-
if (contract.schema) {
|
|
1564
|
-
if (!payload) {
|
|
1565
|
-
issues.push({
|
|
1566
|
-
intent: event.intent,
|
|
1567
|
-
version: contract.version,
|
|
1568
|
-
message: "Payload must be an object for schema validation."
|
|
1569
|
-
});
|
|
1570
|
-
} else {
|
|
1571
|
-
validateObjectSchema(payload, contract.schema, contract, issues);
|
|
1572
|
-
if (contract.allowAdditionalFields === false) {
|
|
1573
|
-
for (const field of Object.keys(payload)) {
|
|
1574
|
-
if (!contract.schema[field]) {
|
|
1575
|
-
issues.push({
|
|
1576
|
-
intent: event.intent,
|
|
1577
|
-
version: contract.version,
|
|
1578
|
-
field,
|
|
1579
|
-
message: "Additional field is not allowed by event contract."
|
|
1580
|
-
});
|
|
1581
|
-
}
|
|
1582
|
-
}
|
|
1583
|
-
}
|
|
1584
|
-
}
|
|
533
|
+
return matches;
|
|
534
|
+
}
|
|
535
|
+
function extractModuleSpecifiers(source) {
|
|
536
|
+
const matches = [];
|
|
537
|
+
const patterns = [
|
|
538
|
+
{
|
|
539
|
+
kind: "import",
|
|
540
|
+
re: /\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g
|
|
541
|
+
},
|
|
542
|
+
{
|
|
543
|
+
kind: "export",
|
|
544
|
+
re: /\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g
|
|
545
|
+
},
|
|
546
|
+
{
|
|
547
|
+
kind: "dynamic-import",
|
|
548
|
+
re: /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g
|
|
549
|
+
},
|
|
550
|
+
{
|
|
551
|
+
kind: "require",
|
|
552
|
+
re: /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g
|
|
1585
553
|
}
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
} else if (result.issues) {
|
|
1595
|
-
for (const issue of result.issues) {
|
|
1596
|
-
issues.push({
|
|
1597
|
-
intent: event.intent,
|
|
1598
|
-
version: contract.version,
|
|
1599
|
-
field: formatStandardSchemaPath(issue.path),
|
|
1600
|
-
message: issue.message
|
|
1601
|
-
});
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
554
|
+
];
|
|
555
|
+
for (const pattern of patterns) {
|
|
556
|
+
let match;
|
|
557
|
+
while ((match = pattern.re.exec(source)) !== null) {
|
|
558
|
+
const index = match.index + match[0].indexOf(match[1]);
|
|
559
|
+
const raw = match[0];
|
|
560
|
+
const typeOnly = pattern.kind === "import" && /\bimport\s+type\b/.test(raw) || pattern.kind === "export" && /\bexport\s+type\b/.test(raw);
|
|
561
|
+
matches.push({ value: match[1], index, kind: pattern.kind, typeOnly });
|
|
1604
562
|
}
|
|
1605
|
-
return { ok: issues.length === 0, contract, issues };
|
|
1606
563
|
}
|
|
1607
|
-
|
|
1608
|
-
this.contracts.clear();
|
|
1609
|
-
}
|
|
1610
|
-
key(intent, version2) {
|
|
1611
|
-
return `${intent}@${version2}`;
|
|
1612
|
-
}
|
|
1613
|
-
};
|
|
1614
|
-
function createEventContractRegistry() {
|
|
1615
|
-
return new EventContractRegistryImpl();
|
|
1616
|
-
}
|
|
1617
|
-
|
|
1618
|
-
// src/kernel/outbox/InMemoryOutboxStore.ts
|
|
1619
|
-
var outboxSequence = 0;
|
|
1620
|
-
function nextOutboxId() {
|
|
1621
|
-
outboxSequence += 1;
|
|
1622
|
-
return `outbox-${Date.now()}-${outboxSequence}`;
|
|
564
|
+
return matches.sort((a, b) => a.index - b.index);
|
|
1623
565
|
}
|
|
1624
|
-
function
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
566
|
+
function extractQuotedStringsAst(ts, source) {
|
|
567
|
+
const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
|
|
568
|
+
const matches = [];
|
|
569
|
+
const visit = (node) => {
|
|
570
|
+
if (ts.isStringLiteralLike(node)) {
|
|
571
|
+
matches.push({ value: node.text, index: node.getStart(sourceFile) });
|
|
1630
572
|
}
|
|
573
|
+
ts.forEachChild(node, visit);
|
|
1631
574
|
};
|
|
575
|
+
visit(sourceFile);
|
|
576
|
+
return matches;
|
|
1632
577
|
}
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
}
|
|
1648
|
-
async markDispatched(id) {
|
|
1649
|
-
const record = this.records.get(id);
|
|
1650
|
-
if (!record) return;
|
|
1651
|
-
record.status = "dispatched";
|
|
1652
|
-
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1653
|
-
}
|
|
1654
|
-
async markFailed(id, error) {
|
|
1655
|
-
const record = this.records.get(id);
|
|
1656
|
-
if (!record) return;
|
|
1657
|
-
record.status = "failed";
|
|
1658
|
-
record.attempts += 1;
|
|
1659
|
-
record.error = error instanceof Error ? error.message : String(error);
|
|
1660
|
-
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1661
|
-
}
|
|
1662
|
-
async list(status) {
|
|
1663
|
-
return Array.from(this.records.values()).filter((record) => !status || record.status === status).map(cloneRecord);
|
|
1664
|
-
}
|
|
1665
|
-
async clear() {
|
|
1666
|
-
this.records.clear();
|
|
1667
|
-
}
|
|
1668
|
-
};
|
|
1669
|
-
|
|
1670
|
-
// src/kernel/observability/ObservabilityReporter.ts
|
|
1671
|
-
function flowKey(flow) {
|
|
1672
|
-
return `${flow.from}->${flow.to}`;
|
|
578
|
+
function hasInfrastructureToken(specifier) {
|
|
579
|
+
const tokens = specifier.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
580
|
+
return [
|
|
581
|
+
"adapter",
|
|
582
|
+
"adapters",
|
|
583
|
+
"infra",
|
|
584
|
+
"infrastructure",
|
|
585
|
+
"persistence",
|
|
586
|
+
"repository",
|
|
587
|
+
"repositories",
|
|
588
|
+
"integration",
|
|
589
|
+
"database",
|
|
590
|
+
"db"
|
|
591
|
+
].some((token) => tokens.includes(token));
|
|
1673
592
|
}
|
|
1674
|
-
function
|
|
1675
|
-
const
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
if (seen.has(key)) continue;
|
|
1680
|
-
seen.add(key);
|
|
1681
|
-
result.push(flow);
|
|
1682
|
-
}
|
|
1683
|
-
return result;
|
|
593
|
+
function isKnownInfrastructurePackage(specifier) {
|
|
594
|
+
const normalized = specifier.toLowerCase();
|
|
595
|
+
return ["sequelize", "prisma", "typeorm", "mongoose", "knex"].some(
|
|
596
|
+
(name) => normalized === name || normalized.startsWith(`${name}/`)
|
|
597
|
+
);
|
|
1684
598
|
}
|
|
1685
|
-
function
|
|
1686
|
-
const
|
|
1687
|
-
return
|
|
599
|
+
function layerHasInfrastructureRole(layerName) {
|
|
600
|
+
const normalized = layerName.toLowerCase();
|
|
601
|
+
return [
|
|
602
|
+
"adapter",
|
|
603
|
+
"infra",
|
|
604
|
+
"persistence",
|
|
605
|
+
"repository",
|
|
606
|
+
"repositories",
|
|
607
|
+
"integration",
|
|
608
|
+
"database"
|
|
609
|
+
].some((token) => normalized.includes(token));
|
|
1688
610
|
}
|
|
1689
|
-
function
|
|
1690
|
-
|
|
1691
|
-
const eventBus = options.eventBus;
|
|
1692
|
-
const graph = options.graph;
|
|
1693
|
-
return {
|
|
1694
|
-
report() {
|
|
1695
|
-
const declaredFromRegistry = registry ? registry.getAllRelationships().filter((relationship) => relationship.kind === "produces").map((relationship) => ({
|
|
1696
|
-
from: relationship.from,
|
|
1697
|
-
to: relationship.to
|
|
1698
|
-
})) : [];
|
|
1699
|
-
const declaredFromGraph = declaredFromRegistry.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "produces").map((edge) => ({ from: edge.from, to: edge.to }));
|
|
1700
|
-
const observedFromHistory = eventBus?.getHistory().map((record) => ({
|
|
1701
|
-
from: record.event.metadata.source,
|
|
1702
|
-
to: record.event.intent
|
|
1703
|
-
})) ?? [];
|
|
1704
|
-
const observedFromGraph = observedFromHistory.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "observed").map((edge) => ({ from: edge.from, to: edge.to }));
|
|
1705
|
-
const declaredProductions = uniqueFlows([
|
|
1706
|
-
...declaredFromRegistry,
|
|
1707
|
-
...declaredFromGraph
|
|
1708
|
-
]);
|
|
1709
|
-
const observedProductions = uniqueFlows([
|
|
1710
|
-
...observedFromHistory,
|
|
1711
|
-
...observedFromGraph
|
|
1712
|
-
]);
|
|
1713
|
-
const unknownSources = observedProductions.filter(
|
|
1714
|
-
(flow) => !flow.from || flow.from === "unknown"
|
|
1715
|
-
);
|
|
1716
|
-
const unregisteredObservedSources = registry ? Array.from(
|
|
1717
|
-
new Set(
|
|
1718
|
-
observedProductions.map((flow) => flow.from).filter(
|
|
1719
|
-
(source) => source && source !== "unknown" && !registry.has(source)
|
|
1720
|
-
)
|
|
1721
|
-
)
|
|
1722
|
-
) : [];
|
|
1723
|
-
const unregisteredObservedIntents = registry ? Array.from(
|
|
1724
|
-
new Set(
|
|
1725
|
-
observedProductions.map((flow) => flow.to).filter((intent) => !registry.has(intent))
|
|
1726
|
-
)
|
|
1727
|
-
) : [];
|
|
1728
|
-
const observedIntentNames = new Set(
|
|
1729
|
-
observedProductions.flatMap((flow) => [flow.from, flow.to])
|
|
1730
|
-
);
|
|
1731
|
-
const registeredButNeverObserved = registry ? registry.list().map((intent) => intent.name).filter((intent) => !observedIntentNames.has(intent)) : [];
|
|
1732
|
-
return {
|
|
1733
|
-
generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1734
|
-
declaredProductions,
|
|
1735
|
-
observedProductions,
|
|
1736
|
-
declaredButUnobserved: difference(declaredProductions, observedProductions),
|
|
1737
|
-
observedButUndeclared: difference(
|
|
1738
|
-
observedProductions.filter((flow) => flow.from !== "unknown"),
|
|
1739
|
-
declaredProductions
|
|
1740
|
-
),
|
|
1741
|
-
unknownSources,
|
|
1742
|
-
unregisteredObservedSources,
|
|
1743
|
-
unregisteredObservedIntents,
|
|
1744
|
-
registeredButNeverObserved
|
|
1745
|
-
};
|
|
1746
|
-
}
|
|
1747
|
-
};
|
|
611
|
+
function tsStringLiteralText(ts, node) {
|
|
612
|
+
return node && ts.isStringLiteralLike(node) ? node.text : void 0;
|
|
1748
613
|
}
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
return
|
|
1753
|
-
events(intent) {
|
|
1754
|
-
return kernel.eventBus.getHistory().map((record) => record.event).filter((event) => !intent || event.intent === intent);
|
|
1755
|
-
},
|
|
1756
|
-
traces(type) {
|
|
1757
|
-
return kernel.eventBus.getTrace().filter((record) => !type || record.type === type);
|
|
1758
|
-
},
|
|
1759
|
-
audit(query) {
|
|
1760
|
-
return kernel.auditTrail.query(query);
|
|
1761
|
-
},
|
|
1762
|
-
outbox(status) {
|
|
1763
|
-
return kernel.outbox.list(status);
|
|
1764
|
-
},
|
|
1765
|
-
observability() {
|
|
1766
|
-
kernel.syncGraph();
|
|
1767
|
-
return kernel.observability.report();
|
|
1768
|
-
},
|
|
1769
|
-
async snapshot() {
|
|
1770
|
-
return {
|
|
1771
|
-
events: this.events(),
|
|
1772
|
-
traces: this.traces(),
|
|
1773
|
-
audit: await this.audit(),
|
|
1774
|
-
outbox: await this.outbox(),
|
|
1775
|
-
observability: this.observability()
|
|
1776
|
-
};
|
|
1777
|
-
},
|
|
1778
|
-
async clear() {
|
|
1779
|
-
kernel.eventBus.clearHistory();
|
|
1780
|
-
kernel.eventBus.clearTrace();
|
|
1781
|
-
await kernel.auditTrail.clear();
|
|
1782
|
-
await kernel.outbox.clear();
|
|
1783
|
-
}
|
|
1784
|
-
};
|
|
614
|
+
function tsPropertyName(ts, node) {
|
|
615
|
+
if (!node) return void 0;
|
|
616
|
+
if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) return node.text;
|
|
617
|
+
return void 0;
|
|
1785
618
|
}
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
return `audit-${Date.now()}-${auditSequence}`;
|
|
1792
|
-
}
|
|
1793
|
-
function matchesQuery(record, query) {
|
|
1794
|
-
if (query.type && record.type !== query.type) return false;
|
|
1795
|
-
if (query.intent && record.intent !== query.intent) return false;
|
|
1796
|
-
if (query.correlationId && record.correlationId !== query.correlationId) return false;
|
|
1797
|
-
if (query.subject && record.subject !== query.subject) return false;
|
|
1798
|
-
if (query.since && record.timestamp < query.since) return false;
|
|
1799
|
-
if (query.until && record.timestamp > query.until) return false;
|
|
1800
|
-
return true;
|
|
1801
|
-
}
|
|
1802
|
-
var InMemoryAuditStore = class {
|
|
1803
|
-
constructor(maxRecords) {
|
|
1804
|
-
this.maxRecords = maxRecords;
|
|
1805
|
-
}
|
|
1806
|
-
maxRecords;
|
|
1807
|
-
records = [];
|
|
1808
|
-
append(record) {
|
|
1809
|
-
this.records.push(record);
|
|
1810
|
-
if (this.maxRecords !== void 0 && this.records.length > this.maxRecords) {
|
|
1811
|
-
this.records.splice(0, this.records.length - this.maxRecords);
|
|
619
|
+
function tsObjectProperty(ts, node, name) {
|
|
620
|
+
if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
|
|
621
|
+
return node.properties.find((property) => {
|
|
622
|
+
if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {
|
|
623
|
+
return false;
|
|
1812
624
|
}
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
const records = this.records.filter((record) => matchesQuery(record, query));
|
|
1816
|
-
return query.limit === void 0 ? [...records] : records.slice(-query.limit);
|
|
1817
|
-
}
|
|
1818
|
-
clear() {
|
|
1819
|
-
this.records.length = 0;
|
|
1820
|
-
}
|
|
1821
|
-
};
|
|
1822
|
-
var AuditTrailImpl = class {
|
|
1823
|
-
constructor(store) {
|
|
1824
|
-
this.store = store;
|
|
1825
|
-
}
|
|
1826
|
-
store;
|
|
1827
|
-
async record(input) {
|
|
1828
|
-
const record = {
|
|
1829
|
-
id: createAuditId(),
|
|
1830
|
-
timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
1831
|
-
type: input.type,
|
|
1832
|
-
source: input.source,
|
|
1833
|
-
actor: input.actor,
|
|
1834
|
-
intent: input.intent,
|
|
1835
|
-
correlationId: input.correlationId,
|
|
1836
|
-
causationId: input.causationId,
|
|
1837
|
-
subject: input.subject,
|
|
1838
|
-
details: input.details
|
|
1839
|
-
};
|
|
1840
|
-
await this.store.append(record);
|
|
1841
|
-
return record;
|
|
1842
|
-
}
|
|
1843
|
-
async query(query) {
|
|
1844
|
-
return this.store.query(query);
|
|
1845
|
-
}
|
|
1846
|
-
async clear() {
|
|
1847
|
-
await this.store.clear();
|
|
1848
|
-
}
|
|
1849
|
-
};
|
|
1850
|
-
function createAuditTrail(options = {}) {
|
|
1851
|
-
return new AuditTrailImpl(
|
|
1852
|
-
options.store ?? new InMemoryAuditStore(options.maxRecords)
|
|
1853
|
-
);
|
|
625
|
+
return tsPropertyName(ts, property.name) === name;
|
|
626
|
+
});
|
|
1854
627
|
}
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
return Array.from(this.nodes.values());
|
|
1872
|
-
}
|
|
1873
|
-
getEdges() {
|
|
1874
|
-
return [...this.edges];
|
|
628
|
+
function tsObjectHasProperty(ts, node, name) {
|
|
629
|
+
return tsObjectProperty(ts, node, name) !== void 0;
|
|
630
|
+
}
|
|
631
|
+
function tsObjectPropertyValue(ts, node, name) {
|
|
632
|
+
const property = tsObjectProperty(ts, node, name);
|
|
633
|
+
return property && ts.isPropertyAssignment(property) ? property.initializer : void 0;
|
|
634
|
+
}
|
|
635
|
+
function tsObjectHasMetadataSource(ts, node) {
|
|
636
|
+
const metadata = tsObjectPropertyValue(ts, node, "metadata");
|
|
637
|
+
return tsObjectHasProperty(ts, metadata, "source");
|
|
638
|
+
}
|
|
639
|
+
function tsLooksLikeIntentCreatorExpression(ts, node) {
|
|
640
|
+
if (!node) return false;
|
|
641
|
+
if (ts.isIdentifier(node)) return /^[A-Z]/.test(node.text);
|
|
642
|
+
if (ts.isPropertyAccessExpression(node)) {
|
|
643
|
+
return tsLooksLikeIntentCreatorExpression(ts, node.name);
|
|
1875
644
|
}
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
let out = "flowchart TD\n";
|
|
1884
|
-
for (const edge of this.edges) {
|
|
1885
|
-
const label = edge.kind ? `|${edge.kind}|` : "";
|
|
1886
|
-
out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
|
|
1887
|
-
`;
|
|
1888
|
-
}
|
|
1889
|
-
const connected = new Set(
|
|
1890
|
-
this.edges.flatMap((e) => [e.from, e.to])
|
|
1891
|
-
);
|
|
1892
|
-
for (const node of this.nodes.keys()) {
|
|
1893
|
-
if (!connected.has(node)) {
|
|
1894
|
-
out += ` ${this.safeId(node)}
|
|
1895
|
-
`;
|
|
1896
|
-
}
|
|
1897
|
-
}
|
|
1898
|
-
return out.trim();
|
|
1899
|
-
}
|
|
1900
|
-
toLayerMermaid(profile) {
|
|
1901
|
-
const nodesByLayer = /* @__PURE__ */ new Map();
|
|
1902
|
-
for (const node of this.nodes.keys()) {
|
|
1903
|
-
const layer = profile.resolveLayer(node) ?? "Unclassified";
|
|
1904
|
-
const current = nodesByLayer.get(layer) ?? [];
|
|
1905
|
-
current.push(node);
|
|
1906
|
-
nodesByLayer.set(layer, current);
|
|
1907
|
-
}
|
|
1908
|
-
let out = "flowchart TD\n";
|
|
1909
|
-
for (const layer of profile.layers) {
|
|
1910
|
-
const nodes = nodesByLayer.get(layer.name) ?? [];
|
|
1911
|
-
if (nodes.length === 0) continue;
|
|
1912
|
-
out += ` subgraph ${this.safeId(layer.name)}[${layer.name}]
|
|
1913
|
-
`;
|
|
1914
|
-
for (const node of nodes) {
|
|
1915
|
-
out += ` ${this.safeId(node)}[${node}]
|
|
1916
|
-
`;
|
|
1917
|
-
}
|
|
1918
|
-
out += " end\n";
|
|
1919
|
-
}
|
|
1920
|
-
const unclassified = nodesByLayer.get("Unclassified") ?? [];
|
|
1921
|
-
if (unclassified.length > 0) {
|
|
1922
|
-
out += " subgraph Unclassified[Unclassified]\n";
|
|
1923
|
-
for (const node of unclassified) {
|
|
1924
|
-
out += ` ${this.safeId(node)}[${node}]
|
|
1925
|
-
`;
|
|
1926
|
-
}
|
|
1927
|
-
out += " end\n";
|
|
1928
|
-
}
|
|
1929
|
-
for (const edge of this.edges) {
|
|
1930
|
-
const label = edge.kind ? `|${edge.kind}|` : "";
|
|
1931
|
-
out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
|
|
1932
|
-
`;
|
|
1933
|
-
}
|
|
1934
|
-
return out.trim();
|
|
1935
|
-
}
|
|
1936
|
-
detectViolations(rules = []) {
|
|
1937
|
-
const violations = [];
|
|
1938
|
-
const cycles = this.findSimpleCycles();
|
|
1939
|
-
if (cycles.length > 0) {
|
|
1940
|
-
violations.push(`Cycle detected: ${cycles.map((c) => c.join("->")).join(", ")}`);
|
|
1941
|
-
}
|
|
1942
|
-
for (const rule of rules) {
|
|
1943
|
-
try {
|
|
1944
|
-
const res = rule(this.edges);
|
|
1945
|
-
if (res && res.length) violations.push(...res);
|
|
1946
|
-
} catch (e) {
|
|
1947
|
-
violations.push(`Rule error: ${e.message}`);
|
|
1948
|
-
}
|
|
1949
|
-
}
|
|
1950
|
-
return violations;
|
|
1951
|
-
}
|
|
1952
|
-
ensureNode(id) {
|
|
1953
|
-
if (!this.nodes.has(id)) {
|
|
1954
|
-
this.nodes.set(id, { id });
|
|
1955
|
-
}
|
|
1956
|
-
}
|
|
1957
|
-
addEdge(edge) {
|
|
1958
|
-
const exists = this.edges.some(
|
|
1959
|
-
(e) => e.from === edge.from && e.to === edge.to && e.kind === edge.kind
|
|
1960
|
-
);
|
|
1961
|
-
if (!exists) {
|
|
1962
|
-
this.edges.push(edge);
|
|
1963
|
-
}
|
|
1964
|
-
}
|
|
1965
|
-
// Very naive cycle detection for small graphs
|
|
1966
|
-
findSimpleCycles() {
|
|
1967
|
-
const graph = /* @__PURE__ */ new Map();
|
|
1968
|
-
for (const e of this.edges) {
|
|
1969
|
-
if (!graph.has(e.from)) graph.set(e.from, []);
|
|
1970
|
-
graph.get(e.from).push(e.to);
|
|
1971
|
-
}
|
|
1972
|
-
const cycles = [];
|
|
1973
|
-
const visited = /* @__PURE__ */ new Set();
|
|
1974
|
-
const stack = [];
|
|
1975
|
-
const dfs = (node) => {
|
|
1976
|
-
visited.add(node);
|
|
1977
|
-
stack.push(node);
|
|
1978
|
-
for (const nei of graph.get(node) || []) {
|
|
1979
|
-
if (!visited.has(nei)) {
|
|
1980
|
-
dfs(nei);
|
|
1981
|
-
} else if (stack.includes(nei)) {
|
|
1982
|
-
const cycleStart = stack.indexOf(nei);
|
|
1983
|
-
const cycle = stack.slice(cycleStart).concat(nei);
|
|
1984
|
-
cycles.push(cycle);
|
|
1985
|
-
}
|
|
1986
|
-
}
|
|
1987
|
-
stack.pop();
|
|
1988
|
-
};
|
|
1989
|
-
for (const node of graph.keys()) {
|
|
1990
|
-
if (!visited.has(node)) dfs(node);
|
|
1991
|
-
}
|
|
1992
|
-
const unique = new Set(cycles.map((c) => c.join("->")));
|
|
1993
|
-
return Array.from(unique).map((s) => s.split("->"));
|
|
1994
|
-
}
|
|
1995
|
-
safeId(id) {
|
|
1996
|
-
return id.replace(/[^a-zA-Z0-9_]/g, "_");
|
|
1997
|
-
}
|
|
1998
|
-
};
|
|
1999
|
-
function createDependencyGraph() {
|
|
2000
|
-
return new DependencyGraphImpl();
|
|
2001
|
-
}
|
|
2002
|
-
|
|
2003
|
-
// src/kernel/graph/sync.ts
|
|
2004
|
-
function syncRegistryToGraph(registry, graph, options = {}) {
|
|
2005
|
-
const requireRegistered = options.requireRegisteredTargets ?? false;
|
|
2006
|
-
for (const rel of registry.getAllRelationships()) {
|
|
2007
|
-
if (requireRegistered && !registry.has(rel.to)) {
|
|
2008
|
-
continue;
|
|
2009
|
-
}
|
|
2010
|
-
if (rel.kind === "dependsOn") {
|
|
2011
|
-
graph.registerDependency(rel.from, rel.to, "declared");
|
|
2012
|
-
} else {
|
|
2013
|
-
graph.registerDependency(rel.from, rel.to, "produces");
|
|
2014
|
-
}
|
|
2015
|
-
}
|
|
2016
|
-
}
|
|
2017
|
-
|
|
2018
|
-
// src/domain/configContract.ts
|
|
2019
|
-
var ARK_CONFIG_SCHEMA_VERSION = "1.0";
|
|
2020
|
-
var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
|
|
2021
|
-
var DEFAULT_LAYER_NAMES = [
|
|
2022
|
-
"DomainModel",
|
|
2023
|
-
"ApplicationOrchestration",
|
|
2024
|
-
"PersistenceAdapters",
|
|
2025
|
-
"IntegrationAdapters",
|
|
2026
|
-
"WorkflowSagaEngine",
|
|
2027
|
-
"BackgroundJobsScheduling",
|
|
2028
|
-
"PresentationAdapters",
|
|
2029
|
-
"ReportingReadModels",
|
|
2030
|
-
"ExtensibilityMetadata",
|
|
2031
|
-
"SecurityAuditObservability",
|
|
2032
|
-
"Kernel"
|
|
2033
|
-
];
|
|
2034
|
-
var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
|
|
2035
|
-
"PresentationAdapters->ApplicationOrchestration",
|
|
2036
|
-
"ApplicationOrchestration->DomainModel",
|
|
2037
|
-
"WorkflowSagaEngine->ApplicationOrchestration",
|
|
2038
|
-
"WorkflowSagaEngine->DomainModel",
|
|
2039
|
-
"BackgroundJobsScheduling->ApplicationOrchestration"
|
|
2040
|
-
]);
|
|
2041
|
-
function createDefaultRules() {
|
|
2042
|
-
const rules = [];
|
|
2043
|
-
for (const from of DEFAULT_LAYER_NAMES) {
|
|
2044
|
-
for (const to of DEFAULT_LAYER_NAMES) {
|
|
2045
|
-
if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
|
|
2046
|
-
rules.push({ from, to, allowed: false });
|
|
2047
|
-
}
|
|
2048
|
-
}
|
|
2049
|
-
return rules;
|
|
2050
|
-
}
|
|
2051
|
-
var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
|
|
2052
|
-
var stringArraySchema = {
|
|
2053
|
-
type: "array",
|
|
2054
|
-
items: { type: "string", minLength: 1 },
|
|
2055
|
-
uniqueItems: true
|
|
2056
|
-
};
|
|
2057
|
-
var ARK_CONFIG_SCHEMA = {
|
|
2058
|
-
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
2059
|
-
$id: ARK_CONFIG_SCHEMA_URL,
|
|
2060
|
-
title: "ArkGate architecture contract",
|
|
2061
|
-
description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
|
|
2062
|
-
type: "object",
|
|
2063
|
-
additionalProperties: false,
|
|
2064
|
-
required: ["$schema", "schemaVersion", "include", "layers", "rules"],
|
|
2065
|
-
properties: {
|
|
2066
|
-
$schema: {
|
|
2067
|
-
type: "string",
|
|
2068
|
-
minLength: 1,
|
|
2069
|
-
default: ARK_CONFIG_SCHEMA_URL,
|
|
2070
|
-
description: "Editor-facing URL or local path for this JSON Schema."
|
|
2071
|
-
},
|
|
2072
|
-
schemaVersion: {
|
|
2073
|
-
type: "string",
|
|
2074
|
-
const: ARK_CONFIG_SCHEMA_VERSION,
|
|
2075
|
-
default: ARK_CONFIG_SCHEMA_VERSION
|
|
2076
|
-
},
|
|
2077
|
-
name: { type: "string", minLength: 1 },
|
|
2078
|
-
include: { ...stringArraySchema, minItems: 1, default: ["src"] },
|
|
2079
|
-
exclude: { ...stringArraySchema, default: [] },
|
|
2080
|
-
excludeGenerated: { type: "boolean", default: true },
|
|
2081
|
-
frameworkOverlay: { type: "string", minLength: 1 },
|
|
2082
|
-
layers: {
|
|
2083
|
-
type: "array",
|
|
2084
|
-
default: [],
|
|
2085
|
-
items: { $ref: "#/$defs/layer" }
|
|
2086
|
-
},
|
|
2087
|
-
rules: {
|
|
2088
|
-
type: "array",
|
|
2089
|
-
default: DEFAULT_ARK_CONFIG_RULES,
|
|
2090
|
-
items: { $ref: "#/$defs/rule" }
|
|
2091
|
-
},
|
|
2092
|
-
cyclePolicy: {
|
|
2093
|
-
type: "string",
|
|
2094
|
-
enum: ["strict", "soft", "framework-soft", "off"],
|
|
2095
|
-
default: "strict"
|
|
2096
|
-
},
|
|
2097
|
-
dynamicImportAllowlist: { ...stringArraySchema, default: [] },
|
|
2098
|
-
safety: {
|
|
2099
|
-
$ref: "#/$defs/safety",
|
|
2100
|
-
default: {
|
|
2101
|
-
maxTsSuppressions: 0,
|
|
2102
|
-
maxAnyCasts: 0,
|
|
2103
|
-
allowInMemory: false,
|
|
2104
|
-
allowDisabledPeerIsolation: false
|
|
2105
|
-
}
|
|
2106
|
-
}
|
|
2107
|
-
},
|
|
2108
|
-
$defs: {
|
|
2109
|
-
layer: {
|
|
2110
|
-
type: "object",
|
|
2111
|
-
additionalProperties: false,
|
|
2112
|
-
required: ["name", "patterns"],
|
|
2113
|
-
properties: {
|
|
2114
|
-
name: { type: "string", minLength: 1 },
|
|
2115
|
-
patterns: { ...stringArraySchema, minItems: 1 },
|
|
2116
|
-
exclude: stringArraySchema,
|
|
2117
|
-
intentPrefixes: stringArraySchema,
|
|
2118
|
-
description: { type: "string", minLength: 1 },
|
|
2119
|
-
forbiddenGlobals: stringArraySchema,
|
|
2120
|
-
mayImportInfrastructure: { type: "boolean" },
|
|
2121
|
-
optional: { type: "boolean" }
|
|
2122
|
-
}
|
|
2123
|
-
},
|
|
2124
|
-
rule: {
|
|
2125
|
-
type: "object",
|
|
2126
|
-
additionalProperties: false,
|
|
2127
|
-
required: ["from", "to", "allowed"],
|
|
2128
|
-
properties: {
|
|
2129
|
-
from: { type: "string", minLength: 1 },
|
|
2130
|
-
to: { type: "string", minLength: 1 },
|
|
2131
|
-
allowed: { type: "boolean" },
|
|
2132
|
-
message: { type: "string", minLength: 1 },
|
|
2133
|
-
peerIsolation: { type: "boolean" },
|
|
2134
|
-
sliceFolders: { ...stringArraySchema, minItems: 1 }
|
|
2135
|
-
}
|
|
2136
|
-
},
|
|
2137
|
-
safety: {
|
|
2138
|
-
type: "object",
|
|
2139
|
-
additionalProperties: false,
|
|
2140
|
-
properties: {
|
|
2141
|
-
maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
|
|
2142
|
-
maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
|
|
2143
|
-
allowInMemory: { type: "boolean", default: false },
|
|
2144
|
-
allowDisabledPeerIsolation: { type: "boolean", default: false }
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
}
|
|
2148
|
-
};
|
|
2149
|
-
var ArkConfigValidationError = class extends Error {
|
|
2150
|
-
issues;
|
|
2151
|
-
source;
|
|
2152
|
-
constructor(source, issues) {
|
|
2153
|
-
super(
|
|
2154
|
-
`Invalid ArkGate config (${source}):
|
|
2155
|
-
${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
|
|
2156
|
-
);
|
|
2157
|
-
this.name = "ArkConfigValidationError";
|
|
2158
|
-
this.source = source;
|
|
2159
|
-
this.issues = issues;
|
|
2160
|
-
}
|
|
2161
|
-
};
|
|
2162
|
-
function isObject(value) {
|
|
2163
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2164
|
-
}
|
|
2165
|
-
function propertyPath(parent, key) {
|
|
2166
|
-
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
|
|
2167
|
-
}
|
|
2168
|
-
function valueType(value) {
|
|
2169
|
-
if (value === null) return "null";
|
|
2170
|
-
if (Array.isArray(value)) return "array";
|
|
2171
|
-
return typeof value;
|
|
2172
|
-
}
|
|
2173
|
-
function resolveSchemaRef(ref, root) {
|
|
2174
|
-
const prefix = "#/$defs/";
|
|
2175
|
-
if (!ref.startsWith(prefix)) return void 0;
|
|
2176
|
-
return root.$defs[ref.slice(prefix.length)];
|
|
2177
|
-
}
|
|
2178
|
-
function validateNode(value, schema, path, root, issues) {
|
|
2179
|
-
if (schema.$ref) {
|
|
2180
|
-
const referenced = resolveSchemaRef(schema.$ref, root);
|
|
2181
|
-
if (!referenced) {
|
|
2182
|
-
issues.push({ path, message: `schema reference ${schema.$ref} cannot be resolved` });
|
|
2183
|
-
return;
|
|
2184
|
-
}
|
|
2185
|
-
validateNode(value, referenced, path, root, issues);
|
|
2186
|
-
return;
|
|
2187
|
-
}
|
|
2188
|
-
if (schema.const !== void 0 && !Object.is(value, schema.const)) {
|
|
2189
|
-
issues.push({ path, message: `must equal ${JSON.stringify(schema.const)}` });
|
|
2190
|
-
return;
|
|
2191
|
-
}
|
|
2192
|
-
if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
|
|
2193
|
-
issues.push({ path, message: `must be one of ${schema.enum.map(String).join(", ")}` });
|
|
2194
|
-
return;
|
|
2195
|
-
}
|
|
2196
|
-
if (schema.type === "object") {
|
|
2197
|
-
if (!isObject(value)) {
|
|
2198
|
-
issues.push({ path, message: `must be an object; received ${valueType(value)}` });
|
|
2199
|
-
return;
|
|
2200
|
-
}
|
|
2201
|
-
const properties = schema.properties ?? {};
|
|
2202
|
-
for (const key of schema.required ?? []) {
|
|
2203
|
-
if (value[key] === void 0) {
|
|
2204
|
-
issues.push({ path: propertyPath(path, key), message: "is required" });
|
|
2205
|
-
}
|
|
2206
|
-
}
|
|
2207
|
-
if (schema.additionalProperties === false) {
|
|
2208
|
-
for (const key of Object.keys(value)) {
|
|
2209
|
-
if (!(key in properties)) {
|
|
2210
|
-
issues.push({ path: propertyPath(path, key), message: "unknown field" });
|
|
2211
|
-
}
|
|
2212
|
-
}
|
|
2213
|
-
}
|
|
2214
|
-
for (const [key, childSchema] of Object.entries(properties)) {
|
|
2215
|
-
if (value[key] !== void 0) {
|
|
2216
|
-
validateNode(value[key], childSchema, propertyPath(path, key), root, issues);
|
|
2217
|
-
}
|
|
2218
|
-
}
|
|
2219
|
-
return;
|
|
2220
|
-
}
|
|
2221
|
-
if (schema.type === "array") {
|
|
2222
|
-
if (!Array.isArray(value)) {
|
|
2223
|
-
issues.push({ path, message: `must be an array; received ${valueType(value)}` });
|
|
2224
|
-
return;
|
|
2225
|
-
}
|
|
2226
|
-
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
2227
|
-
issues.push({ path, message: `must contain at least ${schema.minItems} item(s)` });
|
|
2228
|
-
}
|
|
2229
|
-
if (schema.uniqueItems) {
|
|
2230
|
-
const serialized = value.map((entry) => JSON.stringify(entry));
|
|
2231
|
-
if (new Set(serialized).size !== serialized.length) {
|
|
2232
|
-
issues.push({ path, message: "must not contain duplicate items" });
|
|
2233
|
-
}
|
|
2234
|
-
}
|
|
2235
|
-
if (schema.items) {
|
|
2236
|
-
value.forEach(
|
|
2237
|
-
(entry, index) => validateNode(entry, schema.items, `${path}[${index}]`, root, issues)
|
|
2238
|
-
);
|
|
2239
|
-
}
|
|
2240
|
-
return;
|
|
2241
|
-
}
|
|
2242
|
-
if (schema.type === "string") {
|
|
2243
|
-
if (typeof value !== "string") {
|
|
2244
|
-
issues.push({ path, message: `must be a string; received ${valueType(value)}` });
|
|
2245
|
-
return;
|
|
2246
|
-
}
|
|
2247
|
-
if (schema.minLength !== void 0 && value.length < schema.minLength) {
|
|
2248
|
-
issues.push({ path, message: `must contain at least ${schema.minLength} character(s)` });
|
|
2249
|
-
}
|
|
2250
|
-
return;
|
|
2251
|
-
}
|
|
2252
|
-
if (schema.type === "boolean") {
|
|
2253
|
-
if (typeof value !== "boolean") {
|
|
2254
|
-
issues.push({ path, message: `must be a boolean; received ${valueType(value)}` });
|
|
2255
|
-
}
|
|
2256
|
-
return;
|
|
2257
|
-
}
|
|
2258
|
-
if (schema.type === "integer") {
|
|
2259
|
-
if (!Number.isInteger(value)) {
|
|
2260
|
-
issues.push({ path, message: `must be an integer; received ${valueType(value)}` });
|
|
2261
|
-
return;
|
|
2262
|
-
}
|
|
2263
|
-
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
2264
|
-
issues.push({ path, message: `must be at least ${schema.minimum}` });
|
|
2265
|
-
}
|
|
2266
|
-
}
|
|
2267
|
-
}
|
|
2268
|
-
function defaultedConfig(input) {
|
|
2269
|
-
return {
|
|
2270
|
-
...input,
|
|
2271
|
-
$schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
|
|
2272
|
-
schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
|
|
2273
|
-
include: input.include === void 0 ? ["src"] : input.include,
|
|
2274
|
-
layers: input.layers === void 0 ? [] : input.layers,
|
|
2275
|
-
rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
|
|
2276
|
-
};
|
|
2277
|
-
}
|
|
2278
|
-
function migrateArkConfig(input, source = "ark.config.json") {
|
|
2279
|
-
if (!isObject(input)) {
|
|
2280
|
-
throw new ArkConfigValidationError(source, [
|
|
2281
|
-
{ path: "$", message: `must be an object; received ${valueType(input)}` }
|
|
2282
|
-
]);
|
|
2283
|
-
}
|
|
2284
|
-
const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
|
|
2285
|
-
if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
|
|
2286
|
-
throw new ArkConfigValidationError(source, [
|
|
2287
|
-
{
|
|
2288
|
-
path: "$.schemaVersion",
|
|
2289
|
-
message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
|
|
2290
|
-
}
|
|
2291
|
-
]);
|
|
2292
|
-
}
|
|
2293
|
-
return { candidate: defaultedConfig(input), migratedFrom };
|
|
2294
|
-
}
|
|
2295
|
-
function loadArkConfigContract(input, source = "ark.config.json") {
|
|
2296
|
-
const { candidate, migratedFrom } = migrateArkConfig(input, source);
|
|
2297
|
-
const issues = [];
|
|
2298
|
-
validateNode(
|
|
2299
|
-
candidate,
|
|
2300
|
-
ARK_CONFIG_SCHEMA,
|
|
2301
|
-
"$",
|
|
2302
|
-
ARK_CONFIG_SCHEMA,
|
|
2303
|
-
issues
|
|
2304
|
-
);
|
|
2305
|
-
if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
|
|
2306
|
-
return { config: candidate, migratedFrom };
|
|
2307
|
-
}
|
|
2308
|
-
function parseArkConfigJson(json, source = "ark.config.json") {
|
|
2309
|
-
let input;
|
|
2310
|
-
try {
|
|
2311
|
-
input = JSON.parse(json);
|
|
2312
|
-
} catch (error) {
|
|
2313
|
-
throw new ArkConfigValidationError(source, [
|
|
2314
|
-
{
|
|
2315
|
-
path: "$",
|
|
2316
|
-
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
2317
|
-
}
|
|
2318
|
-
]);
|
|
2319
|
-
}
|
|
2320
|
-
return loadArkConfigContract(input, source);
|
|
2321
|
-
}
|
|
2322
|
-
function withArkConfigMetadata(config) {
|
|
2323
|
-
const result = {
|
|
2324
|
-
$schema: typeof config.$schema === "string" && config.$schema.length > 0 ? config.$schema : ARK_CONFIG_SCHEMA_URL,
|
|
2325
|
-
schemaVersion: ARK_CONFIG_SCHEMA_VERSION
|
|
2326
|
-
};
|
|
2327
|
-
for (const [key, value] of Object.entries(config)) {
|
|
2328
|
-
if (key !== "$schema" && key !== "schemaVersion") result[key] = value;
|
|
2329
|
-
}
|
|
2330
|
-
return result;
|
|
2331
|
-
}
|
|
2332
|
-
|
|
2333
|
-
// src/kernel/layers/ArchitectureProfile.ts
|
|
2334
|
-
function normalizePrefix(prefix) {
|
|
2335
|
-
return prefix.endsWith(".") ? prefix : `${prefix}.`;
|
|
2336
|
-
}
|
|
2337
|
-
function byLongestPrefix(a, b) {
|
|
2338
|
-
const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
|
|
2339
|
-
const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
|
|
2340
|
-
return maxB - maxA;
|
|
2341
|
-
}
|
|
2342
|
-
function createArchitectureProfile(options) {
|
|
2343
|
-
const layers = options.layers.map((layer) => ({
|
|
2344
|
-
...layer,
|
|
2345
|
-
prefixes: layer.prefixes.map(normalizePrefix)
|
|
2346
|
-
}));
|
|
2347
|
-
const sortedLayers = [...layers].sort(byLongestPrefix);
|
|
2348
|
-
const rules = [...options.rules ?? []];
|
|
2349
|
-
return {
|
|
2350
|
-
name: options.name,
|
|
2351
|
-
layers,
|
|
2352
|
-
rules,
|
|
2353
|
-
resolveLayer(name) {
|
|
2354
|
-
return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
|
|
2355
|
-
(layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
|
|
2356
|
-
)?.name;
|
|
2357
|
-
}
|
|
2358
|
-
};
|
|
2359
|
-
}
|
|
2360
|
-
function createArchitectureProfileFromArkConfig(config, options = {}) {
|
|
2361
|
-
return createArchitectureProfile({
|
|
2362
|
-
name: options.name ?? config.name ?? "ark.config.json",
|
|
2363
|
-
layers: config.layers.map((layer, index) => ({
|
|
2364
|
-
name: layer.name,
|
|
2365
|
-
prefixes: layer.intentPrefixes ?? [],
|
|
2366
|
-
description: layer.description,
|
|
2367
|
-
order: index + 1
|
|
2368
|
-
})),
|
|
2369
|
-
rules: config.rules ?? []
|
|
2370
|
-
});
|
|
2371
|
-
}
|
|
2372
|
-
var elevenLayerProfileLayers = [
|
|
2373
|
-
{
|
|
2374
|
-
name: "DomainModel",
|
|
2375
|
-
prefixes: ["Domain"],
|
|
2376
|
-
description: "Rich domain model, business rules, and domain events.",
|
|
2377
|
-
order: 1
|
|
2378
|
-
},
|
|
2379
|
-
{
|
|
2380
|
-
name: "ApplicationOrchestration",
|
|
2381
|
-
prefixes: ["Application"],
|
|
2382
|
-
description: "Use cases and command orchestration.",
|
|
2383
|
-
order: 2
|
|
2384
|
-
},
|
|
2385
|
-
{
|
|
2386
|
-
name: "PersistenceAdapters",
|
|
2387
|
-
prefixes: ["Adapter.Persistence", "Adapter.Repository"],
|
|
2388
|
-
description: "Database, repository, and storage adapters.",
|
|
2389
|
-
order: 3
|
|
2390
|
-
},
|
|
2391
|
-
{
|
|
2392
|
-
name: "IntegrationAdapters",
|
|
2393
|
-
prefixes: ["Adapter.Integration", "Adapter.External"],
|
|
2394
|
-
description: "External systems, APIs, and integration adapters.",
|
|
2395
|
-
order: 4
|
|
2396
|
-
},
|
|
2397
|
-
{
|
|
2398
|
-
name: "WorkflowSagaEngine",
|
|
2399
|
-
prefixes: ["Workflow"],
|
|
2400
|
-
description: "Sagas, workflows, and long-running processes.",
|
|
2401
|
-
order: 5
|
|
2402
|
-
},
|
|
2403
|
-
{
|
|
2404
|
-
name: "BackgroundJobsScheduling",
|
|
2405
|
-
prefixes: ["Job"],
|
|
2406
|
-
description: "Background jobs, scheduled work, and async processors.",
|
|
2407
|
-
order: 6
|
|
2408
|
-
},
|
|
2409
|
-
{
|
|
2410
|
-
name: "PresentationAdapters",
|
|
2411
|
-
prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
|
|
2412
|
-
description: "API, UI, controller, and presentation adapters.",
|
|
2413
|
-
order: 7
|
|
2414
|
-
},
|
|
2415
|
-
{
|
|
2416
|
-
name: "ReportingReadModels",
|
|
2417
|
-
prefixes: ["Reporting"],
|
|
2418
|
-
description: "Read models, projections, and reporting surfaces.",
|
|
2419
|
-
order: 8
|
|
2420
|
-
},
|
|
2421
|
-
{
|
|
2422
|
-
name: "ExtensibilityMetadata",
|
|
2423
|
-
prefixes: ["Metadata"],
|
|
2424
|
-
description: "Metadata, extensions, and schema contracts.",
|
|
2425
|
-
order: 9
|
|
2426
|
-
},
|
|
2427
|
-
{
|
|
2428
|
-
name: "SecurityAuditObservability",
|
|
2429
|
-
prefixes: ["Security", "Audit", "Observability"],
|
|
2430
|
-
description: "Security, audit, and observability concerns.",
|
|
2431
|
-
order: 10
|
|
2432
|
-
},
|
|
2433
|
-
{
|
|
2434
|
-
name: "Kernel",
|
|
2435
|
-
prefixes: ["Kernel"],
|
|
2436
|
-
description: "Ark-owned governance and kernel signals.",
|
|
2437
|
-
order: 11
|
|
2438
|
-
}
|
|
2439
|
-
];
|
|
2440
|
-
var elevenLayerProfile = createArchitectureProfile({
|
|
2441
|
-
name: "Ark 11-layer Hexagonal Event-Driven Profile",
|
|
2442
|
-
layers: elevenLayerProfileLayers,
|
|
2443
|
-
rules: DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule }))
|
|
2444
|
-
});
|
|
2445
|
-
var defaultElevenLayerDirectories = {
|
|
2446
|
-
DomainModel: ["domain"],
|
|
2447
|
-
ApplicationOrchestration: ["application", "app"],
|
|
2448
|
-
PersistenceAdapters: [
|
|
2449
|
-
"adapters/persistence",
|
|
2450
|
-
"adapters/repository",
|
|
2451
|
-
"repositories",
|
|
2452
|
-
"infra/persistence"
|
|
2453
|
-
],
|
|
2454
|
-
IntegrationAdapters: ["adapters/integration", "adapters/external", "integrations"],
|
|
2455
|
-
WorkflowSagaEngine: ["workflows", "sagas"],
|
|
2456
|
-
BackgroundJobsScheduling: ["jobs", "schedules"],
|
|
2457
|
-
PresentationAdapters: ["presentation", "adapters/presentation", "adapters/api"],
|
|
2458
|
-
ReportingReadModels: ["reporting", "read-models", "projections"],
|
|
2459
|
-
ExtensibilityMetadata: ["metadata", "extensions"],
|
|
2460
|
-
SecurityAuditObservability: ["security", "audit", "observability"],
|
|
2461
|
-
Kernel: ["kernel"]
|
|
2462
|
-
};
|
|
2463
|
-
function createElevenLayerArkConfig(options = {}) {
|
|
2464
|
-
const rootDir = options.rootDir ?? "src";
|
|
2465
|
-
const optional = options.optionalLayers ?? true;
|
|
2466
|
-
const prefix = rootDir === "." ? "" : `${rootDir}/`;
|
|
2467
|
-
return withArkConfigMetadata({
|
|
2468
|
-
include: options.include ?? [rootDir],
|
|
2469
|
-
layers: elevenLayerProfile.layers.map((layer) => ({
|
|
2470
|
-
name: layer.name,
|
|
2471
|
-
patterns: (defaultElevenLayerDirectories[layer.name] ?? [layer.name]).map(
|
|
2472
|
-
(directory) => `${prefix}${directory}/**`
|
|
2473
|
-
),
|
|
2474
|
-
intentPrefixes: layer.prefixes,
|
|
2475
|
-
optional
|
|
2476
|
-
})),
|
|
2477
|
-
rules: [...elevenLayerProfile.rules]
|
|
2478
|
-
});
|
|
2479
|
-
}
|
|
2480
|
-
|
|
2481
|
-
// src/kernel/metadata/MetadataRegistry.ts
|
|
2482
|
-
var MetadataRegistryImpl = class {
|
|
2483
|
-
entities = /* @__PURE__ */ new Map();
|
|
2484
|
-
entity(name, meta, options = {}) {
|
|
2485
|
-
if (this.entities.has(name) && !options.allowOverwrite) {
|
|
2486
|
-
throw new Error(`Entity metadata "${name}" is already registered.`);
|
|
2487
|
-
}
|
|
2488
|
-
const full = { name, fields: {}, ...meta };
|
|
2489
|
-
this.entities.set(name, full);
|
|
2490
|
-
return full;
|
|
2491
|
-
}
|
|
2492
|
-
getEntity(name) {
|
|
2493
|
-
return this.entities.get(name);
|
|
2494
|
-
}
|
|
2495
|
-
listEntities() {
|
|
2496
|
-
return Array.from(this.entities.values());
|
|
2497
|
-
}
|
|
2498
|
-
findEntitiesByIntent(intentName) {
|
|
2499
|
-
return this.listEntities().filter(
|
|
2500
|
-
(entity) => entity.emits?.includes(intentName) || entity.consumes?.includes(intentName)
|
|
2501
|
-
);
|
|
2502
|
-
}
|
|
2503
|
-
validate() {
|
|
2504
|
-
const issues = [];
|
|
2505
|
-
for (const entity of this.entities.values()) {
|
|
2506
|
-
if (!entity.name.trim()) {
|
|
2507
|
-
issues.push({ entity: entity.name, message: "Entity name is required." });
|
|
2508
|
-
}
|
|
2509
|
-
for (const [fieldName, field] of Object.entries(entity.fields)) {
|
|
2510
|
-
if (!fieldName.trim()) {
|
|
2511
|
-
issues.push({ entity: entity.name, field: fieldName, message: "Field name is required." });
|
|
2512
|
-
}
|
|
2513
|
-
if (!field.type || typeof field.type !== "string") {
|
|
2514
|
-
issues.push({
|
|
2515
|
-
entity: entity.name,
|
|
2516
|
-
field: fieldName,
|
|
2517
|
-
message: "Field type must be a non-empty string."
|
|
2518
|
-
});
|
|
2519
|
-
}
|
|
2520
|
-
if (field.relation && !this.entities.has(field.relation.entity)) {
|
|
2521
|
-
issues.push({
|
|
2522
|
-
entity: entity.name,
|
|
2523
|
-
field: fieldName,
|
|
2524
|
-
message: `Related entity "${field.relation.entity}" is not registered.`
|
|
2525
|
-
});
|
|
2526
|
-
}
|
|
2527
|
-
}
|
|
2528
|
-
}
|
|
2529
|
-
return { ok: issues.length === 0, issues };
|
|
2530
|
-
}
|
|
2531
|
-
toJSON() {
|
|
2532
|
-
return this.listEntities();
|
|
2533
|
-
}
|
|
2534
|
-
};
|
|
2535
|
-
function createMetadataRegistry() {
|
|
2536
|
-
return new MetadataRegistryImpl();
|
|
2537
|
-
}
|
|
2538
|
-
|
|
2539
|
-
// src/kernel/adapters/ports.ts
|
|
2540
|
-
function definePort(name, options = {}) {
|
|
2541
|
-
return {
|
|
2542
|
-
name,
|
|
2543
|
-
ownerLayer: options.ownerLayer,
|
|
2544
|
-
intent: options.intent,
|
|
2545
|
-
allowedAdapters: options.allowedAdapters ? [...options.allowedAdapters] : void 0
|
|
2546
|
-
};
|
|
2547
|
-
}
|
|
2548
|
-
function createAdapter(port, impl, requiredKeysOrOptions, adapterOptions = {}) {
|
|
2549
|
-
const options = Array.isArray(requiredKeysOrOptions) ? { ...adapterOptions, requiredKeys: requiredKeysOrOptions } : { ...requiredKeysOrOptions ?? {} };
|
|
2550
|
-
const requiredKeys = options.requiredKeys;
|
|
2551
|
-
if (requiredKeys && requiredKeys.length > 0) {
|
|
2552
|
-
const missing = requiredKeys.filter((k) => !hasMember(impl, k));
|
|
2553
|
-
if (missing.length > 0) {
|
|
2554
|
-
throw new Error(
|
|
2555
|
-
`Adapter for port "${port.name}" is missing required members: ${missing.join(", ")}`
|
|
2556
|
-
);
|
|
2557
|
-
}
|
|
2558
|
-
}
|
|
2559
|
-
const adapter = {
|
|
2560
|
-
name: options.name,
|
|
2561
|
-
layer: options.layer,
|
|
2562
|
-
intent: options.intent,
|
|
2563
|
-
port,
|
|
2564
|
-
impl
|
|
2565
|
-
};
|
|
2566
|
-
const governance = checkAdapterGovernance(adapter);
|
|
2567
|
-
if (!governance.ok) {
|
|
2568
|
-
throw new Error(governance.issues.map((issue) => issue.message).join("\n"));
|
|
2569
|
-
}
|
|
2570
|
-
return adapter;
|
|
2571
|
-
}
|
|
2572
|
-
function checkContract(impl, requiredKeys = []) {
|
|
2573
|
-
const missing = requiredKeys.filter((k) => !hasMember(impl, k));
|
|
2574
|
-
return missing.length === 0 ? { ok: true } : { ok: false, missing };
|
|
2575
|
-
}
|
|
2576
|
-
function checkAdapterGovernance(adapter) {
|
|
2577
|
-
const allowed = adapter.port.allowedAdapters ?? [];
|
|
2578
|
-
if (allowed.length === 0) {
|
|
2579
|
-
return { ok: true, issues: [] };
|
|
2580
|
-
}
|
|
2581
|
-
const adapterNames = [adapter.name, adapter.intent].filter(
|
|
2582
|
-
(value) => typeof value === "string" && value.length > 0
|
|
2583
|
-
);
|
|
2584
|
-
const matched = adapterNames.some((name) => allowed.includes(name));
|
|
2585
|
-
if (matched) {
|
|
2586
|
-
return { ok: true, issues: [] };
|
|
2587
|
-
}
|
|
2588
|
-
return {
|
|
2589
|
-
ok: false,
|
|
2590
|
-
issues: [
|
|
2591
|
-
{
|
|
2592
|
-
ruleId: "ADAPTER_NOT_ALLOWED_FOR_PORT",
|
|
2593
|
-
port: adapter.port.name,
|
|
2594
|
-
adapter: adapter.name ?? adapter.intent,
|
|
2595
|
-
message: `Adapter "${adapter.name ?? adapter.intent ?? "unknown"}" is not allowed for port "${adapter.port.name}".`
|
|
2596
|
-
}
|
|
2597
|
-
]
|
|
2598
|
-
};
|
|
2599
|
-
}
|
|
2600
|
-
function hasMember(value, key) {
|
|
2601
|
-
return value != null && (typeof value === "object" || typeof value === "function") && key in value;
|
|
2602
|
-
}
|
|
2603
|
-
|
|
2604
|
-
// src/kernel/ai-gate/AICodeGate.ts
|
|
2605
|
-
function violation(ruleId, message, extra) {
|
|
2606
|
-
return { ruleId, code: ruleId, message, ...extra };
|
|
2607
|
-
}
|
|
2608
|
-
function lineOf(source, index) {
|
|
2609
|
-
return source.slice(0, index).split("\n").length;
|
|
2610
|
-
}
|
|
2611
|
-
function extractQuotedStrings(source) {
|
|
2612
|
-
const matches = [];
|
|
2613
|
-
const re = /['"`]([A-Za-z][A-Za-z0-9_.]*)['"`]/g;
|
|
2614
|
-
let m;
|
|
2615
|
-
while ((m = re.exec(source)) !== null) {
|
|
2616
|
-
matches.push({ value: m[1], index: m.index });
|
|
2617
|
-
}
|
|
2618
|
-
return matches;
|
|
2619
|
-
}
|
|
2620
|
-
function extractModuleSpecifiers(source) {
|
|
2621
|
-
const matches = [];
|
|
2622
|
-
const patterns = [
|
|
2623
|
-
{
|
|
2624
|
-
kind: "import",
|
|
2625
|
-
re: /\bimport\s+(?:type\s+)?(?:[^'"]*?\s+from\s*)?['"]([^'"]+)['"]/g
|
|
2626
|
-
},
|
|
2627
|
-
{
|
|
2628
|
-
kind: "export",
|
|
2629
|
-
re: /\bexport\s+(?:type\s+)?[^'"]*?\s+from\s*['"]([^'"]+)['"]/g
|
|
2630
|
-
},
|
|
2631
|
-
{
|
|
2632
|
-
kind: "dynamic-import",
|
|
2633
|
-
re: /\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g
|
|
2634
|
-
},
|
|
2635
|
-
{
|
|
2636
|
-
kind: "require",
|
|
2637
|
-
re: /\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g
|
|
2638
|
-
}
|
|
2639
|
-
];
|
|
2640
|
-
for (const pattern of patterns) {
|
|
2641
|
-
let match;
|
|
2642
|
-
while ((match = pattern.re.exec(source)) !== null) {
|
|
2643
|
-
const index = match.index + match[0].indexOf(match[1]);
|
|
2644
|
-
const raw = match[0];
|
|
2645
|
-
const typeOnly = pattern.kind === "import" && /\bimport\s+type\b/.test(raw) || pattern.kind === "export" && /\bexport\s+type\b/.test(raw);
|
|
2646
|
-
matches.push({ value: match[1], index, kind: pattern.kind, typeOnly });
|
|
2647
|
-
}
|
|
2648
|
-
}
|
|
2649
|
-
return matches.sort((a, b) => a.index - b.index);
|
|
2650
|
-
}
|
|
2651
|
-
function extractModuleSpecifiersAst(ts, source) {
|
|
2652
|
-
const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
|
|
2653
|
-
const matches = [];
|
|
2654
|
-
const push = (node, value, kind, typeOnly = false) => {
|
|
2655
|
-
matches.push({
|
|
2656
|
-
value,
|
|
2657
|
-
index: node.getStart(sourceFile),
|
|
2658
|
-
kind,
|
|
2659
|
-
typeOnly
|
|
2660
|
-
});
|
|
2661
|
-
};
|
|
2662
|
-
const visit = (node) => {
|
|
2663
|
-
if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
|
|
2664
|
-
const clause = node.importClause;
|
|
2665
|
-
const namedBindings = clause?.namedBindings;
|
|
2666
|
-
const specifiersOnly = clause && !clause.name && namedBindings && ts.isNamedImports(namedBindings) && namedBindings.elements.length > 0 && namedBindings.elements.every((element) => element.isTypeOnly === true);
|
|
2667
|
-
push(
|
|
2668
|
-
node.moduleSpecifier,
|
|
2669
|
-
node.moduleSpecifier.text,
|
|
2670
|
-
"import",
|
|
2671
|
-
Boolean(clause?.isTypeOnly || specifiersOnly)
|
|
2672
|
-
);
|
|
2673
|
-
} else if (ts.isExportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
|
|
2674
|
-
const clause = node.exportClause;
|
|
2675
|
-
const specifiersOnly = clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly === true);
|
|
2676
|
-
push(
|
|
2677
|
-
node.moduleSpecifier,
|
|
2678
|
-
node.moduleSpecifier.text,
|
|
2679
|
-
"export",
|
|
2680
|
-
Boolean(node.isTypeOnly || specifiersOnly)
|
|
2681
|
-
);
|
|
2682
|
-
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
|
2683
|
-
const argument = node.moduleReference.expression;
|
|
2684
|
-
const value = tsStringLiteralText(ts, argument);
|
|
2685
|
-
if (value !== void 0) push(argument, value, "require");
|
|
2686
|
-
} else if (ts.isCallExpression(node)) {
|
|
2687
|
-
const argument = node.arguments[0];
|
|
2688
|
-
const value = tsStringLiteralText(ts, argument);
|
|
2689
|
-
if (value !== void 0 && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
|
|
2690
|
-
push(argument, value, "dynamic-import");
|
|
2691
|
-
} else if (value !== void 0 && ts.isIdentifier(node.expression) && node.expression.text === "require") {
|
|
2692
|
-
push(argument, value, "require");
|
|
2693
|
-
}
|
|
2694
|
-
}
|
|
2695
|
-
ts.forEachChild(node, visit);
|
|
2696
|
-
};
|
|
2697
|
-
visit(sourceFile);
|
|
2698
|
-
return matches.sort((a, b) => a.index - b.index);
|
|
2699
|
-
}
|
|
2700
|
-
function nonLiteralDynamicDependencies(ts, source) {
|
|
2701
|
-
const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
|
|
2702
|
-
const uses = [];
|
|
2703
|
-
const visit = (node) => {
|
|
2704
|
-
if (ts.isCallExpression(node)) {
|
|
2705
|
-
const dynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
|
|
2706
|
-
const directRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
|
|
2707
|
-
const argument = node.arguments[0];
|
|
2708
|
-
if ((dynamicImport || directRequire) && (!argument || !ts.isStringLiteralLike(argument))) {
|
|
2709
|
-
uses.push({
|
|
2710
|
-
line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
|
|
2711
|
-
kind: directRequire ? "require" : "import"
|
|
2712
|
-
});
|
|
2713
|
-
}
|
|
2714
|
-
}
|
|
2715
|
-
ts.forEachChild(node, visit);
|
|
2716
|
-
};
|
|
2717
|
-
visit(sourceFile);
|
|
2718
|
-
return uses;
|
|
2719
|
-
}
|
|
2720
|
-
function extractQuotedStringsAst(ts, source) {
|
|
2721
|
-
const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
|
|
2722
|
-
const matches = [];
|
|
2723
|
-
const visit = (node) => {
|
|
2724
|
-
if (ts.isStringLiteralLike(node)) {
|
|
2725
|
-
matches.push({ value: node.text, index: node.getStart(sourceFile) });
|
|
2726
|
-
}
|
|
2727
|
-
ts.forEachChild(node, visit);
|
|
2728
|
-
};
|
|
2729
|
-
visit(sourceFile);
|
|
2730
|
-
return matches;
|
|
2731
|
-
}
|
|
2732
|
-
function looksLikeIntentName(s) {
|
|
2733
|
-
return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(s);
|
|
2734
|
-
}
|
|
2735
|
-
function hasInfrastructureToken(specifier) {
|
|
2736
|
-
const tokens = specifier.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
|
|
2737
|
-
return [
|
|
2738
|
-
"adapter",
|
|
2739
|
-
"adapters",
|
|
2740
|
-
"infra",
|
|
2741
|
-
"infrastructure",
|
|
2742
|
-
"persistence",
|
|
2743
|
-
"repository",
|
|
2744
|
-
"repositories",
|
|
2745
|
-
"integration",
|
|
2746
|
-
"database",
|
|
2747
|
-
"db"
|
|
2748
|
-
].some((token) => tokens.includes(token));
|
|
2749
|
-
}
|
|
2750
|
-
function isKnownInfrastructurePackage(specifier) {
|
|
2751
|
-
const normalized = specifier.toLowerCase();
|
|
2752
|
-
return ["sequelize", "prisma", "typeorm", "mongoose", "knex"].some(
|
|
2753
|
-
(name) => normalized === name || normalized.startsWith(`${name}/`)
|
|
2754
|
-
);
|
|
2755
|
-
}
|
|
2756
|
-
function layerHasInfrastructureRole(layerName) {
|
|
2757
|
-
const normalized = layerName.toLowerCase();
|
|
2758
|
-
return [
|
|
2759
|
-
"adapter",
|
|
2760
|
-
"infra",
|
|
2761
|
-
"persistence",
|
|
2762
|
-
"repository",
|
|
2763
|
-
"repositories",
|
|
2764
|
-
"integration",
|
|
2765
|
-
"database"
|
|
2766
|
-
].some((token) => normalized.includes(token));
|
|
2767
|
-
}
|
|
2768
|
-
function tsStringLiteralText(ts, node) {
|
|
2769
|
-
return node && ts.isStringLiteralLike(node) ? node.text : void 0;
|
|
2770
|
-
}
|
|
2771
|
-
function tsPropertyName(ts, node) {
|
|
2772
|
-
if (!node) return void 0;
|
|
2773
|
-
if (ts.isIdentifier(node) || ts.isStringLiteralLike(node)) return node.text;
|
|
2774
|
-
return void 0;
|
|
2775
|
-
}
|
|
2776
|
-
function tsObjectProperty(ts, node, name) {
|
|
2777
|
-
if (!node || !ts.isObjectLiteralExpression(node)) return void 0;
|
|
2778
|
-
return node.properties.find((property) => {
|
|
2779
|
-
if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property)) {
|
|
2780
|
-
return false;
|
|
2781
|
-
}
|
|
2782
|
-
return tsPropertyName(ts, property.name) === name;
|
|
2783
|
-
});
|
|
2784
|
-
}
|
|
2785
|
-
function tsObjectHasProperty(ts, node, name) {
|
|
2786
|
-
return tsObjectProperty(ts, node, name) !== void 0;
|
|
2787
|
-
}
|
|
2788
|
-
function tsObjectPropertyValue(ts, node, name) {
|
|
2789
|
-
const property = tsObjectProperty(ts, node, name);
|
|
2790
|
-
return property && ts.isPropertyAssignment(property) ? property.initializer : void 0;
|
|
2791
|
-
}
|
|
2792
|
-
function tsObjectHasMetadataSource(ts, node) {
|
|
2793
|
-
const metadata = tsObjectPropertyValue(ts, node, "metadata");
|
|
2794
|
-
return tsObjectHasProperty(ts, metadata, "source");
|
|
2795
|
-
}
|
|
2796
|
-
function tsLooksLikeIntentCreatorExpression(ts, node) {
|
|
2797
|
-
if (!node) return false;
|
|
2798
|
-
if (ts.isIdentifier(node)) return /^[A-Z]/.test(node.text);
|
|
2799
|
-
if (ts.isPropertyAccessExpression(node)) {
|
|
2800
|
-
return tsLooksLikeIntentCreatorExpression(ts, node.name);
|
|
2801
|
-
}
|
|
2802
|
-
return false;
|
|
2803
|
-
}
|
|
2804
|
-
function tsIsPublishCall(ts, node) {
|
|
2805
|
-
if (!ts.isCallExpression(node)) return false;
|
|
2806
|
-
const expression = node.expression;
|
|
2807
|
-
if (ts.isPropertyAccessExpression(expression)) {
|
|
2808
|
-
return expression.name.text === "publish";
|
|
645
|
+
return false;
|
|
646
|
+
}
|
|
647
|
+
function tsIsPublishCall(ts, node) {
|
|
648
|
+
if (!ts.isCallExpression(node)) return false;
|
|
649
|
+
const expression = node.expression;
|
|
650
|
+
if (ts.isPropertyAccessExpression(expression)) {
|
|
651
|
+
return expression.name.text === "publish";
|
|
2809
652
|
}
|
|
2810
653
|
return ts.isIdentifier(expression) && expression.text === "publish";
|
|
2811
654
|
}
|
|
@@ -2813,7 +656,7 @@ function tsIsArkPublishCandidate(ts, node) {
|
|
|
2813
656
|
if (!ts.isCallExpression(node)) return false;
|
|
2814
657
|
const firstArg = node.arguments[0];
|
|
2815
658
|
const rawIntent = tsStringLiteralText(ts, firstArg);
|
|
2816
|
-
return rawIntent !== void 0 &&
|
|
659
|
+
return rawIntent !== void 0 && looksLikeArkIntent(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent") || tsLooksLikeIntentCreatorExpression(ts, firstArg);
|
|
2817
660
|
}
|
|
2818
661
|
function tsPublishHasSource(ts, node) {
|
|
2819
662
|
if (!ts.isCallExpression(node)) return false;
|
|
@@ -2826,80 +669,6 @@ function tsPublishSourceLiteral(ts, node) {
|
|
|
2826
669
|
const rawMetadata = tsObjectPropertyValue(ts, firstArg, "metadata");
|
|
2827
670
|
return tsStringLiteralText(ts, tsObjectPropertyValue(ts, rawMetadata, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, secondArg, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, thirdArg, "source"));
|
|
2828
671
|
}
|
|
2829
|
-
function singleFileTypeChecker(ts, sourceFile) {
|
|
2830
|
-
const options = {
|
|
2831
|
-
noLib: true,
|
|
2832
|
-
noResolve: true,
|
|
2833
|
-
target: ts.ScriptTarget.Latest
|
|
2834
|
-
};
|
|
2835
|
-
const host = ts.createCompilerHost(options, true);
|
|
2836
|
-
host.getSourceFile = (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0;
|
|
2837
|
-
host.fileExists = (fileName) => fileName === sourceFile.fileName;
|
|
2838
|
-
host.readFile = (fileName) => fileName === sourceFile.fileName ? sourceFile.text : void 0;
|
|
2839
|
-
return ts.createProgram([sourceFile.fileName], options, host).getTypeChecker();
|
|
2840
|
-
}
|
|
2841
|
-
function propertyAccessPath(ts, node) {
|
|
2842
|
-
const segments = [];
|
|
2843
|
-
let current = node;
|
|
2844
|
-
while (ts.isPropertyAccessExpression(current)) {
|
|
2845
|
-
segments.unshift(current.name.text);
|
|
2846
|
-
current = current.expression;
|
|
2847
|
-
}
|
|
2848
|
-
if (!ts.isIdentifier(current)) return void 0;
|
|
2849
|
-
segments.unshift(current.text);
|
|
2850
|
-
return { root: current, segments };
|
|
2851
|
-
}
|
|
2852
|
-
function isRuntimeIdentifierReference(ts, node) {
|
|
2853
|
-
if (ts.isPropertyAccessExpression(node.parent) && node.parent.name === node) return false;
|
|
2854
|
-
return ts.isExpressionNode(node) && !ts.isInTypeQuery(node) || ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
|
|
2855
|
-
}
|
|
2856
|
-
function hasLocalDeclaration(ts, checker, sourceFile, node) {
|
|
2857
|
-
const shorthand = ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
|
|
2858
|
-
const symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(node.parent) : checker.getSymbolAtLocation(node);
|
|
2859
|
-
return Boolean(
|
|
2860
|
-
symbol?.declarations?.some((declaration) => declaration.getSourceFile() === sourceFile)
|
|
2861
|
-
);
|
|
2862
|
-
}
|
|
2863
|
-
function analyzeForbiddenGlobals(ts, source, filePath, layer, forbidden) {
|
|
2864
|
-
const entries = new Set(forbidden);
|
|
2865
|
-
if (entries.size === 0) return [];
|
|
2866
|
-
const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
|
|
2867
|
-
const checker = singleFileTypeChecker(ts, sourceFile);
|
|
2868
|
-
const violations = [];
|
|
2869
|
-
const flag = (name, node) => violations.push(
|
|
2870
|
-
violation("FORBIDDEN_GLOBAL", `${layer} must not use the ambient global "${name}".`, {
|
|
2871
|
-
line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
|
|
2872
|
-
filePath,
|
|
2873
|
-
target: name,
|
|
2874
|
-
fromLayer: layer,
|
|
2875
|
-
suggestion: "Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."
|
|
2876
|
-
})
|
|
2877
|
-
);
|
|
2878
|
-
const visit = (node) => {
|
|
2879
|
-
const nestedPropertyAccess = ts.isPropertyAccessExpression(node) && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node;
|
|
2880
|
-
if (ts.isPropertyAccessExpression(node) && !nestedPropertyAccess) {
|
|
2881
|
-
const path = propertyAccessPath(ts, node);
|
|
2882
|
-
if (path && !hasLocalDeclaration(ts, checker, sourceFile, path.root)) {
|
|
2883
|
-
const explicitGlobalThis = path.segments[0] === "globalThis";
|
|
2884
|
-
const normalized = explicitGlobalThis ? path.segments.slice(1) : path.segments;
|
|
2885
|
-
let match;
|
|
2886
|
-
for (let length = normalized.length; length >= (explicitGlobalThis ? 1 : 2); length -= 1) {
|
|
2887
|
-
const candidate = normalized.slice(0, length).join(".");
|
|
2888
|
-
if (entries.has(candidate)) {
|
|
2889
|
-
match = candidate;
|
|
2890
|
-
break;
|
|
2891
|
-
}
|
|
2892
|
-
}
|
|
2893
|
-
if (match) flag(match, node);
|
|
2894
|
-
}
|
|
2895
|
-
} else if (ts.isIdentifier(node) && entries.has(node.text) && isRuntimeIdentifierReference(ts, node) && !hasLocalDeclaration(ts, checker, sourceFile, node)) {
|
|
2896
|
-
flag(node.text, node);
|
|
2897
|
-
}
|
|
2898
|
-
ts.forEachChild(node, visit);
|
|
2899
|
-
};
|
|
2900
|
-
visit(sourceFile);
|
|
2901
|
-
return violations;
|
|
2902
|
-
}
|
|
2903
672
|
function analyzePublishAst(ts, source, context, profile) {
|
|
2904
673
|
const sourceFile = ts.createSourceFile(
|
|
2905
674
|
"generated.ts",
|
|
@@ -2914,26 +683,21 @@ function analyzePublishAst(ts, source, context, profile) {
|
|
|
2914
683
|
const lineForNode = (node) => sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
|
|
2915
684
|
const visit = (node) => {
|
|
2916
685
|
if (tsIsPublishCall(ts, node)) {
|
|
2917
|
-
const firstArg = node.arguments[0];
|
|
2918
|
-
const rawIntent = tsStringLiteralText(ts, firstArg);
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
2922
|
-
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
}
|
|
2927
|
-
if (tsIsArkPublishCandidate(ts, node) && !tsPublishHasSource(ts, node)) {
|
|
686
|
+
const firstArg = node.arguments[0];
|
|
687
|
+
const rawIntent = tsStringLiteralText(ts, firstArg);
|
|
688
|
+
for (const finding of classifyPublishFacts({
|
|
689
|
+
publishCall: true,
|
|
690
|
+
rawIntentName: rawIntent,
|
|
691
|
+
objectHasIntent: tsObjectHasProperty(ts, firstArg, "intent"),
|
|
692
|
+
arkPublishCandidate: tsIsArkPublishCandidate(ts, node),
|
|
693
|
+
hasSource: tsPublishHasSource(ts, node)
|
|
694
|
+
})) {
|
|
2928
695
|
violations.push(
|
|
2929
|
-
violation(
|
|
2930
|
-
line: lineForNode(node),
|
|
2931
|
-
filePath
|
|
2932
|
-
})
|
|
696
|
+
violation(finding.ruleId, finding.message, { line: lineForNode(node), filePath })
|
|
2933
697
|
);
|
|
2934
698
|
}
|
|
2935
699
|
const sourceIntent = tsPublishSourceLiteral(ts, node);
|
|
2936
|
-
if (profile && contextLayer && sourceIntent &&
|
|
700
|
+
if (profile && contextLayer && sourceIntent && looksLikeArkIntent(sourceIntent)) {
|
|
2937
701
|
const sourceLayer = profile.resolveLayer(sourceIntent);
|
|
2938
702
|
if (sourceLayer && sourceLayer !== contextLayer) {
|
|
2939
703
|
violations.push(
|
|
@@ -2970,10 +734,23 @@ function createAICodeGate(options = {}) {
|
|
|
2970
734
|
const gateContext = context;
|
|
2971
735
|
const filePath = gateContext?.filePath;
|
|
2972
736
|
const contextLayer = gateContext?.layer;
|
|
2973
|
-
const
|
|
737
|
+
const semanticTypescript = options.typescript;
|
|
738
|
+
const semanticSourceFile = semanticTypescript ? semanticTypescript.createSourceFile(
|
|
739
|
+
filePath ?? "generated.ts",
|
|
740
|
+
source,
|
|
741
|
+
semanticTypescript.ScriptTarget.Latest,
|
|
742
|
+
true
|
|
743
|
+
) : void 0;
|
|
744
|
+
const semanticDependencies = semanticSourceFile ? extractSemanticDependencies(options.typescript, semanticSourceFile) : void 0;
|
|
745
|
+
const moduleSpecifiers2 = semanticDependencies ? semanticDependencies.filter((dependency) => dependency.specifier !== void 0).map((dependency) => ({
|
|
746
|
+
value: dependency.specifier,
|
|
747
|
+
index: dependency.node.getStart(semanticSourceFile),
|
|
748
|
+
kind: dependency.kind,
|
|
749
|
+
typeOnly: dependency.typeOnly
|
|
750
|
+
})) : extractModuleSpecifiers(source);
|
|
2974
751
|
const quotedStrings = options.typescript ? extractQuotedStringsAst(options.typescript, source) : extractQuotedStrings(source);
|
|
2975
752
|
if (options.typescript && !options.allowNonLiteralDynamicImport?.(filePath)) {
|
|
2976
|
-
for (const dependency of
|
|
753
|
+
for (const dependency of semanticDependencies?.filter(({ unresolved }) => unresolved) ?? []) {
|
|
2977
754
|
const isRequire = dependency.kind === "require";
|
|
2978
755
|
violations.push(
|
|
2979
756
|
violation(
|
|
@@ -2994,7 +771,7 @@ function createAICodeGate(options = {}) {
|
|
|
2994
771
|
if (match) {
|
|
2995
772
|
violations.push(
|
|
2996
773
|
violation("FORBIDDEN_PATTERN", `Forbidden pattern matched: ${pat}`, {
|
|
2997
|
-
line: match.index === void 0 ? void 0 :
|
|
774
|
+
line: match.index === void 0 ? void 0 : lineOf2(source, match.index),
|
|
2998
775
|
filePath,
|
|
2999
776
|
suggestion: "Remove infrastructure imports from domain/application layers." + infraLayerEscapeHatch
|
|
3000
777
|
})
|
|
@@ -3003,7 +780,7 @@ function createAICodeGate(options = {}) {
|
|
|
3003
780
|
} else if (source.includes(pat)) {
|
|
3004
781
|
violations.push(
|
|
3005
782
|
violation("FORBIDDEN_SUBSTRING", `Forbidden substring: ${pat}`, {
|
|
3006
|
-
line:
|
|
783
|
+
line: lineOf2(source, source.indexOf(pat)),
|
|
3007
784
|
filePath
|
|
3008
785
|
})
|
|
3009
786
|
);
|
|
@@ -3034,7 +811,7 @@ function createAICodeGate(options = {}) {
|
|
|
3034
811
|
"LAYER_IMPORT_VIOLATION",
|
|
3035
812
|
blocked.message ?? (peer ? `Layer "${contextLayer}" must not import across slices into "${targetLayer}".` : `Layer "${contextLayer}" must not import "${targetLayer}".`),
|
|
3036
813
|
{
|
|
3037
|
-
line:
|
|
814
|
+
line: lineOf2(source, specifier.index),
|
|
3038
815
|
source: specifier.value,
|
|
3039
816
|
target: specifier.value,
|
|
3040
817
|
filePath,
|
|
@@ -3064,7 +841,7 @@ function createAICodeGate(options = {}) {
|
|
|
3064
841
|
"FORBIDDEN_IMPORT",
|
|
3065
842
|
`Forbidden ${specifier.kind} target: "${specifier.value}".`,
|
|
3066
843
|
{
|
|
3067
|
-
line:
|
|
844
|
+
line: lineOf2(source, specifier.index),
|
|
3068
845
|
source: specifier.value,
|
|
3069
846
|
target: specifier.value,
|
|
3070
847
|
filePath,
|
|
@@ -3099,114 +876,587 @@ function createAICodeGate(options = {}) {
|
|
|
3099
876
|
}
|
|
3100
877
|
}
|
|
3101
878
|
}
|
|
3102
|
-
if (enforceAllowlist && intentNames.size > 0) {
|
|
3103
|
-
for (const literal of quotedStrings) {
|
|
3104
|
-
if (
|
|
3105
|
-
violations.push(
|
|
3106
|
-
violation(
|
|
3107
|
-
"UNKNOWN_INTENT",
|
|
3108
|
-
`Unknown intent reference: "${literal.value}"`,
|
|
3109
|
-
{
|
|
3110
|
-
line:
|
|
3111
|
-
filePath,
|
|
3112
|
-
target: literal.value,
|
|
3113
|
-
suggestion: `Register intent "${literal.value}" via defineIntent() or remove the reference.`
|
|
3114
|
-
}
|
|
3115
|
-
)
|
|
3116
|
-
);
|
|
3117
|
-
}
|
|
879
|
+
if (enforceAllowlist && intentNames.size > 0) {
|
|
880
|
+
for (const literal of quotedStrings) {
|
|
881
|
+
if (looksLikeArkIntent(literal.value) && !intentNames.has(literal.value)) {
|
|
882
|
+
violations.push(
|
|
883
|
+
violation(
|
|
884
|
+
"UNKNOWN_INTENT",
|
|
885
|
+
`Unknown intent reference: "${literal.value}"`,
|
|
886
|
+
{
|
|
887
|
+
line: lineOf2(source, literal.index),
|
|
888
|
+
filePath,
|
|
889
|
+
target: literal.value,
|
|
890
|
+
suggestion: `Register intent "${literal.value}" via defineIntent() or remove the reference.`
|
|
891
|
+
}
|
|
892
|
+
)
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
if (options.architectureProfile && contextLayer) {
|
|
898
|
+
for (const literal of quotedStrings) {
|
|
899
|
+
if (!looksLikeArkIntent(literal.value)) continue;
|
|
900
|
+
const targetLayer = options.architectureProfile.resolveLayer(literal.value);
|
|
901
|
+
if (!targetLayer) continue;
|
|
902
|
+
const blocked = findDeniedEdgeRule(
|
|
903
|
+
options.architectureProfile.rules,
|
|
904
|
+
contextLayer,
|
|
905
|
+
targetLayer
|
|
906
|
+
);
|
|
907
|
+
if (blocked) {
|
|
908
|
+
violations.push(
|
|
909
|
+
violation(
|
|
910
|
+
"LAYER_REFERENCE_VIOLATION",
|
|
911
|
+
blocked.message ?? `Layer "${contextLayer}" must not reference "${targetLayer}" through "${literal.value}".`,
|
|
912
|
+
{
|
|
913
|
+
line: lineOf2(source, literal.index),
|
|
914
|
+
filePath,
|
|
915
|
+
target: literal.value,
|
|
916
|
+
fromLayer: contextLayer,
|
|
917
|
+
toLayer: targetLayer,
|
|
918
|
+
suggestion: "Route the dependency through an allowed intent, port, or event.",
|
|
919
|
+
details: { rule: blocked }
|
|
920
|
+
}
|
|
921
|
+
)
|
|
922
|
+
);
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
if (options.extensions) {
|
|
927
|
+
for (const ext of options.extensions) {
|
|
928
|
+
try {
|
|
929
|
+
const extViolations = ext.analyze(source, context);
|
|
930
|
+
violations.push(...extViolations);
|
|
931
|
+
} catch (err) {
|
|
932
|
+
violations.push(
|
|
933
|
+
violation(
|
|
934
|
+
"EXTENSION_ERROR",
|
|
935
|
+
`Extension "${ext.name}" failed: ${err instanceof Error ? err.message : String(err)}`
|
|
936
|
+
)
|
|
937
|
+
);
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
if (options.typescript && semanticSourceFile && contextLayer && options.forbiddenGlobals?.[contextLayer]?.length) {
|
|
942
|
+
try {
|
|
943
|
+
violations.push(
|
|
944
|
+
...collectForbiddenCapabilityUses(
|
|
945
|
+
options.typescript,
|
|
946
|
+
semanticSourceFile,
|
|
947
|
+
options.forbiddenGlobals[contextLayer]
|
|
948
|
+
).map(
|
|
949
|
+
(use) => violation(
|
|
950
|
+
"FORBIDDEN_GLOBAL",
|
|
951
|
+
`${contextLayer} must not use the ambient global "${use.name}".`,
|
|
952
|
+
{
|
|
953
|
+
line: use.line,
|
|
954
|
+
filePath,
|
|
955
|
+
target: use.name,
|
|
956
|
+
fromLayer: contextLayer,
|
|
957
|
+
suggestion: "Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."
|
|
958
|
+
}
|
|
959
|
+
)
|
|
960
|
+
)
|
|
961
|
+
);
|
|
962
|
+
} catch (err) {
|
|
963
|
+
violations.push(
|
|
964
|
+
violation(
|
|
965
|
+
"AST_ANALYZER_ERROR",
|
|
966
|
+
`TypeScript AST analyzer failed: ${err instanceof Error ? err.message : String(err)}`
|
|
967
|
+
)
|
|
968
|
+
);
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
if (options.typescript) {
|
|
972
|
+
try {
|
|
973
|
+
violations.push(
|
|
974
|
+
...analyzePublishAst(
|
|
975
|
+
options.typescript,
|
|
976
|
+
source,
|
|
977
|
+
context,
|
|
978
|
+
options.architectureProfile
|
|
979
|
+
)
|
|
980
|
+
);
|
|
981
|
+
} catch (err) {
|
|
982
|
+
violations.push(
|
|
983
|
+
violation(
|
|
984
|
+
"AST_ANALYZER_ERROR",
|
|
985
|
+
`TypeScript AST analyzer failed: ${err instanceof Error ? err.message : String(err)}`
|
|
986
|
+
)
|
|
987
|
+
);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
return {
|
|
991
|
+
valid: violations.length === 0,
|
|
992
|
+
violations
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
// src/domain/configContract.ts
|
|
999
|
+
var ARK_CONFIG_SCHEMA_VERSION = "1.0";
|
|
1000
|
+
var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
|
|
1001
|
+
var DEFAULT_LAYER_NAMES = [
|
|
1002
|
+
"DomainModel",
|
|
1003
|
+
"ApplicationOrchestration",
|
|
1004
|
+
"PersistenceAdapters",
|
|
1005
|
+
"IntegrationAdapters",
|
|
1006
|
+
"WorkflowSagaEngine",
|
|
1007
|
+
"BackgroundJobsScheduling",
|
|
1008
|
+
"PresentationAdapters",
|
|
1009
|
+
"ReportingReadModels",
|
|
1010
|
+
"ExtensibilityMetadata",
|
|
1011
|
+
"SecurityAuditObservability",
|
|
1012
|
+
"Kernel"
|
|
1013
|
+
];
|
|
1014
|
+
var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
|
|
1015
|
+
"PresentationAdapters->ApplicationOrchestration",
|
|
1016
|
+
"ApplicationOrchestration->DomainModel",
|
|
1017
|
+
"WorkflowSagaEngine->ApplicationOrchestration",
|
|
1018
|
+
"WorkflowSagaEngine->DomainModel",
|
|
1019
|
+
"BackgroundJobsScheduling->ApplicationOrchestration"
|
|
1020
|
+
]);
|
|
1021
|
+
function createDefaultRules() {
|
|
1022
|
+
const rules = [];
|
|
1023
|
+
for (const from of DEFAULT_LAYER_NAMES) {
|
|
1024
|
+
for (const to of DEFAULT_LAYER_NAMES) {
|
|
1025
|
+
if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
|
|
1026
|
+
rules.push({ from, to, allowed: false });
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
return rules;
|
|
1030
|
+
}
|
|
1031
|
+
var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
|
|
1032
|
+
var stringArraySchema = {
|
|
1033
|
+
type: "array",
|
|
1034
|
+
items: { type: "string", minLength: 1 },
|
|
1035
|
+
uniqueItems: true
|
|
1036
|
+
};
|
|
1037
|
+
var ARK_CONFIG_SCHEMA = {
|
|
1038
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
1039
|
+
$id: ARK_CONFIG_SCHEMA_URL,
|
|
1040
|
+
title: "ArkGate architecture contract",
|
|
1041
|
+
description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
|
|
1042
|
+
type: "object",
|
|
1043
|
+
additionalProperties: false,
|
|
1044
|
+
required: ["$schema", "schemaVersion", "include", "layers", "rules"],
|
|
1045
|
+
properties: {
|
|
1046
|
+
$schema: {
|
|
1047
|
+
type: "string",
|
|
1048
|
+
minLength: 1,
|
|
1049
|
+
default: ARK_CONFIG_SCHEMA_URL,
|
|
1050
|
+
description: "Editor-facing URL or local path for this JSON Schema."
|
|
1051
|
+
},
|
|
1052
|
+
schemaVersion: {
|
|
1053
|
+
type: "string",
|
|
1054
|
+
const: ARK_CONFIG_SCHEMA_VERSION,
|
|
1055
|
+
default: ARK_CONFIG_SCHEMA_VERSION
|
|
1056
|
+
},
|
|
1057
|
+
name: { type: "string", minLength: 1 },
|
|
1058
|
+
include: { ...stringArraySchema, minItems: 1, default: ["src"] },
|
|
1059
|
+
exclude: { ...stringArraySchema, default: [] },
|
|
1060
|
+
excludeGenerated: { type: "boolean", default: true },
|
|
1061
|
+
frameworkOverlay: { type: "string", minLength: 1 },
|
|
1062
|
+
layers: {
|
|
1063
|
+
type: "array",
|
|
1064
|
+
default: [],
|
|
1065
|
+
items: { $ref: "#/$defs/layer" }
|
|
1066
|
+
},
|
|
1067
|
+
rules: {
|
|
1068
|
+
type: "array",
|
|
1069
|
+
default: DEFAULT_ARK_CONFIG_RULES,
|
|
1070
|
+
items: { $ref: "#/$defs/rule" }
|
|
1071
|
+
},
|
|
1072
|
+
cyclePolicy: {
|
|
1073
|
+
type: "string",
|
|
1074
|
+
enum: ["strict", "soft", "framework-soft", "off"],
|
|
1075
|
+
default: "strict"
|
|
1076
|
+
},
|
|
1077
|
+
dynamicImportAllowlist: { ...stringArraySchema, default: [] },
|
|
1078
|
+
safety: {
|
|
1079
|
+
$ref: "#/$defs/safety",
|
|
1080
|
+
default: {
|
|
1081
|
+
maxTsSuppressions: 0,
|
|
1082
|
+
maxAnyCasts: 0,
|
|
1083
|
+
allowInMemory: false,
|
|
1084
|
+
allowDisabledPeerIsolation: false
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
},
|
|
1088
|
+
$defs: {
|
|
1089
|
+
layer: {
|
|
1090
|
+
type: "object",
|
|
1091
|
+
additionalProperties: false,
|
|
1092
|
+
required: ["name", "patterns"],
|
|
1093
|
+
properties: {
|
|
1094
|
+
name: { type: "string", minLength: 1 },
|
|
1095
|
+
patterns: { ...stringArraySchema, minItems: 1 },
|
|
1096
|
+
exclude: stringArraySchema,
|
|
1097
|
+
intentPrefixes: stringArraySchema,
|
|
1098
|
+
description: { type: "string", minLength: 1 },
|
|
1099
|
+
forbiddenGlobals: stringArraySchema,
|
|
1100
|
+
mayImportInfrastructure: { type: "boolean" },
|
|
1101
|
+
optional: { type: "boolean" }
|
|
1102
|
+
}
|
|
1103
|
+
},
|
|
1104
|
+
rule: {
|
|
1105
|
+
type: "object",
|
|
1106
|
+
additionalProperties: false,
|
|
1107
|
+
required: ["from", "to", "allowed"],
|
|
1108
|
+
properties: {
|
|
1109
|
+
from: { type: "string", minLength: 1 },
|
|
1110
|
+
to: { type: "string", minLength: 1 },
|
|
1111
|
+
allowed: { type: "boolean" },
|
|
1112
|
+
message: { type: "string", minLength: 1 },
|
|
1113
|
+
peerIsolation: { type: "boolean" },
|
|
1114
|
+
sliceFolders: { ...stringArraySchema, minItems: 1 }
|
|
1115
|
+
}
|
|
1116
|
+
},
|
|
1117
|
+
safety: {
|
|
1118
|
+
type: "object",
|
|
1119
|
+
additionalProperties: false,
|
|
1120
|
+
properties: {
|
|
1121
|
+
maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
|
|
1122
|
+
maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
|
|
1123
|
+
allowInMemory: { type: "boolean", default: false },
|
|
1124
|
+
allowDisabledPeerIsolation: { type: "boolean", default: false }
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
};
|
|
1129
|
+
var ArkConfigValidationError = class extends Error {
|
|
1130
|
+
issues;
|
|
1131
|
+
source;
|
|
1132
|
+
constructor(source, issues) {
|
|
1133
|
+
super(
|
|
1134
|
+
`Invalid ArkGate config (${source}):
|
|
1135
|
+
${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
|
|
1136
|
+
);
|
|
1137
|
+
this.name = "ArkConfigValidationError";
|
|
1138
|
+
this.source = source;
|
|
1139
|
+
this.issues = issues;
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
function isObject(value) {
|
|
1143
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1144
|
+
}
|
|
1145
|
+
function propertyPath(parent, key) {
|
|
1146
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
|
|
1147
|
+
}
|
|
1148
|
+
function valueType(value) {
|
|
1149
|
+
if (value === null) return "null";
|
|
1150
|
+
if (Array.isArray(value)) return "array";
|
|
1151
|
+
return typeof value;
|
|
1152
|
+
}
|
|
1153
|
+
function resolveSchemaRef(ref, root) {
|
|
1154
|
+
const prefix = "#/$defs/";
|
|
1155
|
+
if (!ref.startsWith(prefix)) return void 0;
|
|
1156
|
+
return root.$defs[ref.slice(prefix.length)];
|
|
1157
|
+
}
|
|
1158
|
+
function validateNode(value, schema, path, root, issues) {
|
|
1159
|
+
if (schema.$ref) {
|
|
1160
|
+
const referenced = resolveSchemaRef(schema.$ref, root);
|
|
1161
|
+
if (!referenced) {
|
|
1162
|
+
issues.push({ path, message: `schema reference ${schema.$ref} cannot be resolved` });
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
validateNode(value, referenced, path, root, issues);
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
if (schema.const !== void 0 && !Object.is(value, schema.const)) {
|
|
1169
|
+
issues.push({ path, message: `must equal ${JSON.stringify(schema.const)}` });
|
|
1170
|
+
return;
|
|
1171
|
+
}
|
|
1172
|
+
if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
|
|
1173
|
+
issues.push({ path, message: `must be one of ${schema.enum.map(String).join(", ")}` });
|
|
1174
|
+
return;
|
|
1175
|
+
}
|
|
1176
|
+
if (schema.type === "object") {
|
|
1177
|
+
if (!isObject(value)) {
|
|
1178
|
+
issues.push({ path, message: `must be an object; received ${valueType(value)}` });
|
|
1179
|
+
return;
|
|
1180
|
+
}
|
|
1181
|
+
const properties = schema.properties ?? {};
|
|
1182
|
+
for (const key of schema.required ?? []) {
|
|
1183
|
+
if (value[key] === void 0) {
|
|
1184
|
+
issues.push({ path: propertyPath(path, key), message: "is required" });
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
if (schema.additionalProperties === false) {
|
|
1188
|
+
for (const key of Object.keys(value)) {
|
|
1189
|
+
if (!(key in properties)) {
|
|
1190
|
+
issues.push({ path: propertyPath(path, key), message: "unknown field" });
|
|
3118
1191
|
}
|
|
3119
1192
|
}
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
if (!targetLayer) continue;
|
|
3125
|
-
const blocked = findDeniedEdgeRule(
|
|
3126
|
-
options.architectureProfile.rules,
|
|
3127
|
-
contextLayer,
|
|
3128
|
-
targetLayer
|
|
3129
|
-
);
|
|
3130
|
-
if (blocked) {
|
|
3131
|
-
violations.push(
|
|
3132
|
-
violation(
|
|
3133
|
-
"LAYER_REFERENCE_VIOLATION",
|
|
3134
|
-
blocked.message ?? `Layer "${contextLayer}" must not reference "${targetLayer}" through "${literal.value}".`,
|
|
3135
|
-
{
|
|
3136
|
-
line: lineOf(source, literal.index),
|
|
3137
|
-
filePath,
|
|
3138
|
-
target: literal.value,
|
|
3139
|
-
fromLayer: contextLayer,
|
|
3140
|
-
toLayer: targetLayer,
|
|
3141
|
-
suggestion: "Route the dependency through an allowed intent, port, or event.",
|
|
3142
|
-
details: { rule: blocked }
|
|
3143
|
-
}
|
|
3144
|
-
)
|
|
3145
|
-
);
|
|
3146
|
-
}
|
|
3147
|
-
}
|
|
1193
|
+
}
|
|
1194
|
+
for (const [key, childSchema] of Object.entries(properties)) {
|
|
1195
|
+
if (value[key] !== void 0) {
|
|
1196
|
+
validateNode(value[key], childSchema, propertyPath(path, key), root, issues);
|
|
3148
1197
|
}
|
|
3149
|
-
|
|
3150
|
-
|
|
3151
|
-
|
|
3152
|
-
|
|
3153
|
-
|
|
3154
|
-
|
|
3155
|
-
|
|
3156
|
-
|
|
3157
|
-
|
|
3158
|
-
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
|
|
3162
|
-
|
|
1198
|
+
}
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
if (schema.type === "array") {
|
|
1202
|
+
if (!Array.isArray(value)) {
|
|
1203
|
+
issues.push({ path, message: `must be an array; received ${valueType(value)}` });
|
|
1204
|
+
return;
|
|
1205
|
+
}
|
|
1206
|
+
if (schema.minItems !== void 0 && value.length < schema.minItems) {
|
|
1207
|
+
issues.push({ path, message: `must contain at least ${schema.minItems} item(s)` });
|
|
1208
|
+
}
|
|
1209
|
+
if (schema.uniqueItems) {
|
|
1210
|
+
const serialized = value.map((entry) => JSON.stringify(entry));
|
|
1211
|
+
if (new Set(serialized).size !== serialized.length) {
|
|
1212
|
+
issues.push({ path, message: "must not contain duplicate items" });
|
|
3163
1213
|
}
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
|
|
3182
|
-
|
|
1214
|
+
}
|
|
1215
|
+
if (schema.items) {
|
|
1216
|
+
value.forEach(
|
|
1217
|
+
(entry, index) => validateNode(entry, schema.items, `${path}[${index}]`, root, issues)
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
if (schema.type === "string") {
|
|
1223
|
+
if (typeof value !== "string") {
|
|
1224
|
+
issues.push({ path, message: `must be a string; received ${valueType(value)}` });
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
if (schema.minLength !== void 0 && value.length < schema.minLength) {
|
|
1228
|
+
issues.push({ path, message: `must contain at least ${schema.minLength} character(s)` });
|
|
1229
|
+
}
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
if (schema.type === "boolean") {
|
|
1233
|
+
if (typeof value !== "boolean") {
|
|
1234
|
+
issues.push({ path, message: `must be a boolean; received ${valueType(value)}` });
|
|
1235
|
+
}
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
if (schema.type === "integer") {
|
|
1239
|
+
if (!Number.isInteger(value)) {
|
|
1240
|
+
issues.push({ path, message: `must be an integer; received ${valueType(value)}` });
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (schema.minimum !== void 0 && value < schema.minimum) {
|
|
1244
|
+
issues.push({ path, message: `must be at least ${schema.minimum}` });
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
function defaultedConfig(input) {
|
|
1249
|
+
return {
|
|
1250
|
+
...input,
|
|
1251
|
+
$schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
|
|
1252
|
+
schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
|
|
1253
|
+
include: input.include === void 0 ? ["src"] : input.include,
|
|
1254
|
+
layers: input.layers === void 0 ? [] : input.layers,
|
|
1255
|
+
rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
|
|
1256
|
+
};
|
|
1257
|
+
}
|
|
1258
|
+
function migrateArkConfig(input, source = "ark.config.json") {
|
|
1259
|
+
if (!isObject(input)) {
|
|
1260
|
+
throw new ArkConfigValidationError(source, [
|
|
1261
|
+
{ path: "$", message: `must be an object; received ${valueType(input)}` }
|
|
1262
|
+
]);
|
|
1263
|
+
}
|
|
1264
|
+
const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
|
|
1265
|
+
if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
|
|
1266
|
+
throw new ArkConfigValidationError(source, [
|
|
1267
|
+
{
|
|
1268
|
+
path: "$.schemaVersion",
|
|
1269
|
+
message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
|
|
3183
1270
|
}
|
|
3184
|
-
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3191
|
-
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
|
|
1271
|
+
]);
|
|
1272
|
+
}
|
|
1273
|
+
return { candidate: defaultedConfig(input), migratedFrom };
|
|
1274
|
+
}
|
|
1275
|
+
function loadArkConfigContract(input, source = "ark.config.json") {
|
|
1276
|
+
const { candidate, migratedFrom } = migrateArkConfig(input, source);
|
|
1277
|
+
const issues = [];
|
|
1278
|
+
validateNode(
|
|
1279
|
+
candidate,
|
|
1280
|
+
ARK_CONFIG_SCHEMA,
|
|
1281
|
+
"$",
|
|
1282
|
+
ARK_CONFIG_SCHEMA,
|
|
1283
|
+
issues
|
|
1284
|
+
);
|
|
1285
|
+
if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
|
|
1286
|
+
return { config: candidate, migratedFrom };
|
|
1287
|
+
}
|
|
1288
|
+
function parseArkConfigJson(json, source = "ark.config.json") {
|
|
1289
|
+
let input;
|
|
1290
|
+
try {
|
|
1291
|
+
input = JSON.parse(json);
|
|
1292
|
+
} catch (error) {
|
|
1293
|
+
throw new ArkConfigValidationError(source, [
|
|
1294
|
+
{
|
|
1295
|
+
path: "$",
|
|
1296
|
+
message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
|
|
3202
1297
|
}
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
1298
|
+
]);
|
|
1299
|
+
}
|
|
1300
|
+
return loadArkConfigContract(input, source);
|
|
1301
|
+
}
|
|
1302
|
+
function withArkConfigMetadata(config) {
|
|
1303
|
+
const result = {
|
|
1304
|
+
$schema: typeof config.$schema === "string" && config.$schema.length > 0 ? config.$schema : ARK_CONFIG_SCHEMA_URL,
|
|
1305
|
+
schemaVersion: ARK_CONFIG_SCHEMA_VERSION
|
|
1306
|
+
};
|
|
1307
|
+
for (const [key, value] of Object.entries(config)) {
|
|
1308
|
+
if (key !== "$schema" && key !== "schemaVersion") result[key] = value;
|
|
1309
|
+
}
|
|
1310
|
+
return result;
|
|
1311
|
+
}
|
|
1312
|
+
|
|
1313
|
+
// src/kernel/layers/ArchitectureProfile.ts
|
|
1314
|
+
function normalizePrefix(prefix) {
|
|
1315
|
+
return prefix.endsWith(".") ? prefix : `${prefix}.`;
|
|
1316
|
+
}
|
|
1317
|
+
function byLongestPrefix(a, b) {
|
|
1318
|
+
const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
|
|
1319
|
+
const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
|
|
1320
|
+
return maxB - maxA;
|
|
1321
|
+
}
|
|
1322
|
+
function createArchitectureProfile(options) {
|
|
1323
|
+
const layers = options.layers.map((layer) => ({
|
|
1324
|
+
...layer,
|
|
1325
|
+
prefixes: layer.prefixes.map(normalizePrefix)
|
|
1326
|
+
}));
|
|
1327
|
+
const sortedLayers = [...layers].sort(byLongestPrefix);
|
|
1328
|
+
const rules = [...options.rules ?? []];
|
|
1329
|
+
return {
|
|
1330
|
+
name: options.name,
|
|
1331
|
+
layers,
|
|
1332
|
+
rules,
|
|
1333
|
+
resolveLayer(name) {
|
|
1334
|
+
return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
|
|
1335
|
+
(layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
|
|
1336
|
+
)?.name;
|
|
3207
1337
|
}
|
|
3208
1338
|
};
|
|
3209
1339
|
}
|
|
1340
|
+
function createArchitectureProfileFromArkConfig(config, options = {}) {
|
|
1341
|
+
return createArchitectureProfile({
|
|
1342
|
+
name: options.name ?? config.name ?? "ark.config.json",
|
|
1343
|
+
layers: config.layers.map((layer, index) => ({
|
|
1344
|
+
name: layer.name,
|
|
1345
|
+
prefixes: layer.intentPrefixes ?? [],
|
|
1346
|
+
description: layer.description,
|
|
1347
|
+
order: index + 1
|
|
1348
|
+
})),
|
|
1349
|
+
rules: config.rules ?? []
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
var elevenLayerProfileLayers = [
|
|
1353
|
+
{
|
|
1354
|
+
name: "DomainModel",
|
|
1355
|
+
prefixes: ["Domain"],
|
|
1356
|
+
description: "Rich domain model, business rules, and domain events.",
|
|
1357
|
+
order: 1
|
|
1358
|
+
},
|
|
1359
|
+
{
|
|
1360
|
+
name: "ApplicationOrchestration",
|
|
1361
|
+
prefixes: ["Application"],
|
|
1362
|
+
description: "Use cases and command orchestration.",
|
|
1363
|
+
order: 2
|
|
1364
|
+
},
|
|
1365
|
+
{
|
|
1366
|
+
name: "PersistenceAdapters",
|
|
1367
|
+
prefixes: ["Adapter.Persistence", "Adapter.Repository"],
|
|
1368
|
+
description: "Database, repository, and storage adapters.",
|
|
1369
|
+
order: 3
|
|
1370
|
+
},
|
|
1371
|
+
{
|
|
1372
|
+
name: "IntegrationAdapters",
|
|
1373
|
+
prefixes: ["Adapter.Integration", "Adapter.External"],
|
|
1374
|
+
description: "External systems, APIs, and integration adapters.",
|
|
1375
|
+
order: 4
|
|
1376
|
+
},
|
|
1377
|
+
{
|
|
1378
|
+
name: "WorkflowSagaEngine",
|
|
1379
|
+
prefixes: ["Workflow"],
|
|
1380
|
+
description: "Sagas, workflows, and long-running processes.",
|
|
1381
|
+
order: 5
|
|
1382
|
+
},
|
|
1383
|
+
{
|
|
1384
|
+
name: "BackgroundJobsScheduling",
|
|
1385
|
+
prefixes: ["Job"],
|
|
1386
|
+
description: "Background jobs, scheduled work, and async processors.",
|
|
1387
|
+
order: 6
|
|
1388
|
+
},
|
|
1389
|
+
{
|
|
1390
|
+
name: "PresentationAdapters",
|
|
1391
|
+
prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
|
|
1392
|
+
description: "API, UI, controller, and presentation adapters.",
|
|
1393
|
+
order: 7
|
|
1394
|
+
},
|
|
1395
|
+
{
|
|
1396
|
+
name: "ReportingReadModels",
|
|
1397
|
+
prefixes: ["Reporting"],
|
|
1398
|
+
description: "Read models, projections, and reporting surfaces.",
|
|
1399
|
+
order: 8
|
|
1400
|
+
},
|
|
1401
|
+
{
|
|
1402
|
+
name: "ExtensibilityMetadata",
|
|
1403
|
+
prefixes: ["Metadata"],
|
|
1404
|
+
description: "Metadata, extensions, and schema contracts.",
|
|
1405
|
+
order: 9
|
|
1406
|
+
},
|
|
1407
|
+
{
|
|
1408
|
+
name: "SecurityAuditObservability",
|
|
1409
|
+
prefixes: ["Security", "Audit", "Observability"],
|
|
1410
|
+
description: "Security, audit, and observability concerns.",
|
|
1411
|
+
order: 10
|
|
1412
|
+
},
|
|
1413
|
+
{
|
|
1414
|
+
name: "Kernel",
|
|
1415
|
+
prefixes: ["Kernel"],
|
|
1416
|
+
description: "Ark-owned governance and kernel signals.",
|
|
1417
|
+
order: 11
|
|
1418
|
+
}
|
|
1419
|
+
];
|
|
1420
|
+
var elevenLayerProfile = createArchitectureProfile({
|
|
1421
|
+
name: "Ark 11-layer Hexagonal Event-Driven Profile",
|
|
1422
|
+
layers: elevenLayerProfileLayers,
|
|
1423
|
+
rules: DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule }))
|
|
1424
|
+
});
|
|
1425
|
+
var defaultElevenLayerDirectories = {
|
|
1426
|
+
DomainModel: ["domain"],
|
|
1427
|
+
ApplicationOrchestration: ["application", "app"],
|
|
1428
|
+
PersistenceAdapters: [
|
|
1429
|
+
"adapters/persistence",
|
|
1430
|
+
"adapters/repository",
|
|
1431
|
+
"repositories",
|
|
1432
|
+
"infra/persistence"
|
|
1433
|
+
],
|
|
1434
|
+
IntegrationAdapters: ["adapters/integration", "adapters/external", "integrations"],
|
|
1435
|
+
WorkflowSagaEngine: ["workflows", "sagas"],
|
|
1436
|
+
BackgroundJobsScheduling: ["jobs", "schedules"],
|
|
1437
|
+
PresentationAdapters: ["presentation", "adapters/presentation", "adapters/api"],
|
|
1438
|
+
ReportingReadModels: ["reporting", "read-models", "projections"],
|
|
1439
|
+
ExtensibilityMetadata: ["metadata", "extensions"],
|
|
1440
|
+
SecurityAuditObservability: ["security", "audit", "observability"],
|
|
1441
|
+
Kernel: ["kernel"]
|
|
1442
|
+
};
|
|
1443
|
+
function createElevenLayerArkConfig(options = {}) {
|
|
1444
|
+
const rootDir = options.rootDir ?? "src";
|
|
1445
|
+
const optional = options.optionalLayers ?? true;
|
|
1446
|
+
const prefix = rootDir === "." ? "" : `${rootDir}/`;
|
|
1447
|
+
return withArkConfigMetadata({
|
|
1448
|
+
include: options.include ?? [rootDir],
|
|
1449
|
+
layers: elevenLayerProfile.layers.map((layer) => ({
|
|
1450
|
+
name: layer.name,
|
|
1451
|
+
patterns: (defaultElevenLayerDirectories[layer.name] ?? [layer.name]).map(
|
|
1452
|
+
(directory) => `${prefix}${directory}/**`
|
|
1453
|
+
),
|
|
1454
|
+
intentPrefixes: layer.prefixes,
|
|
1455
|
+
optional
|
|
1456
|
+
})),
|
|
1457
|
+
rules: [...elevenLayerProfile.rules]
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
3210
1460
|
|
|
3211
1461
|
// src/domain/analysis.ts
|
|
3212
1462
|
var ANALYSIS_IR_SCHEMA_VERSION = "1.0";
|
|
@@ -3415,600 +1665,296 @@ function explainViolation(violation2) {
|
|
|
3415
1665
|
const target = violation2.edge.to ?? violation2.edge.specifier;
|
|
3416
1666
|
return `${violation2.ruleId} at ${location}: ${violation2.edge.from} imports ${target}. ${violation2.message}`;
|
|
3417
1667
|
}
|
|
3418
|
-
|
|
3419
|
-
|
|
3420
|
-
|
|
3421
|
-
|
|
3422
|
-
|
|
3423
|
-
|
|
3424
|
-
|
|
3425
|
-
|
|
3426
|
-
|
|
3427
|
-
|
|
3428
|
-
|
|
3429
|
-
|
|
3430
|
-
|
|
3431
|
-
|
|
3432
|
-
|
|
1668
|
+
function detectArchitectureCycles(graph) {
|
|
1669
|
+
let index = 0;
|
|
1670
|
+
const indices = /* @__PURE__ */ new Map();
|
|
1671
|
+
const low = /* @__PURE__ */ new Map();
|
|
1672
|
+
const onStack = /* @__PURE__ */ new Set();
|
|
1673
|
+
const stack = [];
|
|
1674
|
+
const components = [];
|
|
1675
|
+
const connect = (file) => {
|
|
1676
|
+
indices.set(file, index);
|
|
1677
|
+
low.set(file, index);
|
|
1678
|
+
index += 1;
|
|
1679
|
+
stack.push(file);
|
|
1680
|
+
onStack.add(file);
|
|
1681
|
+
for (const target of [...graph.get(file) ?? []].sort()) {
|
|
1682
|
+
if (!graph.has(target)) continue;
|
|
1683
|
+
if (!indices.has(target)) {
|
|
1684
|
+
connect(target);
|
|
1685
|
+
low.set(file, Math.min(low.get(file) ?? 0, low.get(target) ?? 0));
|
|
1686
|
+
} else if (onStack.has(target)) {
|
|
1687
|
+
low.set(file, Math.min(low.get(file) ?? 0, indices.get(target) ?? 0));
|
|
1688
|
+
}
|
|
3433
1689
|
}
|
|
3434
|
-
|
|
3435
|
-
|
|
3436
|
-
|
|
3437
|
-
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
3446
|
-
|
|
3447
|
-
}
|
|
3448
|
-
|
|
3449
|
-
|
|
3450
|
-
|
|
1690
|
+
if (low.get(file) !== indices.get(file)) return;
|
|
1691
|
+
const component = [];
|
|
1692
|
+
let member;
|
|
1693
|
+
do {
|
|
1694
|
+
member = stack.pop();
|
|
1695
|
+
if (member === void 0) break;
|
|
1696
|
+
onStack.delete(member);
|
|
1697
|
+
component.push(member);
|
|
1698
|
+
} while (member !== file);
|
|
1699
|
+
if (component.length > 1) components.push(component.sort());
|
|
1700
|
+
};
|
|
1701
|
+
for (const file of [...graph.keys()].sort()) {
|
|
1702
|
+
if (!indices.has(file)) connect(file);
|
|
1703
|
+
}
|
|
1704
|
+
return components.sort((left, right) => left[0].localeCompare(right[0])).map((members) => ({
|
|
1705
|
+
ruleId: "CIRCULAR_DEPENDENCY",
|
|
1706
|
+
file: members[0],
|
|
1707
|
+
line: 1,
|
|
1708
|
+
target: members.join(" \u2192 "),
|
|
1709
|
+
message: `Circular dependency among ${members.length} files: ${members.join(" \u2192 ")} \u2192 ${members[0]}.`,
|
|
1710
|
+
cycleKind: "value"
|
|
1711
|
+
}));
|
|
1712
|
+
}
|
|
1713
|
+
function evaluateArchitectureGraph(input) {
|
|
1714
|
+
const violations = input.contentViolations.map((violation2) => ({ ...violation2 }));
|
|
1715
|
+
const warnings = (input.warnings ?? []).map((warning) => ({ ...warning }));
|
|
1716
|
+
const graph = new Map(
|
|
1717
|
+
input.files.map((file) => [file, /* @__PURE__ */ new Set()])
|
|
1718
|
+
);
|
|
1719
|
+
for (const edge of input.edges) {
|
|
1720
|
+
if (edge.to && edge.to !== edge.from && !edge.typeOnly && graph.has(edge.from)) {
|
|
1721
|
+
graph.get(edge.from)?.add(edge.to);
|
|
3451
1722
|
}
|
|
3452
|
-
|
|
3453
|
-
|
|
3454
|
-
|
|
3455
|
-
|
|
1723
|
+
if (!edge.to || !edge.toLayer) continue;
|
|
1724
|
+
const rule = findDeniedEdgeRule(input.rules, edge.fromLayer, edge.toLayer, {
|
|
1725
|
+
fromPath: edge.from,
|
|
1726
|
+
toPath: edge.to,
|
|
1727
|
+
layers: input.config.layers
|
|
1728
|
+
});
|
|
1729
|
+
if (!rule) continue;
|
|
1730
|
+
const peerIsolation = Boolean(rule.peerIsolation);
|
|
1731
|
+
violations.push({
|
|
1732
|
+
ruleId: "LAYER_IMPORT_VIOLATION",
|
|
1733
|
+
file: edge.from,
|
|
1734
|
+
line: edge.line,
|
|
1735
|
+
fromLayer: edge.fromLayer,
|
|
1736
|
+
toLayer: edge.toLayer,
|
|
1737
|
+
target: edge.to,
|
|
1738
|
+
...edge.typeOnly ? { typeOnly: true } : {},
|
|
1739
|
+
...edge.targetTypeOnlyExports ? { targetTypeOnlyExports: true } : {},
|
|
1740
|
+
...edge.sourcePureTypeModule ? { sourcePureTypeModule: true } : {},
|
|
1741
|
+
...edge.namedBindingsTypeOnly ? { namedBindingsTypeOnly: true } : {},
|
|
1742
|
+
...!peerIsolation && edge.portProofEligible ? { portProofEligible: true } : {},
|
|
1743
|
+
...edge.kind ? { edgeKind: edge.kind } : {},
|
|
1744
|
+
...peerIsolation ? { peerIsolation: true } : {},
|
|
1745
|
+
message: rule.message ?? (peerIsolation ? `${edge.fromLayer} must not ${edge.kind} another slice of ${edge.toLayer} (${edge.from} \u2192 ${edge.to}). Extract shared code or use events/ports across slices.` : `${edge.fromLayer} must not ${edge.kind} ${edge.toLayer}.`)
|
|
3456
1746
|
});
|
|
3457
1747
|
}
|
|
3458
|
-
|
|
3459
|
-
|
|
3460
|
-
|
|
3461
|
-
|
|
3462
|
-
|
|
3463
|
-
|
|
3464
|
-
|
|
3465
|
-
|
|
3466
|
-
|
|
3467
|
-
|
|
3468
|
-
|
|
3469
|
-
|
|
3470
|
-
|
|
3471
|
-
appliedCount: (previous?.appliedCount ?? 0) + 1,
|
|
3472
|
-
lastIntent: event.intent,
|
|
3473
|
-
lastCorrelationId: event.metadata.correlationId,
|
|
3474
|
-
updatedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
3475
|
-
});
|
|
3476
|
-
await this.auditTrail?.record({
|
|
3477
|
-
type: "projection.applied",
|
|
3478
|
-
source: "Kernel.ProjectionRegistry",
|
|
3479
|
-
intent: event.intent,
|
|
3480
|
-
correlationId: event.metadata.correlationId,
|
|
3481
|
-
causationId: event.metadata.causationId,
|
|
3482
|
-
subject: definition.name,
|
|
3483
|
-
details: { projection: definition.name }
|
|
3484
|
-
});
|
|
3485
|
-
applied.push(definition.name);
|
|
3486
|
-
}
|
|
3487
|
-
return applied;
|
|
3488
|
-
}
|
|
3489
|
-
async getState(name) {
|
|
3490
|
-
return this.store.load(name);
|
|
3491
|
-
}
|
|
3492
|
-
getCheckpoint(name) {
|
|
3493
|
-
return this.checkpoints.get(name);
|
|
3494
|
-
}
|
|
3495
|
-
getCheckpoints() {
|
|
3496
|
-
return Array.from(this.checkpoints.values());
|
|
3497
|
-
}
|
|
3498
|
-
async clear() {
|
|
3499
|
-
await this.store.clear();
|
|
3500
|
-
for (const definition of this.definitions.values()) {
|
|
3501
|
-
this.checkpoints.set(definition.name, {
|
|
3502
|
-
projection: definition.name,
|
|
3503
|
-
appliedCount: 0
|
|
3504
|
-
});
|
|
1748
|
+
const cyclePolicy = String(input.config.cyclePolicy ?? "strict").toLowerCase();
|
|
1749
|
+
if (cyclePolicy !== "off") {
|
|
1750
|
+
const cycles = detectArchitectureCycles(graph);
|
|
1751
|
+
if (cyclePolicy === "soft" || cyclePolicy === "framework-soft") {
|
|
1752
|
+
warnings.push(
|
|
1753
|
+
...cycles.map((cycle) => ({
|
|
1754
|
+
...cycle,
|
|
1755
|
+
message: `${cycle.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,
|
|
1756
|
+
failsStrict: false
|
|
1757
|
+
}))
|
|
1758
|
+
);
|
|
1759
|
+
} else {
|
|
1760
|
+
violations.push(...cycles);
|
|
3505
1761
|
}
|
|
3506
1762
|
}
|
|
3507
|
-
};
|
|
3508
|
-
function createProjectionRegistry(options) {
|
|
3509
|
-
return new ProjectionRegistryImpl(options);
|
|
3510
|
-
}
|
|
3511
|
-
|
|
3512
|
-
// src/kernel/manifest/constants.ts
|
|
3513
|
-
var MANIFEST_SCHEMA_VERSION = "1.0";
|
|
3514
|
-
|
|
3515
|
-
// src/kernel/manifest/createArkManifest.ts
|
|
3516
|
-
function policyId(name) {
|
|
3517
|
-
return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
3518
|
-
}
|
|
3519
|
-
var ArkManifestImpl = class {
|
|
3520
|
-
constructor(data) {
|
|
3521
|
-
this.data = data;
|
|
3522
|
-
}
|
|
3523
|
-
data;
|
|
3524
|
-
toJSON() {
|
|
3525
|
-
return { ...this.data };
|
|
3526
|
-
}
|
|
3527
|
-
};
|
|
3528
|
-
function createArkManifest(options = {}) {
|
|
3529
|
-
const registry = options.registry;
|
|
3530
|
-
const policyEngine = options.policyEngine;
|
|
3531
|
-
const metadata = options.metadata;
|
|
3532
|
-
const graph = options.graph;
|
|
3533
|
-
const profile = options.profile;
|
|
3534
|
-
const projections = options.projections;
|
|
3535
|
-
const eventContracts = options.eventContracts;
|
|
3536
|
-
const observability = options.observability;
|
|
3537
|
-
const intents = registry ? registry.list().map((creator) => ({
|
|
3538
|
-
name: creator.name,
|
|
3539
|
-
dependencies: registry.getDependencies(creator.name),
|
|
3540
|
-
productions: registry.getProductions(creator.name)
|
|
3541
|
-
})) : [];
|
|
3542
|
-
const relationships = registry ? registry.getAllRelationships() : [];
|
|
3543
|
-
const policies = policyEngine ? policyEngine.getPolicies().map((p) => ({
|
|
3544
|
-
id: policyId(p.name),
|
|
3545
|
-
name: p.name,
|
|
3546
|
-
severity: p.severity,
|
|
3547
|
-
tags: p.tags ? [...p.tags] : void 0,
|
|
3548
|
-
owner: p.owner,
|
|
3549
|
-
version: p.version,
|
|
3550
|
-
rationale: p.rationale,
|
|
3551
|
-
enforcementMode: p.enforcementMode,
|
|
3552
|
-
deprecated: p.deprecated,
|
|
3553
|
-
replacedBy: p.replacedBy,
|
|
3554
|
-
description: p.tags?.includes("layer") ? "Enforces clean-architecture layer dependency rules on declared relationships." : void 0
|
|
3555
|
-
})) : [];
|
|
3556
|
-
const entities = metadata ? metadata.toJSON() : [];
|
|
3557
|
-
const graphData = graph ? graph.toJSON() : { nodes: [], edges: [] };
|
|
3558
|
-
const entityIntents = entities.filter((e) => (e.emits?.length ?? 0) > 0 || (e.consumes?.length ?? 0) > 0).map((e) => ({
|
|
3559
|
-
entity: e.name,
|
|
3560
|
-
emits: e.emits,
|
|
3561
|
-
consumes: e.consumes
|
|
3562
|
-
}));
|
|
3563
|
-
const projectionData = projections ? projections.list().map((projection) => ({
|
|
3564
|
-
name: projection.name,
|
|
3565
|
-
sourceIntents: projection.sourceIntents,
|
|
3566
|
-
checkpoint: projections.getCheckpoint(projection.name)
|
|
3567
|
-
})) : [];
|
|
3568
|
-
const data = {
|
|
3569
|
-
schemaVersion: MANIFEST_SCHEMA_VERSION,
|
|
3570
|
-
version,
|
|
3571
|
-
exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
3572
|
-
intents,
|
|
3573
|
-
relationships,
|
|
3574
|
-
policies,
|
|
3575
|
-
entities,
|
|
3576
|
-
graph: graphData,
|
|
3577
|
-
architecture: profile ? {
|
|
3578
|
-
profile: profile.name,
|
|
3579
|
-
layers: profile.layers,
|
|
3580
|
-
rules: profile.rules
|
|
3581
|
-
} : void 0,
|
|
3582
|
-
projections: projectionData,
|
|
3583
|
-
eventContracts: eventContracts?.list() ?? [],
|
|
3584
|
-
observability: observability?.report(),
|
|
3585
|
-
links: { entityIntents }
|
|
3586
|
-
};
|
|
3587
|
-
return new ArkManifestImpl(data);
|
|
3588
|
-
}
|
|
3589
|
-
|
|
3590
|
-
// src/kernel/workflow/Saga.ts
|
|
3591
|
-
var workflowSequence = 0;
|
|
3592
|
-
function createWorkflowId(prefix) {
|
|
3593
|
-
workflowSequence += 1;
|
|
3594
|
-
return `${prefix}-${Date.now()}-${workflowSequence}`;
|
|
3595
|
-
}
|
|
3596
|
-
function errorMessage(error) {
|
|
3597
|
-
return error instanceof Error ? error.message : String(error);
|
|
3598
|
-
}
|
|
3599
|
-
function sleep(ms) {
|
|
3600
|
-
return new Promise((resolve) => {
|
|
3601
|
-
setTimeout(resolve, ms);
|
|
3602
|
-
});
|
|
1763
|
+
return { violations, warnings, safety: input.safety };
|
|
3603
1764
|
}
|
|
3604
|
-
|
|
3605
|
-
|
|
3606
|
-
if (timeoutMs === void 0) return operation(controller.signal);
|
|
3607
|
-
let timeout;
|
|
3608
|
-
const timeoutPromise = new Promise((_, reject) => {
|
|
3609
|
-
timeout = setTimeout(() => {
|
|
3610
|
-
const error = new Error(`Workflow step "${stepName}" timed out after ${timeoutMs}ms.`);
|
|
3611
|
-
controller.abort(error);
|
|
3612
|
-
reject(error);
|
|
3613
|
-
}, timeoutMs);
|
|
3614
|
-
});
|
|
3615
|
-
try {
|
|
3616
|
-
return await Promise.race([operation(controller.signal), timeoutPromise]);
|
|
3617
|
-
} finally {
|
|
3618
|
-
if (timeout) clearTimeout(timeout);
|
|
3619
|
-
}
|
|
1765
|
+
function configWarning(ruleId, message, extra = {}) {
|
|
1766
|
+
return { ruleId, message, ...extra };
|
|
3620
1767
|
}
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
|
|
3626
|
-
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
|
|
3630
|
-
|
|
3631
|
-
return Array.from(this.snapshots.values()).filter((snapshot) => !workflowName || snapshot.workflowName === workflowName).map((snapshot) => ({ ...snapshot, context: { ...snapshot.context } }));
|
|
3632
|
-
}
|
|
3633
|
-
clear() {
|
|
3634
|
-
this.snapshots.clear();
|
|
3635
|
-
}
|
|
3636
|
-
};
|
|
3637
|
-
var WorkflowEngineImpl = class {
|
|
3638
|
-
constructor(bus, options = {}) {
|
|
3639
|
-
this.bus = bus;
|
|
3640
|
-
this.options = options;
|
|
3641
|
-
this.store = options.store ?? new InMemoryWorkflowStore();
|
|
1768
|
+
function collectAnalysisConfigWarnings(input) {
|
|
1769
|
+
const { config, rules, files, manifest } = input;
|
|
1770
|
+
const warnings = [];
|
|
1771
|
+
if (config.dynamicImportAllowlist !== void 0 && (!Array.isArray(config.dynamicImportAllowlist) || config.dynamicImportAllowlist.some((entry) => typeof entry !== "string"))) {
|
|
1772
|
+
warnings.push(
|
|
1773
|
+
configWarning(
|
|
1774
|
+
"CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST",
|
|
1775
|
+
"dynamicImportAllowlist must be an array of file globs."
|
|
1776
|
+
)
|
|
1777
|
+
);
|
|
3642
1778
|
}
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
throw new Error(
|
|
3655
|
-
`Workflow "${definition.name}" has duplicate step name "${step.name}".`
|
|
1779
|
+
if (config.safety !== void 0 && (config.safety === null || typeof config.safety !== "object" || Array.isArray(config.safety))) {
|
|
1780
|
+
warnings.push(configWarning("CONFIG_INVALID_SAFETY", "safety must be an object."));
|
|
1781
|
+
} else if (config.safety) {
|
|
1782
|
+
for (const key of ["maxTsSuppressions", "maxAnyCasts"]) {
|
|
1783
|
+
const value = config.safety[key];
|
|
1784
|
+
if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
|
|
1785
|
+
warnings.push(
|
|
1786
|
+
configWarning(
|
|
1787
|
+
"CONFIG_INVALID_SAFETY_THRESHOLD",
|
|
1788
|
+
`safety.${key} must be a non-negative integer.`
|
|
1789
|
+
)
|
|
3656
1790
|
);
|
|
3657
1791
|
}
|
|
3658
|
-
names.add(step.name);
|
|
3659
|
-
}
|
|
3660
|
-
this.definitions.set(definition.name, definition);
|
|
3661
|
-
if (definition.startOn) {
|
|
3662
|
-
const trigger = definition.startOn;
|
|
3663
|
-
this.bus.subscribe(trigger.intent, async (event) => {
|
|
3664
|
-
await this.start(definition.name, trigger.mapEventToPayload(event));
|
|
3665
|
-
});
|
|
3666
1792
|
}
|
|
3667
1793
|
}
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
1794
|
+
const layers = Array.isArray(config.layers) ? config.layers : [];
|
|
1795
|
+
const manifestLayers = Array.isArray(manifest?.architecture?.layers) ? manifest.architecture.layers : [];
|
|
1796
|
+
const knownLayers = /* @__PURE__ */ new Set([
|
|
1797
|
+
...layers.map((layer) => layer.name).filter(Boolean),
|
|
1798
|
+
...manifestLayers.map((layer) => layer.name).filter((name) => Boolean(name))
|
|
1799
|
+
]);
|
|
1800
|
+
if (layers.length === 0) {
|
|
1801
|
+
warnings.push(
|
|
1802
|
+
configWarning(
|
|
1803
|
+
"CONFIG_NO_LAYERS",
|
|
1804
|
+
"No file layers are configured; ark-check cannot classify files for import-boundary enforcement."
|
|
1805
|
+
)
|
|
1806
|
+
);
|
|
1807
|
+
}
|
|
1808
|
+
const seenLayers = /* @__PURE__ */ new Set();
|
|
1809
|
+
const duplicateLayers = /* @__PURE__ */ new Set();
|
|
1810
|
+
for (const layer of layers) {
|
|
1811
|
+
if (!layer.name) {
|
|
1812
|
+
warnings.push(configWarning("CONFIG_LAYER_WITHOUT_NAME", "A configured layer is missing a name."));
|
|
1813
|
+
continue;
|
|
3672
1814
|
}
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
};
|
|
3684
|
-
await this.store.save(snapshot);
|
|
3685
|
-
await this.audit("workflow.started", snapshot, { workflowName });
|
|
3686
|
-
try {
|
|
3687
|
-
for (const step of definition.steps) {
|
|
3688
|
-
await this.runStep(snapshot, step);
|
|
3689
|
-
}
|
|
3690
|
-
snapshot.status = "completed";
|
|
3691
|
-
snapshot.currentStep = void 0;
|
|
3692
|
-
snapshot.completedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3693
|
-
snapshot.updatedAt = snapshot.completedAt;
|
|
3694
|
-
await this.store.save(snapshot);
|
|
3695
|
-
await this.audit("workflow.completed", snapshot, { workflowName });
|
|
3696
|
-
return { ...snapshot, context: { ...snapshot.context } };
|
|
3697
|
-
} catch (err) {
|
|
3698
|
-
await this.compensate(snapshot, definition.steps, err);
|
|
3699
|
-
snapshot.status = "failed";
|
|
3700
|
-
snapshot.currentStep = void 0;
|
|
3701
|
-
snapshot.error = errorMessage(err);
|
|
3702
|
-
snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3703
|
-
await this.store.save(snapshot);
|
|
3704
|
-
await this.audit("workflow.failed", snapshot, {
|
|
3705
|
-
workflowName,
|
|
3706
|
-
error: snapshot.error,
|
|
3707
|
-
failedStep: snapshot.failedStep
|
|
3708
|
-
});
|
|
3709
|
-
throw err;
|
|
1815
|
+
if (seenLayers.has(layer.name)) duplicateLayers.add(layer.name);
|
|
1816
|
+
seenLayers.add(layer.name);
|
|
1817
|
+
if (layer.forbiddenGlobals !== void 0 && (!Array.isArray(layer.forbiddenGlobals) || layer.forbiddenGlobals.some((entry) => typeof entry !== "string"))) {
|
|
1818
|
+
warnings.push(
|
|
1819
|
+
configWarning(
|
|
1820
|
+
"CONFIG_INVALID_FORBIDDEN_GLOBALS",
|
|
1821
|
+
`Layer "${layer.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,
|
|
1822
|
+
{ layer: layer.name }
|
|
1823
|
+
)
|
|
1824
|
+
);
|
|
3710
1825
|
}
|
|
3711
|
-
|
|
3712
|
-
|
|
3713
|
-
|
|
3714
|
-
|
|
3715
|
-
|
|
3716
|
-
|
|
3717
|
-
|
|
3718
|
-
|
|
3719
|
-
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
3723
|
-
|
|
3724
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
3725
|
-
snapshot.attempts[step.name] = attempt;
|
|
3726
|
-
await this.store.save(snapshot);
|
|
3727
|
-
let result;
|
|
1826
|
+
const patterns = Array.isArray(layer.patterns) ? layer.patterns : [];
|
|
1827
|
+
if (patterns.length === 0) {
|
|
1828
|
+
warnings.push(
|
|
1829
|
+
configWarning(
|
|
1830
|
+
"CONFIG_LAYER_WITHOUT_PATTERNS",
|
|
1831
|
+
`Layer "${layer.name}" has no file patterns and will never classify files.`,
|
|
1832
|
+
{ layer: layer.name }
|
|
1833
|
+
)
|
|
1834
|
+
);
|
|
1835
|
+
continue;
|
|
1836
|
+
}
|
|
1837
|
+
for (const pattern of patterns) {
|
|
1838
|
+
let expression;
|
|
3728
1839
|
try {
|
|
3729
|
-
|
|
3730
|
-
|
|
3731
|
-
|
|
3732
|
-
|
|
1840
|
+
expression = globToRegExp(pattern);
|
|
1841
|
+
} catch (error) {
|
|
1842
|
+
warnings.push(
|
|
1843
|
+
configWarning(
|
|
1844
|
+
"CONFIG_INVALID_LAYER_PATTERN",
|
|
1845
|
+
`Layer "${layer.name}" has an invalid pattern "${pattern}": ${error instanceof Error ? error.message : String(error)}`,
|
|
1846
|
+
{ layer: layer.name, pattern }
|
|
1847
|
+
)
|
|
1848
|
+
);
|
|
1849
|
+
continue;
|
|
1850
|
+
}
|
|
1851
|
+
if (!files.some((file) => expression.test(file)) && !layer.optional) {
|
|
1852
|
+
warnings.push(
|
|
1853
|
+
configWarning(
|
|
1854
|
+
"CONFIG_LAYER_PATTERN_NO_MATCHES",
|
|
1855
|
+
`Layer "${layer.name}" pattern "${pattern}" matched no included files.`,
|
|
1856
|
+
{ layer: layer.name, pattern, failsStrict: false }
|
|
1857
|
+
)
|
|
3733
1858
|
);
|
|
3734
|
-
} catch (err) {
|
|
3735
|
-
if (attempt < maxAttempts) {
|
|
3736
|
-
if (retry.delayMs) await sleep(retry.delayMs);
|
|
3737
|
-
continue;
|
|
3738
|
-
}
|
|
3739
|
-
snapshot.failedStep = step.name;
|
|
3740
|
-
snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3741
|
-
await this.store.save(snapshot);
|
|
3742
|
-
await this.audit("workflow.step.failed", snapshot, {
|
|
3743
|
-
step: step.name,
|
|
3744
|
-
attempt,
|
|
3745
|
-
error: errorMessage(err)
|
|
3746
|
-
});
|
|
3747
|
-
throw err;
|
|
3748
1859
|
}
|
|
3749
|
-
if (result) Object.assign(snapshot.context, result);
|
|
3750
|
-
snapshot.completedSteps.push(step.name);
|
|
3751
|
-
snapshot.currentStep = void 0;
|
|
3752
|
-
snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
3753
|
-
await this.store.save(snapshot);
|
|
3754
|
-
await this.audit("workflow.step.completed", snapshot, {
|
|
3755
|
-
step: step.name,
|
|
3756
|
-
attempt
|
|
3757
|
-
});
|
|
3758
|
-
return;
|
|
3759
1860
|
}
|
|
3760
|
-
throw new Error(`Workflow step "${step.name}" did not complete.`);
|
|
3761
1861
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
(step) => snapshot.completedSteps.includes(step.name)
|
|
1862
|
+
for (const name of duplicateLayers) {
|
|
1863
|
+
warnings.push(
|
|
1864
|
+
configWarning("CONFIG_DUPLICATE_LAYER", `Layer "${name}" is configured more than once.`, {
|
|
1865
|
+
layer: name
|
|
1866
|
+
})
|
|
3768
1867
|
);
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
1868
|
+
}
|
|
1869
|
+
if (knownLayers.size > 0) {
|
|
1870
|
+
for (const rule of rules ?? []) {
|
|
1871
|
+
if (rule.from && !knownLayers.has(rule.from)) {
|
|
1872
|
+
warnings.push(
|
|
1873
|
+
configWarning(
|
|
1874
|
+
"CONFIG_RULE_UNKNOWN_FROM_LAYER",
|
|
1875
|
+
`Rule references unknown source layer "${rule.from}".`,
|
|
1876
|
+
{ fromLayer: rule.from, toLayer: rule.to }
|
|
1877
|
+
)
|
|
1878
|
+
);
|
|
1879
|
+
}
|
|
1880
|
+
if (rule.to && !knownLayers.has(rule.to)) {
|
|
1881
|
+
warnings.push(
|
|
1882
|
+
configWarning(
|
|
1883
|
+
"CONFIG_RULE_UNKNOWN_TO_LAYER",
|
|
1884
|
+
`Rule references unknown target layer "${rule.to}".`,
|
|
1885
|
+
{ fromLayer: rule.from, toLayer: rule.to }
|
|
1886
|
+
)
|
|
1887
|
+
);
|
|
3783
1888
|
}
|
|
3784
1889
|
}
|
|
3785
1890
|
}
|
|
3786
|
-
|
|
3787
|
-
|
|
3788
|
-
|
|
3789
|
-
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
3802
|
-
const sagaId = options.id ?? createWorkflowId(def.name);
|
|
3803
|
-
let status = "idle";
|
|
3804
|
-
let completedStepNames = [];
|
|
3805
|
-
return {
|
|
3806
|
-
id: sagaId,
|
|
3807
|
-
definition: def,
|
|
3808
|
-
get status() {
|
|
3809
|
-
return status;
|
|
3810
|
-
},
|
|
3811
|
-
get completedSteps() {
|
|
3812
|
-
return [...completedStepNames];
|
|
3813
|
-
},
|
|
3814
|
-
async run(initialPayload) {
|
|
3815
|
-
status = "running";
|
|
3816
|
-
completedStepNames = [];
|
|
3817
|
-
try {
|
|
3818
|
-
const snapshot = await engine.start(def.name, initialPayload, { id: sagaId });
|
|
3819
|
-
status = snapshot.status === "waiting" ? "idle" : snapshot.status;
|
|
3820
|
-
completedStepNames = [...snapshot.completedSteps];
|
|
3821
|
-
} catch (err) {
|
|
3822
|
-
const snapshot = await engine.get(sagaId);
|
|
3823
|
-
status = snapshot?.status === "waiting" ? "idle" : snapshot?.status ?? "failed";
|
|
3824
|
-
completedStepNames = snapshot?.completedSteps ?? [];
|
|
3825
|
-
throw err;
|
|
1891
|
+
const ambiguousPairs = /* @__PURE__ */ new Set();
|
|
1892
|
+
if (layers.length > 1) {
|
|
1893
|
+
for (const file of files) {
|
|
1894
|
+
let topScore = -1;
|
|
1895
|
+
let topLayers = [];
|
|
1896
|
+
for (const layer of layers) {
|
|
1897
|
+
for (const pattern of layer.patterns ?? []) {
|
|
1898
|
+
if (!globToRegExp(pattern).test(file)) continue;
|
|
1899
|
+
const score = patternSpecificity(pattern);
|
|
1900
|
+
if (score > topScore) {
|
|
1901
|
+
topScore = score;
|
|
1902
|
+
topLayers = [layer.name];
|
|
1903
|
+
} else if (score === topScore && !topLayers.includes(layer.name)) {
|
|
1904
|
+
topLayers.push(layer.name);
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
3826
1907
|
}
|
|
1908
|
+
if (topLayers.length > 1) ambiguousPairs.add([...topLayers].sort().join(" + "));
|
|
3827
1909
|
}
|
|
3828
|
-
}
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
3833
|
-
|
|
3834
|
-
|
|
3835
|
-
|
|
3836
|
-
|
|
3837
|
-
}
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
|
|
3841
|
-
|
|
3842
|
-
|
|
3843
|
-
|
|
3844
|
-
|
|
3845
|
-
|
|
3846
|
-
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
const projections = options.projections ?? createProjectionRegistry({ auditTrail });
|
|
3850
|
-
const policyEngine = new PolicyEngine([
|
|
3851
|
-
defineArchitectureProfilePolicy(profile),
|
|
3852
|
-
...options.policies ?? []
|
|
3853
|
-
]);
|
|
3854
|
-
const syncGraph = () => {
|
|
3855
|
-
syncRegistryToGraph(registry, graph, { requireRegisteredTargets: true });
|
|
3856
|
-
};
|
|
3857
|
-
const eventBus = createEventBus({
|
|
3858
|
-
intentRegistry: registry,
|
|
3859
|
-
dependencyGraph: graph,
|
|
3860
|
-
policyEngine,
|
|
3861
|
-
strictRegistry: true,
|
|
3862
|
-
validateIntentNaming: true,
|
|
3863
|
-
auditTrail,
|
|
3864
|
-
eventContracts,
|
|
3865
|
-
strictEventContracts: options.strictEventContracts ?? strict,
|
|
3866
|
-
requireKnownSource: options.requireKnownSource ?? true,
|
|
3867
|
-
architectureProfile: profile,
|
|
3868
|
-
enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? (strict ? "hard" : "off"),
|
|
3869
|
-
outbox,
|
|
3870
|
-
instanceId,
|
|
3871
|
-
maxHistorySize,
|
|
3872
|
-
onPublish: options.autoApplyProjections === false ? void 0 : async (event) => {
|
|
3873
|
-
await projections.apply(event);
|
|
3874
|
-
}
|
|
3875
|
-
});
|
|
3876
|
-
const workflowEngine = createWorkflowEngine(eventBus, { auditTrail });
|
|
3877
|
-
const observability = createObservabilityReporter({
|
|
3878
|
-
registry,
|
|
3879
|
-
eventBus,
|
|
3880
|
-
graph
|
|
3881
|
-
});
|
|
3882
|
-
return {
|
|
3883
|
-
instanceId,
|
|
3884
|
-
profile,
|
|
3885
|
-
registry,
|
|
3886
|
-
graph,
|
|
3887
|
-
metadata,
|
|
3888
|
-
auditTrail,
|
|
3889
|
-
eventContracts,
|
|
3890
|
-
outbox,
|
|
3891
|
-
projections,
|
|
3892
|
-
policyEngine,
|
|
3893
|
-
eventBus,
|
|
3894
|
-
workflowEngine,
|
|
3895
|
-
observability,
|
|
3896
|
-
publisher(source) {
|
|
3897
|
-
return eventBus.createPublisher(source);
|
|
3898
|
-
},
|
|
3899
|
-
syncGraph,
|
|
3900
|
-
manifest() {
|
|
3901
|
-
syncGraph();
|
|
3902
|
-
return createArkManifest({
|
|
3903
|
-
registry,
|
|
3904
|
-
policyEngine,
|
|
3905
|
-
metadata,
|
|
3906
|
-
graph,
|
|
3907
|
-
profile,
|
|
3908
|
-
projections,
|
|
3909
|
-
eventContracts,
|
|
3910
|
-
observability
|
|
3911
|
-
});
|
|
3912
|
-
}
|
|
3913
|
-
};
|
|
3914
|
-
}
|
|
3915
|
-
function createStrictArkKernel(options = {}) {
|
|
3916
|
-
return createArkKernel({
|
|
3917
|
-
...options,
|
|
3918
|
-
strict: true,
|
|
3919
|
-
strictEventContracts: options.strictEventContracts ?? true,
|
|
3920
|
-
requireKnownSource: options.requireKnownSource ?? true,
|
|
3921
|
-
enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? "hard"
|
|
3922
|
-
});
|
|
3923
|
-
}
|
|
3924
|
-
function createOptionsFromConfig(config, options = {}) {
|
|
3925
|
-
const { profileName, ...kernelOptions } = options;
|
|
3926
|
-
return {
|
|
3927
|
-
...kernelOptions,
|
|
3928
|
-
profile: createArchitectureProfileFromArkConfig(config, { name: profileName })
|
|
3929
|
-
};
|
|
3930
|
-
}
|
|
3931
|
-
function createArkKernelFromConfig(config, options = {}) {
|
|
3932
|
-
return createArkKernel(createOptionsFromConfig(config, options));
|
|
3933
|
-
}
|
|
3934
|
-
function createStrictArkKernelFromConfig(config, options = {}) {
|
|
3935
|
-
return createStrictArkKernel(createOptionsFromConfig(config, options));
|
|
3936
|
-
}
|
|
3937
|
-
function createLenientArkKernelFromConfig(config, options = {}) {
|
|
3938
|
-
return createLenientArkKernel(createOptionsFromConfig(config, options));
|
|
3939
|
-
}
|
|
3940
|
-
function createLenientArkKernel(options = {}) {
|
|
3941
|
-
return createArkKernel({
|
|
3942
|
-
...options,
|
|
3943
|
-
strict: false,
|
|
3944
|
-
strictEventContracts: options.strictEventContracts ?? false,
|
|
3945
|
-
enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? "off"
|
|
3946
|
-
});
|
|
1910
|
+
}
|
|
1911
|
+
if (ambiguousPairs.size > 0) {
|
|
1912
|
+
warnings.push(
|
|
1913
|
+
configWarning(
|
|
1914
|
+
"CONFIG_AMBIGUOUS_LAYERS",
|
|
1915
|
+
`Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...ambiguousPairs].join(", ")}.`,
|
|
1916
|
+
{ pairs: [...ambiguousPairs] }
|
|
1917
|
+
)
|
|
1918
|
+
);
|
|
1919
|
+
}
|
|
1920
|
+
const unclassified = files.filter((file) => !layerForRelativePath(file, layers));
|
|
1921
|
+
if (unclassified.length > 0) {
|
|
1922
|
+
warnings.push(
|
|
1923
|
+
configWarning(
|
|
1924
|
+
"CONFIG_UNCLASSIFIED_FILES",
|
|
1925
|
+
`${unclassified.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,
|
|
1926
|
+
{ count: unclassified.length, samples: unclassified.slice(0, 5) }
|
|
1927
|
+
)
|
|
1928
|
+
);
|
|
1929
|
+
}
|
|
1930
|
+
return warnings;
|
|
3947
1931
|
}
|
|
3948
1932
|
// Annotate the CommonJS export names for ESM import in node:
|
|
3949
1933
|
0 && (module.exports = {
|
|
3950
1934
|
ANALYSIS_IR_SCHEMA_VERSION,
|
|
3951
|
-
|
|
3952
|
-
|
|
3953
|
-
|
|
3954
|
-
|
|
3955
|
-
InMemoryOutboxStore,
|
|
3956
|
-
InMemoryReadModelStore,
|
|
3957
|
-
InMemoryWorkflowStore,
|
|
3958
|
-
IntentRegistry,
|
|
3959
|
-
InvalidIntentNameError,
|
|
3960
|
-
LayerPolicyContextError,
|
|
3961
|
-
MANIFEST_SCHEMA_VERSION,
|
|
3962
|
-
ObservedLayerFlowViolationError,
|
|
3963
|
-
PolicyEngine,
|
|
3964
|
-
PolicyViolationError,
|
|
3965
|
-
SourceMetadataOverrideError,
|
|
3966
|
-
UnknownEventSourceError,
|
|
3967
|
-
UnregisteredIntentError,
|
|
1935
|
+
ARK_ANALYSIS_RESULT_SCHEMA,
|
|
1936
|
+
ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
|
|
1937
|
+
ARK_CONFIG_SCHEMA,
|
|
1938
|
+
ARK_CONFIG_SCHEMA_VERSION,
|
|
3968
1939
|
analyzeChange,
|
|
3969
1940
|
analyzeProject,
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
checkAdapterGovernance,
|
|
3973
|
-
checkContract,
|
|
1941
|
+
collectAnalysisConfigWarnings,
|
|
1942
|
+
collectForbiddenCapabilityUses,
|
|
3974
1943
|
createAICodeGate,
|
|
3975
|
-
|
|
1944
|
+
createAdapterResult,
|
|
3976
1945
|
createArchitectureProfile,
|
|
3977
1946
|
createArchitectureProfileFromArkConfig,
|
|
3978
|
-
createArkKernel,
|
|
3979
|
-
createArkKernelFromConfig,
|
|
3980
|
-
createArkManifest,
|
|
3981
|
-
createArkTestHarness,
|
|
3982
|
-
createAuditTrail,
|
|
3983
|
-
createDependencyGraph,
|
|
3984
1947
|
createElevenLayerArkConfig,
|
|
3985
|
-
|
|
3986
|
-
createEventContractRegistry,
|
|
3987
|
-
createIntentRegistry,
|
|
3988
|
-
createLenientArkKernel,
|
|
3989
|
-
createLenientArkKernelFromConfig,
|
|
3990
|
-
createMetadataRegistry,
|
|
3991
|
-
createObservabilityReporter,
|
|
3992
|
-
createProjectionRegistry,
|
|
3993
|
-
createSaga,
|
|
3994
|
-
createStrictArkKernel,
|
|
3995
|
-
createStrictArkKernelFromConfig,
|
|
3996
|
-
createWorkflowEngine,
|
|
3997
|
-
defaultIntentRegistry,
|
|
3998
|
-
defineArchitectureProfilePolicy,
|
|
3999
|
-
defineIntent,
|
|
4000
|
-
defineLayerPolicy,
|
|
4001
|
-
definePolicy,
|
|
4002
|
-
definePort,
|
|
4003
|
-
definePublishPolicy,
|
|
1948
|
+
detectArchitectureCycles,
|
|
4004
1949
|
deterministicHash,
|
|
4005
1950
|
elevenLayerProfile,
|
|
1951
|
+
evaluateArchitectureGraph,
|
|
4006
1952
|
explainViolation,
|
|
4007
|
-
|
|
1953
|
+
extractSemanticDependencies,
|
|
1954
|
+
loadArkConfigContract,
|
|
4008
1955
|
loadContract,
|
|
1956
|
+
parseArkConfigJson,
|
|
4009
1957
|
stableSerialize,
|
|
4010
|
-
|
|
4011
|
-
validateIntentName,
|
|
1958
|
+
toAdapterDiagnostic,
|
|
4012
1959
|
version
|
|
4013
1960
|
});
|
|
4014
|
-
//# sourceMappingURL=index.cjs.map
|