arkgate 2.12.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +90 -51
  3. package/bin/ark-check.mjs +156 -39
  4. package/bin/ark-mcp.mjs +119 -6
  5. package/bin/ark-shared.mjs +216 -129
  6. package/bin/ark.mjs +134 -34
  7. package/bin/lib/adapter-contract.mjs +93 -0
  8. package/bin/lib/agent-gates.mjs +13 -0
  9. package/bin/lib/analysis-engine.mjs +1171 -0
  10. package/bin/lib/architecture-scan.mjs +84 -127
  11. package/bin/lib/ci-and-commands.mjs +40 -3
  12. package/bin/lib/codex-home.mjs +7 -0
  13. package/bin/lib/config-contract.mjs +331 -0
  14. package/bin/lib/config-warnings.mjs +7 -205
  15. package/bin/lib/doctor-plan.mjs +43 -16
  16. package/bin/lib/enforcement-profiles.mjs +97 -0
  17. package/bin/lib/field-install.mjs +67 -10
  18. package/bin/lib/gate-files.mjs +42 -3
  19. package/bin/lib/graph-cycles.mjs +4 -54
  20. package/bin/lib/hook-templates.mjs +33 -1
  21. package/bin/lib/host-support-matrix.mjs +83 -0
  22. package/bin/lib/install-migrate.mjs +99 -30
  23. package/bin/lib/mcp-adoption.mjs +35 -3
  24. package/bin/lib/open-html.mjs +75 -0
  25. package/bin/lib/presets.mjs +45 -4
  26. package/bin/lib/safety-diagnostics.mjs +36 -15
  27. package/bin/lib/scan-files.mjs +12 -1
  28. package/bin/lib/skill-install.mjs +72 -1
  29. package/bin/lib/source-policy.mjs +36 -0
  30. package/bin/lib/start-preview.mjs +271 -0
  31. package/bin/lib/ts-resolve.mjs +13 -3
  32. package/bin/lib/weakest-link.mjs +417 -0
  33. package/bin/lib/write-path-capabilities.mjs +186 -0
  34. package/bin/lib/write-path-detect.mjs +62 -99
  35. package/compat/nestjs.cjs +2 -0
  36. package/compat/nestjs.d.ts +2 -0
  37. package/compat/nestjs.js +1 -0
  38. package/compat/runtime.cjs +2 -0
  39. package/compat/runtime.d.ts +2 -0
  40. package/compat/runtime.js +1 -0
  41. package/dist/configContract-BxSIwVRo.d.cts +259 -0
  42. package/dist/configContract-BxSIwVRo.d.ts +259 -0
  43. package/dist/eslint/index.cjs +500 -61
  44. package/dist/eslint/index.d.cts +36 -20
  45. package/dist/eslint/index.d.ts +36 -20
  46. package/dist/eslint/index.js +500 -61
  47. package/dist/index.cjs +1349 -2741
  48. package/dist/index.d.cts +449 -483
  49. package/dist/index.d.ts +449 -483
  50. package/dist/index.js +1325 -2687
  51. package/docs/agent-guide.md +58 -34
  52. package/docs/ai-gates.md +79 -21
  53. package/docs/configuration.md +97 -0
  54. package/docs/enthusiast/README.md +3 -3
  55. package/docs/enthusiast/how-to-agent-gates.md +7 -3
  56. package/docs/migrate-from-ark-runtime-kernel.md +5 -3
  57. package/docs/package-surface.md +19 -19
  58. package/docs/production-hardening.md +31 -5
  59. package/docs/threat-model.md +65 -0
  60. package/docs/typescript-support.md +30 -3
  61. package/package.json +46 -11
  62. package/schemas/ark.analysis-result.schema.json +91 -0
  63. package/schemas/ark.config.schema.json +750 -0
  64. package/server.json +2 -2
  65. package/templates/hooks/pre-commit-ark +37 -0
  66. package/templates/skills/ark-architect.md +3 -2
  67. package/templates/skills/ark-coverage.md +2 -2
  68. package/templates/skills/ark-runtime.md +8 -5
  69. package/templates/skills/ark-upgrade.md +36 -16
  70. package/tests/fixtures/ts-consumer/ark.config.json +2 -0
  71. package/dist/eslint/index.cjs.map +0 -1
  72. package/dist/eslint/index.js.map +0 -1
  73. package/dist/index.cjs.map +0 -1
  74. package/dist/index.js.map +0 -1
  75. package/dist/nestjs/index.cjs +0 -2498
  76. package/dist/nestjs/index.cjs.map +0 -1
  77. package/dist/nestjs/index.d.cts +0 -22
  78. package/dist/nestjs/index.d.ts +0 -22
  79. package/dist/nestjs/index.js +0 -2474
  80. package/dist/nestjs/index.js.map +0 -1
  81. package/dist/runtime/index.cjs +0 -3352
  82. package/dist/runtime/index.cjs.map +0 -1
  83. package/dist/runtime/index.d.cts +0 -2
  84. package/dist/runtime/index.d.ts +0 -2
  85. package/dist/runtime/index.js +0 -3270
  86. package/dist/runtime/index.js.map +0 -1
  87. package/dist/types-BZ17b9i5.d.cts +0 -1068
  88. package/dist/types-BZ17b9i5.d.ts +0 -1068
