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