package/dist/index.cjs CHANGED
@@ -17,733 +17,131 @@ var __copyProps = (to, from, except, desc) => {
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
- // src/index.ts
21
- var index_exports = {};
22
- __export(index_exports, {
23
- DEFAULT_MAX_HISTORY_SIZE: () => DEFAULT_MAX_HISTORY_SIZE,
24
- EventContractRegistryImpl: () => EventContractRegistryImpl,
25
- EventContractViolationError: () => EventContractViolationError,
26
- InMemoryAuditStore: () => InMemoryAuditStore,
27
- InMemoryOutboxStore: () => InMemoryOutboxStore,
28
- InMemoryReadModelStore: () => InMemoryReadModelStore,
29
- InMemoryWorkflowStore: () => InMemoryWorkflowStore,
30
- IntentRegistry: () => IntentRegistry,
31
- InvalidIntentNameError: () => InvalidIntentNameError,
32
- LayerPolicyContextError: () => LayerPolicyContextError,
33
- MANIFEST_SCHEMA_VERSION: () => MANIFEST_SCHEMA_VERSION,
34
- ObservedLayerFlowViolationError: () => ObservedLayerFlowViolationError,
35
- PolicyEngine: () => PolicyEngine,
36
- PolicyViolationError: () => PolicyViolationError,
37
- SourceMetadataOverrideError: () => SourceMetadataOverrideError,
38
- UnknownEventSourceError: () => UnknownEventSourceError,
39
- UnregisteredIntentError: () => UnregisteredIntentError,
40
- architecturalPolicies: () => architecturalPolicies,
41
- buildPublishPolicyContext: () => buildPublishPolicyContext,
42
- checkAdapterGovernance: () => checkAdapterGovernance,
43
- checkContract: () => checkContract,
20
+ // src/gate.ts
21
+ var gate_exports = {};
22
+ __export(gate_exports, {
23
+ ANALYSIS_IR_SCHEMA_VERSION: () => ANALYSIS_IR_SCHEMA_VERSION,
24
+ ARK_ANALYSIS_RESULT_SCHEMA: () => ARK_ANALYSIS_RESULT_SCHEMA,
25
+ ARK_ANALYSIS_RESULT_SCHEMA_VERSION: () => ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
26
+ ARK_CONFIG_SCHEMA: () => ARK_CONFIG_SCHEMA,
27
+ ARK_CONFIG_SCHEMA_VERSION: () => ARK_CONFIG_SCHEMA_VERSION,
28
+ analyzeChange: () => analyzeChange,
29
+ analyzeProject: () => analyzeProject,
30
+ collectAnalysisConfigWarnings: () => collectAnalysisConfigWarnings,
31
+ collectForbiddenCapabilityUses: () => collectForbiddenCapabilityUses,
44
32
  createAICodeGate: () => createAICodeGate,
45
- createAdapter: () => createAdapter,
33
+ createAdapterResult: () => createAdapterResult,
46
34
  createArchitectureProfile: () => createArchitectureProfile,
47
35
  createArchitectureProfileFromArkConfig: () => createArchitectureProfileFromArkConfig,
48
- createArkKernel: () => createArkKernel,
49
- createArkKernelFromConfig: () => createArkKernelFromConfig,
50
- createArkManifest: () => createArkManifest,
51
- createArkTestHarness: () => createArkTestHarness,
52
- createAuditTrail: () => createAuditTrail,
53
- createDependencyGraph: () => createDependencyGraph,
54
36
  createElevenLayerArkConfig: () => createElevenLayerArkConfig,
55
- createEventBus: () => createEventBus,
56
- createEventContractRegistry: () => createEventContractRegistry,
57
- createIntentRegistry: () => createIntentRegistry,
58
- createLenientArkKernel: () => createLenientArkKernel,
59
- createLenientArkKernelFromConfig: () => createLenientArkKernelFromConfig,
60
- createMetadataRegistry: () => createMetadataRegistry,
61
- createObservabilityReporter: () => createObservabilityReporter,
62
- createProjectionRegistry: () => createProjectionRegistry,
63
- createSaga: () => createSaga,
64
- createStrictArkKernel: () => createStrictArkKernel,
65
- createStrictArkKernelFromConfig: () => createStrictArkKernelFromConfig,
66
- createWorkflowEngine: () => createWorkflowEngine,
67
- defaultIntentRegistry: () => defaultIntentRegistry,
68
- defineArchitectureProfilePolicy: () => defineArchitectureProfilePolicy,
69
- defineIntent: () => defineIntent,
70
- defineLayerPolicy: () => defineLayerPolicy,
71
- definePolicy: () => definePolicy,
72
- definePort: () => definePort,
73
- definePublishPolicy: () => definePublishPolicy,
37
+ detectArchitectureCycles: () => detectArchitectureCycles,
38
+ deterministicHash: () => deterministicHash,
74
39
  elevenLayerProfile: () => elevenLayerProfile,
75
- isLayerPolicy: () => isLayerPolicy,
76
- syncRegistryToGraph: () => syncRegistryToGraph,
77
- validateIntentName: () => validateIntentName,
40
+ evaluateArchitectureGraph: () => evaluateArchitectureGraph,
41
+ explainViolation: () => explainViolation,
42
+ extractSemanticDependencies: () => extractSemanticDependencies,
43
+ loadArkConfigContract: () => loadArkConfigContract,
44
+ loadContract: () => loadContract,
45
+ parseArkConfigJson: () => parseArkConfigJson,
46
+ stableSerialize: () => stableSerialize,
47
+ toAdapterDiagnostic: () => toAdapterDiagnostic,
78
48
  version: () => version
79
49
  });
80
- module.exports = __toCommonJS(index_exports);
50
+ module.exports = __toCommonJS(gate_exports);
81
51
 
82
52
  // src/version.ts
83
- var version = "2.12.0";
53
+ var version = "3.0.0";
84
54
 
85
- // src/kernel/intent/IntentRegistry.ts
86
- var IntentRegistry = class {
87
- intents = /* @__PURE__ */ new Map();
88
- dependencies = /* @__PURE__ */ new Map();
89
- productions = /* @__PURE__ */ new Map();
90
- /**
91
- * Define/register a new intent.
92
- *
93
- * @param name - Semantic intent name following the convention (Domain.*, Application.*, etc.)
94
- * @param options - Optional relationship declarations
95
- * @throws Error if an intent with the same name is already registered
96
- */
97
- define(name, options) {
98
- if (this.intents.has(name)) {
99
- throw new Error(
100
- `Intent "${name}" is already registered. Intent names must be unique within a registry.`
101
- );
102
- }
103
- const fn = (payload) => ({
104
- intent: name,
105
- payload,
106
- metadata: {
107
- occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
108
- source: "unknown"
109
- }
110
- });
111
- Object.defineProperty(fn, "name", {
112
- value: name,
113
- enumerable: true,
114
- configurable: false,
115
- writable: false
116
- });
117
- const creator = fn;
118
- this.intents.set(name, creator);
119
- if (options?.dependsOn) {
120
- for (const dep of options.dependsOn) {
121
- this.declareDependency(name, dep);
122
- }
123
- }
124
- if (options?.produces) {
125
- for (const prod of options.produces) {
126
- this.declareProduction(name, prod);
127
- }
128
- }
129
- return creator;
130
- }
131
- /**
132
- * Declare that one intent depends on / relates to another.
133
- * This information is used by the DependencyGraph (future iterations) and for policy checks.
134
- *
135
- * @param from - The source intent (e.g. an Application operation)
136
- * @param to - The target intent it depends on (e.g. a Domain event or concept)
137
- */
138
- declareDependency(from, to) {
139
- if (!this.dependencies.has(from)) {
140
- this.dependencies.set(from, /* @__PURE__ */ new Set());
141
- }
142
- this.dependencies.get(from).add(to);
143
- }
144
- /**
145
- * Declare that one intent produces / emits another (e.g. use case → domain event).
146
- */
147
- declareProduction(from, to) {
148
- if (!this.productions.has(from)) {
149
- this.productions.set(from, /* @__PURE__ */ new Set());
150
- }
151
- this.productions.get(from).add(to);
152
- }
153
- /**
154
- * Retrieve a previously defined intent creator by name.
155
- */
156
- get(name) {
157
- return this.intents.get(name);
158
- }
159
- /**
160
- * List all registered intent creators.
161
- */
162
- list() {
163
- return Array.from(this.intents.values());
164
- }
165
- /**
166
- * Get all declared dependencies for a given intent.
167
- */
168
- getDependencies(intentName) {
169
- const deps = this.dependencies.get(intentName);
170
- return deps ? Array.from(deps) : [];
171
- }
172
- /**
173
- * Get all intents produced / emitted by a given intent.
174
- */
175
- getProductions(intentName) {
176
- const prods = this.productions.get(intentName);
177
- return prods ? Array.from(prods) : [];
178
- }
179
- /**
180
- * Get all declared relationships (useful for graph generation).
181
- */
182
- getAllRelationships() {
183
- const result = [];
184
- for (const [from, tos] of this.dependencies.entries()) {
185
- for (const to of tos) {
186
- result.push({ from, to, kind: "dependsOn" });
187
- }
188
- }
189
- for (const [from, tos] of this.productions.entries()) {
190
- for (const to of tos) {
191
- result.push({ from, to, kind: "produces" });
192
- }
193
- }
194
- return result;
195
- }
196
- /**
197
- * Check if an intent name has been registered.
198
- */
199
- has(name) {
200
- return this.intents.has(name);
201
- }
202
- /**
203
- * Clear the registry. Primarily useful for tests.
204
- */
205
- clear() {
206
- this.intents.clear();
207
- this.dependencies.clear();
208
- this.productions.clear();
209
- }
210
- };
211
-
212
- // src/kernel/intent/defineIntent.ts
213
- var defaultRegistry = new IntentRegistry();
214
- function defineIntent(name, options) {
215
- return defaultRegistry.define(name, options);
216
- }
217
- function createIntentRegistry() {
218
- return new IntentRegistry();
219
- }
220
- var defaultIntentRegistry = defaultRegistry;
221
-
222
- // src/kernel/intent/validateIntentName.ts
223
- var ALLOWED_PREFIXES = [
224
- "Domain.",
225
- "Application.",
226
- "Adapter.",
227
- "Workflow.",
228
- "Job.",
229
- "Presentation.",
230
- "Reporting.",
231
- "Metadata.",
232
- "Security.",
233
- "Audit.",
234
- "Observability.",
235
- "Kernel."
236
- ];
237
- function validateIntentName(name) {
238
- if (!name || typeof name !== "string") {
239
- return { valid: false, reason: "Intent name must be a non-empty string" };
240
- }
241
- if (!ALLOWED_PREFIXES.some((p) => name.startsWith(p))) {
242
- return {
243
- valid: false,
244
- reason: `Intent "${name}" must start with one of: ${ALLOWED_PREFIXES.join(", ")}`
245
- };
246
- }
247
- const rest = name.slice(name.indexOf(".") + 1);
248
- if (!rest || !/^[A-Za-z][A-Za-z0-9_.]*$/.test(rest)) {
249
- return {
250
- valid: false,
251
- reason: `Intent "${name}" has an invalid segment after the layer prefix`
252
- };
253
- }
254
- return { valid: true };
255
- }
256
-
257
- // src/kernel/policy/PolicyViolationError.ts
258
- var PolicyViolationError = class extends Error {
259
- violations;
260
- constructor(violations) {
261
- const messages = violations.map((v) => `- ${v.policyName}: ${v.message}`).join("\n");
262
- super(`Hard policy violation(s) detected:
263
- ${messages}`);
264
- this.name = "PolicyViolationError";
265
- this.violations = violations;
266
- }
267
- };
268
-
269
- // src/kernel/policy/PolicyEngine.ts
270
- var PolicyEngine = class {
271
- policies = [];
272
- constructor(initialPolicies = []) {
273
- for (const policy of initialPolicies) {
274
- this.add(policy);
275
- }
276
- }
277
- /**
278
- * Adds a policy to the engine.
279
- */
280
- add(policy) {
281
- if (this.policies.some((p) => p.name === policy.name)) {
282
- throw new Error(`Policy "${policy.name}" is already registered in this engine.`);
283
- }
284
- this.policies.push(policy);
285
- }
286
- /**
287
- * Returns all registered policies.
288
- */
289
- getPolicies() {
290
- return [...this.policies];
291
- }
292
- /**
293
- * Evaluates all policies against the provided context.
294
- */
295
- evaluate(context) {
296
- const violations = [];
297
- for (const policy of this.policies) {
298
- const result = policy.check(context);
299
- if (result === true) {
300
- continue;
301
- }
302
- if (result === false) {
303
- violations.push({
304
- policyName: policy.name,
305
- severity: policy.severity,
306
- message: `Policy "${policy.name}" was violated.`
307
- });
308
- continue;
309
- }
310
- if (Array.isArray(result)) {
311
- for (const v of result) {
312
- violations.push({
313
- policyName: policy.name,
314
- severity: policy.severity,
315
- message: v.message,
316
- details: v.details
317
- });
318
- }
319
- } else {
320
- violations.push({
321
- policyName: policy.name,
322
- severity: policy.severity,
323
- message: result.message,
324
- details: result.details
325
- });
326
- }
327
- }
328
- const hardViolations = violations.filter((v) => v.severity === "hard");
329
- const softViolations = violations.filter((v) => v.severity === "soft");
330
- return {
331
- passed: violations.length === 0,
332
- violations,
333
- hardViolations,
334
- softViolations
335
- };
336
- }
337
- /**
338
- * Enforces all policies.
339
- *
340
- * - Soft violations are collected and can be observed (returned or logged).
341
- * - Hard violations cause an error to be thrown (by default).
342
- *
343
- * @returns Evaluation result (including any soft violations)
344
- * @throws Error if any hard policy is violated
345
- */
346
- enforce(context) {
347
- const result = this.evaluate(context);
348
- if (result.hardViolations.length > 0) {
349
- throw new PolicyViolationError(result.hardViolations);
350
- }
351
- return result;
352
- }
353
- /**
354
- * Clears all registered policies.
355
- */
356
- clear() {
357
- this.policies.length = 0;
358
- }
359
- };
360
-
361
- // src/kernel/policy/definePolicy.ts
362
- function definePolicy(options) {
363
- const severity = options.severity ?? "soft";
364
- const policy = {
365
- name: options.name,
366
- severity,
367
- tags: options.tags,
368
- owner: options.owner,
369
- version: options.version,
370
- rationale: options.rationale,
371
- enforcementMode: options.enforcementMode,
372
- deprecated: options.deprecated,
373
- replacedBy: options.replacedBy,
374
- check: options.check
55
+ // src/domain/adapterContract.ts
56
+ var ARK_ANALYSIS_RESULT_SCHEMA_VERSION = "1.0";
57
+ function text(value) {
58
+ return typeof value === "string" && value.length > 0 ? value : void 0;
59
+ }
60
+ function positiveInteger(value, fallback) {
61
+ return Number.isInteger(value) && Number(value) > 0 ? Number(value) : fallback;
62
+ }
63
+ function toAdapterDiagnostic(violation2, fallbackSeverity = "error") {
64
+ const ruleId = text(violation2.ruleId) ?? text(violation2.code) ?? "ARK_UNKNOWN";
65
+ const severity = violation2.severity === "warning" ? "warning" : fallbackSeverity;
66
+ const evidence = {
67
+ ...text(violation2.target) ? { target: text(violation2.target) } : {},
68
+ ...text(violation2.fromLayer) ? { fromLayer: text(violation2.fromLayer) } : {},
69
+ ...text(violation2.toLayer) ? { toLayer: text(violation2.toLayer) } : {},
70
+ ...typeof violation2.typeOnly === "boolean" ? { typeOnly: violation2.typeOnly } : {}
375
71
  };
376
- return policy;
377
- }
378
-
379
- // src/kernel/policy/builtins.ts
380
- function defaultLayerOf(name) {
381
- const dot = name.indexOf(".");
382
- return dot >= 0 ? name.slice(0, dot) : name;
383
- }
384
- function resolveLayer(name, options) {
385
- return options.resolveLayer?.(name) ?? defaultLayerOf(name);
386
- }
387
- function matchesRule(fromLayer, toLayer, rule) {
388
- return fromLayer === rule.from && toLayer === rule.to;
389
- }
390
- function defineLayerPolicy(options) {
391
- const name = options.name ?? "Layer isolation";
392
- const severity = options.severity ?? "hard";
393
- return definePolicy({
394
- name,
72
+ return {
73
+ ruleId,
395
74
  severity,
396
- tags: ["layer"],
397
- check: (ctx) => {
398
- const edges = [
399
- ...(ctx.edges ?? []).filter((e) => e.kind === "declared" || e.kind === "produces").map((e) => ({ from: e.from, to: e.to })),
400
- ...(ctx.relationships ?? []).filter((r) => r.kind === "dependsOn").map((r) => ({ from: r.from, to: r.to }))
401
- ];
402
- const violations = [];
403
- for (const edge of edges) {
404
- const fromLayer = resolveLayer(edge.from, options);
405
- const toLayer = resolveLayer(edge.to, options);
406
- for (const rule of options.rules) {
407
- if (!rule.allowed && matchesRule(fromLayer, toLayer, rule)) {
408
- violations.push({
409
- policyName: name,
410
- severity,
411
- message: rule.message ?? `Layer violation: ${edge.from} (${fromLayer}) must not relate to ${edge.to} (${toLayer})`
412
- });
413
- }
414
- }
415
- }
416
- return violations.length > 0 ? violations : true;
417
- }
418
- });
419
- }
420
- function isLayerPolicy(policy) {
421
- return policy.tags?.includes("layer") ?? false;
422
- }
423
- var architecturalPolicies = {
424
- /**
425
- * @deprecated Use cleanArchitectureMatrix() for full layer rules.
426
- * Blocks Domain → Adapter declared dependencies only.
427
- */
428
- layerIsolation() {
429
- return architecturalPolicies.cleanArchitectureMatrix();
430
- },
431
- /**
432
- * Clean-architecture dependency matrix (declared dependsOn / declared edges only).
433
- * Does not block observed event flows (Domain events consumed by Application).
434
- */
435
- cleanArchitectureMatrix() {
436
- return defineLayerPolicy({
437
- name: "Clean architecture matrix",
438
- severity: "hard",
439
- rules: [
440
- { from: "Domain", to: "Adapter", allowed: false },
441
- { from: "Domain", to: "Application", allowed: false },
442
- { from: "Adapter", to: "Application", allowed: false },
443
- { from: "Adapter", to: "Domain", allowed: false }
444
- ]
445
- });
446
- }
447
- };
448
- function defineArchitectureProfilePolicy(profile, options = {}) {
449
- return defineLayerPolicy({
450
- name: options.name ?? `${profile.name} layer policy`,
451
- severity: options.severity ?? "hard",
452
- rules: profile.rules,
453
- resolveLayer: profile.resolveLayer
454
- });
455
- }
456
-
457
- // src/kernel/event-bus/policyContext.ts
458
- function buildPublishPolicyContext(options) {
459
- return (event) => ({
460
- event,
461
- relationships: options.intentRegistry?.getAllRelationships(),
462
- edges: options.dependencyGraph?.getEdges()
463
- });
464
- }
465
- function definePublishPolicy(options) {
466
- return definePolicy(options);
467
- }
468
-
469
- // src/kernel/event-bus/errors.ts
470
- var UnregisteredIntentError = class extends Error {
471
- intentName;
472
- constructor(intentName) {
473
- super(
474
- `Intent "${intentName}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`
475
- );
476
- this.name = "UnregisteredIntentError";
477
- this.intentName = intentName;
478
- }
479
- };
480
- var InvalidIntentNameError = class extends Error {
481
- intentName;
482
- reason;
483
- constructor(intentName, reason) {
484
- super(`Invalid intent name "${intentName}": ${reason}`);
485
- this.name = "InvalidIntentNameError";
486
- this.intentName = intentName;
487
- this.reason = reason;
488
- }
489
- };
490
- var LayerPolicyContextError = class extends Error {
491
- constructor() {
492
- super(
493
- "Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."
494
- );
495
- this.name = "LayerPolicyContextError";
496
- }
497
- };
498
- var EventContractViolationError = class extends Error {
499
- intentName;
500
- issues;
501
- constructor(intentName, issues) {
502
- super(
503
- `Event contract violation for "${intentName}". Register a matching event contract/version or fix the payload before publishing.`
504
- );
505
- this.name = "EventContractViolationError";
506
- this.intentName = intentName;
507
- this.issues = issues;
508
- }
509
- };
510
- var UnknownEventSourceError = class extends Error {
511
- intentName;
512
- source;
513
- constructor(intentName, source) {
514
- super(
515
- 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.`
516
- );
517
- this.name = "UnknownEventSourceError";
518
- this.intentName = intentName;
519
- this.source = source;
520
- }
521
- };
522
- var SourceMetadataOverrideError = class extends Error {
523
- boundSource;
524
- attemptedSource;
525
- constructor(boundSource, attemptedSource) {
526
- super(
527
- `Source-bound publisher for "${boundSource}" cannot publish with metadata.source "${attemptedSource}". Create a publisher for the intended source instead.`
528
- );
529
- this.name = "SourceMetadataOverrideError";
530
- this.boundSource = boundSource;
531
- this.attemptedSource = attemptedSource;
532
- }
533
- };
534
- var ObservedLayerFlowViolationError = class extends Error {
535
- source;
536
- intentName;
537
- fromLayer;
538
- toLayer;
539
- constructor(source, intentName, fromLayer, toLayer, message) {
540
- super(
541
- message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${intentName}" (${toLayer}). Route this through an allowed layer or adjust the architecture profile rule.`
542
- );
543
- this.name = "ObservedLayerFlowViolationError";
544
- this.source = source;
545
- this.intentName = intentName;
546
- this.fromLayer = fromLayer;
547
- this.toLayer = toLayer;
548
- }
549
- };
550
-
551
- // src/kernel/event-bus/publishGuards.ts
552
- function assertIntentAllowed(intentName, options) {
553
- if (!options.strictRegistry && !options.validateIntentNaming) {
554
- return;
555
- }
556
- if (options.validateIntentNaming) {
557
- const validation = validateIntentName(intentName);
558
- if (!validation.valid) {
559
- throw new InvalidIntentNameError(intentName, validation.reason);
560
- }
561
- }
562
- if (options.strictRegistry && options.intentRegistry && !options.intentRegistry.has(intentName)) {
563
- throw new UnregisteredIntentError(intentName);
564
- }
565
- }
566
- function assertSourceAllowed(event, options) {
567
- if (!options.requireKnownSource) return;
568
- if (!event.metadata.source || event.metadata.source === "unknown") {
569
- throw new UnknownEventSourceError(event.intent);
570
- }
571
- if (options.intentRegistry && !options.intentRegistry.has(event.metadata.source)) {
572
- throw new UnknownEventSourceError(event.intent, event.metadata.source);
573
- }
574
- }
575
- function assertContractAllowed(event, options) {
576
- if (!options.eventContracts) return;
577
- const result = options.eventContracts.validate(event);
578
- if (!result.ok && (options.strictEventContracts || result.contract)) {
579
- throw new EventContractViolationError(event.intent, result.issues);
580
- }
581
- }
582
-
583
- // src/kernel/event-bus/payloadPatch.ts
584
- function isPlainRecord(value) {
585
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
586
- return false;
587
- }
588
- const proto = Object.getPrototypeOf(value);
589
- return proto === Object.prototype || proto === null;
590
- }
591
- function clonePatchValue(value) {
592
- if (Array.isArray(value)) return value.map(clonePatchValue);
593
- if (isPlainRecord(value)) {
594
- return Object.fromEntries(
595
- Object.entries(value).map(([key, child]) => [key, clonePatchValue(child)])
596
- );
597
- }
598
- return value;
599
- }
600
- function mergeRecordPatch(target, patch, path = "payload") {
601
- const next = { ...target };
602
- for (const [key, value] of Object.entries(patch)) {
603
- const childPath = `${path}.${key}`;
604
- if (!(key in next) || next[key] === void 0) {
605
- next[key] = clonePatchValue(value);
606
- continue;
607
- }
608
- if (isPlainRecord(next[key]) && isPlainRecord(value)) {
609
- next[key] = mergeRecordPatch(next[key], value, childPath);
610
- continue;
611
- }
612
- if (Array.isArray(next[key]) && Array.isArray(value)) {
613
- next[key] = mergeArrayPatch(next[key], value, childPath);
614
- continue;
615
- }
616
- throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
617
- }
618
- return next;
619
- }
620
- function mergeArrayPatch(target, patch, path = "payload") {
621
- const next = [...target];
622
- patch.forEach((value, index) => {
623
- const childPath = `${path}[${index}]`;
624
- if (index >= next.length || next[index] === void 0) {
625
- next[index] = clonePatchValue(value);
626
- return;
627
- }
628
- if (isPlainRecord(next[index]) && isPlainRecord(value)) {
629
- next[index] = mergeRecordPatch(next[index], value, childPath);
630
- return;
631
- }
632
- if (Array.isArray(next[index]) && Array.isArray(value)) {
633
- next[index] = mergeArrayPatch(next[index], value, childPath);
634
- return;
635
- }
636
- throw new Error(`Interceptor patch cannot overwrite existing ${childPath}.`);
637
- });
638
- return next;
75
+ message: text(violation2.message) ?? ruleId,
76
+ location: {
77
+ file: text(violation2.file) ?? "<unknown>",
78
+ line: positiveInteger(violation2.line, 1),
79
+ column: positiveInteger(violation2.column, 1)
80
+ },
81
+ evidence
82
+ };
639
83
  }
640
- function applyPayloadPatch(payload, patch) {
641
- if (Array.isArray(patch)) {
642
- if (payload === void 0) return clonePatchValue(patch);
643
- if (!Array.isArray(payload)) {
644
- throw new Error("Array interceptor patch requires an array payload.");
645
- }
646
- return mergeArrayPatch(payload, patch);
647
- }
648
- if (payload === void 0) return clonePatchValue(patch);
649
- if (!isPlainRecord(payload)) {
650
- throw new Error("Object interceptor patch requires an object payload.");
651
- }
652
- return mergeRecordPatch(payload, patch);
84
+ function createAdapterResult(input) {
85
+ return {
86
+ schemaVersion: ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
87
+ valid: input.valid,
88
+ diagnostics: [
89
+ ...(input.violations ?? []).map((item) => toAdapterDiagnostic(item, "error")),
90
+ ...(input.warnings ?? []).map((item) => toAdapterDiagnostic(item, "warning"))
91
+ ]
92
+ };
653
93
  }
654
-
655
- // src/kernel/event-bus/publishInterceptors.ts
656
- async function applyInterceptors(event, deps) {
657
- if (event.metadata.allowInterception === false) {
658
- return event;
659
- }
660
- const matching = [...deps.interceptorsForIntent(event.intent)];
661
- let current = event;
662
- for (const registration of matching) {
663
- const patches = [];
664
- try {
665
- await Promise.resolve(
666
- registration.interceptor({
667
- event: current,
668
- intercept: (patch) => {
669
- patches.push(patch);
94
+ var ARK_ANALYSIS_RESULT_SCHEMA = {
95
+ $schema: "https://json-schema.org/draft/2020-12/schema",
96
+ $id: "https://unpkg.com/arkgate@2/schemas/ark.analysis-result.schema.json",
97
+ title: "ArkGate analysis result",
98
+ type: "object",
99
+ additionalProperties: false,
100
+ required: ["schemaVersion", "valid", "diagnostics"],
101
+ properties: {
102
+ schemaVersion: { const: ARK_ANALYSIS_RESULT_SCHEMA_VERSION },
103
+ valid: { type: "boolean" },
104
+ diagnostics: {
105
+ type: "array",
106
+ items: {
107
+ type: "object",
108
+ additionalProperties: false,
109
+ required: ["ruleId", "severity", "message", "location", "evidence"],
110
+ properties: {
111
+ ruleId: { type: "string", minLength: 1 },
112
+ severity: { enum: ["error", "warning"] },
113
+ message: { type: "string", minLength: 1 },
114
+ location: {
115
+ type: "object",
116
+ additionalProperties: false,
117
+ required: ["file", "line", "column"],
118
+ properties: {
119
+ file: { type: "string", minLength: 1 },
120
+ line: { type: "integer", minimum: 1 },
121
+ column: { type: "integer", minimum: 1 }
122
+ }
123
+ },
124
+ evidence: {
125
+ type: "object",
126
+ additionalProperties: false,
127
+ properties: {
128
+ target: { type: "string" },
129
+ fromLayer: { type: "string" },
130
+ toLayer: { type: "string" },
131
+ typeOnly: { type: "boolean" }
132
+ }
670
133
  }
671
- })
672
- );
673
- if (patches.length === 0) {
674
- continue;
675
- }
676
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
677
- let candidate = {
678
- ...current,
679
- metadata: {
680
- ...current.metadata,
681
- interceptions: [
682
- ...current.metadata.interceptions ?? [],
683
- { interceptorId: registration.interceptorId, timestamp }
684
- ]
685
134
  }
686
- };
687
- for (const patch of patches) {
688
- candidate = {
689
- ...candidate,
690
- payload: applyPayloadPatch(candidate.payload, patch),
691
- metadata: { ...candidate.metadata }
692
- };
693
135
  }
694
- assertContractAllowed(candidate, {
695
- eventContracts: deps.eventContracts,
696
- strictEventContracts: deps.strictEventContracts
697
- });
698
- current = candidate;
699
- registration.lastInterceptedAt = timestamp;
700
- deps.appendTrace({
701
- type: "event.intercepted",
702
- timestamp,
703
- intent: current.intent,
704
- correlationId: current.metadata.correlationId,
705
- traceId: current.metadata.traceId,
706
- spanId: current.metadata.spanId,
707
- details: {
708
- registrationId: registration.registrationId,
709
- interceptorId: registration.interceptorId,
710
- patchesApplied: patches.length
711
- }
712
- });
713
- await deps.recordAudit("event.intercepted", current, {
714
- registrationId: registration.registrationId,
715
- interceptorId: registration.interceptorId,
716
- patchesApplied: patches.length
717
- });
718
- } catch (err) {
719
- await recordInterceptorError(registration, current, err, deps);
720
136
  }
721
137
  }
722
- return current;
723
- }
724
- async function recordInterceptorError(interceptor, event, error, deps) {
725
- const message = error instanceof Error ? error.message : String(error);
726
- deps.appendTrace({
727
- type: "interceptor.error",
728
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
729
- intent: event.intent,
730
- correlationId: event.metadata.correlationId,
731
- traceId: event.metadata.traceId,
732
- spanId: event.metadata.spanId,
733
- details: {
734
- registrationId: interceptor.registrationId,
735
- interceptorId: interceptor.interceptorId,
736
- error: message
737
- }
738
- });
739
- await deps.recordAudit("interceptor.error", event, {
740
- registrationId: interceptor.registrationId,
741
- interceptorId: interceptor.interceptorId,
742
- error: message
743
- });
744
- }
138
+ };
745
139
 
746
140
  // src/domain/layerMatch.ts
141
+ var regexpCache = /* @__PURE__ */ new Map();
142
+ function escapeLiteral(ch) {
143
+ return /[.*+?^${}()|[\]\\]/.test(ch) ? `\\${ch}` : ch;
144
+ }
747
145
  function normalizeGlobSeparators(pattern) {
748
146
  let out = "";
749
147
  for (let i = 0; i < pattern.length; i += 1) {
@@ -762,6 +160,91 @@ function normalizeGlobSeparators(pattern) {
762
160
  }
763
161
  return out;
764
162
  }
163
+ function bracesBalanced(glob) {
164
+ let depth = 0;
165
+ for (let i = 0; i < glob.length; i += 1) {
166
+ const c = glob[i];
167
+ if (c === "\\") {
168
+ i += 1;
169
+ continue;
170
+ }
171
+ if (c === "{") depth += 1;
172
+ else if (c === "}") {
173
+ depth -= 1;
174
+ if (depth < 0) return false;
175
+ }
176
+ }
177
+ return depth === 0;
178
+ }
179
+ function globToRegExp(pattern) {
180
+ const cached = regexpCache.get(pattern);
181
+ if (cached) return cached;
182
+ const glob = normalizeGlobSeparators(pattern);
183
+ const useBraces = bracesBalanced(glob);
184
+ let out = "";
185
+ let braceDepth = 0;
186
+ for (let i = 0; i < glob.length; i += 1) {
187
+ const c = glob[i];
188
+ if (c === "\\" && i + 1 < glob.length) {
189
+ out += escapeLiteral(glob[i + 1]);
190
+ i += 1;
191
+ } else if (c === "*") {
192
+ if (glob[i + 1] === "*") {
193
+ if (glob[i + 2] === "/") {
194
+ out += "(?:.*/)?";
195
+ i += 2;
196
+ } else {
197
+ out += ".*";
198
+ i += 1;
199
+ }
200
+ } else {
201
+ out += "[^/]*";
202
+ }
203
+ } else if (c === "?") {
204
+ out += "[^/]";
205
+ } else if (c === "{" && useBraces) {
206
+ out += "(?:";
207
+ braceDepth += 1;
208
+ } else if (c === "}" && useBraces && braceDepth > 0) {
209
+ out += ")";
210
+ braceDepth -= 1;
211
+ } else if (c === "," && useBraces && braceDepth > 0) {
212
+ out += "|";
213
+ } else {
214
+ out += escapeLiteral(c);
215
+ }
216
+ }
217
+ const re = new RegExp(`^${out}$`);
218
+ regexpCache.set(pattern, re);
219
+ return re;
220
+ }
221
+ function patternSpecificity(pattern) {
222
+ const glob = normalizeGlobSeparators(String(pattern));
223
+ const beforeWildcard = glob.split("*")[0];
224
+ const literalSegments = beforeWildcard.split("/").filter(Boolean).length;
225
+ const literalLength = glob.replace(/\*/g, "").length;
226
+ return literalSegments * 1e4 + literalLength;
227
+ }
228
+ function layerForRelativePath(relPath, layers) {
229
+ const rel = String(relPath).split(/[/\\]/).join("/");
230
+ let bestName;
231
+ let bestScore = -1;
232
+ for (const layer of layers ?? []) {
233
+ if ((layer.exclude ?? []).some((pattern) => globToRegExp(pattern).test(rel))) {
234
+ continue;
235
+ }
236
+ for (const pattern of layer.patterns ?? []) {
237
+ if (globToRegExp(pattern).test(rel)) {
238
+ const score = patternSpecificity(pattern);
239
+ if (score > bestScore) {
240
+ bestScore = score;
241
+ bestName = layer.name;
242
+ }
243
+ }
244
+ }
245
+ }
246
+ return bestName;
247
+ }
765
248
  function sliceIdForPath(relPath, sliceFolders) {
766
249
  if (!sliceFolders?.length) return void 0;
767
250
  const parts = String(relPath).split(/[/\\]/).filter(Boolean);
@@ -819,1407 +302,225 @@ function findDeniedEdgeRule(rules, from, to, options) {
819
302
  return void 0;
820
303
  }
821
304
 
822
- // src/kernel/event-bus/observedLayerFlow.ts
823
- async function assertObservedLayerFlowAllowed(event, deps) {
824
- if (deps.mode === "off" || !deps.architectureProfile) {
825
- return;
826
- }
827
- const source = event.metadata.source;
828
- if (!source || source === "unknown") return;
829
- const profile = deps.architectureProfile;
830
- const fromLayer = profile.resolveLayer(source);
831
- const toLayer = profile.resolveLayer(event.intent);
832
- if (!fromLayer || !toLayer) return;
833
- const blocked = findDeniedEdgeRule(profile.rules, fromLayer, toLayer);
834
- if (!blocked) return;
835
- const severity = deps.mode;
836
- const message = blocked.message ?? `Observed layer violation: "${source}" (${fromLayer}) must not produce "${event.intent}" (${toLayer}).`;
837
- const details = {
838
- source,
839
- intent: event.intent,
840
- fromLayer,
841
- toLayer,
842
- severity,
843
- message,
844
- rule: blocked
845
- };
846
- deps.appendTrace({
847
- type: "layer.observedViolation",
848
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
849
- intent: event.intent,
850
- correlationId: event.metadata.correlationId,
851
- traceId: event.metadata.traceId,
852
- spanId: event.metadata.spanId,
853
- details
854
- });
855
- await deps.recordAudit("layer.observedViolation", event, details);
856
- if (severity === "hard") {
857
- throw new ObservedLayerFlowViolationError(
858
- source,
859
- event.intent,
860
- fromLayer,
861
- toLayer,
862
- message
863
- );
864
- }
305
+ // src/domain/sourcePolicy.ts
306
+ var SOURCE_POLICY_MESSAGES = {
307
+ RAW_EVENT_PUBLISH: "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",
308
+ PUBLISH_MISSING_SOURCE: "Strict Ark publish calls must include metadata.source."
309
+ };
310
+ function looksLikeArkIntent(value) {
311
+ return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(
312
+ value
313
+ );
865
314
  }
866
-
867
- // src/kernel/event-bus/publishPolicy.ts
868
- async function enforcePublishPolicy(event, deps) {
869
- const ctx = deps.getPolicyContext(event);
870
- let policyResult;
871
- try {
872
- policyResult = deps.policyEngine.enforce(ctx);
873
- } catch (err) {
874
- if (err instanceof PolicyViolationError) {
875
- deps.appendTrace({
876
- type: "policy.hardViolation",
877
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
878
- intent: event.intent,
879
- correlationId: event.metadata.correlationId,
880
- traceId: event.metadata.traceId,
881
- spanId: event.metadata.spanId,
882
- details: { violations: err.violations }
883
- });
884
- await deps.recordAudit("policy.hardViolation", event, {
885
- violations: err.violations
886
- });
887
- }
888
- throw err;
889
- }
890
- if (policyResult.softViolations.length > 0) {
891
- deps.appendTrace({
892
- type: "policy.softViolation",
893
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
894
- intent: event.intent,
895
- correlationId: event.metadata.correlationId,
896
- traceId: event.metadata.traceId,
897
- spanId: event.metadata.spanId,
898
- details: { violations: policyResult.softViolations }
315
+ function classifyPublishFacts(facts) {
316
+ if (!facts.publishCall) return [];
317
+ const findings = [];
318
+ if (facts.rawIntentName !== void 0 && looksLikeArkIntent(facts.rawIntentName) || facts.objectHasIntent) {
319
+ findings.push({
320
+ ruleId: "RAW_EVENT_PUBLISH",
321
+ message: SOURCE_POLICY_MESSAGES.RAW_EVENT_PUBLISH
899
322
  });
900
- await deps.recordAudit("policy.softViolation", event, {
901
- violations: policyResult.softViolations
323
+ }
324
+ if (facts.arkPublishCandidate && !facts.hasSource) {
325
+ findings.push({
326
+ ruleId: "PUBLISH_MISSING_SOURCE",
327
+ message: SOURCE_POLICY_MESSAGES.PUBLISH_MISSING_SOURCE
902
328
  });
903
- if (deps.onSoftViolation) {
904
- await deps.safeHook(
905
- () => deps.onSoftViolation(policyResult, event),
906
- "onSoftViolation",
907
- event
908
- );
909
- }
910
329
  }
330
+ return findings;
911
331
  }
912
332
 
913
- // src/kernel/event-bus/publishRecording.ts
914
- function appendHistory(buffers, record) {
915
- buffers.history.push(record);
916
- if (buffers.maxHistorySize !== void 0 && buffers.history.length > buffers.maxHistorySize) {
917
- buffers.history.splice(0, buffers.history.length - buffers.maxHistorySize);
918
- }
333
+ // src/kernel/semanticAnalysis.ts
334
+ function literalText(ts, node) {
335
+ return node && ts.isStringLiteralLike(node) ? node.text : void 0;
919
336
  }
920
- function appendTrace(buffers, record) {
921
- buffers.trace.push(record);
922
- if (buffers.maxHistorySize !== void 0 && buffers.trace.length > buffers.maxHistorySize) {
923
- buffers.trace.splice(0, buffers.trace.length - buffers.maxHistorySize);
337
+ function lineOf(sourceFile, node) {
338
+ return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1;
339
+ }
340
+ function isTypeOnlyReference(ts, node) {
341
+ if (ts.isImportDeclaration(node)) {
342
+ const clause = node.importClause;
343
+ if (!clause) return false;
344
+ if (clause.isTypeOnly) return true;
345
+ const named = clause.namedBindings;
346
+ return Boolean(
347
+ named && ts.isNamedImports(named) && named.elements.length > 0 && named.elements.every((element) => element.isTypeOnly)
348
+ );
924
349
  }
925
- for (const sink of buffers.traceSinks) {
926
- try {
927
- sink(record);
928
- } catch {
929
- }
350
+ if (ts.isExportDeclaration(node)) {
351
+ if (node.isTypeOnly) return true;
352
+ const clause = node.exportClause;
353
+ return Boolean(
354
+ clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly)
355
+ );
930
356
  }
357
+ return false;
358
+ }
359
+ function singleFileChecker(ts, sourceFile) {
360
+ const options = { noLib: true, noResolve: true, target: ts.ScriptTarget.Latest };
361
+ const host = ts.createCompilerHost(options, true);
362
+ host.getSourceFile = (fileName) => fileName === sourceFile.fileName ? sourceFile : void 0;
363
+ host.fileExists = (fileName) => fileName === sourceFile.fileName;
364
+ host.readFile = (fileName) => fileName === sourceFile.fileName ? sourceFile.text : void 0;
365
+ return ts.createProgram([sourceFile.fileName], options, host).getTypeChecker();
931
366
  }
932
- async function recordAudit(buffers, type, event, details) {
933
- if (!buffers.auditTrail) return;
367
+ function symbolAt(checker, node) {
934
368
  try {
935
- await buffers.auditTrail.record({
936
- type,
937
- source: event.metadata.source,
938
- intent: event.intent,
939
- correlationId: event.metadata.correlationId,
940
- causationId: event.metadata.causationId,
941
- subject: event.intent,
942
- details
943
- });
944
- } catch (err) {
945
- appendTrace(buffers, {
946
- type: "hook.error",
947
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
948
- intent: event.intent,
949
- correlationId: event.metadata.correlationId,
950
- traceId: event.metadata.traceId,
951
- spanId: event.metadata.spanId,
952
- details: {
953
- hook: "auditTrail",
954
- error: err instanceof Error ? err.message : String(err)
955
- }
956
- });
369
+ return checker.getSymbolAtLocation(node);
370
+ } catch {
371
+ return void 0;
957
372
  }
958
373
  }
959
- async function recordRawPublishDiagnostic(buffers, event) {
960
- const details = {
961
- intent: event.intent,
962
- source: event.metadata.source,
963
- suggestion: "Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."
964
- };
965
- appendTrace(buffers, {
966
- type: "event.rawPublish",
967
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
968
- intent: event.intent,
969
- correlationId: event.metadata.correlationId,
970
- traceId: event.metadata.traceId,
971
- spanId: event.metadata.spanId,
972
- details
973
- });
974
- await recordAudit(buffers, "event.rawPublish", event, details);
374
+ function localDeclaration(ts, checker, sourceFile, node) {
375
+ const shorthand = node.parent && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node;
376
+ let symbol;
377
+ try {
378
+ symbol = shorthand ? checker.getShorthandAssignmentValueSymbol(node.parent) : symbolAt(checker, node);
379
+ } catch {
380
+ symbol = void 0;
381
+ }
382
+ return Boolean(
383
+ symbol?.declarations?.some(
384
+ (declaration) => declaration.getSourceFile().fileName === sourceFile.fileName
385
+ )
386
+ );
975
387
  }
976
- async function recordSuccessfulPublish(buffers, event, subscribersNotified) {
977
- const record = {
978
- event,
979
- publishedAt: (/* @__PURE__ */ new Date()).toISOString(),
980
- subscribersNotified
981
- };
982
- appendHistory(buffers, record);
983
- await buffers.outbox?.enqueue(event);
984
- appendTrace(buffers, {
985
- type: "event.published",
986
- timestamp: record.publishedAt,
987
- intent: event.intent,
988
- correlationId: event.metadata.correlationId,
989
- traceId: event.metadata.traceId,
990
- spanId: event.metadata.spanId,
991
- details: { subscribersNotified }
388
+ function extractSemanticDependencies(ts, sourceFile) {
389
+ let checker;
390
+ const dependencies = [];
391
+ const add = (node, kind, specifier, typeOnly = false) => dependencies.push({
392
+ specifier,
393
+ kind,
394
+ line: lineOf(sourceFile, node),
395
+ typeOnly,
396
+ unresolved: specifier === void 0,
397
+ node
992
398
  });
993
- await recordAudit(buffers, "event.published", event, {
994
- subscribersNotified
995
- });
996
- return record;
997
- }
998
- function enrichMetadata(base, extra, instanceId) {
999
- return {
1000
- ...base,
1001
- ...extra,
1002
- occurredAt: extra.occurredAt || base.occurredAt || (/* @__PURE__ */ new Date()).toISOString(),
1003
- source: extra.source || base.source || "unknown",
1004
- kernelInstanceId: extra.kernelInstanceId ?? base.kernelInstanceId ?? instanceId,
1005
- eventVersion: extra.eventVersion ?? base.eventVersion,
1006
- schemaVersion: extra.schemaVersion ?? base.schemaVersion,
1007
- allowInterception: extra.allowInterception ?? base.allowInterception,
1008
- interceptions: extra.interceptions ?? base.interceptions,
1009
- correlationId: extra.correlationId ?? base.correlationId,
1010
- causationId: extra.causationId ?? base.causationId,
1011
- traceId: extra.traceId ?? base.traceId,
1012
- spanId: extra.spanId ?? base.spanId,
1013
- parentSpanId: extra.parentSpanId ?? base.parentSpanId
399
+ const visit = (node) => {
400
+ if (ts.isImportDeclaration(node)) {
401
+ add(node, "import", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
402
+ } else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
403
+ add(node, "export", literalText(ts, node.moduleSpecifier), isTypeOnlyReference(ts, node));
404
+ } else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
405
+ add(node, "require", literalText(ts, node.moduleReference.expression));
406
+ } else if (ts.isCallExpression(node)) {
407
+ const dynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
408
+ const requireCall = ts.isIdentifier(node.expression) && node.expression.text === "require";
409
+ const directRequire = requireCall && !localDeclaration(
410
+ ts,
411
+ checker ?? (checker = singleFileChecker(ts, sourceFile)),
412
+ sourceFile,
413
+ node.expression
414
+ );
415
+ if (dynamicImport || directRequire) {
416
+ add(node, directRequire ? "require" : "dynamic-import", literalText(ts, node.arguments[0]));
417
+ }
418
+ }
419
+ ts.forEachChild(node, visit);
1014
420
  };
421
+ visit(sourceFile);
422
+ return dependencies;
423
+ }
424
+ function staticAccessPath(ts, node) {
425
+ const segments = [];
426
+ let current = node;
427
+ while (ts.isPropertyAccessExpression(current) || ts.isElementAccessExpression(current)) {
428
+ if (ts.isPropertyAccessExpression(current)) segments.unshift(current.name.text);
429
+ else {
430
+ const property = literalText(ts, current.argumentExpression);
431
+ if (property === void 0) return void 0;
432
+ segments.unshift(property);
433
+ }
434
+ current = current.expression;
435
+ }
436
+ if (!ts.isIdentifier(current)) return void 0;
437
+ segments.unshift(current.text);
438
+ return { root: current, segments };
439
+ }
440
+ function runtimeIdentifierReference(ts, node) {
441
+ const parent = node.parent;
442
+ if (ts.isPropertyAccessExpression(parent) || ts.isElementAccessExpression(parent)) return false;
443
+ return ts.isExpressionNode(node) && !ts.isInTypeQuery(node) || ts.isShorthandPropertyAssignment(parent) && parent.name === node;
444
+ }
445
+ function bestForbiddenMatch(entries, segments) {
446
+ const normalized = segments[0] === "globalThis" ? segments.slice(1) : segments;
447
+ for (let length = normalized.length; length >= 1; length -= 1) {
448
+ const candidate = normalized.slice(0, length).join(".");
449
+ if (entries.has(candidate)) return candidate;
450
+ }
451
+ return void 0;
1015
452
  }
1016
-
1017
- // src/kernel/event-bus/EventBus.ts
1018
- var interceptorSequence = 0;
1019
- function nextInterceptorRegistrationId() {
1020
- interceptorSequence += 1;
1021
- return `interceptor-${Date.now()}-${interceptorSequence}`;
1022
- }
1023
- var EventBusImpl = class {
1024
- subscriptions = [];
1025
- subscriptionsByIntent = /* @__PURE__ */ new Map();
1026
- interceptors = [];
1027
- interceptorsByIntent = /* @__PURE__ */ new Map();
1028
- recording;
1029
- onPublish;
1030
- onSoftViolation;
1031
- onHandlerError;
1032
- eventContracts;
1033
- strictEventContracts;
1034
- requireKnownSource;
1035
- architectureProfile;
1036
- enforceObservedLayerFlowMode;
1037
- rethrowHandlerErrors;
1038
- policyEngine;
1039
- getPolicyContext;
1040
- intentRegistry;
1041
- dependencyGraph;
1042
- strictRegistry;
1043
- validateIntentNaming;
1044
- constructor(options = {}) {
1045
- this.onPublish = options.onPublish;
1046
- this.onSoftViolation = options.onSoftViolation;
1047
- this.onHandlerError = options.onHandlerError;
1048
- this.eventContracts = options.eventContracts;
1049
- this.strictEventContracts = options.strictEventContracts ?? false;
1050
- this.requireKnownSource = options.requireKnownSource ?? false;
1051
- this.architectureProfile = options.architectureProfile;
1052
- this.enforceObservedLayerFlowMode = options.enforceObservedLayerFlow ?? "off";
1053
- this.rethrowHandlerErrors = options.rethrowHandlerErrors ?? false;
1054
- this.intentRegistry = options.intentRegistry;
1055
- this.dependencyGraph = options.dependencyGraph;
1056
- this.strictRegistry = options.strictRegistry ?? options.intentRegistry !== void 0;
1057
- this.validateIntentNaming = options.validateIntentNaming ?? this.strictRegistry;
1058
- this.recording = {
1059
- history: [],
1060
- trace: [],
1061
- maxHistorySize: options.maxHistorySize,
1062
- traceSinks: [...options.traceSinks ?? []],
1063
- auditTrail: options.auditTrail,
1064
- outbox: options.outbox,
1065
- instanceId: options.instanceId
1066
- };
1067
- if (options.policyEngine) {
1068
- this.policyEngine = options.policyEngine;
1069
- } else if (options.policies && options.policies.length > 0) {
1070
- this.policyEngine = new PolicyEngine(options.policies);
1071
- }
1072
- const allPolicies = this.policyEngine?.getPolicies() ?? options.policies ?? [];
1073
- if (allPolicies.some(isLayerPolicy) && !options.intentRegistry && !options.dependencyGraph && !options.getPolicyContext) {
1074
- throw new LayerPolicyContextError();
1075
- }
1076
- if (options.getPolicyContext) {
1077
- this.getPolicyContext = options.getPolicyContext;
1078
- } else if (options.intentRegistry || options.dependencyGraph) {
1079
- this.getPolicyContext = buildPublishPolicyContext({
1080
- intentRegistry: options.intentRegistry,
1081
- dependencyGraph: options.dependencyGraph
1082
- });
1083
- } else {
1084
- this.getPolicyContext = (event) => ({ event });
453
+ function collectForbiddenCapabilityUses(ts, sourceFile, forbidden) {
454
+ if (forbidden.length === 0) return [];
455
+ const entries = new Set(forbidden);
456
+ const checker = singleFileChecker(ts, sourceFile);
457
+ const aliases = /* @__PURE__ */ new Map();
458
+ const topLevelNames = /* @__PURE__ */ new Set();
459
+ for (const statement of sourceFile.statements) {
460
+ if (ts.isVariableStatement(statement)) {
461
+ for (const declaration of statement.declarationList.declarations) {
462
+ if (ts.isIdentifier(declaration.name)) topLevelNames.add(declaration.name.text);
463
+ }
1085
464
  }
1086
465
  }
1087
- async publish(eventOrCreator, payloadOrMeta, metadata) {
1088
- let event;
1089
- const rawPublish = typeof eventOrCreator !== "function";
1090
- if (!rawPublish) {
1091
- const creator = eventOrCreator;
1092
- const payload = payloadOrMeta;
1093
- const extraMeta = metadata ?? {};
1094
- const created = creator(payload);
1095
- event = {
1096
- ...created,
1097
- metadata: enrichMetadata(
1098
- created.metadata,
1099
- extraMeta,
1100
- this.recording.instanceId
1101
- )
1102
- };
1103
- } else {
1104
- const rawEvent = eventOrCreator;
1105
- const extraMeta = metadata ?? payloadOrMeta ?? {};
1106
- event = {
1107
- ...rawEvent,
1108
- metadata: enrichMetadata(
1109
- rawEvent.metadata,
1110
- extraMeta,
1111
- this.recording.instanceId
1112
- )
1113
- };
466
+ const resolvePath = (node) => {
467
+ const path = staticAccessPath(ts, node);
468
+ if (!path) return void 0;
469
+ const symbol = symbolAt(checker, path.root);
470
+ const alias = symbol ? aliases.get(symbol) : void 0;
471
+ if (alias) return [...alias, ...path.segments.slice(1)];
472
+ return localDeclaration(ts, checker, sourceFile, path.root) || topLevelNames.has(path.root.text) ? void 0 : path.segments;
473
+ };
474
+ for (const statement of sourceFile.statements) {
475
+ if (!ts.isVariableStatement(statement)) continue;
476
+ for (const declaration of statement.declarationList.declarations) {
477
+ if (!declaration.initializer || !ts.isIdentifier(declaration.name)) continue;
478
+ const path = resolvePath(declaration.initializer);
479
+ const symbol = symbolAt(checker, declaration.name);
480
+ if (!path || !symbol) continue;
481
+ aliases.set(symbol, path);
1114
482
  }
1115
- if (rawPublish && this.strictRegistry) {
1116
- await recordRawPublishDiagnostic(this.recording, event);
483
+ }
484
+ const uses = [];
485
+ const seen = /* @__PURE__ */ new Set();
486
+ const flag = (name, node) => {
487
+ const line = lineOf(sourceFile, node);
488
+ const key = `${name}:${node.getStart(sourceFile)}`;
489
+ if (seen.has(key)) return;
490
+ seen.add(key);
491
+ uses.push({ name, line, node });
492
+ };
493
+ const visit = (node) => {
494
+ const parentContinuesPath = node.parent && (ts.isPropertyAccessExpression(node.parent) || ts.isElementAccessExpression(node.parent)) && node.parent.expression === node;
495
+ if ((ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) && !parentContinuesPath) {
496
+ const path = resolvePath(node);
497
+ const match = path ? bestForbiddenMatch(entries, path) : void 0;
498
+ if (match) flag(match, node);
499
+ } else if (ts.isIdentifier(node) && entries.has(node.text) && runtimeIdentifierReference(ts, node) && !localDeclaration(ts, checker, sourceFile, node)) {
500
+ flag(node.text, node);
501
+ }
502
+ if (ts.isVariableDeclaration(node) && ts.isObjectBindingPattern(node.name) && node.initializer) {
503
+ const base = resolvePath(node.initializer);
504
+ if (base) {
505
+ for (const element of node.name.elements) {
506
+ if (!ts.isIdentifier(element.name)) continue;
507
+ const property = element.propertyName ? literalText(ts, element.propertyName) ?? element.propertyName.text : element.name.text;
508
+ const match = bestForbiddenMatch(entries, [...base, property]);
509
+ if (match) flag(match, node.initializer);
510
+ }
511
+ }
1117
512
  }
1118
- assertIntentAllowed(event.intent, {
1119
- strictRegistry: this.strictRegistry,
1120
- validateIntentNaming: this.validateIntentNaming,
1121
- intentRegistry: this.intentRegistry
1122
- });
1123
- assertSourceAllowed(event, {
1124
- requireKnownSource: this.requireKnownSource,
1125
- intentRegistry: this.intentRegistry
1126
- });
1127
- assertContractAllowed(event, {
1128
- eventContracts: this.eventContracts,
1129
- strictEventContracts: this.strictEventContracts
1130
- });
1131
- event = await applyInterceptors(event, {
1132
- interceptorsForIntent: (intent) => this.interceptorsByIntent.get(intent) ?? [],
1133
- eventContracts: this.eventContracts,
1134
- strictEventContracts: this.strictEventContracts,
1135
- appendTrace: (r) => this.appendTrace(r),
1136
- recordAudit: (type, e, details) => this.recordAudit(type, e, details)
1137
- });
1138
- assertContractAllowed(event, {
1139
- eventContracts: this.eventContracts,
1140
- strictEventContracts: this.strictEventContracts
1141
- });
1142
- await assertObservedLayerFlowAllowed(event, {
1143
- mode: this.enforceObservedLayerFlowMode,
1144
- architectureProfile: this.architectureProfile,
1145
- appendTrace: (r) => this.appendTrace(r),
1146
- recordAudit: (type, e, details) => this.recordAudit(type, e, details)
1147
- });
1148
- this.dependencyGraph?.registerEventFlow(event.metadata.source, event.intent);
1149
- const matching = [...this.subscriptionsByIntent.get(event.intent) ?? []];
1150
- if (this.policyEngine) {
1151
- await enforcePublishPolicy(event, {
1152
- policyEngine: this.policyEngine,
1153
- getPolicyContext: this.getPolicyContext,
1154
- appendTrace: (r) => this.appendTrace(r),
1155
- recordAudit: (type, e, details) => this.recordAudit(type, e, details),
1156
- onSoftViolation: this.onSoftViolation,
1157
- safeHook: (fn, name, e) => this.safeHook(fn, name, e)
1158
- });
1159
- }
1160
- await recordSuccessfulPublish(
1161
- this.recording,
1162
- event,
1163
- matching.length
1164
- );
1165
- await Promise.all(
1166
- matching.map((sub) => this.invokeHandler(sub, event))
1167
- );
1168
- if (this.onPublish) {
1169
- await this.safeHook(
1170
- () => this.onPublish(event),
1171
- "onPublish",
1172
- event
1173
- );
1174
- }
1175
- }
1176
- createPublisher(source) {
1177
- const sourceName = typeof source === "string" ? source : source.name;
1178
- assertIntentAllowed(sourceName, {
1179
- strictRegistry: this.strictRegistry,
1180
- validateIntentNaming: this.validateIntentNaming,
1181
- intentRegistry: this.intentRegistry
1182
- });
1183
- return {
1184
- source: sourceName,
1185
- publish: async (intent, payload, metadata = {}) => {
1186
- if (metadata.source && metadata.source !== sourceName) {
1187
- throw new SourceMetadataOverrideError(sourceName, metadata.source);
1188
- }
1189
- await this.publish(intent, payload, {
1190
- ...metadata,
1191
- source: sourceName
1192
- });
1193
- }
1194
- };
1195
- }
1196
- subscribe(intent, handler) {
1197
- const intentName = typeof intent === "string" ? intent : intent.name;
1198
- assertIntentAllowed(intentName, {
1199
- strictRegistry: this.strictRegistry,
1200
- validateIntentNaming: this.validateIntentNaming,
1201
- intentRegistry: this.intentRegistry
1202
- });
1203
- const sub = {
1204
- intentName,
1205
- handler
1206
- };
1207
- this.subscriptions.push(sub);
1208
- const subscriptionsForIntent = this.subscriptionsByIntent.get(intentName) ?? [];
1209
- subscriptionsForIntent.push(sub);
1210
- this.subscriptionsByIntent.set(intentName, subscriptionsForIntent);
1211
- return () => {
1212
- const idx = this.subscriptions.indexOf(sub);
1213
- if (idx >= 0) this.subscriptions.splice(idx, 1);
1214
- const byIntent = this.subscriptionsByIntent.get(intentName);
1215
- if (!byIntent) return;
1216
- const intentIdx = byIntent.indexOf(sub);
1217
- if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
1218
- if (byIntent.length === 0) this.subscriptionsByIntent.delete(intentName);
1219
- };
1220
- }
1221
- registerInterceptor(intent, interceptor, interceptorId) {
1222
- const intentName = typeof intent === "string" ? intent : intent.name;
1223
- assertIntentAllowed(intentName, {
1224
- strictRegistry: this.strictRegistry,
1225
- validateIntentNaming: this.validateIntentNaming,
1226
- intentRegistry: this.intentRegistry
1227
- });
1228
- const registration = {
1229
- registrationId: nextInterceptorRegistrationId(),
1230
- interceptorId: interceptorId ?? intentName,
1231
- intentName,
1232
- interceptor,
1233
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1234
- };
1235
- this.interceptors.push(registration);
1236
- const interceptorsForIntent = this.interceptorsByIntent.get(intentName) ?? [];
1237
- interceptorsForIntent.push(registration);
1238
- this.interceptorsByIntent.set(intentName, interceptorsForIntent);
1239
- return registration.registrationId;
1240
- }
1241
- unregisterInterceptor(registrationId) {
1242
- const interceptor = this.interceptors.find(
1243
- (candidate) => candidate.registrationId === registrationId
1244
- );
1245
- if (!interceptor) return false;
1246
- const idx = this.interceptors.indexOf(interceptor);
1247
- if (idx >= 0) this.interceptors.splice(idx, 1);
1248
- const byIntent = this.interceptorsByIntent.get(interceptor.intentName);
1249
- if (byIntent) {
1250
- const intentIdx = byIntent.indexOf(interceptor);
1251
- if (intentIdx >= 0) byIntent.splice(intentIdx, 1);
1252
- if (byIntent.length === 0) this.interceptorsByIntent.delete(interceptor.intentName);
1253
- }
1254
- return true;
1255
- }
1256
- listInterceptors(intent) {
1257
- return this.interceptors.filter((interceptor) => !intent || interceptor.intentName === intent).map((interceptor) => ({
1258
- registrationId: interceptor.registrationId,
1259
- interceptorId: interceptor.interceptorId,
1260
- intent: interceptor.intentName,
1261
- createdAt: interceptor.createdAt,
1262
- lastInterceptedAt: interceptor.lastInterceptedAt
1263
- }));
1264
- }
1265
- getHistory() {
1266
- return [...this.recording.history];
1267
- }
1268
- clearHistory() {
1269
- this.recording.history.length = 0;
1270
- }
1271
- getTrace() {
1272
- return [...this.recording.trace];
1273
- }
1274
- clearTrace() {
1275
- this.recording.trace.length = 0;
1276
- }
1277
- appendTrace(record) {
1278
- appendTrace(this.recording, record);
1279
- }
1280
- async recordAudit(type, event, details) {
1281
- await recordAudit(this.recording, type, event, details);
1282
- }
1283
- async invokeHandler(sub, event) {
1284
- try {
1285
- await Promise.resolve(sub.handler(event));
1286
- } catch (err) {
1287
- this.appendTrace({
1288
- type: "handler.error",
1289
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1290
- intent: event.intent,
1291
- correlationId: event.metadata.correlationId,
1292
- traceId: event.metadata.traceId,
1293
- spanId: event.metadata.spanId,
1294
- details: { error: err instanceof Error ? err.message : String(err) }
1295
- });
1296
- await this.recordAudit("handler.error", event, {
1297
- handlerIntent: sub.intentName,
1298
- error: err instanceof Error ? err.message : String(err)
1299
- });
1300
- if (this.onHandlerError) {
1301
- await this.safeHook(
1302
- () => this.onHandlerError(err, event, sub.intentName),
1303
- "onHandlerError",
1304
- event
1305
- );
1306
- }
1307
- if (this.rethrowHandlerErrors) {
1308
- throw err;
1309
- }
1310
- }
1311
- }
1312
- async safeHook(fn, hookName, event) {
1313
- try {
1314
- await Promise.resolve(fn());
1315
- } catch (err) {
1316
- this.appendTrace({
1317
- type: "hook.error",
1318
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1319
- intent: event.intent,
1320
- correlationId: event.metadata.correlationId,
1321
- traceId: event.metadata.traceId,
1322
- spanId: event.metadata.spanId,
1323
- details: {
1324
- hook: hookName,
1325
- error: err instanceof Error ? err.message : String(err)
1326
- }
1327
- });
1328
- await this.recordAudit("hook.error", event, {
1329
- hook: hookName,
1330
- error: err instanceof Error ? err.message : String(err)
1331
- });
1332
- }
1333
- }
1334
- };
1335
- function createEventBus(options) {
1336
- return new EventBusImpl(options);
1337
- }
1338
-
1339
- // src/kernel/event-contracts/EventContractRegistry.ts
1340
- function formatStandardSchemaPath(path) {
1341
- if (!path || path.length === 0) return void 0;
1342
- return path.map(
1343
- (segment) => typeof segment === "object" && segment !== null && "key" in segment ? String(segment.key) : String(segment)
1344
- ).join(".");
1345
- }
1346
- function actualType(value) {
1347
- if (Array.isArray(value)) return "array";
1348
- if (value === null) return "object";
1349
- const type = typeof value;
1350
- if (type === "string" || type === "number" || type === "boolean" || type === "object") {
1351
- return type;
1352
- }
1353
- return "unknown";
1354
- }
1355
- function formatPath(parent, field) {
1356
- return parent ? `${parent}.${field}` : field;
1357
- }
1358
- function validateSchemaField(value, fieldSchema, path, contract, issues) {
1359
- const valueType = actualType(value);
1360
- if (fieldSchema.type !== "unknown" && valueType !== fieldSchema.type) {
1361
- issues.push({
1362
- intent: contract.intent,
1363
- version: contract.version,
1364
- field: path,
1365
- message: `Expected ${fieldSchema.type}, received ${valueType}.`
1366
- });
1367
- return;
1368
- }
1369
- if (fieldSchema.enum && !fieldSchema.enum.some((allowed) => Object.is(allowed, value))) {
1370
- issues.push({
1371
- intent: contract.intent,
1372
- version: contract.version,
1373
- field: path,
1374
- message: "Value is not allowed by event contract enum."
1375
- });
1376
- }
1377
- if (fieldSchema.type === "object" && fieldSchema.fields) {
1378
- if (value === null || typeof value !== "object" || Array.isArray(value)) {
1379
- issues.push({
1380
- intent: contract.intent,
1381
- version: contract.version,
1382
- field: path,
1383
- message: "Nested object field must be a non-array object."
1384
- });
1385
- return;
1386
- }
1387
- validateObjectSchema(
1388
- value,
1389
- fieldSchema.fields,
1390
- contract,
1391
- issues,
1392
- path
1393
- );
1394
- }
1395
- if (fieldSchema.type === "array" && fieldSchema.items && Array.isArray(value)) {
1396
- value.forEach((item, index) => {
1397
- validateSchemaField(
1398
- item,
1399
- fieldSchema.items,
1400
- `${path}[${index}]`,
1401
- contract,
1402
- issues
1403
- );
1404
- });
1405
- }
1406
- }
1407
- function validateObjectSchema(payload, schema, contract, issues, parentPath) {
1408
- for (const [field, fieldSchema] of Object.entries(schema)) {
1409
- const path = formatPath(parentPath, field);
1410
- const value = payload[field];
1411
- if (value === void 0) {
1412
- if (fieldSchema.required) {
1413
- issues.push({
1414
- intent: contract.intent,
1415
- version: contract.version,
1416
- field: path,
1417
- message: "Required field is missing."
1418
- });
1419
- }
1420
- continue;
1421
- }
1422
- validateSchemaField(value, fieldSchema, path, contract, issues);
1423
- }
1424
- }
1425
- var EventContractRegistryImpl = class {
1426
- contracts = /* @__PURE__ */ new Map();
1427
- register(contract) {
1428
- const key = this.key(contract.intent, contract.version);
1429
- if (this.contracts.has(key)) {
1430
- throw new Error(`Event contract "${key}" is already registered.`);
1431
- }
1432
- this.contracts.set(key, { allowAdditionalFields: true, ...contract });
1433
- }
1434
- get(intent, version2) {
1435
- if (version2) return this.contracts.get(this.key(intent, version2));
1436
- return this.list(intent).at(-1);
1437
- }
1438
- list(intent) {
1439
- return Array.from(this.contracts.values()).filter(
1440
- (contract) => !intent || contract.intent === intent
1441
- );
1442
- }
1443
- validate(event) {
1444
- const version2 = event.metadata.eventVersion;
1445
- const contract = this.get(event.intent, version2);
1446
- const issues = [];
1447
- if (!contract) {
1448
- return {
1449
- ok: false,
1450
- issues: [
1451
- {
1452
- intent: event.intent,
1453
- version: version2,
1454
- message: version2 ? `No event contract registered for version "${version2}".` : "No event contract registered for intent."
1455
- }
1456
- ]
1457
- };
1458
- }
1459
- if (contract.deprecated) {
1460
- issues.push({
1461
- intent: event.intent,
1462
- version: contract.version,
1463
- message: typeof contract.deprecated === "string" ? contract.deprecated : "Event contract is deprecated."
1464
- });
1465
- }
1466
- const payload = event.payload != null && typeof event.payload === "object" ? event.payload : void 0;
1467
- if (contract.schema) {
1468
- if (!payload) {
1469
- issues.push({
1470
- intent: event.intent,
1471
- version: contract.version,
1472
- message: "Payload must be an object for schema validation."
1473
- });
1474
- } else {
1475
- validateObjectSchema(payload, contract.schema, contract, issues);
1476
- if (contract.allowAdditionalFields === false) {
1477
- for (const field of Object.keys(payload)) {
1478
- if (!contract.schema[field]) {
1479
- issues.push({
1480
- intent: event.intent,
1481
- version: contract.version,
1482
- field,
1483
- message: "Additional field is not allowed by event contract."
1484
- });
1485
- }
1486
- }
1487
- }
1488
- }
1489
- }
1490
- if (contract.standardSchema) {
1491
- const result = contract.standardSchema["~standard"].validate(event.payload);
1492
- if (result instanceof Promise) {
1493
- issues.push({
1494
- intent: event.intent,
1495
- version: contract.version,
1496
- message: "Standard Schema validator returned a Promise; event contract validation is synchronous."
1497
- });
1498
- } else if (result.issues) {
1499
- for (const issue of result.issues) {
1500
- issues.push({
1501
- intent: event.intent,
1502
- version: contract.version,
1503
- field: formatStandardSchemaPath(issue.path),
1504
- message: issue.message
1505
- });
1506
- }
1507
- }
1508
- }
1509
- return { ok: issues.length === 0, contract, issues };
1510
- }
1511
- clear() {
1512
- this.contracts.clear();
1513
- }
1514
- key(intent, version2) {
1515
- return `${intent}@${version2}`;
1516
- }
1517
- };
1518
- function createEventContractRegistry() {
1519
- return new EventContractRegistryImpl();
1520
- }
1521
-
1522
- // src/kernel/outbox/InMemoryOutboxStore.ts
1523
- var outboxSequence = 0;
1524
- function nextOutboxId() {
1525
- outboxSequence += 1;
1526
- return `outbox-${Date.now()}-${outboxSequence}`;
1527
- }
1528
- function cloneRecord(record) {
1529
- return {
1530
- ...record,
1531
- event: {
1532
- ...record.event,
1533
- metadata: { ...record.event.metadata }
1534
- }
1535
- };
1536
- }
1537
- var InMemoryOutboxStore = class {
1538
- records = /* @__PURE__ */ new Map();
1539
- async enqueue(event) {
1540
- const now = (/* @__PURE__ */ new Date()).toISOString();
1541
- const record = {
1542
- id: nextOutboxId(),
1543
- event,
1544
- status: "pending",
1545
- attempts: 0,
1546
- createdAt: now,
1547
- updatedAt: now
1548
- };
1549
- this.records.set(record.id, record);
1550
- return cloneRecord(record);
1551
- }
1552
- async markDispatched(id) {
1553
- const record = this.records.get(id);
1554
- if (!record) return;
1555
- record.status = "dispatched";
1556
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1557
- }
1558
- async markFailed(id, error) {
1559
- const record = this.records.get(id);
1560
- if (!record) return;
1561
- record.status = "failed";
1562
- record.attempts += 1;
1563
- record.error = error instanceof Error ? error.message : String(error);
1564
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1565
- }
1566
- async list(status) {
1567
- return Array.from(this.records.values()).filter((record) => !status || record.status === status).map(cloneRecord);
1568
- }
1569
- async clear() {
1570
- this.records.clear();
1571
- }
1572
- };
1573
-
1574
- // src/kernel/observability/ObservabilityReporter.ts
1575
- function flowKey(flow) {
1576
- return `${flow.from}->${flow.to}`;
1577
- }
1578
- function uniqueFlows(flows) {
1579
- const seen = /* @__PURE__ */ new Set();
1580
- const result = [];
1581
- for (const flow of flows) {
1582
- const key = flowKey(flow);
1583
- if (seen.has(key)) continue;
1584
- seen.add(key);
1585
- result.push(flow);
1586
- }
1587
- return result;
1588
- }
1589
- function difference(left, right) {
1590
- const rightKeys = new Set(right.map(flowKey));
1591
- return left.filter((flow) => !rightKeys.has(flowKey(flow)));
1592
- }
1593
- function createObservabilityReporter(options) {
1594
- const registry = options.registry;
1595
- const eventBus = options.eventBus;
1596
- const graph = options.graph;
1597
- return {
1598
- report() {
1599
- const declaredFromRegistry = registry ? registry.getAllRelationships().filter((relationship) => relationship.kind === "produces").map((relationship) => ({
1600
- from: relationship.from,
1601
- to: relationship.to
1602
- })) : [];
1603
- const declaredFromGraph = declaredFromRegistry.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "produces").map((edge) => ({ from: edge.from, to: edge.to }));
1604
- const observedFromHistory = eventBus?.getHistory().map((record) => ({
1605
- from: record.event.metadata.source,
1606
- to: record.event.intent
1607
- })) ?? [];
1608
- const observedFromGraph = observedFromHistory.length > 0 || !graph ? [] : graph.getEdges().filter((edge) => edge.kind === "observed").map((edge) => ({ from: edge.from, to: edge.to }));
1609
- const declaredProductions = uniqueFlows([
1610
- ...declaredFromRegistry,
1611
- ...declaredFromGraph
1612
- ]);
1613
- const observedProductions = uniqueFlows([
1614
- ...observedFromHistory,
1615
- ...observedFromGraph
1616
- ]);
1617
- const unknownSources = observedProductions.filter(
1618
- (flow) => !flow.from || flow.from === "unknown"
1619
- );
1620
- const unregisteredObservedSources = registry ? Array.from(
1621
- new Set(
1622
- observedProductions.map((flow) => flow.from).filter(
1623
- (source) => source && source !== "unknown" && !registry.has(source)
1624
- )
1625
- )
1626
- ) : [];
1627
- const unregisteredObservedIntents = registry ? Array.from(
1628
- new Set(
1629
- observedProductions.map((flow) => flow.to).filter((intent) => !registry.has(intent))
1630
- )
1631
- ) : [];
1632
- const observedIntentNames = new Set(
1633
- observedProductions.flatMap((flow) => [flow.from, flow.to])
1634
- );
1635
- const registeredButNeverObserved = registry ? registry.list().map((intent) => intent.name).filter((intent) => !observedIntentNames.has(intent)) : [];
1636
- return {
1637
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1638
- declaredProductions,
1639
- observedProductions,
1640
- declaredButUnobserved: difference(declaredProductions, observedProductions),
1641
- observedButUndeclared: difference(
1642
- observedProductions.filter((flow) => flow.from !== "unknown"),
1643
- declaredProductions
1644
- ),
1645
- unknownSources,
1646
- unregisteredObservedSources,
1647
- unregisteredObservedIntents,
1648
- registeredButNeverObserved
1649
- };
1650
- }
1651
- };
1652
- }
1653
-
1654
- // src/kernel/testing/ArkTestHarness.ts
1655
- function createArkTestHarness(kernel) {
1656
- return {
1657
- events(intent) {
1658
- return kernel.eventBus.getHistory().map((record) => record.event).filter((event) => !intent || event.intent === intent);
1659
- },
1660
- traces(type) {
1661
- return kernel.eventBus.getTrace().filter((record) => !type || record.type === type);
1662
- },
1663
- audit(query) {
1664
- return kernel.auditTrail.query(query);
1665
- },
1666
- outbox(status) {
1667
- return kernel.outbox.list(status);
1668
- },
1669
- observability() {
1670
- kernel.syncGraph();
1671
- return kernel.observability.report();
1672
- },
1673
- async snapshot() {
1674
- return {
1675
- events: this.events(),
1676
- traces: this.traces(),
1677
- audit: await this.audit(),
1678
- outbox: await this.outbox(),
1679
- observability: this.observability()
1680
- };
1681
- },
1682
- async clear() {
1683
- kernel.eventBus.clearHistory();
1684
- kernel.eventBus.clearTrace();
1685
- await kernel.auditTrail.clear();
1686
- await kernel.outbox.clear();
1687
- }
1688
- };
1689
- }
1690
-
1691
- // src/kernel/audit/AuditTrail.ts
1692
- var auditSequence = 0;
1693
- function createAuditId() {
1694
- auditSequence += 1;
1695
- return `audit-${Date.now()}-${auditSequence}`;
1696
- }
1697
- function matchesQuery(record, query) {
1698
- if (query.type && record.type !== query.type) return false;
1699
- if (query.intent && record.intent !== query.intent) return false;
1700
- if (query.correlationId && record.correlationId !== query.correlationId) return false;
1701
- if (query.subject && record.subject !== query.subject) return false;
1702
- if (query.since && record.timestamp < query.since) return false;
1703
- if (query.until && record.timestamp > query.until) return false;
1704
- return true;
1705
- }
1706
- var InMemoryAuditStore = class {
1707
- constructor(maxRecords) {
1708
- this.maxRecords = maxRecords;
1709
- }
1710
- maxRecords;
1711
- records = [];
1712
- append(record) {
1713
- this.records.push(record);
1714
- if (this.maxRecords !== void 0 && this.records.length > this.maxRecords) {
1715
- this.records.splice(0, this.records.length - this.maxRecords);
1716
- }
1717
- }
1718
- query(query = {}) {
1719
- const records = this.records.filter((record) => matchesQuery(record, query));
1720
- return query.limit === void 0 ? [...records] : records.slice(-query.limit);
1721
- }
1722
- clear() {
1723
- this.records.length = 0;
1724
- }
1725
- };
1726
- var AuditTrailImpl = class {
1727
- constructor(store) {
1728
- this.store = store;
1729
- }
1730
- store;
1731
- async record(input) {
1732
- const record = {
1733
- id: createAuditId(),
1734
- timestamp: input.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
1735
- type: input.type,
1736
- source: input.source,
1737
- actor: input.actor,
1738
- intent: input.intent,
1739
- correlationId: input.correlationId,
1740
- causationId: input.causationId,
1741
- subject: input.subject,
1742
- details: input.details
1743
- };
1744
- await this.store.append(record);
1745
- return record;
1746
- }
1747
- async query(query) {
1748
- return this.store.query(query);
1749
- }
1750
- async clear() {
1751
- await this.store.clear();
1752
- }
1753
- };
1754
- function createAuditTrail(options = {}) {
1755
- return new AuditTrailImpl(
1756
- options.store ?? new InMemoryAuditStore(options.maxRecords)
1757
- );
1758
- }
1759
-
1760
- // src/kernel/graph/DependencyGraph.ts
1761
- var DependencyGraphImpl = class {
1762
- nodes = /* @__PURE__ */ new Map();
1763
- edges = [];
1764
- registerDependency(from, to, kind = "declared") {
1765
- this.ensureNode(from);
1766
- this.ensureNode(to);
1767
- this.addEdge({ from, to, kind });
1768
- }
1769
- registerEventFlow(producer, consumer) {
1770
- this.ensureNode(producer);
1771
- this.ensureNode(consumer);
1772
- this.addEdge({ from: producer, to: consumer, kind: "observed" });
1773
- }
1774
- getNodes() {
1775
- return Array.from(this.nodes.values());
1776
- }
1777
- getEdges() {
1778
- return [...this.edges];
1779
- }
1780
- toJSON() {
1781
- return {
1782
- nodes: this.getNodes(),
1783
- edges: this.getEdges()
1784
- };
1785
- }
1786
- toMermaid() {
1787
- let out = "flowchart TD\n";
1788
- for (const edge of this.edges) {
1789
- const label = edge.kind ? `|${edge.kind}|` : "";
1790
- out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
1791
- `;
1792
- }
1793
- const connected = new Set(
1794
- this.edges.flatMap((e) => [e.from, e.to])
1795
- );
1796
- for (const node of this.nodes.keys()) {
1797
- if (!connected.has(node)) {
1798
- out += ` ${this.safeId(node)}
1799
- `;
1800
- }
1801
- }
1802
- return out.trim();
1803
- }
1804
- toLayerMermaid(profile) {
1805
- const nodesByLayer = /* @__PURE__ */ new Map();
1806
- for (const node of this.nodes.keys()) {
1807
- const layer = profile.resolveLayer(node) ?? "Unclassified";
1808
- const current = nodesByLayer.get(layer) ?? [];
1809
- current.push(node);
1810
- nodesByLayer.set(layer, current);
1811
- }
1812
- let out = "flowchart TD\n";
1813
- for (const layer of profile.layers) {
1814
- const nodes = nodesByLayer.get(layer.name) ?? [];
1815
- if (nodes.length === 0) continue;
1816
- out += ` subgraph ${this.safeId(layer.name)}[${layer.name}]
1817
- `;
1818
- for (const node of nodes) {
1819
- out += ` ${this.safeId(node)}[${node}]
1820
- `;
1821
- }
1822
- out += " end\n";
1823
- }
1824
- const unclassified = nodesByLayer.get("Unclassified") ?? [];
1825
- if (unclassified.length > 0) {
1826
- out += " subgraph Unclassified[Unclassified]\n";
1827
- for (const node of unclassified) {
1828
- out += ` ${this.safeId(node)}[${node}]
1829
- `;
1830
- }
1831
- out += " end\n";
1832
- }
1833
- for (const edge of this.edges) {
1834
- const label = edge.kind ? `|${edge.kind}|` : "";
1835
- out += ` ${this.safeId(edge.from)} -->${label} ${this.safeId(edge.to)}
1836
- `;
1837
- }
1838
- return out.trim();
1839
- }
1840
- detectViolations(rules = []) {
1841
- const violations = [];
1842
- const cycles = this.findSimpleCycles();
1843
- if (cycles.length > 0) {
1844
- violations.push(`Cycle detected: ${cycles.map((c) => c.join("->")).join(", ")}`);
1845
- }
1846
- for (const rule of rules) {
1847
- try {
1848
- const res = rule(this.edges);
1849
- if (res && res.length) violations.push(...res);
1850
- } catch (e) {
1851
- violations.push(`Rule error: ${e.message}`);
1852
- }
1853
- }
1854
- return violations;
1855
- }
1856
- ensureNode(id) {
1857
- if (!this.nodes.has(id)) {
1858
- this.nodes.set(id, { id });
1859
- }
1860
- }
1861
- addEdge(edge) {
1862
- const exists = this.edges.some(
1863
- (e) => e.from === edge.from && e.to === edge.to && e.kind === edge.kind
1864
- );
1865
- if (!exists) {
1866
- this.edges.push(edge);
1867
- }
1868
- }
1869
- // Very naive cycle detection for small graphs
1870
- findSimpleCycles() {
1871
- const graph = /* @__PURE__ */ new Map();
1872
- for (const e of this.edges) {
1873
- if (!graph.has(e.from)) graph.set(e.from, []);
1874
- graph.get(e.from).push(e.to);
1875
- }
1876
- const cycles = [];
1877
- const visited = /* @__PURE__ */ new Set();
1878
- const stack = [];
1879
- const dfs = (node) => {
1880
- visited.add(node);
1881
- stack.push(node);
1882
- for (const nei of graph.get(node) || []) {
1883
- if (!visited.has(nei)) {
1884
- dfs(nei);
1885
- } else if (stack.includes(nei)) {
1886
- const cycleStart = stack.indexOf(nei);
1887
- const cycle = stack.slice(cycleStart).concat(nei);
1888
- cycles.push(cycle);
1889
- }
1890
- }
1891
- stack.pop();
1892
- };
1893
- for (const node of graph.keys()) {
1894
- if (!visited.has(node)) dfs(node);
1895
- }
1896
- const unique = new Set(cycles.map((c) => c.join("->")));
1897
- return Array.from(unique).map((s) => s.split("->"));
1898
- }
1899
- safeId(id) {
1900
- return id.replace(/[^a-zA-Z0-9_]/g, "_");
1901
- }
1902
- };
1903
- function createDependencyGraph() {
1904
- return new DependencyGraphImpl();
1905
- }
1906
-
1907
- // src/kernel/graph/sync.ts
1908
- function syncRegistryToGraph(registry, graph, options = {}) {
1909
- const requireRegistered = options.requireRegisteredTargets ?? false;
1910
- for (const rel of registry.getAllRelationships()) {
1911
- if (requireRegistered && !registry.has(rel.to)) {
1912
- continue;
1913
- }
1914
- if (rel.kind === "dependsOn") {
1915
- graph.registerDependency(rel.from, rel.to, "declared");
1916
- } else {
1917
- graph.registerDependency(rel.from, rel.to, "produces");
1918
- }
1919
- }
1920
- }
1921
-
1922
- // src/kernel/layers/ArchitectureProfile.ts
1923
- function normalizePrefix(prefix) {
1924
- return prefix.endsWith(".") ? prefix : `${prefix}.`;
1925
- }
1926
- function byLongestPrefix(a, b) {
1927
- const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
1928
- const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
1929
- return maxB - maxA;
1930
- }
1931
- function flowKey2(from, to) {
1932
- return `${from}->${to}`;
1933
- }
1934
- function createStrictDenyRules(layers, allowedFlows) {
1935
- const allowed = new Set(allowedFlows.map((flow) => flowKey2(flow.from, flow.to)));
1936
- const rules = [];
1937
- for (const from of layers) {
1938
- for (const to of layers) {
1939
- if (from.name === to.name) continue;
1940
- if (allowed.has(flowKey2(from.name, to.name))) continue;
1941
- rules.push({ from: from.name, to: to.name, allowed: false });
1942
- }
1943
- }
1944
- return rules;
1945
- }
1946
- function createArchitectureProfile(options) {
1947
- const layers = options.layers.map((layer) => ({
1948
- ...layer,
1949
- prefixes: layer.prefixes.map(normalizePrefix)
1950
- }));
1951
- const sortedLayers = [...layers].sort(byLongestPrefix);
1952
- const rules = [...options.rules ?? []];
1953
- return {
1954
- name: options.name,
1955
- layers,
1956
- rules,
1957
- resolveLayer(name) {
1958
- return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
1959
- (layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
1960
- )?.name;
1961
- }
1962
- };
1963
- }
1964
- function createArchitectureProfileFromArkConfig(config, options = {}) {
1965
- return createArchitectureProfile({
1966
- name: options.name ?? config.name ?? "ark.config.json",
1967
- layers: config.layers.map((layer, index) => ({
1968
- name: layer.name,
1969
- prefixes: layer.intentPrefixes ?? [],
1970
- description: layer.description,
1971
- order: index + 1
1972
- })),
1973
- rules: config.rules ?? []
1974
- });
1975
- }
1976
- var elevenLayerProfileLayers = [
1977
- {
1978
- name: "DomainModel",
1979
- prefixes: ["Domain"],
1980
- description: "Rich domain model, business rules, and domain events.",
1981
- order: 1
1982
- },
1983
- {
1984
- name: "ApplicationOrchestration",
1985
- prefixes: ["Application"],
1986
- description: "Use cases and command orchestration.",
1987
- order: 2
1988
- },
1989
- {
1990
- name: "PersistenceAdapters",
1991
- prefixes: ["Adapter.Persistence", "Adapter.Repository"],
1992
- description: "Database, repository, and storage adapters.",
1993
- order: 3
1994
- },
1995
- {
1996
- name: "IntegrationAdapters",
1997
- prefixes: ["Adapter.Integration", "Adapter.External"],
1998
- description: "External systems, APIs, and integration adapters.",
1999
- order: 4
2000
- },
2001
- {
2002
- name: "WorkflowSagaEngine",
2003
- prefixes: ["Workflow"],
2004
- description: "Sagas, workflows, and long-running processes.",
2005
- order: 5
2006
- },
2007
- {
2008
- name: "BackgroundJobsScheduling",
2009
- prefixes: ["Job"],
2010
- description: "Background jobs, scheduled work, and async processors.",
2011
- order: 6
2012
- },
2013
- {
2014
- name: "PresentationAdapters",
2015
- prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
2016
- description: "API, UI, controller, and presentation adapters.",
2017
- order: 7
2018
- },
2019
- {
2020
- name: "ReportingReadModels",
2021
- prefixes: ["Reporting"],
2022
- description: "Read models, projections, and reporting surfaces.",
2023
- order: 8
2024
- },
2025
- {
2026
- name: "ExtensibilityMetadata",
2027
- prefixes: ["Metadata"],
2028
- description: "Metadata, extensions, and schema contracts.",
2029
- order: 9
2030
- },
2031
- {
2032
- name: "SecurityAuditObservability",
2033
- prefixes: ["Security", "Audit", "Observability"],
2034
- description: "Security, audit, and observability concerns.",
2035
- order: 10
2036
- },
2037
- {
2038
- name: "Kernel",
2039
- prefixes: ["Kernel"],
2040
- description: "Ark-owned governance and kernel signals.",
2041
- order: 11
2042
- }
2043
- ];
2044
- var elevenLayerAllowedFlows = [
2045
- { from: "PresentationAdapters", to: "ApplicationOrchestration" },
2046
- { from: "ApplicationOrchestration", to: "DomainModel" },
2047
- { from: "WorkflowSagaEngine", to: "ApplicationOrchestration" },
2048
- { from: "WorkflowSagaEngine", to: "DomainModel" },
2049
- { from: "BackgroundJobsScheduling", to: "ApplicationOrchestration" }
2050
- ];
2051
- var elevenLayerProfile = createArchitectureProfile({
2052
- name: "Ark 11-layer Hexagonal Event-Driven Profile",
2053
- layers: elevenLayerProfileLayers,
2054
- rules: createStrictDenyRules(
2055
- elevenLayerProfileLayers,
2056
- elevenLayerAllowedFlows
2057
- )
2058
- });
2059
- var defaultElevenLayerDirectories = {
2060
- DomainModel: ["domain"],
2061
- ApplicationOrchestration: ["application", "app"],
2062
- PersistenceAdapters: [
2063
- "adapters/persistence",
2064
- "adapters/repository",
2065
- "repositories",
2066
- "infra/persistence"
2067
- ],
2068
- IntegrationAdapters: ["adapters/integration", "adapters/external", "integrations"],
2069
- WorkflowSagaEngine: ["workflows", "sagas"],
2070
- BackgroundJobsScheduling: ["jobs", "schedules"],
2071
- PresentationAdapters: ["presentation", "adapters/presentation", "adapters/api"],
2072
- ReportingReadModels: ["reporting", "read-models", "projections"],
2073
- ExtensibilityMetadata: ["metadata", "extensions"],
2074
- SecurityAuditObservability: ["security", "audit", "observability"],
2075
- Kernel: ["kernel"]
2076
- };
2077
- function createElevenLayerArkConfig(options = {}) {
2078
- const rootDir = options.rootDir ?? "src";
2079
- const optional = options.optionalLayers ?? true;
2080
- const prefix = rootDir === "." ? "" : `${rootDir}/`;
2081
- return {
2082
- include: options.include ?? [rootDir],
2083
- layers: elevenLayerProfile.layers.map((layer) => ({
2084
- name: layer.name,
2085
- patterns: (defaultElevenLayerDirectories[layer.name] ?? [layer.name]).map(
2086
- (directory) => `${prefix}${directory}/**`
2087
- ),
2088
- intentPrefixes: layer.prefixes,
2089
- optional
2090
- })),
2091
- rules: [...elevenLayerProfile.rules]
2092
- };
2093
- }
2094
-
2095
- // src/kernel/metadata/MetadataRegistry.ts
2096
- var MetadataRegistryImpl = class {
2097
- entities = /* @__PURE__ */ new Map();
2098
- entity(name, meta, options = {}) {
2099
- if (this.entities.has(name) && !options.allowOverwrite) {
2100
- throw new Error(`Entity metadata "${name}" is already registered.`);
2101
- }
2102
- const full = { name, fields: {}, ...meta };
2103
- this.entities.set(name, full);
2104
- return full;
2105
- }
2106
- getEntity(name) {
2107
- return this.entities.get(name);
2108
- }
2109
- listEntities() {
2110
- return Array.from(this.entities.values());
2111
- }
2112
- findEntitiesByIntent(intentName) {
2113
- return this.listEntities().filter(
2114
- (entity) => entity.emits?.includes(intentName) || entity.consumes?.includes(intentName)
2115
- );
2116
- }
2117
- validate() {
2118
- const issues = [];
2119
- for (const entity of this.entities.values()) {
2120
- if (!entity.name.trim()) {
2121
- issues.push({ entity: entity.name, message: "Entity name is required." });
2122
- }
2123
- for (const [fieldName, field] of Object.entries(entity.fields)) {
2124
- if (!fieldName.trim()) {
2125
- issues.push({ entity: entity.name, field: fieldName, message: "Field name is required." });
2126
- }
2127
- if (!field.type || typeof field.type !== "string") {
2128
- issues.push({
2129
- entity: entity.name,
2130
- field: fieldName,
2131
- message: "Field type must be a non-empty string."
2132
- });
2133
- }
2134
- if (field.relation && !this.entities.has(field.relation.entity)) {
2135
- issues.push({
2136
- entity: entity.name,
2137
- field: fieldName,
2138
- message: `Related entity "${field.relation.entity}" is not registered.`
2139
- });
2140
- }
2141
- }
2142
- }
2143
- return { ok: issues.length === 0, issues };
2144
- }
2145
- toJSON() {
2146
- return this.listEntities();
2147
- }
2148
- };
2149
- function createMetadataRegistry() {
2150
- return new MetadataRegistryImpl();
2151
- }
2152
-
2153
- // src/kernel/adapters/ports.ts
2154
- function definePort(name, options = {}) {
2155
- return {
2156
- name,
2157
- ownerLayer: options.ownerLayer,
2158
- intent: options.intent,
2159
- allowedAdapters: options.allowedAdapters ? [...options.allowedAdapters] : void 0
2160
- };
2161
- }
2162
- function createAdapter(port, impl, requiredKeysOrOptions, adapterOptions = {}) {
2163
- const options = Array.isArray(requiredKeysOrOptions) ? { ...adapterOptions, requiredKeys: requiredKeysOrOptions } : { ...requiredKeysOrOptions ?? {} };
2164
- const requiredKeys = options.requiredKeys;
2165
- if (requiredKeys && requiredKeys.length > 0) {
2166
- const missing = requiredKeys.filter((k) => !hasMember(impl, k));
2167
- if (missing.length > 0) {
2168
- throw new Error(
2169
- `Adapter for port "${port.name}" is missing required members: ${missing.join(", ")}`
2170
- );
2171
- }
2172
- }
2173
- const adapter = {
2174
- name: options.name,
2175
- layer: options.layer,
2176
- intent: options.intent,
2177
- port,
2178
- impl
2179
- };
2180
- const governance = checkAdapterGovernance(adapter);
2181
- if (!governance.ok) {
2182
- throw new Error(governance.issues.map((issue) => issue.message).join("\n"));
2183
- }
2184
- return adapter;
2185
- }
2186
- function checkContract(impl, requiredKeys = []) {
2187
- const missing = requiredKeys.filter((k) => !hasMember(impl, k));
2188
- return missing.length === 0 ? { ok: true } : { ok: false, missing };
2189
- }
2190
- function checkAdapterGovernance(adapter) {
2191
- const allowed = adapter.port.allowedAdapters ?? [];
2192
- if (allowed.length === 0) {
2193
- return { ok: true, issues: [] };
2194
- }
2195
- const adapterNames = [adapter.name, adapter.intent].filter(
2196
- (value) => typeof value === "string" && value.length > 0
2197
- );
2198
- const matched = adapterNames.some((name) => allowed.includes(name));
2199
- if (matched) {
2200
- return { ok: true, issues: [] };
2201
- }
2202
- return {
2203
- ok: false,
2204
- issues: [
2205
- {
2206
- ruleId: "ADAPTER_NOT_ALLOWED_FOR_PORT",
2207
- port: adapter.port.name,
2208
- adapter: adapter.name ?? adapter.intent,
2209
- message: `Adapter "${adapter.name ?? adapter.intent ?? "unknown"}" is not allowed for port "${adapter.port.name}".`
2210
- }
2211
- ]
513
+ ts.forEachChild(node, visit);
2212
514
  };
2213
- }
2214
- function hasMember(value, key) {
2215
- return value != null && (typeof value === "object" || typeof value === "function") && key in value;
515
+ visit(sourceFile);
516
+ return uses;
2216
517
  }
2217
518
 
2218
519
  // src/kernel/ai-gate/AICodeGate.ts
2219
520
  function violation(ruleId, message, extra) {
2220
521
  return { ruleId, code: ruleId, message, ...extra };
2221
522
  }
2222
- function lineOf(source, index) {
523
+ function lineOf2(source, index) {
2223
524
  return source.slice(0, index).split("\n").length;
2224
525
  }
2225
526
  function extractQuotedStrings(source) {
@@ -2262,63 +563,6 @@ function extractModuleSpecifiers(source) {
2262
563
  }
2263
564
  return matches.sort((a, b) => a.index - b.index);
2264
565
  }
2265
- function extractModuleSpecifiersAst(ts, source) {
2266
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2267
- const matches = [];
2268
- const push = (node, value, kind, typeOnly = false) => {
2269
- matches.push({
2270
- value,
2271
- index: node.getStart(sourceFile),
2272
- kind,
2273
- typeOnly
2274
- });
2275
- };
2276
- const visit = (node) => {
2277
- if (ts.isImportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
2278
- const clause = node.importClause;
2279
- const namedBindings = clause?.namedBindings;
2280
- const specifiersOnly = clause && !clause.name && namedBindings && ts.isNamedImports(namedBindings) && namedBindings.elements.length > 0 && namedBindings.elements.every((element) => element.isTypeOnly === true);
2281
- push(
2282
- node.moduleSpecifier,
2283
- node.moduleSpecifier.text,
2284
- "import",
2285
- Boolean(clause?.isTypeOnly || specifiersOnly)
2286
- );
2287
- } else if (ts.isExportDeclaration(node) && ts.isStringLiteralLike(node.moduleSpecifier)) {
2288
- const clause = node.exportClause;
2289
- const specifiersOnly = clause && ts.isNamedExports(clause) && clause.elements.length > 0 && clause.elements.every((element) => element.isTypeOnly === true);
2290
- push(
2291
- node.moduleSpecifier,
2292
- node.moduleSpecifier.text,
2293
- "export",
2294
- Boolean(node.isTypeOnly || specifiersOnly)
2295
- );
2296
- } else if (ts.isCallExpression(node) && node.arguments.length === 1) {
2297
- const argument = node.arguments[0];
2298
- const value = tsStringLiteralText(ts, argument);
2299
- if (value !== void 0 && node.expression.kind === ts.SyntaxKind.ImportKeyword) {
2300
- push(argument, value, "dynamic-import");
2301
- } else if (value !== void 0 && ts.isIdentifier(node.expression) && node.expression.text === "require") {
2302
- push(argument, value, "require");
2303
- }
2304
- }
2305
- ts.forEachChild(node, visit);
2306
- };
2307
- visit(sourceFile);
2308
- return matches.sort((a, b) => a.index - b.index);
2309
- }
2310
- function nonLiteralDynamicImportLines(ts, source) {
2311
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2312
- const lines = [];
2313
- const visit = (node) => {
2314
- if (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.ImportKeyword && (!node.arguments[0] || !ts.isStringLiteralLike(node.arguments[0]))) {
2315
- lines.push(sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1);
2316
- }
2317
- ts.forEachChild(node, visit);
2318
- };
2319
- visit(sourceFile);
2320
- return lines;
2321
- }
2322
566
  function extractQuotedStringsAst(ts, source) {
2323
567
  const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2324
568
  const matches = [];
@@ -2331,9 +575,6 @@ function extractQuotedStringsAst(ts, source) {
2331
575
  visit(sourceFile);
2332
576
  return matches;
2333
577
  }
2334
- function looksLikeIntentName(s) {
2335
- return /^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(s);
2336
- }
2337
578
  function hasInfrastructureToken(specifier) {
2338
579
  const tokens = specifier.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
2339
580
  return [
@@ -2415,7 +656,7 @@ function tsIsArkPublishCandidate(ts, node) {
2415
656
  if (!ts.isCallExpression(node)) return false;
2416
657
  const firstArg = node.arguments[0];
2417
658
  const rawIntent = tsStringLiteralText(ts, firstArg);
2418
- return rawIntent !== void 0 && looksLikeIntentName(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent") || tsLooksLikeIntentCreatorExpression(ts, firstArg);
659
+ return rawIntent !== void 0 && looksLikeArkIntent(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent") || tsLooksLikeIntentCreatorExpression(ts, firstArg);
2419
660
  }
2420
661
  function tsPublishHasSource(ts, node) {
2421
662
  if (!ts.isCallExpression(node)) return false;
@@ -2428,33 +669,6 @@ function tsPublishSourceLiteral(ts, node) {
2428
669
  const rawMetadata = tsObjectPropertyValue(ts, firstArg, "metadata");
2429
670
  return tsStringLiteralText(ts, tsObjectPropertyValue(ts, rawMetadata, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, secondArg, "source")) ?? tsStringLiteralText(ts, tsObjectPropertyValue(ts, thirdArg, "source"));
2430
671
  }
2431
- function analyzeForbiddenGlobals(ts, source, filePath, layer, forbidden) {
2432
- const entries = new Set(forbidden);
2433
- if (entries.size === 0) return [];
2434
- const sourceFile = ts.createSourceFile("generated.ts", source, ts.ScriptTarget.Latest, true);
2435
- const violations = [];
2436
- const flag = (name, node) => violations.push(
2437
- violation("FORBIDDEN_GLOBAL", `${layer} must not use the ambient global "${name}".`, {
2438
- line: sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1,
2439
- filePath,
2440
- target: name,
2441
- fromLayer: layer,
2442
- suggestion: "Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."
2443
- })
2444
- );
2445
- const visit = (node) => {
2446
- if (ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.expression)) {
2447
- const dotted = `${node.expression.text}.${node.name.text}`;
2448
- if (entries.has(dotted)) flag(dotted, node);
2449
- else if (entries.has(node.expression.text)) flag(node.expression.text, node);
2450
- } else if ((ts.isCallExpression(node) || ts.isNewExpression(node)) && node.expression && ts.isIdentifier(node.expression) && entries.has(node.expression.text)) {
2451
- flag(node.expression.text, node);
2452
- }
2453
- ts.forEachChild(node, visit);
2454
- };
2455
- visit(sourceFile);
2456
- return violations;
2457
- }
2458
672
  function analyzePublishAst(ts, source, context, profile) {
2459
673
  const sourceFile = ts.createSourceFile(
2460
674
  "generated.ts",
@@ -2471,24 +685,19 @@ function analyzePublishAst(ts, source, context, profile) {
2471
685
  if (tsIsPublishCall(ts, node)) {
2472
686
  const firstArg = node.arguments[0];
2473
687
  const rawIntent = tsStringLiteralText(ts, firstArg);
2474
- if (rawIntent && looksLikeIntentName(rawIntent) || tsObjectHasProperty(ts, firstArg, "intent")) {
2475
- violations.push(
2476
- violation("RAW_EVENT_PUBLISH", "Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.", {
2477
- line: lineForNode(node),
2478
- filePath
2479
- })
2480
- );
2481
- }
2482
- if (tsIsArkPublishCandidate(ts, node) && !tsPublishHasSource(ts, node)) {
688
+ for (const finding of classifyPublishFacts({
689
+ publishCall: true,
690
+ rawIntentName: rawIntent,
691
+ objectHasIntent: tsObjectHasProperty(ts, firstArg, "intent"),
692
+ arkPublishCandidate: tsIsArkPublishCandidate(ts, node),
693
+ hasSource: tsPublishHasSource(ts, node)
694
+ })) {
2483
695
  violations.push(
2484
- violation("PUBLISH_MISSING_SOURCE", "Strict Ark publish calls must include metadata.source.", {
2485
- line: lineForNode(node),
2486
- filePath
2487
- })
696
+ violation(finding.ruleId, finding.message, { line: lineForNode(node), filePath })
2488
697
  );
2489
698
  }
2490
699
  const sourceIntent = tsPublishSourceLiteral(ts, node);
2491
- if (profile && contextLayer && sourceIntent && looksLikeIntentName(sourceIntent)) {
700
+ if (profile && contextLayer && sourceIntent && looksLikeArkIntent(sourceIntent)) {
2492
701
  const sourceLayer = profile.resolveLayer(sourceIntent);
2493
702
  if (sourceLayer && sourceLayer !== contextLayer) {
2494
703
  violations.push(
@@ -2525,15 +734,29 @@ function createAICodeGate(options = {}) {
2525
734
  const gateContext = context;
2526
735
  const filePath = gateContext?.filePath;
2527
736
  const contextLayer = gateContext?.layer;
2528
- const moduleSpecifiers = options.typescript ? extractModuleSpecifiersAst(options.typescript, source) : extractModuleSpecifiers(source);
737
+ const semanticTypescript = options.typescript;
738
+ const semanticSourceFile = semanticTypescript ? semanticTypescript.createSourceFile(
739
+ filePath ?? "generated.ts",
740
+ source,
741
+ semanticTypescript.ScriptTarget.Latest,
742
+ true
743
+ ) : void 0;
744
+ const semanticDependencies = semanticSourceFile ? extractSemanticDependencies(options.typescript, semanticSourceFile) : void 0;
745
+ const moduleSpecifiers2 = semanticDependencies ? semanticDependencies.filter((dependency) => dependency.specifier !== void 0).map((dependency) => ({
746
+ value: dependency.specifier,
747
+ index: dependency.node.getStart(semanticSourceFile),
748
+ kind: dependency.kind,
749
+ typeOnly: dependency.typeOnly
750
+ })) : extractModuleSpecifiers(source);
2529
751
  const quotedStrings = options.typescript ? extractQuotedStringsAst(options.typescript, source) : extractQuotedStrings(source);
2530
752
  if (options.typescript && !options.allowNonLiteralDynamicImport?.(filePath)) {
2531
- for (const line of nonLiteralDynamicImportLines(options.typescript, source)) {
753
+ for (const dependency of semanticDependencies?.filter(({ unresolved }) => unresolved) ?? []) {
754
+ const isRequire = dependency.kind === "require";
2532
755
  violations.push(
2533
756
  violation(
2534
- "DYNAMIC_IMPORT_NOT_ALLOWLISTED",
2535
- "Non-literal dynamic import cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.",
2536
- { line, filePath }
757
+ isRequire ? "DYNAMIC_REQUIRE_NOT_ALLOWLISTED" : "DYNAMIC_IMPORT_NOT_ALLOWLISTED",
758
+ `Non-literal ${isRequire ? "require call" : "dynamic import"} cannot be resolved statically; add the reviewed file to dynamicImportAllowlist.`,
759
+ { line: dependency.line, filePath }
2537
760
  )
2538
761
  );
2539
762
  }
@@ -2548,7 +771,7 @@ function createAICodeGate(options = {}) {
2548
771
  if (match) {
2549
772
  violations.push(
2550
773
  violation("FORBIDDEN_PATTERN", `Forbidden pattern matched: ${pat}`, {
2551
- line: match.index === void 0 ? void 0 : lineOf(source, match.index),
774
+ line: match.index === void 0 ? void 0 : lineOf2(source, match.index),
2552
775
  filePath,
2553
776
  suggestion: "Remove infrastructure imports from domain/application layers." + infraLayerEscapeHatch
2554
777
  })
@@ -2557,13 +780,13 @@ function createAICodeGate(options = {}) {
2557
780
  } else if (source.includes(pat)) {
2558
781
  violations.push(
2559
782
  violation("FORBIDDEN_SUBSTRING", `Forbidden substring: ${pat}`, {
2560
- line: lineOf(source, source.indexOf(pat)),
783
+ line: lineOf2(source, source.indexOf(pat)),
2561
784
  filePath
2562
785
  })
2563
786
  );
2564
787
  }
2565
788
  }
2566
- for (const specifier of moduleSpecifiers) {
789
+ for (const specifier of moduleSpecifiers2) {
2567
790
  const targetHit = options.resolveImportTarget?.(specifier.value, filePath) ?? (options.resolveImportLayer ? { layer: options.resolveImportLayer(specifier.value, filePath) } : void 0);
2568
791
  const sourceHit = typeof filePath === "string" ? options.resolveImportTarget?.(filePath) ?? (options.resolveImportLayer ? { layer: contextLayer, relPath: void 0 } : void 0) : void 0;
2569
792
  const targetLayer = targetHit?.layer;
@@ -2588,7 +811,7 @@ function createAICodeGate(options = {}) {
2588
811
  "LAYER_IMPORT_VIOLATION",
2589
812
  blocked.message ?? (peer ? `Layer "${contextLayer}" must not import across slices into "${targetLayer}".` : `Layer "${contextLayer}" must not import "${targetLayer}".`),
2590
813
  {
2591
- line: lineOf(source, specifier.index),
814
+ line: lineOf2(source, specifier.index),
2592
815
  source: specifier.value,
2593
816
  target: specifier.value,
2594
817
  filePath,
@@ -2618,7 +841,7 @@ function createAICodeGate(options = {}) {
2618
841
  "FORBIDDEN_IMPORT",
2619
842
  `Forbidden ${specifier.kind} target: "${specifier.value}".`,
2620
843
  {
2621
- line: lineOf(source, specifier.index),
844
+ line: lineOf2(source, specifier.index),
2622
845
  source: specifier.value,
2623
846
  target: specifier.value,
2624
847
  filePath,
@@ -2655,13 +878,13 @@ function createAICodeGate(options = {}) {
2655
878
  }
2656
879
  if (enforceAllowlist && intentNames.size > 0) {
2657
880
  for (const literal of quotedStrings) {
2658
- if (looksLikeIntentName(literal.value) && !intentNames.has(literal.value)) {
881
+ if (looksLikeArkIntent(literal.value) && !intentNames.has(literal.value)) {
2659
882
  violations.push(
2660
883
  violation(
2661
884
  "UNKNOWN_INTENT",
2662
885
  `Unknown intent reference: "${literal.value}"`,
2663
886
  {
2664
- line: lineOf(source, literal.index),
887
+ line: lineOf2(source, literal.index),
2665
888
  filePath,
2666
889
  target: literal.value,
2667
890
  suggestion: `Register intent "${literal.value}" via defineIntent() or remove the reference.`
@@ -2673,7 +896,7 @@ function createAICodeGate(options = {}) {
2673
896
  }
2674
897
  if (options.architectureProfile && contextLayer) {
2675
898
  for (const literal of quotedStrings) {
2676
- if (!looksLikeIntentName(literal.value)) continue;
899
+ if (!looksLikeArkIntent(literal.value)) continue;
2677
900
  const targetLayer = options.architectureProfile.resolveLayer(literal.value);
2678
901
  if (!targetLayer) continue;
2679
902
  const blocked = findDeniedEdgeRule(
@@ -2687,7 +910,7 @@ function createAICodeGate(options = {}) {
2687
910
  "LAYER_REFERENCE_VIOLATION",
2688
911
  blocked.message ?? `Layer "${contextLayer}" must not reference "${targetLayer}" through "${literal.value}".`,
2689
912
  {
2690
- line: lineOf(source, literal.index),
913
+ line: lineOf2(source, literal.index),
2691
914
  filePath,
2692
915
  target: literal.value,
2693
916
  fromLayer: contextLayer,
@@ -2715,15 +938,25 @@ function createAICodeGate(options = {}) {
2715
938
  }
2716
939
  }
2717
940
  }
2718
- if (options.typescript && contextLayer && options.forbiddenGlobals?.[contextLayer]?.length) {
941
+ if (options.typescript && semanticSourceFile && contextLayer && options.forbiddenGlobals?.[contextLayer]?.length) {
2719
942
  try {
2720
943
  violations.push(
2721
- ...analyzeForbiddenGlobals(
944
+ ...collectForbiddenCapabilityUses(
2722
945
  options.typescript,
2723
- source,
2724
- filePath,
2725
- contextLayer,
946
+ semanticSourceFile,
2726
947
  options.forbiddenGlobals[contextLayer]
948
+ ).map(
949
+ (use) => violation(
950
+ "FORBIDDEN_GLOBAL",
951
+ `${contextLayer} must not use the ambient global "${use.name}".`,
952
+ {
953
+ line: use.line,
954
+ filePath,
955
+ target: use.name,
956
+ fromLayer: contextLayer,
957
+ suggestion: "Inject the capability through a port (e.g. a Clock, IdGenerator, or HttpPort) instead of reaching for the ambient global."
958
+ }
959
+ )
2727
960
  )
2728
961
  );
2729
962
  } catch (err) {
@@ -2761,592 +994,967 @@ function createAICodeGate(options = {}) {
2761
994
  }
2762
995
  };
2763
996
  }
2764
-
2765
- // src/kernel/projections/ProjectionRegistry.ts
2766
- var InMemoryReadModelStore = class {
2767
- states = /* @__PURE__ */ new Map();
2768
- load(name) {
2769
- return this.states.get(name);
2770
- }
2771
- save(name, state) {
2772
- this.states.set(name, state);
997
+
998
+ // src/domain/configContract.ts
999
+ var ARK_CONFIG_SCHEMA_VERSION = "1.0";
1000
+ var ARK_CONFIG_SCHEMA_URL = "https://unpkg.com/arkgate@2/schemas/ark.config.schema.json";
1001
+ var DEFAULT_LAYER_NAMES = [
1002
+ "DomainModel",
1003
+ "ApplicationOrchestration",
1004
+ "PersistenceAdapters",
1005
+ "IntegrationAdapters",
1006
+ "WorkflowSagaEngine",
1007
+ "BackgroundJobsScheduling",
1008
+ "PresentationAdapters",
1009
+ "ReportingReadModels",
1010
+ "ExtensibilityMetadata",
1011
+ "SecurityAuditObservability",
1012
+ "Kernel"
1013
+ ];
1014
+ var DEFAULT_ALLOWED_FLOWS = /* @__PURE__ */ new Set([
1015
+ "PresentationAdapters->ApplicationOrchestration",
1016
+ "ApplicationOrchestration->DomainModel",
1017
+ "WorkflowSagaEngine->ApplicationOrchestration",
1018
+ "WorkflowSagaEngine->DomainModel",
1019
+ "BackgroundJobsScheduling->ApplicationOrchestration"
1020
+ ]);
1021
+ function createDefaultRules() {
1022
+ const rules = [];
1023
+ for (const from of DEFAULT_LAYER_NAMES) {
1024
+ for (const to of DEFAULT_LAYER_NAMES) {
1025
+ if (from === to || DEFAULT_ALLOWED_FLOWS.has(`${from}->${to}`)) continue;
1026
+ rules.push({ from, to, allowed: false });
1027
+ }
1028
+ }
1029
+ return rules;
1030
+ }
1031
+ var DEFAULT_ARK_CONFIG_RULES = createDefaultRules();
1032
+ var stringArraySchema = {
1033
+ type: "array",
1034
+ items: { type: "string", minLength: 1 },
1035
+ uniqueItems: true
1036
+ };
1037
+ var ARK_CONFIG_SCHEMA = {
1038
+ $schema: "https://json-schema.org/draft/2020-12/schema",
1039
+ $id: ARK_CONFIG_SCHEMA_URL,
1040
+ title: "ArkGate architecture contract",
1041
+ description: "Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",
1042
+ type: "object",
1043
+ additionalProperties: false,
1044
+ required: ["$schema", "schemaVersion", "include", "layers", "rules"],
1045
+ properties: {
1046
+ $schema: {
1047
+ type: "string",
1048
+ minLength: 1,
1049
+ default: ARK_CONFIG_SCHEMA_URL,
1050
+ description: "Editor-facing URL or local path for this JSON Schema."
1051
+ },
1052
+ schemaVersion: {
1053
+ type: "string",
1054
+ const: ARK_CONFIG_SCHEMA_VERSION,
1055
+ default: ARK_CONFIG_SCHEMA_VERSION
1056
+ },
1057
+ name: { type: "string", minLength: 1 },
1058
+ include: { ...stringArraySchema, minItems: 1, default: ["src"] },
1059
+ exclude: { ...stringArraySchema, default: [] },
1060
+ excludeGenerated: { type: "boolean", default: true },
1061
+ frameworkOverlay: { type: "string", minLength: 1 },
1062
+ layers: {
1063
+ type: "array",
1064
+ default: [],
1065
+ items: { $ref: "#/$defs/layer" }
1066
+ },
1067
+ rules: {
1068
+ type: "array",
1069
+ default: DEFAULT_ARK_CONFIG_RULES,
1070
+ items: { $ref: "#/$defs/rule" }
1071
+ },
1072
+ cyclePolicy: {
1073
+ type: "string",
1074
+ enum: ["strict", "soft", "framework-soft", "off"],
1075
+ default: "strict"
1076
+ },
1077
+ dynamicImportAllowlist: { ...stringArraySchema, default: [] },
1078
+ safety: {
1079
+ $ref: "#/$defs/safety",
1080
+ default: {
1081
+ maxTsSuppressions: 0,
1082
+ maxAnyCasts: 0,
1083
+ allowInMemory: false,
1084
+ allowDisabledPeerIsolation: false
1085
+ }
1086
+ }
1087
+ },
1088
+ $defs: {
1089
+ layer: {
1090
+ type: "object",
1091
+ additionalProperties: false,
1092
+ required: ["name", "patterns"],
1093
+ properties: {
1094
+ name: { type: "string", minLength: 1 },
1095
+ patterns: { ...stringArraySchema, minItems: 1 },
1096
+ exclude: stringArraySchema,
1097
+ intentPrefixes: stringArraySchema,
1098
+ description: { type: "string", minLength: 1 },
1099
+ forbiddenGlobals: stringArraySchema,
1100
+ mayImportInfrastructure: { type: "boolean" },
1101
+ optional: { type: "boolean" }
1102
+ }
1103
+ },
1104
+ rule: {
1105
+ type: "object",
1106
+ additionalProperties: false,
1107
+ required: ["from", "to", "allowed"],
1108
+ properties: {
1109
+ from: { type: "string", minLength: 1 },
1110
+ to: { type: "string", minLength: 1 },
1111
+ allowed: { type: "boolean" },
1112
+ message: { type: "string", minLength: 1 },
1113
+ peerIsolation: { type: "boolean" },
1114
+ sliceFolders: { ...stringArraySchema, minItems: 1 }
1115
+ }
1116
+ },
1117
+ safety: {
1118
+ type: "object",
1119
+ additionalProperties: false,
1120
+ properties: {
1121
+ maxTsSuppressions: { type: "integer", minimum: 0, default: 0 },
1122
+ maxAnyCasts: { type: "integer", minimum: 0, default: 0 },
1123
+ allowInMemory: { type: "boolean", default: false },
1124
+ allowDisabledPeerIsolation: { type: "boolean", default: false }
1125
+ }
1126
+ }
1127
+ }
1128
+ };
1129
+ var ArkConfigValidationError = class extends Error {
1130
+ issues;
1131
+ source;
1132
+ constructor(source, issues) {
1133
+ super(
1134
+ `Invalid ArkGate config (${source}):
1135
+ ${issues.map((issue) => `- ${issue.path}: ${issue.message}`).join("\n")}`
1136
+ );
1137
+ this.name = "ArkConfigValidationError";
1138
+ this.source = source;
1139
+ this.issues = issues;
1140
+ }
1141
+ };
1142
+ function isObject(value) {
1143
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1144
+ }
1145
+ function propertyPath(parent, key) {
1146
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;
1147
+ }
1148
+ function valueType(value) {
1149
+ if (value === null) return "null";
1150
+ if (Array.isArray(value)) return "array";
1151
+ return typeof value;
1152
+ }
1153
+ function resolveSchemaRef(ref, root) {
1154
+ const prefix = "#/$defs/";
1155
+ if (!ref.startsWith(prefix)) return void 0;
1156
+ return root.$defs[ref.slice(prefix.length)];
1157
+ }
1158
+ function validateNode(value, schema, path, root, issues) {
1159
+ if (schema.$ref) {
1160
+ const referenced = resolveSchemaRef(schema.$ref, root);
1161
+ if (!referenced) {
1162
+ issues.push({ path, message: `schema reference ${schema.$ref} cannot be resolved` });
1163
+ return;
1164
+ }
1165
+ validateNode(value, referenced, path, root, issues);
1166
+ return;
1167
+ }
1168
+ if (schema.const !== void 0 && !Object.is(value, schema.const)) {
1169
+ issues.push({ path, message: `must equal ${JSON.stringify(schema.const)}` });
1170
+ return;
1171
+ }
1172
+ if (schema.enum && !schema.enum.some((candidate) => Object.is(candidate, value))) {
1173
+ issues.push({ path, message: `must be one of ${schema.enum.map(String).join(", ")}` });
1174
+ return;
1175
+ }
1176
+ if (schema.type === "object") {
1177
+ if (!isObject(value)) {
1178
+ issues.push({ path, message: `must be an object; received ${valueType(value)}` });
1179
+ return;
1180
+ }
1181
+ const properties = schema.properties ?? {};
1182
+ for (const key of schema.required ?? []) {
1183
+ if (value[key] === void 0) {
1184
+ issues.push({ path: propertyPath(path, key), message: "is required" });
1185
+ }
1186
+ }
1187
+ if (schema.additionalProperties === false) {
1188
+ for (const key of Object.keys(value)) {
1189
+ if (!(key in properties)) {
1190
+ issues.push({ path: propertyPath(path, key), message: "unknown field" });
1191
+ }
1192
+ }
1193
+ }
1194
+ for (const [key, childSchema] of Object.entries(properties)) {
1195
+ if (value[key] !== void 0) {
1196
+ validateNode(value[key], childSchema, propertyPath(path, key), root, issues);
1197
+ }
1198
+ }
1199
+ return;
1200
+ }
1201
+ if (schema.type === "array") {
1202
+ if (!Array.isArray(value)) {
1203
+ issues.push({ path, message: `must be an array; received ${valueType(value)}` });
1204
+ return;
1205
+ }
1206
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
1207
+ issues.push({ path, message: `must contain at least ${schema.minItems} item(s)` });
1208
+ }
1209
+ if (schema.uniqueItems) {
1210
+ const serialized = value.map((entry) => JSON.stringify(entry));
1211
+ if (new Set(serialized).size !== serialized.length) {
1212
+ issues.push({ path, message: "must not contain duplicate items" });
1213
+ }
1214
+ }
1215
+ if (schema.items) {
1216
+ value.forEach(
1217
+ (entry, index) => validateNode(entry, schema.items, `${path}[${index}]`, root, issues)
1218
+ );
1219
+ }
1220
+ return;
1221
+ }
1222
+ if (schema.type === "string") {
1223
+ if (typeof value !== "string") {
1224
+ issues.push({ path, message: `must be a string; received ${valueType(value)}` });
1225
+ return;
1226
+ }
1227
+ if (schema.minLength !== void 0 && value.length < schema.minLength) {
1228
+ issues.push({ path, message: `must contain at least ${schema.minLength} character(s)` });
1229
+ }
1230
+ return;
1231
+ }
1232
+ if (schema.type === "boolean") {
1233
+ if (typeof value !== "boolean") {
1234
+ issues.push({ path, message: `must be a boolean; received ${valueType(value)}` });
1235
+ }
1236
+ return;
1237
+ }
1238
+ if (schema.type === "integer") {
1239
+ if (!Number.isInteger(value)) {
1240
+ issues.push({ path, message: `must be an integer; received ${valueType(value)}` });
1241
+ return;
1242
+ }
1243
+ if (schema.minimum !== void 0 && value < schema.minimum) {
1244
+ issues.push({ path, message: `must be at least ${schema.minimum}` });
1245
+ }
1246
+ }
1247
+ }
1248
+ function defaultedConfig(input) {
1249
+ return {
1250
+ ...input,
1251
+ $schema: input.$schema === void 0 ? ARK_CONFIG_SCHEMA_URL : input.$schema,
1252
+ schemaVersion: input.schemaVersion === void 0 ? ARK_CONFIG_SCHEMA_VERSION : input.schemaVersion,
1253
+ include: input.include === void 0 ? ["src"] : input.include,
1254
+ layers: input.layers === void 0 ? [] : input.layers,
1255
+ rules: input.rules === void 0 ? DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule })) : input.rules
1256
+ };
1257
+ }
1258
+ function migrateArkConfig(input, source = "ark.config.json") {
1259
+ if (!isObject(input)) {
1260
+ throw new ArkConfigValidationError(source, [
1261
+ { path: "$", message: `must be an object; received ${valueType(input)}` }
1262
+ ]);
1263
+ }
1264
+ const migratedFrom = input.schemaVersion === void 0 ? "unversioned" : null;
1265
+ if (input.schemaVersion !== void 0 && input.schemaVersion !== ARK_CONFIG_SCHEMA_VERSION) {
1266
+ throw new ArkConfigValidationError(source, [
1267
+ {
1268
+ path: "$.schemaVersion",
1269
+ message: `unsupported version ${JSON.stringify(input.schemaVersion)}; expected ${ARK_CONFIG_SCHEMA_VERSION}`
1270
+ }
1271
+ ]);
1272
+ }
1273
+ return { candidate: defaultedConfig(input), migratedFrom };
1274
+ }
1275
+ function loadArkConfigContract(input, source = "ark.config.json") {
1276
+ const { candidate, migratedFrom } = migrateArkConfig(input, source);
1277
+ const issues = [];
1278
+ validateNode(
1279
+ candidate,
1280
+ ARK_CONFIG_SCHEMA,
1281
+ "$",
1282
+ ARK_CONFIG_SCHEMA,
1283
+ issues
1284
+ );
1285
+ if (issues.length > 0) throw new ArkConfigValidationError(source, issues);
1286
+ return { config: candidate, migratedFrom };
1287
+ }
1288
+ function parseArkConfigJson(json, source = "ark.config.json") {
1289
+ let input;
1290
+ try {
1291
+ input = JSON.parse(json);
1292
+ } catch (error) {
1293
+ throw new ArkConfigValidationError(source, [
1294
+ {
1295
+ path: "$",
1296
+ message: `invalid JSON: ${error instanceof Error ? error.message : String(error)}`
1297
+ }
1298
+ ]);
1299
+ }
1300
+ return loadArkConfigContract(input, source);
1301
+ }
1302
+ function withArkConfigMetadata(config) {
1303
+ const result = {
1304
+ $schema: typeof config.$schema === "string" && config.$schema.length > 0 ? config.$schema : ARK_CONFIG_SCHEMA_URL,
1305
+ schemaVersion: ARK_CONFIG_SCHEMA_VERSION
1306
+ };
1307
+ for (const [key, value] of Object.entries(config)) {
1308
+ if (key !== "$schema" && key !== "schemaVersion") result[key] = value;
1309
+ }
1310
+ return result;
1311
+ }
1312
+
1313
+ // src/kernel/layers/ArchitectureProfile.ts
1314
+ function normalizePrefix(prefix) {
1315
+ return prefix.endsWith(".") ? prefix : `${prefix}.`;
1316
+ }
1317
+ function byLongestPrefix(a, b) {
1318
+ const maxA = a.prefixes.length ? Math.max(...a.prefixes.map((p) => p.length)) : 0;
1319
+ const maxB = b.prefixes.length ? Math.max(...b.prefixes.map((p) => p.length)) : 0;
1320
+ return maxB - maxA;
1321
+ }
1322
+ function createArchitectureProfile(options) {
1323
+ const layers = options.layers.map((layer) => ({
1324
+ ...layer,
1325
+ prefixes: layer.prefixes.map(normalizePrefix)
1326
+ }));
1327
+ const sortedLayers = [...layers].sort(byLongestPrefix);
1328
+ const rules = [...options.rules ?? []];
1329
+ return {
1330
+ name: options.name,
1331
+ layers,
1332
+ rules,
1333
+ resolveLayer(name) {
1334
+ return layers.find((layer) => layer.match?.(name))?.name ?? sortedLayers.find(
1335
+ (layer) => layer.prefixes.some((prefix) => name.startsWith(prefix))
1336
+ )?.name;
1337
+ }
1338
+ };
1339
+ }
1340
+ function createArchitectureProfileFromArkConfig(config, options = {}) {
1341
+ return createArchitectureProfile({
1342
+ name: options.name ?? config.name ?? "ark.config.json",
1343
+ layers: config.layers.map((layer, index) => ({
1344
+ name: layer.name,
1345
+ prefixes: layer.intentPrefixes ?? [],
1346
+ description: layer.description,
1347
+ order: index + 1
1348
+ })),
1349
+ rules: config.rules ?? []
1350
+ });
1351
+ }
1352
+ var elevenLayerProfileLayers = [
1353
+ {
1354
+ name: "DomainModel",
1355
+ prefixes: ["Domain"],
1356
+ description: "Rich domain model, business rules, and domain events.",
1357
+ order: 1
1358
+ },
1359
+ {
1360
+ name: "ApplicationOrchestration",
1361
+ prefixes: ["Application"],
1362
+ description: "Use cases and command orchestration.",
1363
+ order: 2
1364
+ },
1365
+ {
1366
+ name: "PersistenceAdapters",
1367
+ prefixes: ["Adapter.Persistence", "Adapter.Repository"],
1368
+ description: "Database, repository, and storage adapters.",
1369
+ order: 3
1370
+ },
1371
+ {
1372
+ name: "IntegrationAdapters",
1373
+ prefixes: ["Adapter.Integration", "Adapter.External"],
1374
+ description: "External systems, APIs, and integration adapters.",
1375
+ order: 4
1376
+ },
1377
+ {
1378
+ name: "WorkflowSagaEngine",
1379
+ prefixes: ["Workflow"],
1380
+ description: "Sagas, workflows, and long-running processes.",
1381
+ order: 5
1382
+ },
1383
+ {
1384
+ name: "BackgroundJobsScheduling",
1385
+ prefixes: ["Job"],
1386
+ description: "Background jobs, scheduled work, and async processors.",
1387
+ order: 6
1388
+ },
1389
+ {
1390
+ name: "PresentationAdapters",
1391
+ prefixes: ["Presentation", "Adapter.Presentation", "Adapter.Api"],
1392
+ description: "API, UI, controller, and presentation adapters.",
1393
+ order: 7
1394
+ },
1395
+ {
1396
+ name: "ReportingReadModels",
1397
+ prefixes: ["Reporting"],
1398
+ description: "Read models, projections, and reporting surfaces.",
1399
+ order: 8
1400
+ },
1401
+ {
1402
+ name: "ExtensibilityMetadata",
1403
+ prefixes: ["Metadata"],
1404
+ description: "Metadata, extensions, and schema contracts.",
1405
+ order: 9
1406
+ },
1407
+ {
1408
+ name: "SecurityAuditObservability",
1409
+ prefixes: ["Security", "Audit", "Observability"],
1410
+ description: "Security, audit, and observability concerns.",
1411
+ order: 10
1412
+ },
1413
+ {
1414
+ name: "Kernel",
1415
+ prefixes: ["Kernel"],
1416
+ description: "Ark-owned governance and kernel signals.",
1417
+ order: 11
2773
1418
  }
2774
- clear(name) {
2775
- if (name) {
2776
- this.states.delete(name);
1419
+ ];
1420
+ var elevenLayerProfile = createArchitectureProfile({
1421
+ name: "Ark 11-layer Hexagonal Event-Driven Profile",
1422
+ layers: elevenLayerProfileLayers,
1423
+ rules: DEFAULT_ARK_CONFIG_RULES.map((rule) => ({ ...rule }))
1424
+ });
1425
+ var defaultElevenLayerDirectories = {
1426
+ DomainModel: ["domain"],
1427
+ ApplicationOrchestration: ["application", "app"],
1428
+ PersistenceAdapters: [
1429
+ "adapters/persistence",
1430
+ "adapters/repository",
1431
+ "repositories",
1432
+ "infra/persistence"
1433
+ ],
1434
+ IntegrationAdapters: ["adapters/integration", "adapters/external", "integrations"],
1435
+ WorkflowSagaEngine: ["workflows", "sagas"],
1436
+ BackgroundJobsScheduling: ["jobs", "schedules"],
1437
+ PresentationAdapters: ["presentation", "adapters/presentation", "adapters/api"],
1438
+ ReportingReadModels: ["reporting", "read-models", "projections"],
1439
+ ExtensibilityMetadata: ["metadata", "extensions"],
1440
+ SecurityAuditObservability: ["security", "audit", "observability"],
1441
+ Kernel: ["kernel"]
1442
+ };
1443
+ function createElevenLayerArkConfig(options = {}) {
1444
+ const rootDir = options.rootDir ?? "src";
1445
+ const optional = options.optionalLayers ?? true;
1446
+ const prefix = rootDir === "." ? "" : `${rootDir}/`;
1447
+ return withArkConfigMetadata({
1448
+ include: options.include ?? [rootDir],
1449
+ layers: elevenLayerProfile.layers.map((layer) => ({
1450
+ name: layer.name,
1451
+ patterns: (defaultElevenLayerDirectories[layer.name] ?? [layer.name]).map(
1452
+ (directory) => `${prefix}${directory}/**`
1453
+ ),
1454
+ intentPrefixes: layer.prefixes,
1455
+ optional
1456
+ })),
1457
+ rules: [...elevenLayerProfile.rules]
1458
+ });
1459
+ }
1460
+
1461
+ // src/domain/analysis.ts
1462
+ var ANALYSIS_IR_SCHEMA_VERSION = "1.0";
1463
+ function deterministicHash(value) {
1464
+ let hash = 2166136261;
1465
+ for (let index = 0; index < value.length; index += 1) {
1466
+ hash ^= value.charCodeAt(index);
1467
+ hash = Math.imul(hash, 16777619);
1468
+ }
1469
+ return `fnv1a-${(hash >>> 0).toString(16).padStart(8, "0")}`;
1470
+ }
1471
+ function stableSerialize(value) {
1472
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
1473
+ if (Array.isArray(value)) return `[${value.map(stableSerialize).join(",")}]`;
1474
+ const object = value;
1475
+ return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${stableSerialize(object[key])}`).join(",")}}`;
1476
+ }
1477
+
1478
+ // src/kernel/analysis.ts
1479
+ function loadContract(input, source) {
1480
+ const loaded = typeof input === "string" ? parseArkConfigJson(input, source) : loadArkConfigContract(input, source);
1481
+ return { ...loaded, policyHash: deterministicHash(stableSerialize(loaded.config)) };
1482
+ }
1483
+ function normalizePath(value) {
1484
+ return value.replace(/\\/g, "/").replace(/^\.\//, "");
1485
+ }
1486
+ function isIdentifierCharacter(value) {
1487
+ return value !== void 0 && /[A-Za-z0-9_$]/.test(value);
1488
+ }
1489
+ function skipWhitespace(source, index) {
1490
+ while (index < source.length && /\s/.test(source[index])) index += 1;
1491
+ return index;
1492
+ }
1493
+ function readString(source, index) {
1494
+ const quote = source[index];
1495
+ if (quote !== "'" && quote !== '"') return void 0;
1496
+ const start = index;
1497
+ let value = "";
1498
+ for (index += 1; index < source.length; index += 1) {
1499
+ const current = source[index];
1500
+ if (current === quote) {
1501
+ return { value, offset: start, excerpt: source.slice(start, index + 1) };
1502
+ }
1503
+ if (current === "\\" && index + 1 < source.length) {
1504
+ value += source[index + 1];
1505
+ index += 1;
2777
1506
  } else {
2778
- this.states.clear();
1507
+ value += current;
2779
1508
  }
2780
1509
  }
2781
- };
2782
- function initialState(definition) {
2783
- return typeof definition.initialState === "function" ? definition.initialState() : definition.initialState;
2784
- }
2785
- var ProjectionRegistryImpl = class {
2786
- definitions = /* @__PURE__ */ new Map();
2787
- checkpoints = /* @__PURE__ */ new Map();
2788
- store;
2789
- auditTrail;
2790
- constructor(options = {}) {
2791
- this.store = options.store ?? new InMemoryReadModelStore();
2792
- this.auditTrail = options.auditTrail;
2793
- }
2794
- register(definition) {
2795
- if (this.definitions.has(definition.name)) {
2796
- throw new Error(`Projection "${definition.name}" is already registered.`);
1510
+ return void 0;
1511
+ }
1512
+ function isWordAt(source, word, index) {
1513
+ return source.startsWith(word, index) && !isIdentifierCharacter(source[index - 1]) && !isIdentifierCharacter(source[index + word.length]);
1514
+ }
1515
+ function specifierAfterImport(source, index) {
1516
+ index = skipWhitespace(source, index + "import".length);
1517
+ if (source[index] === "(") return readString(source, skipWhitespace(source, index + 1));
1518
+ return specifierInStaticStatement(source, index, true);
1519
+ }
1520
+ function specifierAfterExport(source, index) {
1521
+ return specifierInStaticStatement(source, index + "export".length, false);
1522
+ }
1523
+ function specifierInStaticStatement(source, index, allowDirectSpecifier) {
1524
+ for (; index < source.length; index += 1) {
1525
+ if (source[index] === ";") return void 0;
1526
+ if (isWordAt(source, "from", index)) {
1527
+ return readString(source, skipWhitespace(source, index + "from".length));
2797
1528
  }
2798
- this.definitions.set(definition.name, definition);
2799
- this.checkpoints.set(definition.name, {
2800
- projection: definition.name,
2801
- appliedCount: 0
2802
- });
2803
- }
2804
- list() {
2805
- return Array.from(this.definitions.values());
2806
- }
2807
- async apply(event) {
2808
- const applied = [];
2809
- for (const definition of this.definitions.values()) {
2810
- if (!definition.sourceIntents.includes(event.intent)) continue;
2811
- const current = await this.store.load(definition.name) ?? initialState(definition);
2812
- const next = await definition.project(event, current);
2813
- await this.store.save(definition.name, next);
2814
- const previous = this.checkpoints.get(definition.name);
2815
- this.checkpoints.set(definition.name, {
2816
- projection: definition.name,
2817
- appliedCount: (previous?.appliedCount ?? 0) + 1,
2818
- lastIntent: event.intent,
2819
- lastCorrelationId: event.metadata.correlationId,
2820
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2821
- });
2822
- await this.auditTrail?.record({
2823
- type: "projection.applied",
2824
- source: "Kernel.ProjectionRegistry",
2825
- intent: event.intent,
2826
- correlationId: event.metadata.correlationId,
2827
- causationId: event.metadata.causationId,
2828
- subject: definition.name,
2829
- details: { projection: definition.name }
2830
- });
2831
- applied.push(definition.name);
1529
+ if (allowDirectSpecifier && (source[index] === "'" || source[index] === '"')) {
1530
+ return readString(source, index);
1531
+ }
1532
+ if (index > 0 && (isWordAt(source, "import", index) || isWordAt(source, "export", index))) {
1533
+ return void 0;
2832
1534
  }
2833
- return applied;
2834
- }
2835
- async getState(name) {
2836
- return this.store.load(name);
2837
- }
2838
- getCheckpoint(name) {
2839
- return this.checkpoints.get(name);
2840
- }
2841
- getCheckpoints() {
2842
- return Array.from(this.checkpoints.values());
2843
1535
  }
2844
- async clear() {
2845
- await this.store.clear();
2846
- for (const definition of this.definitions.values()) {
2847
- this.checkpoints.set(definition.name, {
2848
- projection: definition.name,
2849
- appliedCount: 0
2850
- });
1536
+ return void 0;
1537
+ }
1538
+ function moduleSpecifiers(source) {
1539
+ const result = [];
1540
+ for (let index = 0; index < source.length; index += 1) {
1541
+ const current = source[index];
1542
+ if (current === "/" && source[index + 1] === "/") {
1543
+ index = source.indexOf("\n", index + 2);
1544
+ if (index < 0) break;
1545
+ continue;
1546
+ }
1547
+ if (current === "/" && source[index + 1] === "*") {
1548
+ const end = source.indexOf("*/", index + 2);
1549
+ if (end < 0) break;
1550
+ index = end + 1;
1551
+ continue;
2851
1552
  }
1553
+ if (current === "'" || current === '"' || current === "`") {
1554
+ const string = readString(source, index);
1555
+ if (string) index = string.offset + string.excerpt.length - 1;
1556
+ continue;
1557
+ }
1558
+ const specifier = isWordAt(source, "import", index) ? specifierAfterImport(source, index) : isWordAt(source, "export", index) ? specifierAfterExport(source, index) : void 0;
1559
+ if (specifier) result.push(specifier);
2852
1560
  }
2853
- };
2854
- function createProjectionRegistry(options) {
2855
- return new ProjectionRegistryImpl(options);
1561
+ return result;
2856
1562
  }
2857
-
2858
- // src/kernel/manifest/constants.ts
2859
- var MANIFEST_SCHEMA_VERSION = "1.0";
2860
-
2861
- // src/kernel/manifest/createArkManifest.ts
2862
- function policyId(name) {
2863
- return name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
1563
+ function importEdges(file, files) {
1564
+ const edges = [];
1565
+ for (const moduleSpecifier of moduleSpecifiers(file.content)) {
1566
+ const specifier = moduleSpecifier.value;
1567
+ if (!specifier.startsWith(".")) continue;
1568
+ const line = file.content.slice(0, moduleSpecifier.offset).split("\n").length;
1569
+ const evidence = {
1570
+ kind: "import",
1571
+ file: file.path,
1572
+ line,
1573
+ excerpt: moduleSpecifier.excerpt
1574
+ };
1575
+ const target = resolveSpecifier(file.path, specifier, files);
1576
+ edges.push({
1577
+ from: file.path,
1578
+ specifier,
1579
+ to: target?.path ?? null,
1580
+ resolution: target ? "resolved" : "unresolved",
1581
+ fromLayer: file.layer,
1582
+ toLayer: target?.layer ?? null,
1583
+ evidence
1584
+ });
1585
+ }
1586
+ return edges;
2864
1587
  }
2865
- var ArkManifestImpl = class {
2866
- constructor(data) {
2867
- this.data = data;
1588
+ function resolveSpecifier(from, specifier, files) {
1589
+ const segments = from.split("/");
1590
+ segments.pop();
1591
+ for (const segment of specifier.split("/")) {
1592
+ if (segment === "." || segment === "") continue;
1593
+ if (segment === "..") segments.pop();
1594
+ else segments.push(segment);
2868
1595
  }
2869
- data;
2870
- toJSON() {
2871
- return { ...this.data };
1596
+ const base = segments.join("/");
1597
+ for (const candidate of [base, `${base}.ts`, `${base}.tsx`, `${base}.mts`, `${base}.cts`, `${base}/index.ts`, `${base}/index.tsx`]) {
1598
+ const found = files.get(candidate);
1599
+ if (found) return found;
2872
1600
  }
2873
- };
2874
- function createArkManifest(options = {}) {
2875
- const registry = options.registry;
2876
- const policyEngine = options.policyEngine;
2877
- const metadata = options.metadata;
2878
- const graph = options.graph;
2879
- const profile = options.profile;
2880
- const projections = options.projections;
2881
- const eventContracts = options.eventContracts;
2882
- const observability = options.observability;
2883
- const intents = registry ? registry.list().map((creator) => ({
2884
- name: creator.name,
2885
- dependencies: registry.getDependencies(creator.name),
2886
- productions: registry.getProductions(creator.name)
2887
- })) : [];
2888
- const relationships = registry ? registry.getAllRelationships() : [];
2889
- const policies = policyEngine ? policyEngine.getPolicies().map((p) => ({
2890
- id: policyId(p.name),
2891
- name: p.name,
2892
- severity: p.severity,
2893
- tags: p.tags ? [...p.tags] : void 0,
2894
- owner: p.owner,
2895
- version: p.version,
2896
- rationale: p.rationale,
2897
- enforcementMode: p.enforcementMode,
2898
- deprecated: p.deprecated,
2899
- replacedBy: p.replacedBy,
2900
- description: p.tags?.includes("layer") ? "Enforces clean-architecture layer dependency rules on declared relationships." : void 0
2901
- })) : [];
2902
- const entities = metadata ? metadata.toJSON() : [];
2903
- const graphData = graph ? graph.toJSON() : { nodes: [], edges: [] };
2904
- const entityIntents = entities.filter((e) => (e.emits?.length ?? 0) > 0 || (e.consumes?.length ?? 0) > 0).map((e) => ({
2905
- entity: e.name,
2906
- emits: e.emits,
2907
- consumes: e.consumes
2908
- }));
2909
- const projectionData = projections ? projections.list().map((projection) => ({
2910
- name: projection.name,
2911
- sourceIntents: projection.sourceIntents,
2912
- checkpoint: projections.getCheckpoint(projection.name)
2913
- })) : [];
2914
- const data = {
2915
- schemaVersion: MANIFEST_SCHEMA_VERSION,
2916
- version,
2917
- exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
2918
- intents,
2919
- relationships,
2920
- policies,
2921
- entities,
2922
- graph: graphData,
2923
- architecture: profile ? {
2924
- profile: profile.name,
2925
- layers: profile.layers,
2926
- rules: profile.rules
2927
- } : void 0,
2928
- projections: projectionData,
2929
- eventContracts: eventContracts?.list() ?? [],
2930
- observability: observability?.report(),
2931
- links: { entityIntents }
1601
+ return void 0;
1602
+ }
1603
+ function violationsFor(edges, config) {
1604
+ const violations = [];
1605
+ for (const edge of edges) {
1606
+ if (!edge.to || !edge.fromLayer || !edge.toLayer) continue;
1607
+ const rule = findDeniedEdgeRule(config.rules, edge.fromLayer, edge.toLayer, {
1608
+ fromPath: edge.from,
1609
+ toPath: edge.to,
1610
+ layers: config.layers
1611
+ });
1612
+ if (!rule) continue;
1613
+ violations.push({
1614
+ ruleId: `layer-dependency:${rule.from}->${rule.to}`,
1615
+ message: rule.message ?? `${rule.from} must not depend on ${rule.to}.`,
1616
+ edge,
1617
+ evidence: edge.evidence
1618
+ });
1619
+ }
1620
+ return violations;
1621
+ }
1622
+ function analyzeProject(input) {
1623
+ const files = input.files.map((inputFile) => {
1624
+ const path = normalizePath(inputFile.path);
1625
+ return {
1626
+ path,
1627
+ content: inputFile.content,
1628
+ contentHash: deterministicHash(inputFile.content),
1629
+ layer: layerForRelativePath(path, input.contract.config.layers) ?? null
1630
+ };
1631
+ }).sort((left, right) => left.path.localeCompare(right.path));
1632
+ const fileByPath = new Map(files.map((file) => [file.path, file]));
1633
+ const edges = files.flatMap((file) => importEdges(file, fileByPath));
1634
+ const capabilityUses = [];
1635
+ const violations = violationsFor(edges, input.contract.config);
1636
+ return {
1637
+ ir: {
1638
+ schemaVersion: ANALYSIS_IR_SCHEMA_VERSION,
1639
+ policyHash: input.contract.policyHash,
1640
+ compilerOptionsHash: deterministicHash(stableSerialize(input.compilerOptions ?? {})),
1641
+ files,
1642
+ layers: input.contract.config.layers.map((layer) => layer.name),
1643
+ edges,
1644
+ capabilityUses,
1645
+ violations
1646
+ }
2932
1647
  };
2933
- return new ArkManifestImpl(data);
2934
1648
  }
2935
-
2936
- // src/kernel/workflow/Saga.ts
2937
- var workflowSequence = 0;
2938
- function createWorkflowId(prefix) {
2939
- workflowSequence += 1;
2940
- return `${prefix}-${Date.now()}-${workflowSequence}`;
2941
- }
2942
- function errorMessage(error) {
2943
- return error instanceof Error ? error.message : String(error);
2944
- }
2945
- function sleep(ms) {
2946
- return new Promise((resolve) => {
2947
- setTimeout(resolve, ms);
1649
+ function analyzeChange(input) {
1650
+ const files = new Map(input.files.map((file) => [normalizePath(file.path), file]));
1651
+ for (const change of input.changes) {
1652
+ const path = normalizePath(change.path);
1653
+ if ("delete" in change && change.delete) files.delete(path);
1654
+ else if ("content" in change) files.set(path, { path, content: change.content });
1655
+ }
1656
+ return analyzeProject({
1657
+ contract: input.contract,
1658
+ files: [...files.values()],
1659
+ compilerOptions: input.compilerOptions
2948
1660
  });
2949
1661
  }
2950
- async function withTimeout(operation, timeoutMs, stepName) {
2951
- const controller = new AbortController();
2952
- if (timeoutMs === void 0) return operation(controller.signal);
2953
- let timeout;
2954
- const timeoutPromise = new Promise((_, reject) => {
2955
- timeout = setTimeout(() => {
2956
- const error = new Error(`Workflow step "${stepName}" timed out after ${timeoutMs}ms.`);
2957
- controller.abort(error);
2958
- reject(error);
2959
- }, timeoutMs);
2960
- });
2961
- try {
2962
- return await Promise.race([operation(controller.signal), timeoutPromise]);
2963
- } finally {
2964
- if (timeout) clearTimeout(timeout);
2965
- }
1662
+ function explainViolation(violation2) {
1663
+ const location = `${violation2.evidence.file}:${violation2.evidence.line}`;
1664
+ if (!violation2.edge) return `${violation2.ruleId} at ${location}: ${violation2.message}`;
1665
+ const target = violation2.edge.to ?? violation2.edge.specifier;
1666
+ return `${violation2.ruleId} at ${location}: ${violation2.edge.from} imports ${target}. ${violation2.message}`;
1667
+ }
1668
+ function detectArchitectureCycles(graph) {
1669
+ let index = 0;
1670
+ const indices = /* @__PURE__ */ new Map();
1671
+ const low = /* @__PURE__ */ new Map();
1672
+ const onStack = /* @__PURE__ */ new Set();
1673
+ const stack = [];
1674
+ const components = [];
1675
+ const connect = (file) => {
1676
+ indices.set(file, index);
1677
+ low.set(file, index);
1678
+ index += 1;
1679
+ stack.push(file);
1680
+ onStack.add(file);
1681
+ for (const target of [...graph.get(file) ?? []].sort()) {
1682
+ if (!graph.has(target)) continue;
1683
+ if (!indices.has(target)) {
1684
+ connect(target);
1685
+ low.set(file, Math.min(low.get(file) ?? 0, low.get(target) ?? 0));
1686
+ } else if (onStack.has(target)) {
1687
+ low.set(file, Math.min(low.get(file) ?? 0, indices.get(target) ?? 0));
1688
+ }
1689
+ }
1690
+ if (low.get(file) !== indices.get(file)) return;
1691
+ const component = [];
1692
+ let member;
1693
+ do {
1694
+ member = stack.pop();
1695
+ if (member === void 0) break;
1696
+ onStack.delete(member);
1697
+ component.push(member);
1698
+ } while (member !== file);
1699
+ if (component.length > 1) components.push(component.sort());
1700
+ };
1701
+ for (const file of [...graph.keys()].sort()) {
1702
+ if (!indices.has(file)) connect(file);
1703
+ }
1704
+ return components.sort((left, right) => left[0].localeCompare(right[0])).map((members) => ({
1705
+ ruleId: "CIRCULAR_DEPENDENCY",
1706
+ file: members[0],
1707
+ line: 1,
1708
+ target: members.join(" \u2192 "),
1709
+ message: `Circular dependency among ${members.length} files: ${members.join(" \u2192 ")} \u2192 ${members[0]}.`,
1710
+ cycleKind: "value"
1711
+ }));
2966
1712
  }
2967
- var InMemoryWorkflowStore = class {
2968
- snapshots = /* @__PURE__ */ new Map();
2969
- save(snapshot) {
2970
- this.snapshots.set(snapshot.id, { ...snapshot, context: { ...snapshot.context } });
2971
- }
2972
- get(id) {
2973
- const snapshot = this.snapshots.get(id);
2974
- return snapshot ? { ...snapshot, context: { ...snapshot.context } } : void 0;
2975
- }
2976
- list(workflowName) {
2977
- return Array.from(this.snapshots.values()).filter((snapshot) => !workflowName || snapshot.workflowName === workflowName).map((snapshot) => ({ ...snapshot, context: { ...snapshot.context } }));
1713
+ function evaluateArchitectureGraph(input) {
1714
+ const violations = input.contentViolations.map((violation2) => ({ ...violation2 }));
1715
+ const warnings = (input.warnings ?? []).map((warning) => ({ ...warning }));
1716
+ const graph = new Map(
1717
+ input.files.map((file) => [file, /* @__PURE__ */ new Set()])
1718
+ );
1719
+ for (const edge of input.edges) {
1720
+ if (edge.to && edge.to !== edge.from && !edge.typeOnly && graph.has(edge.from)) {
1721
+ graph.get(edge.from)?.add(edge.to);
1722
+ }
1723
+ if (!edge.to || !edge.toLayer) continue;
1724
+ const rule = findDeniedEdgeRule(input.rules, edge.fromLayer, edge.toLayer, {
1725
+ fromPath: edge.from,
1726
+ toPath: edge.to,
1727
+ layers: input.config.layers
1728
+ });
1729
+ if (!rule) continue;
1730
+ const peerIsolation = Boolean(rule.peerIsolation);
1731
+ violations.push({
1732
+ ruleId: "LAYER_IMPORT_VIOLATION",
1733
+ file: edge.from,
1734
+ line: edge.line,
1735
+ fromLayer: edge.fromLayer,
1736
+ toLayer: edge.toLayer,
1737
+ target: edge.to,
1738
+ ...edge.typeOnly ? { typeOnly: true } : {},
1739
+ ...edge.targetTypeOnlyExports ? { targetTypeOnlyExports: true } : {},
1740
+ ...edge.sourcePureTypeModule ? { sourcePureTypeModule: true } : {},
1741
+ ...edge.namedBindingsTypeOnly ? { namedBindingsTypeOnly: true } : {},
1742
+ ...!peerIsolation && edge.portProofEligible ? { portProofEligible: true } : {},
1743
+ ...edge.kind ? { edgeKind: edge.kind } : {},
1744
+ ...peerIsolation ? { peerIsolation: true } : {},
1745
+ message: rule.message ?? (peerIsolation ? `${edge.fromLayer} must not ${edge.kind} another slice of ${edge.toLayer} (${edge.from} \u2192 ${edge.to}). Extract shared code or use events/ports across slices.` : `${edge.fromLayer} must not ${edge.kind} ${edge.toLayer}.`)
1746
+ });
2978
1747
  }
2979
- clear() {
2980
- this.snapshots.clear();
1748
+ const cyclePolicy = String(input.config.cyclePolicy ?? "strict").toLowerCase();
1749
+ if (cyclePolicy !== "off") {
1750
+ const cycles = detectArchitectureCycles(graph);
1751
+ if (cyclePolicy === "soft" || cyclePolicy === "framework-soft") {
1752
+ warnings.push(
1753
+ ...cycles.map((cycle) => ({
1754
+ ...cycle,
1755
+ message: `${cycle.message} (soft cycle policy \u2014 advisory only; set cyclePolicy: "strict" to fail the check)`,
1756
+ failsStrict: false
1757
+ }))
1758
+ );
1759
+ } else {
1760
+ violations.push(...cycles);
1761
+ }
2981
1762
  }
2982
- };
2983
- var WorkflowEngineImpl = class {
2984
- constructor(bus, options = {}) {
2985
- this.bus = bus;
2986
- this.options = options;
2987
- this.store = options.store ?? new InMemoryWorkflowStore();
1763
+ return { violations, warnings, safety: input.safety };
1764
+ }
1765
+ function configWarning(ruleId, message, extra = {}) {
1766
+ return { ruleId, message, ...extra };
1767
+ }
1768
+ function collectAnalysisConfigWarnings(input) {
1769
+ const { config, rules, files, manifest } = input;
1770
+ const warnings = [];
1771
+ if (config.dynamicImportAllowlist !== void 0 && (!Array.isArray(config.dynamicImportAllowlist) || config.dynamicImportAllowlist.some((entry) => typeof entry !== "string"))) {
1772
+ warnings.push(
1773
+ configWarning(
1774
+ "CONFIG_INVALID_DYNAMIC_IMPORT_ALLOWLIST",
1775
+ "dynamicImportAllowlist must be an array of file globs."
1776
+ )
1777
+ );
2988
1778
  }
2989
- bus;
2990
- options;
2991
- definitions = /* @__PURE__ */ new Map();
2992
- store;
2993
- register(definition) {
2994
- if (this.definitions.has(definition.name)) {
2995
- throw new Error(`Workflow "${definition.name}" is already registered.`);
2996
- }
2997
- const names = /* @__PURE__ */ new Set();
2998
- for (const step of definition.steps) {
2999
- if (names.has(step.name)) {
3000
- throw new Error(
3001
- `Workflow "${definition.name}" has duplicate step name "${step.name}".`
1779
+ if (config.safety !== void 0 && (config.safety === null || typeof config.safety !== "object" || Array.isArray(config.safety))) {
1780
+ warnings.push(configWarning("CONFIG_INVALID_SAFETY", "safety must be an object."));
1781
+ } else if (config.safety) {
1782
+ for (const key of ["maxTsSuppressions", "maxAnyCasts"]) {
1783
+ const value = config.safety[key];
1784
+ if (value !== void 0 && (!Number.isInteger(value) || value < 0)) {
1785
+ warnings.push(
1786
+ configWarning(
1787
+ "CONFIG_INVALID_SAFETY_THRESHOLD",
1788
+ `safety.${key} must be a non-negative integer.`
1789
+ )
3002
1790
  );
3003
1791
  }
3004
- names.add(step.name);
3005
- }
3006
- this.definitions.set(definition.name, definition);
3007
- if (definition.startOn) {
3008
- const trigger = definition.startOn;
3009
- this.bus.subscribe(trigger.intent, async (event) => {
3010
- await this.start(definition.name, trigger.mapEventToPayload(event));
3011
- });
3012
1792
  }
3013
1793
  }
3014
- async start(workflowName, initialPayload, options = {}) {
3015
- const definition = this.definitions.get(workflowName);
3016
- if (!definition) {
3017
- throw new Error(`Workflow "${workflowName}" is not registered.`);
1794
+ const layers = Array.isArray(config.layers) ? config.layers : [];
1795
+ const manifestLayers = Array.isArray(manifest?.architecture?.layers) ? manifest.architecture.layers : [];
1796
+ const knownLayers = /* @__PURE__ */ new Set([
1797
+ ...layers.map((layer) => layer.name).filter(Boolean),
1798
+ ...manifestLayers.map((layer) => layer.name).filter((name) => Boolean(name))
1799
+ ]);
1800
+ if (layers.length === 0) {
1801
+ warnings.push(
1802
+ configWarning(
1803
+ "CONFIG_NO_LAYERS",
1804
+ "No file layers are configured; ark-check cannot classify files for import-boundary enforcement."
1805
+ )
1806
+ );
1807
+ }
1808
+ const seenLayers = /* @__PURE__ */ new Set();
1809
+ const duplicateLayers = /* @__PURE__ */ new Set();
1810
+ for (const layer of layers) {
1811
+ if (!layer.name) {
1812
+ warnings.push(configWarning("CONFIG_LAYER_WITHOUT_NAME", "A configured layer is missing a name."));
1813
+ continue;
3018
1814
  }
3019
- const now = (/* @__PURE__ */ new Date()).toISOString();
3020
- const snapshot = {
3021
- id: options.id ?? createWorkflowId(workflowName),
3022
- workflowName,
3023
- status: "running",
3024
- context: { ...initialPayload },
3025
- completedSteps: [],
3026
- attempts: {},
3027
- startedAt: now,
3028
- updatedAt: now
3029
- };
3030
- await this.store.save(snapshot);
3031
- await this.audit("workflow.started", snapshot, { workflowName });
3032
- try {
3033
- for (const step of definition.steps) {
3034
- await this.runStep(snapshot, step);
3035
- }
3036
- snapshot.status = "completed";
3037
- snapshot.currentStep = void 0;
3038
- snapshot.completedAt = (/* @__PURE__ */ new Date()).toISOString();
3039
- snapshot.updatedAt = snapshot.completedAt;
3040
- await this.store.save(snapshot);
3041
- await this.audit("workflow.completed", snapshot, { workflowName });
3042
- return { ...snapshot, context: { ...snapshot.context } };
3043
- } catch (err) {
3044
- await this.compensate(snapshot, definition.steps, err);
3045
- snapshot.status = "failed";
3046
- snapshot.currentStep = void 0;
3047
- snapshot.error = errorMessage(err);
3048
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3049
- await this.store.save(snapshot);
3050
- await this.audit("workflow.failed", snapshot, {
3051
- workflowName,
3052
- error: snapshot.error,
3053
- failedStep: snapshot.failedStep
3054
- });
3055
- throw err;
1815
+ if (seenLayers.has(layer.name)) duplicateLayers.add(layer.name);
1816
+ seenLayers.add(layer.name);
1817
+ if (layer.forbiddenGlobals !== void 0 && (!Array.isArray(layer.forbiddenGlobals) || layer.forbiddenGlobals.some((entry) => typeof entry !== "string"))) {
1818
+ warnings.push(
1819
+ configWarning(
1820
+ "CONFIG_INVALID_FORBIDDEN_GLOBALS",
1821
+ `Layer "${layer.name}" has an invalid forbiddenGlobals value; expected an array of strings (e.g. ["fetch", "Date.now"]). The entry is ignored.`,
1822
+ { layer: layer.name }
1823
+ )
1824
+ );
3056
1825
  }
3057
- }
3058
- async get(id) {
3059
- return this.store.get(id);
3060
- }
3061
- async list(workflowName) {
3062
- return this.store.list(workflowName);
3063
- }
3064
- async runStep(snapshot, step) {
3065
- const retry = step.retry ?? this.options.defaultRetry ?? { attempts: 1 };
3066
- const maxAttempts = Math.max(1, retry.attempts);
3067
- snapshot.currentStep = step.name;
3068
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3069
- await this.store.save(snapshot);
3070
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
3071
- snapshot.attempts[step.name] = attempt;
3072
- await this.store.save(snapshot);
1826
+ const patterns = Array.isArray(layer.patterns) ? layer.patterns : [];
1827
+ if (patterns.length === 0) {
1828
+ warnings.push(
1829
+ configWarning(
1830
+ "CONFIG_LAYER_WITHOUT_PATTERNS",
1831
+ `Layer "${layer.name}" has no file patterns and will never classify files.`,
1832
+ { layer: layer.name }
1833
+ )
1834
+ );
1835
+ continue;
1836
+ }
1837
+ for (const pattern of patterns) {
1838
+ let expression;
3073
1839
  try {
3074
- const result = await withTimeout(
3075
- (signal) => Promise.resolve(step.execute(snapshot.context, this.bus, signal)),
3076
- step.timeoutMs,
3077
- step.name
1840
+ expression = globToRegExp(pattern);
1841
+ } catch (error) {
1842
+ warnings.push(
1843
+ configWarning(
1844
+ "CONFIG_INVALID_LAYER_PATTERN",
1845
+ `Layer "${layer.name}" has an invalid pattern "${pattern}": ${error instanceof Error ? error.message : String(error)}`,
1846
+ { layer: layer.name, pattern }
1847
+ )
1848
+ );
1849
+ continue;
1850
+ }
1851
+ if (!files.some((file) => expression.test(file)) && !layer.optional) {
1852
+ warnings.push(
1853
+ configWarning(
1854
+ "CONFIG_LAYER_PATTERN_NO_MATCHES",
1855
+ `Layer "${layer.name}" pattern "${pattern}" matched no included files.`,
1856
+ { layer: layer.name, pattern, failsStrict: false }
1857
+ )
3078
1858
  );
3079
- if (result) Object.assign(snapshot.context, result);
3080
- snapshot.completedSteps.push(step.name);
3081
- snapshot.currentStep = void 0;
3082
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3083
- await this.store.save(snapshot);
3084
- await this.audit("workflow.step.completed", snapshot, {
3085
- step: step.name,
3086
- attempt
3087
- });
3088
- return;
3089
- } catch (err) {
3090
- if (attempt < maxAttempts) {
3091
- if (retry.delayMs) await sleep(retry.delayMs);
3092
- continue;
3093
- }
3094
- snapshot.failedStep = step.name;
3095
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3096
- await this.store.save(snapshot);
3097
- await this.audit("workflow.step.failed", snapshot, {
3098
- step: step.name,
3099
- attempt,
3100
- error: errorMessage(err)
3101
- });
3102
- throw err;
3103
1859
  }
3104
1860
  }
3105
- throw new Error(`Workflow step "${step.name}" did not complete.`);
3106
1861
  }
3107
- async compensate(snapshot, steps, error) {
3108
- snapshot.status = "compensating";
3109
- snapshot.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
3110
- await this.store.save(snapshot);
3111
- const completed = steps.filter(
3112
- (step) => snapshot.completedSteps.includes(step.name)
1862
+ for (const name of duplicateLayers) {
1863
+ warnings.push(
1864
+ configWarning("CONFIG_DUPLICATE_LAYER", `Layer "${name}" is configured more than once.`, {
1865
+ layer: name
1866
+ })
3113
1867
  );
3114
- for (let index = completed.length - 1; index >= 0; index -= 1) {
3115
- const step = completed[index];
3116
- if (!step.compensate) continue;
3117
- try {
3118
- await Promise.resolve(step.compensate(snapshot.context, this.bus, error));
3119
- await this.audit("workflow.compensation.completed", snapshot, {
3120
- step: step.name
3121
- });
3122
- } catch (compensationError) {
3123
- await this.audit("workflow.step.failed", snapshot, {
3124
- step: step.name,
3125
- compensation: true,
3126
- error: errorMessage(compensationError)
3127
- });
1868
+ }
1869
+ if (knownLayers.size > 0) {
1870
+ for (const rule of rules ?? []) {
1871
+ if (rule.from && !knownLayers.has(rule.from)) {
1872
+ warnings.push(
1873
+ configWarning(
1874
+ "CONFIG_RULE_UNKNOWN_FROM_LAYER",
1875
+ `Rule references unknown source layer "${rule.from}".`,
1876
+ { fromLayer: rule.from, toLayer: rule.to }
1877
+ )
1878
+ );
1879
+ }
1880
+ if (rule.to && !knownLayers.has(rule.to)) {
1881
+ warnings.push(
1882
+ configWarning(
1883
+ "CONFIG_RULE_UNKNOWN_TO_LAYER",
1884
+ `Rule references unknown target layer "${rule.to}".`,
1885
+ { fromLayer: rule.from, toLayer: rule.to }
1886
+ )
1887
+ );
3128
1888
  }
3129
1889
  }
3130
1890
  }
3131
- async audit(type, snapshot, details) {
3132
- await this.options.auditTrail?.record({
3133
- type,
3134
- source: "Kernel.WorkflowEngine",
3135
- subject: snapshot.id,
3136
- details
3137
- });
3138
- }
3139
- };
3140
- function createWorkflowEngine(bus, options) {
3141
- return new WorkflowEngineImpl(bus, options);
3142
- }
3143
- function createSaga(def, bus, options = {}) {
3144
- const engine = createWorkflowEngine(bus, options);
3145
- const definition = { name: def.name, steps: def.steps };
3146
- engine.register(definition);
3147
- const sagaId = options.id ?? createWorkflowId(def.name);
3148
- let status = "idle";
3149
- let completedStepNames = [];
3150
- return {
3151
- id: sagaId,
3152
- definition: def,
3153
- get status() {
3154
- return status;
3155
- },
3156
- get completedSteps() {
3157
- return [...completedStepNames];
3158
- },
3159
- async run(initialPayload) {
3160
- status = "running";
3161
- completedStepNames = [];
3162
- try {
3163
- const snapshot = await engine.start(def.name, initialPayload, { id: sagaId });
3164
- status = snapshot.status === "waiting" ? "idle" : snapshot.status;
3165
- completedStepNames = [...snapshot.completedSteps];
3166
- } catch (err) {
3167
- const snapshot = await engine.get(sagaId);
3168
- status = snapshot?.status === "waiting" ? "idle" : snapshot?.status ?? "failed";
3169
- completedStepNames = snapshot?.completedSteps ?? [];
3170
- throw err;
1891
+ const ambiguousPairs = /* @__PURE__ */ new Set();
1892
+ if (layers.length > 1) {
1893
+ for (const file of files) {
1894
+ let topScore = -1;
1895
+ let topLayers = [];
1896
+ for (const layer of layers) {
1897
+ for (const pattern of layer.patterns ?? []) {
1898
+ if (!globToRegExp(pattern).test(file)) continue;
1899
+ const score = patternSpecificity(pattern);
1900
+ if (score > topScore) {
1901
+ topScore = score;
1902
+ topLayers = [layer.name];
1903
+ } else if (score === topScore && !topLayers.includes(layer.name)) {
1904
+ topLayers.push(layer.name);
1905
+ }
1906
+ }
3171
1907
  }
1908
+ if (topLayers.length > 1) ambiguousPairs.add([...topLayers].sort().join(" + "));
3172
1909
  }
3173
- };
3174
- }
3175
-
3176
- // src/kernel/runtime/createArkKernel.ts
3177
- var DEFAULT_MAX_HISTORY_SIZE = 1e3;
3178
- var kernelSequence = 0;
3179
- function nextKernelInstanceId() {
3180
- kernelSequence += 1;
3181
- return `ark-kernel-${Date.now()}-${kernelSequence}`;
3182
- }
3183
- function createArkKernel(options = {}) {
3184
- const strict = options.strict ?? true;
3185
- const instanceId = options.instanceId ?? nextKernelInstanceId();
3186
- const profile = options.profile ?? elevenLayerProfile;
3187
- const maxHistorySize = options.maxHistorySize ?? DEFAULT_MAX_HISTORY_SIZE;
3188
- const registry = createIntentRegistry();
3189
- const graph = createDependencyGraph();
3190
- const metadata = options.metadata ?? createMetadataRegistry();
3191
- const auditTrail = options.auditTrail ?? createAuditTrail({ maxRecords: maxHistorySize });
3192
- const eventContracts = options.eventContracts ?? createEventContractRegistry();
3193
- const outbox = options.outbox ?? new InMemoryOutboxStore();
3194
- const projections = options.projections ?? createProjectionRegistry({ auditTrail });
3195
- const policyEngine = new PolicyEngine([
3196
- defineArchitectureProfilePolicy(profile),
3197
- ...options.policies ?? []
3198
- ]);
3199
- const syncGraph = () => {
3200
- syncRegistryToGraph(registry, graph, { requireRegisteredTargets: true });
3201
- };
3202
- const eventBus = createEventBus({
3203
- intentRegistry: registry,
3204
- dependencyGraph: graph,
3205
- policyEngine,
3206
- strictRegistry: true,
3207
- validateIntentNaming: true,
3208
- auditTrail,
3209
- eventContracts,
3210
- strictEventContracts: options.strictEventContracts ?? strict,
3211
- requireKnownSource: options.requireKnownSource ?? true,
3212
- architectureProfile: profile,
3213
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? (strict ? "hard" : "off"),
3214
- outbox,
3215
- instanceId,
3216
- maxHistorySize,
3217
- onPublish: options.autoApplyProjections === false ? void 0 : async (event) => {
3218
- await projections.apply(event);
3219
- }
3220
- });
3221
- const workflowEngine = createWorkflowEngine(eventBus, { auditTrail });
3222
- const observability = createObservabilityReporter({
3223
- registry,
3224
- eventBus,
3225
- graph
3226
- });
3227
- return {
3228
- instanceId,
3229
- profile,
3230
- registry,
3231
- graph,
3232
- metadata,
3233
- auditTrail,
3234
- eventContracts,
3235
- outbox,
3236
- projections,
3237
- policyEngine,
3238
- eventBus,
3239
- workflowEngine,
3240
- observability,
3241
- publisher(source) {
3242
- return eventBus.createPublisher(source);
3243
- },
3244
- syncGraph,
3245
- manifest() {
3246
- syncGraph();
3247
- return createArkManifest({
3248
- registry,
3249
- policyEngine,
3250
- metadata,
3251
- graph,
3252
- profile,
3253
- projections,
3254
- eventContracts,
3255
- observability
3256
- });
3257
- }
3258
- };
3259
- }
3260
- function createStrictArkKernel(options = {}) {
3261
- return createArkKernel({
3262
- ...options,
3263
- strict: true,
3264
- strictEventContracts: options.strictEventContracts ?? true,
3265
- requireKnownSource: options.requireKnownSource ?? true,
3266
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? "hard"
3267
- });
3268
- }
3269
- function createOptionsFromConfig(config, options = {}) {
3270
- const { profileName, ...kernelOptions } = options;
3271
- return {
3272
- ...kernelOptions,
3273
- profile: createArchitectureProfileFromArkConfig(config, { name: profileName })
3274
- };
3275
- }
3276
- function createArkKernelFromConfig(config, options = {}) {
3277
- return createArkKernel(createOptionsFromConfig(config, options));
3278
- }
3279
- function createStrictArkKernelFromConfig(config, options = {}) {
3280
- return createStrictArkKernel(createOptionsFromConfig(config, options));
3281
- }
3282
- function createLenientArkKernelFromConfig(config, options = {}) {
3283
- return createLenientArkKernel(createOptionsFromConfig(config, options));
3284
- }
3285
- function createLenientArkKernel(options = {}) {
3286
- return createArkKernel({
3287
- ...options,
3288
- strict: false,
3289
- strictEventContracts: options.strictEventContracts ?? false,
3290
- enforceObservedLayerFlow: options.enforceObservedLayerFlow ?? "off"
3291
- });
1910
+ }
1911
+ if (ambiguousPairs.size > 0) {
1912
+ warnings.push(
1913
+ configWarning(
1914
+ "CONFIG_AMBIGUOUS_LAYERS",
1915
+ `Some files match multiple layers at equal specificity; classification falls back to declaration order. Disambiguate the overlapping patterns: ${[...ambiguousPairs].join(", ")}.`,
1916
+ { pairs: [...ambiguousPairs] }
1917
+ )
1918
+ );
1919
+ }
1920
+ const unclassified = files.filter((file) => !layerForRelativePath(file, layers));
1921
+ if (unclassified.length > 0) {
1922
+ warnings.push(
1923
+ configWarning(
1924
+ "CONFIG_UNCLASSIFIED_FILES",
1925
+ `${unclassified.length} included source file(s) are not matched by any configured layer; ark-check will not enforce import rules for those source files.`,
1926
+ { count: unclassified.length, samples: unclassified.slice(0, 5) }
1927
+ )
1928
+ );
1929
+ }
1930
+ return warnings;
3292
1931
  }
3293
1932
  // Annotate the CommonJS export names for ESM import in node:
3294
1933
  0 && (module.exports = {
3295
- DEFAULT_MAX_HISTORY_SIZE,
3296
- EventContractRegistryImpl,
3297
- EventContractViolationError,
3298
- InMemoryAuditStore,
3299
- InMemoryOutboxStore,
3300
- InMemoryReadModelStore,
3301
- InMemoryWorkflowStore,
3302
- IntentRegistry,
3303
- InvalidIntentNameError,
3304
- LayerPolicyContextError,
3305
- MANIFEST_SCHEMA_VERSION,
3306
- ObservedLayerFlowViolationError,
3307
- PolicyEngine,
3308
- PolicyViolationError,
3309
- SourceMetadataOverrideError,
3310
- UnknownEventSourceError,
3311
- UnregisteredIntentError,
3312
- architecturalPolicies,
3313
- buildPublishPolicyContext,
3314
- checkAdapterGovernance,
3315
- checkContract,
1934
+ ANALYSIS_IR_SCHEMA_VERSION,
1935
+ ARK_ANALYSIS_RESULT_SCHEMA,
1936
+ ARK_ANALYSIS_RESULT_SCHEMA_VERSION,
1937
+ ARK_CONFIG_SCHEMA,
1938
+ ARK_CONFIG_SCHEMA_VERSION,
1939
+ analyzeChange,
1940
+ analyzeProject,
1941
+ collectAnalysisConfigWarnings,
1942
+ collectForbiddenCapabilityUses,
3316
1943
  createAICodeGate,
3317
- createAdapter,
1944
+ createAdapterResult,
3318
1945
  createArchitectureProfile,
3319
1946
  createArchitectureProfileFromArkConfig,
3320
- createArkKernel,
3321
- createArkKernelFromConfig,
3322
- createArkManifest,
3323
- createArkTestHarness,
3324
- createAuditTrail,
3325
- createDependencyGraph,
3326
1947
  createElevenLayerArkConfig,
3327
- createEventBus,
3328
- createEventContractRegistry,
3329
- createIntentRegistry,
3330
- createLenientArkKernel,
3331
- createLenientArkKernelFromConfig,
3332
- createMetadataRegistry,
3333
- createObservabilityReporter,
3334
- createProjectionRegistry,
3335
- createSaga,
3336
- createStrictArkKernel,
3337
- createStrictArkKernelFromConfig,
3338
- createWorkflowEngine,
3339
- defaultIntentRegistry,
3340
- defineArchitectureProfilePolicy,
3341
- defineIntent,
3342
- defineLayerPolicy,
3343
- definePolicy,
3344
- definePort,
3345
- definePublishPolicy,
1948
+ detectArchitectureCycles,
1949
+ deterministicHash,
3346
1950
  elevenLayerProfile,
3347
- isLayerPolicy,
3348
- syncRegistryToGraph,
3349
- validateIntentName,
1951
+ evaluateArchitectureGraph,
1952
+ explainViolation,
1953
+ extractSemanticDependencies,
1954
+ loadArkConfigContract,
1955
+ loadContract,
1956
+ parseArkConfigJson,
1957
+ stableSerialize,
1958
+ toAdapterDiagnostic,
3350
1959
  version
3351
1960
  });
3352
- //# sourceMappingURL=index.cjs.map