arkgate 4.8.24 → 4.8.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +85 -0
- package/README.md +2 -2
- package/bin/ark-check-runtime.mjs +17 -14
- package/bin/ark-layer-match.mjs +115 -13
- package/bin/ark-mcp-runtime.mjs +36 -31
- package/bin/ark-shared.mjs +4 -23
- package/bin/lib/adoption-stance.mjs +2 -2
- package/bin/lib/adr-path.mjs +3 -3
- package/bin/lib/agent-gates.mjs +0 -61
- package/bin/lib/agent-homes.mjs +12 -21
- package/bin/lib/agent-projection-command.mjs +4 -4
- package/bin/lib/ambient-state.mjs +9 -30
- package/bin/lib/analysis-engine.mjs +14 -14
- package/bin/lib/architecture-scan.mjs +11 -9
- package/bin/lib/ark-order-doctor.mjs +3 -28
- package/bin/lib/ark-order-facts.mjs +6 -99
- package/bin/lib/ark-order-types.mjs +1 -2
- package/bin/lib/ark-run-doctor.mjs +3 -28
- package/bin/lib/ark-run-facts.mjs +30 -40
- package/bin/lib/ark-run-sensors.mjs +1 -1
- package/bin/lib/arkrule-file-hints.mjs +2 -47
- package/bin/lib/arkrules-contract.mjs +124 -133
- package/bin/lib/arkrules-sensors.mjs +7 -5
- package/bin/lib/check-args.mjs +63 -1
- package/bin/lib/ci-and-commands.mjs +8 -72
- package/bin/lib/ci-merge-boundary.mjs +1 -1
- package/bin/lib/class-source-scan.mjs +5 -5
- package/bin/lib/clone-detection.mjs +474 -0
- package/bin/lib/codex-home.mjs +1 -1
- package/bin/lib/config-contract-slices.mjs +44 -6
- package/bin/lib/config-contract.mjs +40 -117
- package/bin/lib/config-extras.mjs +16 -22
- package/bin/lib/contract-smells.mjs +33 -15
- package/bin/lib/core-ratchet.mjs +0 -2
- package/bin/lib/dashboard-cli.mjs +2 -2
- package/bin/lib/deep-module-coach.mjs +2 -4
- package/bin/lib/deploy-path.mjs +13 -38
- package/bin/lib/design-smells.mjs +2 -2
- package/bin/lib/diagnostic-catalog.mjs +8 -1
- package/bin/lib/doctor-advisories.mjs +55 -9
- package/bin/lib/doctor-green-cite.mjs +1 -1
- package/bin/lib/doctor-human.mjs +1 -1
- package/bin/lib/doctor-next-actions.mjs +2 -2
- package/bin/lib/doctor-plan.mjs +4 -6
- package/bin/lib/duplication-io.mjs +572 -0
- package/bin/lib/effective-contract-load.mjs +181 -44
- package/bin/lib/entry-points-io.mjs +424 -0
- package/bin/lib/extra-merge-teeth.mjs +36 -0
- package/bin/lib/field-install.mjs +38 -14
- package/bin/lib/first-run-help.mjs +7 -3
- package/bin/lib/flat-parent-importers.mjs +5 -3
- package/bin/lib/gate-files.mjs +30 -89
- package/bin/lib/github-enforcement.mjs +165 -28
- package/bin/lib/golden-pattern.mjs +1 -1
- package/bin/lib/hook-templates.mjs +16 -16
- package/bin/lib/html-report-advisories.mjs +4 -0
- package/bin/lib/html-report-depth.mjs +2 -2
- package/bin/lib/html-report.mjs +2 -2
- package/bin/lib/import-graph-projection.mjs +112 -0
- package/bin/lib/improvement-compass-doctor.mjs +1 -24
- package/bin/lib/invariant-coverage-io.mjs +4 -3
- package/bin/lib/invariant-coverage.mjs +26 -0
- package/bin/lib/invariant-probe-cli.mjs +347 -0
- package/bin/lib/invariant-probe-io.mjs +165 -0
- package/bin/lib/invariant-probe-runner.mjs +268 -0
- package/bin/lib/invariant-probe-sites.mjs +174 -0
- package/bin/lib/invariant-probe-workspace.mjs +183 -0
- package/bin/lib/invariant-probe.mjs +461 -0
- package/bin/lib/invariant-tests-path.mjs +16 -22
- package/bin/lib/literal-path-drift.mjs +4 -2
- package/bin/lib/managed-upgrade.mjs +2 -8
- package/bin/lib/mcp-adoption.mjs +4 -5
- package/bin/lib/mcp-hook-payload.mjs +4 -4
- package/bin/lib/orphan-modules-io.mjs +458 -0
- package/bin/lib/orphan-modules.mjs +251 -0
- package/bin/lib/outside-importers.mjs +197 -0
- package/bin/lib/package-manager.mjs +3 -3
- package/bin/lib/parse-health.mjs +1 -1
- package/bin/lib/persistence-write-hint.mjs +33 -8
- package/bin/lib/pin-dependent-gates.mjs +2 -2
- package/bin/lib/policy-delta-io.mjs +55 -8
- package/bin/lib/post-green-path.mjs +1 -1
- package/bin/lib/prepare-change.mjs +3 -9
- package/bin/lib/prepare-write.mjs +1 -2
- package/bin/lib/presets.mjs +56 -68
- package/bin/lib/product-copy.mjs +1 -6
- package/bin/lib/project-root.mjs +31 -62
- package/bin/lib/resolved-candidate-facts.mjs +90 -62
- package/bin/lib/rules-under-contract.mjs +72 -8
- package/bin/lib/scan-files.mjs +4 -4
- package/bin/lib/schema-validation.mjs +130 -0
- package/bin/lib/sensor-promote-cli.mjs +2 -11
- package/bin/lib/sensor-promote-io.mjs +33 -22
- package/bin/lib/sensor-promotion.mjs +1 -1
- package/bin/lib/skill-catalog-apply.mjs +1 -1
- package/bin/lib/skill-install.mjs +42 -38
- package/bin/lib/snippet-analysis.mjs +1 -1
- package/bin/lib/start-install-recovery.mjs +1 -1
- package/bin/lib/start-preview.mjs +1 -1
- package/bin/lib/states-transitions-presence.mjs +3 -3
- package/bin/lib/status-command.mjs +2 -18
- package/bin/lib/status-manifest.mjs +18 -26
- package/bin/lib/status-transition-catalog.mjs +0 -6
- package/bin/lib/suggestions.mjs +3 -3
- package/bin/lib/team-parliament-io.mjs +3 -17
- package/bin/lib/team-parliament.mjs +15 -9
- package/bin/lib/upgrade-behavior-changes.mjs +2 -2
- package/bin/lib/upgrade-command.mjs +2 -24
- package/bin/lib/upgrade-outcome.mjs +1 -1
- package/bin/lib/upstream-report.mjs +21 -10
- package/bin/lib/violations.mjs +10 -9
- package/bin/lib/weakest-link.mjs +13 -0
- package/bin/lib/write-path-capabilities.mjs +2 -2
- package/dist/chunk-AHACEKSV.js +16 -0
- package/dist/chunk-UN5EH4QV.cjs +16 -0
- package/dist/{configTypes-BJbaeoj4.d.cts → configTypes-GPvvdleM.d.cts} +12 -1
- package/dist/{configTypes-BJbaeoj4.d.ts → configTypes-GPvvdleM.d.ts} +12 -1
- package/dist/eslint/index.cjs +11 -11
- package/dist/eslint/index.d.cts +10 -1
- package/dist/eslint/index.d.ts +10 -1
- package/dist/eslint/index.js +11 -11
- package/dist/index.cjs +34 -34
- package/dist/index.d.cts +587 -515
- package/dist/index.d.ts +587 -515
- package/dist/index.js +34 -34
- package/dist/nestjs/index.cjs +1 -1
- package/dist/nestjs/index.d.cts +1 -1
- package/dist/nestjs/index.d.ts +1 -1
- package/dist/nestjs/index.js +1 -1
- package/dist/order/index.cjs +1 -1
- package/dist/order/index.js +1 -1
- package/dist/runtime/index.cjs +12 -12
- package/dist/runtime/index.d.cts +174 -136
- package/dist/runtime/index.d.ts +174 -136
- package/dist/runtime/index.js +12 -12
- package/dist/{types-DRinG-vT.d.cts → types-CnauMQQL.d.cts} +33 -25
- package/dist/{types-DRinG-vT.d.ts → types-CnauMQQL.d.ts} +33 -25
- package/docs/README.md +2 -1
- package/docs/agent-guide.md +134 -2
- package/docs/ai-gates.md +15 -1
- package/docs/configuration.md +40 -11
- package/docs/diagnostics.md +118 -2
- package/docs/package-surface.md +4 -1
- package/docs/product-voice.md +7 -1
- package/package.json +11 -2
- package/schemas/ark.config.schema.json +31 -3
- package/schemas/ark.invariant-probe.schema.json +368 -0
- package/server.json +2 -2
- package/templates/agent-skills/README.md +1 -1
- package/templates/agent-skills/ark-adopt/SKILL.md +1 -0
- package/templates/agent-skills/ark-contract/SKILL.md +17 -0
- package/templates/agent-skills/ark-coverage/SKILL.md +2 -0
- package/templates/agent-skills/ark-explore/SKILL.md +7 -0
- package/templates/agent-skills/ark-fix/SKILL.md +20 -0
- package/templates/agent-skills/ark-place/SKILL.md +8 -0
- package/templates/skills/ark-adopt.md +1 -0
- package/templates/skills/ark-contract.md +17 -0
- package/templates/skills/ark-coverage.md +2 -0
- package/templates/skills/ark-explore.md +7 -0
- package/templates/skills/ark-fix.md +20 -0
- package/templates/skills/ark-place.md +8 -0
- package/bin/lib/ark-order-error.mjs +0 -18
- package/bin/lib/ark-order-invariants.mjs +0 -388
- package/bin/lib/stable-hash.mjs +0 -90
- package/dist/chunk-MBXCFLO4.js +0 -16
- package/dist/chunk-RNQHRDCQ.cjs +0 -16
package/bin/lib/violations.mjs
CHANGED
|
@@ -2,7 +2,8 @@ import fs from 'node:fs';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
|
|
4
4
|
const useColor = process.stderr.isTTY && !process.env.NO_COLOR;
|
|
5
|
-
|
|
5
|
+
/** ANSI styling for ark-check's stderr; plain text when stderr is not a TTY or NO_COLOR is set. */
|
|
6
|
+
export const color = {
|
|
6
7
|
red: (s) => (useColor ? `\x1b[31m${s}\x1b[0m` : s),
|
|
7
8
|
yellow: (s) => (useColor ? `\x1b[33m${s}\x1b[0m` : s),
|
|
8
9
|
green: (s) => (useColor ? `\x1b[32m${s}\x1b[0m` : s),
|
|
@@ -17,10 +18,10 @@ import { toAdapterDiagnostic } from './adapter-contract.mjs';
|
|
|
17
18
|
export { baselineKey, baselineOccurrenceKeys };
|
|
18
19
|
|
|
19
20
|
/** Real regenerate flags: freeze-refuse needs --force; law PR needs --contract-session; stewards[] needs --author. */
|
|
20
|
-
|
|
21
|
+
const REGENERATE_BASELINE_COMMAND =
|
|
21
22
|
'ark-check --update-baseline --force --contract-session --author <steward>';
|
|
22
23
|
|
|
23
|
-
|
|
24
|
+
const BASELINE_NOTE =
|
|
24
25
|
`Frozen ark-check violations (one record per edge). Only NEW keys vs the merge-base fail --against / --baseline. Regenerate with: ${REGENERATE_BASELINE_COMMAND} (--author when stewards[] is set)`;
|
|
25
26
|
|
|
26
27
|
export function readBaseline(root, baselinePath) {
|
|
@@ -98,7 +99,7 @@ export function printWarning(warning) {
|
|
|
98
99
|
}
|
|
99
100
|
|
|
100
101
|
/** Advisory the engine emits once per shared-root → slice edge. Humans see a group. */
|
|
101
|
-
|
|
102
|
+
const SHARED_IMPORTS_SLICE_RULE_ID = 'SHARED_IMPORTS_SLICE';
|
|
102
103
|
|
|
103
104
|
/**
|
|
104
105
|
* Where the full per-edge list lives. Human check output names this on every
|
|
@@ -118,7 +119,7 @@ function layerLabel(value) {
|
|
|
118
119
|
}
|
|
119
120
|
|
|
120
121
|
/** Group key: one fact per rule and layer edge. */
|
|
121
|
-
|
|
122
|
+
function sharedImportsSliceGroupKey(warning) {
|
|
122
123
|
return [
|
|
123
124
|
typeof warning?.ruleId === 'string' ? warning.ruleId : SHARED_IMPORTS_SLICE_RULE_ID,
|
|
124
125
|
layerLabel(warning?.fromLayer),
|
|
@@ -207,7 +208,7 @@ export function printSharedImportsSliceBridgeList(warnings) {
|
|
|
207
208
|
}
|
|
208
209
|
|
|
209
210
|
/** Non-blocking type-only placement debt: exit stays 0; do not paint ✖. */
|
|
210
|
-
|
|
211
|
+
function isNonBlockingPlacementDebt(violation) {
|
|
211
212
|
return violation?.failsStrict === false;
|
|
212
213
|
}
|
|
213
214
|
|
|
@@ -241,7 +242,7 @@ export const CONCENTRATION_MIN_VIOLATIONS = 10;
|
|
|
241
242
|
export const CONCENTRATION_SHARE = 0.9;
|
|
242
243
|
|
|
243
244
|
/** Sensor id for STRUCTURE findings. Orchestration-only is code debt, not a missing toLayer. */
|
|
244
|
-
|
|
245
|
+
function violationSensorId(violation) {
|
|
245
246
|
if (typeof violation?.sensor === 'string' && violation.sensor.trim()) return violation.sensor.trim();
|
|
246
247
|
if (typeof violation?.arkruleId === 'string' && violation.arkruleId.trim()) return violation.arkruleId.trim();
|
|
247
248
|
return undefined;
|
|
@@ -257,11 +258,11 @@ export function violationEdge(violation) {
|
|
|
257
258
|
}
|
|
258
259
|
|
|
259
260
|
/** Layer-import arrows can mean a contract bug. Structural-sensor blobs are code debt. */
|
|
260
|
-
|
|
261
|
+
function isContractConcentrationEdge(edge) {
|
|
261
262
|
return typeof edge === 'string' && edge.includes(' → ');
|
|
262
263
|
}
|
|
263
264
|
|
|
264
|
-
|
|
265
|
+
function isContractStyleViolation(violation) {
|
|
265
266
|
if (violationSensorId(violation)) return false;
|
|
266
267
|
if (violation.ruleId === 'CIRCULAR_DEPENDENCY') return true;
|
|
267
268
|
if (violation.ruleId === 'FORBIDDEN_GLOBAL') return true;
|
package/bin/lib/weakest-link.mjs
CHANGED
|
@@ -296,6 +296,19 @@ export function collectWeakestLinkGaps(root, opts = {}) {
|
|
|
296
296
|
fix: 'Add the architecture CI job name to required status checks',
|
|
297
297
|
});
|
|
298
298
|
}
|
|
299
|
+
const upstream = Array.isArray(github.arkCheckUpstreamNotRequired)
|
|
300
|
+
? github.arkCheckUpstreamNotRequired
|
|
301
|
+
: [];
|
|
302
|
+
if (github.available && upstream.length > 0) {
|
|
303
|
+
gaps.push({
|
|
304
|
+
id: 'enforcement-ark-check-upstream-not-required',
|
|
305
|
+
severity: 'warn',
|
|
306
|
+
message:
|
|
307
|
+
`The required architecture job has needs: that are not required (${upstream.join(', ')}); ` +
|
|
308
|
+
'if one fails, the architecture job is skipped and a skipped job satisfies branch protection',
|
|
309
|
+
fix: 'Require those jobs too, or give the architecture job `if: ${{ always() }}` and fail it when a needed job failed',
|
|
310
|
+
});
|
|
311
|
+
}
|
|
299
312
|
}
|
|
300
313
|
|
|
301
314
|
return {
|
|
@@ -22,7 +22,7 @@ import { detectCiEnforcement } from './weakest-link.mjs';
|
|
|
22
22
|
import { buildEnforcementState, packageInstallation } from './enforcement-state.mjs';
|
|
23
23
|
import { npxArkgatePrefixLength } from './package-manager.mjs';
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
const WRITE_CAPABILITY_NAMES = [
|
|
26
26
|
'hard-write',
|
|
27
27
|
'advisory-write',
|
|
28
28
|
'merge-gate',
|
|
@@ -451,7 +451,7 @@ function hostRecord(hard, advisory, repair, merge, extras = {}) {
|
|
|
451
451
|
};
|
|
452
452
|
}
|
|
453
453
|
|
|
454
|
-
|
|
454
|
+
function detectWritePathInventory(root) {
|
|
455
455
|
// Merge-gate evidence only when CI uses the fail-closed profile (not bare ark-check).
|
|
456
456
|
const ci = detectCiEnforcement(root);
|
|
457
457
|
const merge = ci.failClosed ? ci.arkWorkflowFiles : [];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import{I as Le,N as At,P as ce,Q as kt,R as Et,T as Rt,V as Pt,a,e as St,f as wt,r as It,t as vt,x as bt}from"./chunk-SVSQVGFJ.js";var Ct="4.8.25";var C={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},xt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},compositionRoots:{...C,default:[]},kernelRoots:{...C},managedLayers:{...C,default:[]},requireDeclarations:{type:"boolean",default:!0},ignoreDirectNewForErrors:{type:"boolean",default:!0}}},Lt={type:"object",additionalProperties:!1,properties:{mode:{type:"string",enum:["advisory","enforced"],default:"advisory"},planeRoots:{...C,default:[]},managedLayers:{...C,default:[]},maxXiKeys:{type:"integer",minimum:1,default:7},xiKeys:{...C,default:[]},appliesTo:{...C,default:[]}}};function z(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(z,"isObject");function er(t){let e=new Set;if(!Array.isArray(t.layers))return e;for(let n of t.layers)z(n)&&typeof n.name=="string"&&n.name.length>0&&e.add(n.name);return e}a(er,"declaredLayerNames");function Ot(t){if(!z(t))return t;let e={mode:t.mode===void 0?"advisory":t.mode,compositionRoots:t.compositionRoots===void 0?[]:t.compositionRoots,managedLayers:t.managedLayers===void 0?[]:t.managedLayers,requireDeclarations:t.requireDeclarations===void 0?!0:t.requireDeclarations};return t.kernelRoots!==void 0&&(e.kernelRoots=t.kernelRoots),t.ignoreDirectNewForErrors!==void 0&&(e.ignoreDirectNewForErrors=t.ignoreDirectNewForErrors),{...t,...e}}a(Ot,"defaultedArkRun");function $t(t){if(!z(t))return t;let e=typeof t.maxXiKeys=="number"&&t.maxXiKeys>0?t.maxXiKeys:7;return{...t,mode:t.mode===void 0?"advisory":t.mode,planeRoots:t.planeRoots===void 0?[]:t.planeRoots,managedLayers:t.managedLayers===void 0?[]:t.managedLayers,maxXiKeys:e,xiKeys:t.xiKeys===void 0?[]:t.xiKeys}}a($t,"defaultedArkOrder");function Dt(t,e,n,r){if(!Array.isArray(e))return;let o=er(t);e.forEach((i,s)=>{typeof i=="string"&&i.length>0&&!o.has(i)&&r.push({path:`$.${n}.managedLayers[${s}]`,message:`layer ${JSON.stringify(i)} is not declared in layers[]`})})}a(Dt,"validateManagedLayersDeclared");function Nt(t,e){let n=t.arkRun;if(n===void 0||!z(n))return;let r=n.managedLayers;if(Dt(t,r,"arkRun",e),n.mode==="enforced"){let o=n.kernelRoots??n.compositionRoots;(!Array.isArray(o)||o.length===0)&&e.push({path:n.kernelRoots!==void 0?"$.arkRun.kernelRoots":"$.arkRun.compositionRoots",message:"ARKRUN_MISSING_ROOT: enforced mode requires at least one kernel root"}),(!Array.isArray(r)||r.length===0)&&e.push({path:"$.arkRun.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Nt,"validateArkRunExtra");function Tt(t,e){let n=t.arkOrder;if(n===void 0||!z(n))return;let r=n.managedLayers;if(Dt(t,r,"arkOrder",e),n.mode==="enforced"){let o=n.planeRoots;(!Array.isArray(o)||o.length===0)&&e.push({path:"$.arkOrder.planeRoots",message:"ARKORDER_MISSING_PLANE: enforced mode requires at least one plane root"}),(!Array.isArray(r)||r.length===0)&&e.push({path:"$.arkOrder.managedLayers",message:"enforced mode requires at least one managed layer"})}}a(Tt,"validateArkOrderExtra");var ue={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Ht={description:'deny blocks every shared-root import of a slice. deny-cross-parent leaves that hop as a warning and, in ark-check and CI only, reports a slice that reaches another universe through a shared root. The write hook and ESLint see one edge and do not block it. The object form { mode: "deny-cross-parent", stopAt } names composition roots (bootstrap, DI registrations) the whole-graph walk never starts at or passes through; a stop file must still sit under sharedRoots, and stopAt does not silence the direct SHARED_IMPORTS_SLICE warning. arkgate 4.8.22 and older reject deny-cross-parent. arkgate 4.8.23 and older reject the object form (must be one of deny, deny-cross-parent).',oneOf:[{type:"string",enum:["deny","deny-cross-parent"]},{type:"object",additionalProperties:!1,required:["mode","stopAt"],properties:{mode:{type:"string",enum:["deny-cross-parent"]},stopAt:{...ue,minItems:1}}}]},Kt={type:"object",additionalProperties:!1,required:["sliceFolders"],description:`Optional inner wall under this rule. Runs only on a rule with peerIsolation: true and allowed: false; elsewhere it is inert and ark-check warns CONFIG_CHILD_SLICES_INERT (config load still accepts it, as 4.8.23 did). Absent keeps today's universe wall. sliceFolders names children. Flat files are universe common, and so is a commonFolders directory directly under the universe (a folder of that name inside a child belongs to that child). siblings is "deny" (default), "advisory", or { default, enforce, ratchet }. parentMayImportChild defaults to false. message is the text for inner-wall findings. allowedCrossSlice may use a whole-segment *. It clears only a sibling crossing. Cross-parent has no advisory knob. arkgate 4.8.22 and older reject this key. A build that still rejects unknown childSlices fields rejects allowedCrossSlice at config load. A build that still types siblings as a string enum rejects the object at config load.`,properties:{sliceFolders:{...ue,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"]},commonFolders:{...ue,minItems:1},siblings:{description:'"deny" or "advisory", or { default, enforce, ratchet } so listed subtrees are errors while the default stays advisory. ratchet absent: a new advisory crossing fails only when the baseline in use already records an advisory crossing of this rule. ratchet true: any unrecorded advisory crossing fails when a baseline is in use. ratchet false: measure only, never fails. A string-enum build rejects the object at config load (must be one of deny, advisory). arkgate 4.8.23 and older reject ratchet (unknown field).',oneOf:[{type:"string",enum:["deny","advisory"]},{type:"object",additionalProperties:!1,required:["default"],properties:{default:{type:"string",enum:["deny","advisory"]},enforce:{...ue},ratchet:{type:"boolean"}}}]},parentMayImportChild:{type:"boolean"},message:{type:"string",minLength:1,description:"Text for inner-wall findings (CROSS_SIBLING_SLICE and universe common importing a child). The rule message stays the universe-wall text (CROSS_PARENT_SLICE and fail-closed denies). Absent: ArkGate default text, never the rule message. arkgate 4.8.23 and older reject this field (unknown field)."},arkRulesFile:{type:"string",minLength:1,description:"Filename read at each child slice root this wall already resolved. The only token is <Layer>, replaced with a declared layer name (arkrules.<Layer>.json). No slash and no wildcard. A discovered file that omits appliesTo is scoped to that slice directory. Explicit appliesTo outside the slice fails config load (ARKRULE_SCOPE_ESCAPES_SLICE). The effective id is <childId>#<localId>. A build that rejects unknown childSlices fields fails at config load (unknown field)."},sliceAliases:{type:"array",minItems:1,description:"Maps a source path glob onto a child slice id (universe id plus one child segment) so files outside the slice trees take that universe and child for both walls. A path without a wildcard also covers everything under it, as sharedRoots does. A bare name, a universe id alone, a target outside every universe shape, and a wildcard in to are rejected. Under stars identity a target written against the 4.8.23 stars id (star bindings before the last literal dropped, e.g. api/v1/x for modules/*/api/*) still loads when it maps to one universe shape, and ark-check warns CONFIG_SLICE_LEGACY_STARS_ID with the new id; it is rejected only when it maps to more than one shape. Config load checks only the shape; doctor reports a target universe no file belongs to. The glob may not overlap a slice folder, and two aliases may not match the same file. Doctor lists each unpinned alias as an owed move. pinned true lists the alias separately and does not count it as debt. reason is a doctor label and does not pin by itself. A build that rejects unknown childSlices fields fails at config load (unknown field). arkgate 4.8.22 and older reject childSlices.",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},pinned:{type:"boolean",description:"True when a framework forces the path to stay. The alias is not an owed move and does not clear other honesty debt."},reason:{type:"string",minLength:1,description:"Doctor label, such as framework-route. A label alone does not pin."}}}},allowedCrossSlice:{type:"array",minItems:1,description:"Directed child-slice allowances. * matches one whole path segment (features/projects/*). ** and a partial segment are rejected. A bare name is rejected. This list clears only CROSS_SIBLING_SLICE. It cannot clear CROSS_PARENT_SLICE or CROSS_PARENT_VIA_SHARED. The universe allowedCrossSlice still treats * as a literal. A build that rejects unknown childSlices fields fails at config load (unknown field).",items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}}}};function I(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(I,"isObject");function fe(t,e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`}a(fe,"propertyPath");function P(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(P,"trimTrailingSlashes");function Vt(t,e){ir(t,e),ar(t,e),ur(t,e),Rr(t,e),Er(t,e)}a(Vt,"validateSliceContract");var Mt='must be "deny", "deny-cross-parent", or { "mode": "deny-cross-parent", "stopAt": ["<composition root path or glob>"] }',Ft="must not cover the whole tree. Name the composition root itself (bootstrap file, DI registrations folder).";function tr(t){return t==="*"||t==="**"}a(tr,"isWildcardSegment");function Wt(t){let e=t.toLowerCase().split("/").filter(o=>o.length>0&&o!==".");(e[0]==="src"||e[0]==="app")&&(e=e.slice(1));let n=e.length;for(;n>0&&tr(e[n-1]??"");)n-=1;let r=e.slice(0,n);return r.some(o=>o.includes("*"))?null:r}a(Wt,"coveredFolder");function nr(t,e){return t.length<=e.length&&t.every((n,r)=>e[r]===n)}a(nr,"isPrefixOf");function rr(t,e){let n=t.layers;if(!Array.isArray(n))return[];let r=new Set([e.from,e.to].filter(i=>typeof i=="string")),o=[];for(let i of n){if(!I(i)||typeof i.name!="string"||!r.has(i.name))continue;let s=Array.isArray(i.patterns)?i.patterns:[];for(let l of s){if(typeof l!="string")continue;let c=l.replace(/\\/g,"/").split("/"),d=c.findIndex(m=>m.includes("*")),f=d===-1?c:c.slice(0,d),p=Wt(f.join("/"));p&&o.push(p)}}return o}a(rr,"ruleLayerFolders");function or(t,e){let n=P(t.trim().replace(/\\/g,"/"));if(n.length===0)return"must be a non-empty path or glob";let r=n.replace(/^[./]+/,"");if(r===""||r==="*"||r==="**")return Ft;for(let i of n.split("/"))if(i.length===0||i==="."||i==="..")return"must be a path or glob without empty, . or .. segments";let o=Wt(n);return o===null?null:o.length===0?Ft:e.some(i=>nr(o,i))?"must not cover a whole layer root of this rule. Name the composition root itself (bootstrap file, DI registrations folder).":null}a(or,"stopAtEntryIssue");function ir(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r)||r.sharedImportsSlice===void 0)return;let i=r.sharedImportsSlice,s=`$.rules[${o}].sharedImportsSlice`;if(typeof i=="string"){i!=="deny"&&i!=="deny-cross-parent"&&e.push({path:s,message:Mt});return}if(!I(i)){e.push({path:s,message:Mt});return}for(let f of Object.keys(i))f!=="mode"&&f!=="stopAt"&&e.push({path:fe(s,f),message:"unknown field"});i.mode===void 0?e.push({path:`${s}.mode`,message:"is required"}):i.mode!=="deny-cross-parent"&&e.push({path:`${s}.mode`,message:'must be deny-cross-parent. stopAt has no meaning for deny; use the string "deny".'});let l=i.stopAt;if(l===void 0){e.push({path:`${s}.stopAt`,message:"is required"});return}if(!Array.isArray(l)||l.length===0){e.push({path:`${s}.stopAt`,message:"must be a non-empty array of paths or globs"});return}let c=new Set,d=rr(t,r);l.forEach((f,p)=>{let m=`${s}.stopAt[${p}]`;if(typeof f!="string"){e.push({path:m,message:"must be a non-empty path or glob"});return}let h=or(f,d);if(h){e.push({path:m,message:h});return}let S=P(f.trim().replace(/\\/g,"/")).toLowerCase();if(c.has(S)){e.push({path:m,message:"duplicate stopAt entry"});return}c.add(S)})})}a(ir,"validateSharedImportsSlice");var sr=["deny","advisory"],_t='must be "deny", "advisory", or { "default": "deny" | "advisory", "enforce": ["<child id or subtree path>"], "ratchet": true | false }';function ar(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.siblings===void 0)return;let s=i.siblings,l=`$.rules[${o}].childSlices.siblings`;if(typeof s=="string"){sr.includes(s)||e.push({path:l,message:_t});return}if(!I(s)){e.push({path:l,message:_t});return}for(let d of Object.keys(s))d!=="default"&&d!=="enforce"&&d!=="ratchet"&&e.push({path:fe(l,d),message:"unknown field"});if(s.ratchet!==void 0&&typeof s.ratchet!="boolean"&&e.push({path:`${l}.ratchet`,message:"must be a boolean"}),s.default===void 0?e.push({path:`${l}.default`,message:"is required"}):s.default!=="deny"&&s.default!=="advisory"&&e.push({path:`${l}.default`,message:"must be deny or advisory"}),s.enforce===void 0)return;if(!Array.isArray(s.enforce)){e.push({path:`${l}.enforce`,message:"must be an array of child slice ids or subtree paths"});return}let c=new Set;s.enforce.forEach((d,f)=>{let p=`${l}.enforce[${f}]`;if(typeof d!="string"||d.trim().length===0){e.push({path:p,message:"must be a non-empty child slice id or subtree path"});return}let m=P(d.trim().replace(/\\/g,"/"));if(m.split("/").some(h=>h.length===0||h==="."||h==="..")){e.push({path:p,message:"must be a child slice id or subtree path without . or .."});return}if(m.includes("*")){e.push({path:p,message:"must be a child slice id or subtree path. * is not a wildcard on siblings.enforce"});return}if(c.has(m)){e.push({path:p,message:"duplicate enforce entry"});return}c.add(m)})})}a(ar,"validateChildSliceSiblings");var lr="must be a slice id with a slash. A bare name is ambiguous across universes.",cr="* matches one whole path segment. ** and a partial segment are not wildcards.";function dr(t){let e=P(t.trim().replace(/\\/g,"/"));if(e.length===0)return"must be a non-empty slice id";if(!e.includes("/"))return lr;let n=e.split("/");for(let r of n){if(r.length===0||r==="."||r==="..")return"must be a slice id without empty, . or .. segments";if(r.includes("*")&&r!=="*")return cr}return null}a(dr,"childCrossSlicePatternIssue");function Bt(t){return P(t.trim().replace(/\\/g,"/")).toLowerCase()}a(Bt,"childCrossSlicePatternKey");function ur(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.allowedCrossSlice===void 0)return;let s=i.allowedCrossSlice,l=`$.rules[${o}].childSlices.allowedCrossSlice`;if(!Array.isArray(s)){e.push({path:l,message:"must be an array of { from, to } child slice ids"});return}let c=new Set;s.forEach((d,f)=>{let p=`${l}[${f}]`;if(!I(d)){e.push({path:p,message:"must be an object with from and to"});return}for(let h of Object.keys(d))h!=="from"&&h!=="to"&&e.push({path:fe(p,h),message:"unknown field"});for(let h of["from","to"]){let S=d[h],u=`${p}.${h}`;if(typeof S!="string"||S.trim().length===0){e.push({path:u,message:"must be a non-empty slice id"});continue}let y=dr(S);y&&e.push({path:u,message:y})}if(typeof d.from!="string"||typeof d.to!="string")return;let m=`${Bt(d.from)}\0${Bt(d.to)}`;if(!m.startsWith("\0")&&!m.endsWith("\0")){if(c.has(m)){e.push({path:p,message:"duplicate child slice allowance"});return}c.add(m)}})})}a(ur,"validateChildSliceAllowedCrossSlice");var M="must be a child of a universe shape this rule names (its universe sliceFolders shape plus one child segment). A bare name, a universe id alone, a target outside every universe shape, and a wildcard are rejected. Config load checks the shape only; doctor reports a target universe no file belongs to.",fr="is a 4.8.23 stars id (star bindings before the last literal dropped) that maps to more than one universe shape of this rule. Write the new stars id, which keeps every star binding (e.g. orders/api/v1/x for modules/*/api/*).",pr="overlaps a slice folder. An alias covers only files outside the slice trees.",gr="two slice aliases match the same file";function mr(t){return P(t.trim().replace(/\\/g,"/")).toLowerCase().split("/").filter(e=>e.length>0)}a(mr,"aliasPathSegments");function hr(t){let e=t[t.length-1];return e===void 0||e.includes("*")?[...t]:[...t,"**"]}a(hr,"aliasSegmentsWithSubtree");function Ut(t){let e=[];for(let n of t){if(n.includes("*"))break;e.push(n)}return e}a(Ut,"concreteGlobPrefix");function J(t,e){if(t.length>e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}a(J,"segmentsArePrefix");function yr(t){let e=t.split(/[/\\]/).filter(Boolean).map(r=>r.toLowerCase());if(e.length<2||e[0]==="*"||e[0]==="**"||!e.some(r=>r==="*"))return null;let n=[];for(let r of e){if(r==="*"||r==="**")break;if(r.includes("*"))return null;n.push(r)}return n.length>0?n:null}a(yr,"anchoredSlicePrefix");function Sr(t,e){let n=Ut(t),r=n.length<t.length,o=n[0]==="src"||n[0]==="app"?n.slice(1):n;return J(e,n)||J(e,o)?!0:r?J(n,e)&&n.length<e.length||J(n,["src",...e])&&n.length<e.length+1||J(n,["app",...e])&&n.length<e.length+1:!1}a(Sr,"globOverlapsAnchored");function wr(t,e){for(let r=0;r<t.length;r+=1){if(t[r]!==e&&t[r]!=="*")continue;let o=t.slice(r+1);if(o.length>=2||o.some(i=>i==="*"||i==="**"))return!0}let n=Ut(t);return n.length<t.length&&(n.length===0||n.length===1&&(n[0]==="src"||n[0]==="app"))}a(wr,"globOverlapsBare");function Ir(t,e){let n=e.split(/[/\\]/).filter(Boolean).map(o=>o.toLowerCase());if(n.length===1&&n[0]&&!n[0].includes("*"))return wr(t,n[0]);let r=yr(e);return r?Sr(t,r):!1}a(Ir,"globOverlapsSliceEntry");function vr(t){let e=P(t.trim().replace(/\\/g,"/"));if(e.length===0)return"must be a non-empty path glob";if(e==="*"||e==="**")return"must not cover the whole tree";for(let n of e.split("/")){if(n.length===0||n==="."||n==="..")return"must be a path glob without empty, . or .. segments";if(!(n==="*"||n==="**")&&(n.includes("*")||n.includes("?")||n.includes("{")||n.includes("[")))return"* matches one whole path segment. ** is a whole segment. A partial segment is not a wildcard."}return null}a(vr,"aliasGlobIssue");function br(t,e){let n=[];if(!Array.isArray(t))return n;let r=e==="stars";for(let o of t){if(typeof o!="string"||o.length===0)continue;let i=o.split(/[/\\]/).filter(Boolean).map(s=>s.toLowerCase());if(i.length===1&&i[0]&&!i[0].includes("*")){n.push({literals:[i[0],null]});continue}if(!i.some(s=>s==="**"||s.includes("*")&&s!=="*")&&i.includes("*")){if(r){let s=-1;for(let d=0;d<i.length;d+=1)i[d]!=="*"&&(s=d);if(s<0)continue;let l=i.filter((d,f)=>f>=s||d==="*").map(d=>d==="*"?null:d),c=i.slice(s).map(d=>d==="*"?null:d);n.push(c.length===l.length?{literals:l}:{literals:l,legacy:c});continue}n.push({literals:i.map(s=>s==="*"?null:s)})}}return n}a(br,"universeShapes");function de(t,e){return t.literals.length!==e.length?!1:t.literals.every((n,r)=>n===null||n===e[r])}a(de,"shapeMatches");function Ar(t,e){let n=P(t.trim().replace(/\\/g,"/"));if(n.length===0||n.split("/").some(i=>i.length===0||i==="."||i==="..")||n.includes("*")||!n.includes("/"))return M;let r=n.split("/").map(i=>i.toLowerCase());if(e.length===0||e.some(i=>de(i,r)))return M;if(e.some(i=>de(i,r.slice(0,-1))))return null;let o=new Set(e.filter(i=>i.legacy!==void 0&&!de({literals:i.legacy},r)&&de({literals:i.legacy},r.slice(0,-1))).map(i=>i.literals.map(s=>s??"*").join("/")));return o.size===1?null:o.size>1?fr:M}a(Ar,"aliasTargetIssue");function jt(t){let e=t[0];return(e==="src"||e==="app")&&t.length>1?[t,t.slice(1)]:[t]}a(jt,"aliasGlobVariants");function kr(t,e){let n=jt(t),r=jt(e);for(let o of n)if(x(o,e,0,0,new Map))return!0;for(let o of r)if(x(t,o,0,0,new Map))return!0;return!1}a(kr,"aliasesCanMatchSameFile");function x(t,e,n,r,o){let i=`${n}:${r}`,s=o.get(i);if(s!==void 0)return s;let l=!1;if(n===t.length&&r===e.length)l=!0;else if(n<t.length&&t[n]==="**")l=x(t,e,n+1,r,o)||r<e.length&&x(t,e,n,r+1,o);else if(r<e.length&&e[r]==="**")l=x(t,e,n,r+1,o)||n<t.length&&x(t,e,n+1,r,o);else if(n<t.length&&r<e.length){let c=t[n],d=e[r];(c===d||c==="*"||d==="*")&&(l=x(t,e,n+1,r+1,o))}return o.set(i,l),l}a(x,"globsCanMatchSame");var Gt="must be a filename with exactly one <Layer> token and no slash or wildcard (arkrules.<Layer>.json)";function Er(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.arkRulesFile===void 0)return;let s=`$.rules[${o}].childSlices.arkRulesFile`,l=i.arkRulesFile;if(typeof l!="string"||l.length===0){e.push({path:s,message:Gt});return}(l.split("<Layer>").length!==2||/[*\\/]/.test(l)||l.includes(".."))&&e.push({path:s,message:Gt})})}a(Er,"validateChildSliceArkRulesFile");function Rr(t,e){let n=t.rules;Array.isArray(n)&&n.forEach((r,o)=>{if(!I(r))return;let i=r.childSlices;if(!I(i)||i.sliceAliases===void 0)return;let s=i.sliceAliases,l=`$.rules[${o}].childSlices.sliceAliases`;if(!Array.isArray(s)){e.push({path:l,message:"must be an array of { from, to } slice aliases"});return}let c=br(r.sliceFolders,r.sliceIdentity),d=[...Array.isArray(r.sliceFolders)?r.sliceFolders:[],...Array.isArray(i.sliceFolders)?i.sliceFolders:[]].filter(p=>typeof p=="string"&&p.length>0),f=[];s.forEach((p,m)=>{let h=`${l}[${m}]`;if(!I(p)){e.push({path:h,message:"must be an object with from and to"});return}for(let y of Object.keys(p))y!=="from"&&y!=="to"&&y!=="pinned"&&y!=="reason"&&e.push({path:fe(h,y),message:"unknown field"});let S=p.from,u=p.to;if(typeof S!="string"||S.trim().length===0)e.push({path:`${h}.from`,message:"must be a non-empty path glob"});else{let y=vr(S);if(y)e.push({path:`${h}.from`,message:y});else{let g=hr(mr(S));d.some(v=>Ir(g,v))&&e.push({path:`${h}.from`,message:pr});for(let v of f)if(kr(v,g)){e.push({path:h,message:gr});break}f.push(g)}}if(typeof u!="string"||u.trim().length===0)e.push({path:`${h}.to`,message:M});else{let y=Ar(u,c);y&&e.push({path:`${h}.to`,message:y})}})})}a(Rr,"validateChildSliceAliases");function pe(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}a(pe,"isObject");function F(t,e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?`${t}.${e}`:`${t}[${JSON.stringify(e)}]`}a(F,"propertyPath");function L(t){return t===null?"null":Array.isArray(t)?"array":typeof t}a(L,"valueType");function Pr(t,e){let n="#/$defs/";if(t.startsWith(n))return e.$defs[t.slice(n.length)]}a(Pr,"resolveSchemaRef");function _(t,e,n,r,o){if(e.$ref){let i=Pr(e.$ref,r);if(!i){o.push({path:n,message:`schema reference ${e.$ref} cannot be resolved`});return}_(t,i,n,r,o);return}if(e.const!==void 0&&!Object.is(t,e.const)){o.push({path:n,message:`must equal ${JSON.stringify(e.const)}`});return}if(e.enum&&!e.enum.some(i=>Object.is(i,t))){o.push({path:n,message:`must be one of ${e.enum.map(String).join(", ")}`});return}if(e.type==="object"){if(!pe(t)){o.push({path:n,message:`must be an object; received ${L(t)}`});return}let i=e.properties??{};for(let s of e.required??[])t[s]===void 0&&o.push({path:F(n,s),message:"is required"});if(e.additionalProperties===!1)for(let s of Object.keys(t))s in i||o.push({path:F(n,s),message:"unknown field"});else if(e.additionalProperties!==void 0&&e.additionalProperties!==!0&&typeof e.additionalProperties=="object"){let s=e.additionalProperties;for(let l of Object.keys(t))l in i||_(t[l],s,F(n,l),r,o)}for(let[s,l]of Object.entries(i))t[s]!==void 0&&_(t[s],l,F(n,s),r,o);return}if(e.type==="array"){if(!Array.isArray(t)){o.push({path:n,message:`must be an array; received ${L(t)}`});return}if(e.minItems!==void 0&&t.length<e.minItems&&o.push({path:n,message:`must contain at least ${e.minItems} item(s)`}),e.uniqueItems){let i=t.map(s=>JSON.stringify(s));new Set(i).size!==i.length&&o.push({path:n,message:"must not contain duplicate items"})}e.items&&t.forEach((i,s)=>_(i,e.items,`${n}[${s}]`,r,o));return}if(e.type==="string"){if(typeof t!="string"){o.push({path:n,message:`must be a string; received ${L(t)}`});return}e.minLength!==void 0&&t.length<e.minLength&&o.push({path:n,message:`must contain at least ${e.minLength} character(s)`});return}if(e.type==="boolean"){typeof t!="boolean"&&o.push({path:n,message:`must be a boolean; received ${L(t)}`});return}if(e.type==="integer"){if(!Number.isInteger(t)){o.push({path:n,message:`must be an integer; received ${L(t)}`});return}e.minimum!==void 0&&t<e.minimum&&o.push({path:n,message:`must be at least ${e.minimum}`})}}a(_,"validateSchemaNode");function ge(t){if(typeof t!="string")return null;let e=t.trim().replace(/^@/,"").toLowerCase();return e.length>0?e:null}a(ge,"normalizeStewardId");function qt(t){let e=ge(t);return!e||Oe(e)||e.includes(" ")||e.includes("@")?!1:/^(?!-)[a-z0-9-]{1,39}(?<!-)$/.test(e)}a(qt,"isGitHubHandle");function Cr(t){if(typeof t!="string")return!1;let e=t.trim().toLowerCase();if(!e.includes("@")||e.includes(" ")||Oe(e))return!1;let n=e.split("@");if(n.length!==2||!n[0]||/\s/.test(e))return!1;let r=n[1].lastIndexOf(".");return r>0&&r<n[1].length-1}a(Cr,"isGitHubEmail");function xr(t){if(typeof t!="string")return null;let e=t.trim().match(/^(?:\d+\+)?([^@]+)@users\.noreply\.github\.com$/i);return e&&qt(e[1])?ge(e[1]):null}a(xr,"githubHandleFromEmail");function zt(t){let e=xr(t);if(e)return e;let n=ge(t);return!n||Oe(n)?null:qt(n)||Cr(n)?n:null}a(zt,"canonicalStewardId");var Lr=/bot\b|\[bot\]|dependabot|renovate|github-actions|imgbot|codecov/i;function Oe(t){let e=ge(t);return!e||Lr.test(e)}a(Oe,"isAutomationAuthor");var A="1.3",Or=["public","auth","admin","internal"];function $r(t){return t?.optional===!0||t?.reserved===!0||t?.allowEmpty===!0}a($r,"isFutureHouseLayer");function Dr(t){let e=t&&typeof t=="object"?t.owners:void 0;if(!Array.isArray(e)||e.length===0)return;let n=e.filter(r=>typeof r=="string"&&r.length>0);return n.length>0?n:void 0}a(Dr,"layerOwnersList");function yi(t){return t?.requireLayerOwners!==!0||!Array.isArray(t.layers)?[]:t.layers.filter(e=>!$r(e)&&!Dr(e)).map(e=>e.name)}a(yi,"layersMissingRequiredOwners");function Si(t){return`Add a GitHub handle or email to ${t}'s owners in ark.config.json (/ark-adopt).`}a(Si,"missingLayerOwnersNextAction");var me="https://unpkg.com/arkgate@4/schemas/ark.config.schema.json",Jt=["DomainModel","ApplicationOrchestration","PersistenceAdapters","IntegrationAdapters","WorkflowSagaEngine","BackgroundJobsScheduling","PresentationAdapters","ReportingReadModels","ExtensibilityMetadata","SecurityAuditObservability","Kernel"],Nr=new Set(["PresentationAdapters->ApplicationOrchestration","ApplicationOrchestration->DomainModel","WorkflowSagaEngine->ApplicationOrchestration","WorkflowSagaEngine->DomainModel","BackgroundJobsScheduling->ApplicationOrchestration"]);function Tr(){let t=[];for(let e of Jt)for(let n of Jt)e===n||Nr.has(`${e}->${n}`)||t.push({from:e,to:n,allowed:!1});return t}a(Tr,"createDefaultRules");var he=Tr(),$e=[{from:"unversioned",to:"1.0"},{from:"1.0",to:"1.1"},{from:"1.1",to:"1.2"},{from:"1.2",to:"1.3"}],b={type:"array",items:{type:"string",minLength:1},uniqueItems:!0},Yt={$schema:"https://json-schema.org/draft/2020-12/schema",$id:me,title:"ArkGate architecture contract",description:"Versioned contract consumed identically by ArkGate CLI, MCP, and ESLint surfaces.",type:"object",additionalProperties:!1,required:["$schema","schemaVersion","include","layers","rules"],properties:{$schema:{type:"string",minLength:1,default:me,description:"Editor-facing URL or local path for this JSON Schema."},schemaVersion:{type:"string",const:A,default:A},name:{type:"string",minLength:1},include:{...b,minItems:1,default:["src"]},exclude:{...b,default:[]},excludeGenerated:{type:"boolean",default:!0},frameworkOverlay:{type:"string",minLength:1},layers:{type:"array",default:[],items:{$ref:"#/$defs/layer"}},rules:{type:"array",default:he,items:{$ref:"#/$defs/rule"}},cyclePolicy:{type:"string",enum:["strict","soft","framework-soft","off"],default:"strict"},dynamicImportAllowlist:{...b,default:[]},safety:{$ref:"#/$defs/safety",default:{maxTsSuppressions:0,maxAnyCasts:0,allowInMemory:!1,allowDisabledPeerIsolation:!1}},coverage:{$ref:"#/$defs/coverage"},arkRules:{type:"object",additionalProperties:{description:"A project-relative ArkRules path, or a list of paths merged into one catalog for this layer. A string keeps today's behaviour. An older build that types this value as a string rejects an array at config load.",oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,uniqueItems:!0,items:{type:"string",minLength:1}}]},default:{}},arkRun:{$ref:"#/$defs/arkRun"},arkOrder:{$ref:"#/$defs/arkOrder"},stewards:{...b,default:[]},requireLayerOwners:{type:"boolean"}},$defs:{layer:{type:"object",additionalProperties:!1,required:["name","patterns"],properties:{name:{type:"string",minLength:1},patterns:{...b,minItems:1},exclude:b,intentPrefixes:b,description:{type:"string",minLength:1},trustBoundary:{type:"string",enum:[...Or]},owners:{...b,minItems:1},forbiddenGlobals:b,capabilities:{type:"object",additionalProperties:!1,properties:{deny:{type:"array",uniqueItems:!0,items:{type:"string",enum:["network","filesystem","clock","randomness","environment","process","persistence"]}}}},pure:{type:"boolean"},mayImportInfrastructure:{type:"boolean"},optional:{type:"boolean"},reserved:{type:"boolean"},allowEmpty:{type:"boolean"}}},rule:{type:"object",additionalProperties:!1,required:["from","to","allowed"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1},allowed:{type:"boolean"},message:{type:"string",minLength:1},peerIsolation:{type:"boolean"},sliceFolders:{...b,minItems:1},sliceIdentity:{type:"string",enum:["path","stars"],description:"How a starred sliceFolders prefix is named. Absent and path keep today's ids (every literal and star binding). stars keeps the last literal plus every star binding (a star before the last literal is kept too), so parallel trees share one feature id. Bare names are unchanged."},sharedRoots:{...b,minItems:1},allowedCrossSlice:{type:"array",minItems:1,items:{type:"object",additionalProperties:!1,required:["from","to"],properties:{from:{type:"string",minLength:1},to:{type:"string",minLength:1}}}},sharedImportsSlice:Ht,childSlices:Kt}},safety:{type:"object",additionalProperties:!1,properties:{maxTsSuppressions:{type:"integer",minimum:0,default:0},maxAnyCasts:{type:"integer",minimum:0,default:0},allowInMemory:{type:"boolean",default:!1},allowDisabledPeerIsolation:{type:"boolean",default:!1}}},coverage:{type:"object",additionalProperties:!1,description:"Invariant coverage scan controls. testGlobs replaces the built-in test-name heuristic; maxFiles raises or lowers the evidence file budget and also bounds structural-hint preload for orchestration-only, thin-adapter, and writes-via-aggregate (default 400; there is no arkrules.hintBudget); coverageRoots declares where the project runs its tests, so a covering test found outside them is reported instead of silently certifying an invariant. When any invariant is enforced, missing coverageRoots fails closed.",properties:{testGlobs:{...b,minItems:1},maxFiles:{type:"integer",minimum:1,description:"Evidence file budget (default 400) and structural-hint preload cap for orchestration-only, thin-adapter, and writes-via-aggregate. Raise this when hinted/governed counts show truncated sensors. There is no separate arkrules.hintBudget."},coverageRoots:{...b,minItems:1}}},arkRun:xt,arkOrder:Lt}},R=class extends Error{static{a(this,"ArkConfigValidationError")}issues;source;constructor(e,n){super(`Invalid ArkGate config (${e}):
|
|
2
|
+
${n.map(r=>`- ${r.path}: ${r.message}`).join(`
|
|
3
|
+
`)}`),this.name="ArkConfigValidationError",this.source=e,this.issues=n}};function Mr(t,e){let n=t.arkRules;if(!(n===void 0||!pe(n)))for(let[r,o]of Object.entries(n)){let i=F("$.arkRules",r);if(typeof o=="string"){o.length===0&&e.push({path:i,message:"must be a non-empty relative path string"});continue}if(!Array.isArray(o)||o.length===0){e.push({path:i,message:"must be a non-empty path string or an array of paths"});continue}let s=new Set;o.forEach((l,c)=>{let d=`${i}[${c}]`;if(typeof l!="string"||l.length===0){e.push({path:d,message:"must be a non-empty relative path string"});return}s.has(l)&&e.push({path:d,message:"duplicate path"}),s.add(l)})}}a(Mr,"validateArkRulesRefs");function Fr(t,e){let n=t.layers;Array.isArray(n)&&n.forEach((r,o)=>{if(!r||typeof r!="object"||Array.isArray(r)||!("owners"in r))return;let i=r.owners;Array.isArray(i)&&i.forEach((s,l)=>{typeof s=="string"&&(zt(s)||e.push({path:`$.layers[${o}].owners[${l}]`,message:"must be a GitHub handle or email (not a display name)"}))})})}a(Fr,"validateLayerOwners");function _r(t){let e={...t,$schema:t.$schema===void 0?me:t.$schema,schemaVersion:t.schemaVersion===void 0?A:t.schemaVersion,include:t.include===void 0?["src"]:t.include,layers:t.layers===void 0?[]:t.layers,rules:t.rules===void 0?he.map(n=>({...n})):t.rules};return t.arkRun!==void 0&&(e.arkRun=Ot(t.arkRun)),t.arkOrder!==void 0&&(e.arkOrder=$t(t.arkOrder)),e}a(_r,"defaultedConfig");function Br(t){return t===A?null:t==="unversioned"?"unversioned":t==="1.0"||t==="1.1"||t==="1.2"?t:null}a(Br,"migratedFromOf");function jr(){let t=new Set([A]);for(let e of $e)e.from!=="unversioned"&&t.add(e.from),t.add(e.to);return t}a(jr,"knownInputVersions");function Gr(t,e="ark.config.json"){if(!pe(t))throw new R(e,[{path:"$",message:`must be an object; received ${L(t)}`}]);let n=jr(),r=t.schemaVersion===void 0?"unversioned":typeof t.schemaVersion=="string"?t.schemaVersion:null;if(r===null)throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(t.schemaVersion)}; expected ${A}`}]);if(r!=="unversioned"&&!n.has(r))throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${A}`}]);let o=r,i={...t},s=0;for(;o!==A&&s<$e.length+1;){s+=1;let l=$e.find(c=>c.from===o);if(!l)throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(o)}; expected ${A}`}]);o=l.to,i.schemaVersion=o}if(o!==A)throw new R(e,[{path:"$.schemaVersion",message:`unsupported version ${JSON.stringify(r)}; expected ${A}`}]);return{candidate:_r(i),migratedFrom:Br(r)}}a(Gr,"migrateArkConfig");function Hr(t,e="ark.config.json"){let{candidate:n,migratedFrom:r}=Gr(t,e),o=[];if(_(n,Yt,"$",Yt,o),Nt(n,o),Tt(n,o),Fr(n,o),Vt(n,o),Mr(n,o),o.length>0)throw new R(e,o);return{config:n,migratedFrom:r}}a(Hr,"loadArkConfigContract");function wi(t,e="ark.config.json"){let n;try{n=JSON.parse(t)}catch(r){throw new R(e,[{path:"$",message:`invalid JSON: ${r instanceof Error?r.message:String(r)}`}])}return Hr(n,e)}a(wi,"parseArkConfigJson");function Xt(t){let e={$schema:typeof t.$schema=="string"&&t.$schema.length>0?t.$schema:me,schemaVersion:A};for(let[n,r]of Object.entries(t))n!=="$schema"&&n!=="schemaVersion"&&(e[n]=r);return e}a(Xt,"withArkConfigMetadata");var Zt={RAW_EVENT_PUBLISH:"Publish through a registered intent creator; raw event objects or intent strings bypass Ark contracts and tooling.",PUBLISH_MISSING_SOURCE:"Strict Ark publish calls must include metadata.source."},Kr=Object.freeze([{layer:"DomainModel",prefixes:["Domain."]},{layer:"ApplicationOrchestration",prefixes:["Application."]},{layer:"PersistenceAdapters",prefixes:["Adapter.Persistence.","Adapter.Repository."]},{layer:"IntegrationAdapters",prefixes:["Adapter.Integration.","Adapter.External."]},{layer:"WorkflowSagaEngine",prefixes:["Workflow."]},{layer:"BackgroundJobsScheduling",prefixes:["Job."]},{layer:"PresentationAdapters",prefixes:["Presentation.","Adapter.Presentation.","Adapter.Api."]},{layer:"ReportingReadModels",prefixes:["Reporting."]},{layer:"ExtensibilityMetadata",prefixes:["Metadata."]},{layer:"SecurityAuditObservability",prefixes:["Security.","Audit.","Observability."]},{layer:"Kernel",prefixes:["Kernel."]}]);function De(t){let e=(t.intentPrefixes??[]).filter(n=>n.trim().length>0);return e.length>0?e:Kr.find(n=>n.layer===t.name)?.prefixes??[]}a(De,"effectiveIntentPrefixes");function Qt(t){let e=new Set(t.layers.filter(r=>De(r).length>0).map(r=>r.name)),n=new Set;for(let r of t.rules??[])if(!(r.allowed!==!1||r.peerIsolation===!0))for(let o of[r.from,r.to])e.has(o)||n.add(o);return[...n].sort()}a(Qt,"unresolvableLayerFlowLayers");function bi(t,e){return e.flatMap((r,o)=>(r.prefixes??r.intentPrefixes??[]).map(i=>({layer:r.name,layerIndex:o,prefix:i.endsWith(".")?i:`${i}.`}))).filter(({prefix:r})=>t.startsWith(r)).sort((r,o)=>o.prefix.length-r.prefix.length||r.layerIndex-o.layerIndex)[0]?.layer}a(bi,"resolveIntentLayer");function Vr(t){return/^(Domain|Application|Adapter|Workflow|Job|Presentation|Reporting|Metadata|Security|Audit|Observability|Kernel)\.[A-Za-z0-9_.]+$/.test(t)}a(Vr,"looksLikeArkIntent");function Ai(t){if(!t.publishCall)return[];let e=[];return(t.rawIntentName!==void 0&&Vr(t.rawIntentName)||t.objectHasIntent)&&e.push({ruleId:"RAW_EVENT_PUBLISH",message:Zt.RAW_EVENT_PUBLISH}),t.arkPublishCandidate&&!t.hasSource&&e.push({ruleId:"PUBLISH_MISSING_SOURCE",message:Zt.PUBLISH_MISSING_SOURCE}),e}a(Ai,"classifyPublishFacts");function Wr(t){return t.endsWith(".")?t:`${t}.`}a(Wr,"normalizePrefix");function Ur(t,e){let n=t.prefixes.length?Math.max(...t.prefixes.map(o=>o.length)):0;return(e.prefixes.length?Math.max(...e.prefixes.map(o=>o.length)):0)-n}a(Ur,"byLongestPrefix");function Ne(t){let e=t.layers.map(o=>({...o,prefixes:o.prefixes.map(Wr)})),n=[...e].sort(Ur),r=[...t.rules??[]];return{name:t.name,layers:e,rules:r,resolveLayer(o){return e.find(i=>i.match?.(o))?.name??n.find(i=>i.prefixes.some(s=>o.startsWith(s)))?.name}}}a(Ne,"createArchitectureProfile");function Te(t,e={}){return Ne({name:e.name??t.name??"ark.config.json",layers:t.layers.map((n,r)=>({name:n.name,prefixes:[...De(n)],description:n.description,trustBoundary:n.trustBoundary,owners:n.owners,order:r+1})),rules:t.rules??[]})}a(Te,"createArchitectureProfileFromArkConfig");var qr=[{name:"DomainModel",prefixes:["Domain"],description:"Rich domain model, business rules, and domain events.",order:1},{name:"ApplicationOrchestration",prefixes:["Application"],description:"Use cases and command orchestration.",order:2},{name:"PersistenceAdapters",prefixes:["Adapter.Persistence","Adapter.Repository"],description:"Database, repository, and storage adapters.",order:3},{name:"IntegrationAdapters",prefixes:["Adapter.Integration","Adapter.External"],description:"External systems, APIs, and integration adapters.",order:4},{name:"WorkflowSagaEngine",prefixes:["Workflow"],description:"Sagas, workflows, and long-running processes.",order:5},{name:"BackgroundJobsScheduling",prefixes:["Job"],description:"Background jobs, scheduled work, and async processors.",order:6},{name:"PresentationAdapters",prefixes:["Presentation","Adapter.Presentation","Adapter.Api"],description:"API, UI, controller, and presentation adapters.",order:7},{name:"ReportingReadModels",prefixes:["Reporting"],description:"Read models, projections, and reporting surfaces.",order:8},{name:"ExtensibilityMetadata",prefixes:["Metadata"],description:"Metadata, extensions, and schema contracts.",order:9},{name:"SecurityAuditObservability",prefixes:["Security","Audit","Observability"],description:"Security, audit, and observability concerns.",order:10},{name:"Kernel",prefixes:["Kernel"],description:"Ark-owned governance and kernel signals.",order:11}],Y=Ne({name:"Ark 11-layer Hexagonal Event-Driven Profile",layers:qr,rules:he.map(t=>({...t}))}),zr={DomainModel:["domain"],ApplicationOrchestration:["application","app"],PersistenceAdapters:["adapters/persistence","adapters/repository","repositories","infra/persistence"],IntegrationAdapters:["adapters/integration","adapters/external","integrations"],WorkflowSagaEngine:["workflows","sagas"],BackgroundJobsScheduling:["jobs","schedules"],PresentationAdapters:["presentation","adapters/presentation","adapters/api"],ReportingReadModels:["reporting","read-models","projections"],ExtensibilityMetadata:["metadata","extensions"],SecurityAuditObservability:["security","audit","observability"],Kernel:["kernel"]};function Jr(t={}){let e=t.rootDir??"src",n=t.optionalLayers??!0,r=e==="."?"":`${e}/`;return Xt({include:t.include??[e],layers:Y.layers.map(o=>({name:o.name,patterns:(zr[o.name]??[o.name]).map(i=>`${r}${i}/**`),intentPrefixes:o.prefixes,optional:n})),rules:[...Y.rules]})}a(Jr,"createElevenLayerArkConfig");var X=class{static{a(this,"IntentRegistry")}intents=new Map;dependencies=new Map;productions=new Map;define(e,n){if(this.intents.has(e))throw new Error(`Intent "${e}" is already registered. Intent names must be unique within a registry.`);let r=a(i=>({intent:e,payload:i,metadata:{occurredAt:new Date().toISOString(),source:"unknown"}}),"fn");Object.defineProperty(r,"name",{value:e,enumerable:!0,configurable:!1,writable:!1});let o=r;if(this.intents.set(e,o),n?.dependsOn)for(let i of n.dependsOn)this.declareDependency(e,i);if(n?.produces)for(let i of n.produces)this.declareProduction(e,i);return o}declareDependency(e,n){this.dependencies.has(e)||this.dependencies.set(e,new Set),this.dependencies.get(e).add(n)}declareProduction(e,n){this.productions.has(e)||this.productions.set(e,new Set),this.productions.get(e).add(n)}get(e){return this.intents.get(e)}list(){return Array.from(this.intents.values())}getDependencies(e){let n=this.dependencies.get(e);return n?Array.from(n):[]}getProductions(e){let n=this.productions.get(e);return n?Array.from(n):[]}getAllRelationships(){let e=[];for(let[n,r]of this.dependencies.entries())for(let o of r)e.push({from:n,to:o,kind:"dependsOn"});for(let[n,r]of this.productions.entries())for(let o of r)e.push({from:n,to:o,kind:"produces"});return e}has(e){return this.intents.has(e)}clear(){this.intents.clear(),this.dependencies.clear(),this.productions.clear()}};var en=new X;function Yr(t,e){return en.define(t,e)}a(Yr,"defineIntent");function Me(){return new X}a(Me,"createIntentRegistry");var Xr=en;var tn=["Domain.","Application.","Adapter.","Workflow.","Job.","Presentation.","Reporting.","Metadata.","Security.","Audit.","Observability.","Kernel."];function Fe(t){if(!t||typeof t!="string")return{valid:!1,reason:"Intent name must be a non-empty string"};if(!tn.some(n=>t.startsWith(n)))return{valid:!1,reason:`Intent "${t}" must start with one of: ${tn.join(", ")}`};let e=t.slice(t.indexOf(".")+1);return!e||!/^[A-Za-z][A-Za-z0-9_.]*$/.test(e)?{valid:!1,reason:`Intent "${t}" has an invalid segment after the layer prefix`}:{valid:!0}}a(Fe,"validateIntentName");var O=class extends Error{static{a(this,"PolicyViolationError")}violations;constructor(e){let n=e.map(r=>`- ${r.policyName}: ${r.message}`).join(`
|
|
4
|
+
`);super(`Hard policy violation(s) detected:
|
|
5
|
+
${n}`),this.name="PolicyViolationError",this.violations=e}};var B=class{static{a(this,"PolicyEngine")}policies=[];constructor(e=[]){for(let n of e)this.add(n)}add(e){if(this.policies.some(n=>n.name===e.name))throw new Error(`Policy "${e.name}" is already registered in this engine.`);this.policies.push(e)}getPolicies(){return[...this.policies]}evaluate(e){let n=[];for(let i of this.policies){let s=i.check(e);if(s!==!0){if(s===!1){n.push({policyName:i.name,severity:i.severity,message:`Policy "${i.name}" was violated.`});continue}if(Array.isArray(s))for(let l of s)n.push({policyName:i.name,severity:i.severity,message:l.message,details:l.details});else n.push({policyName:i.name,severity:i.severity,message:s.message,details:s.details})}}let r=n.filter(i=>i.severity==="hard"),o=n.filter(i=>i.severity==="soft");return{passed:n.length===0,violations:n,hardViolations:r,softViolations:o}}enforce(e){let n=this.evaluate(e);if(n.hardViolations.length>0)throw new O(n.hardViolations);return n}clear(){this.policies.length=0}};function Z(t){let e=t.severity??"soft";return{name:t.name,severity:e,tags:t.tags,owner:t.owner,version:t.version,rationale:t.rationale,enforcementMode:t.enforcementMode,deprecated:t.deprecated,replacedBy:t.replacedBy,check:t.check}}a(Z,"definePolicy");function Zr(t){let e=t.indexOf(".");return e>=0?t.slice(0,e):t}a(Zr,"defaultLayerOf");function nn(t,e){return e.resolveLayer?.(t)??Zr(t)}a(nn,"resolveLayer");function Qr(t,e,n){return t===n.from&&e===n.to}a(Qr,"matchesRule");function _e(t){let e=t.name??"Layer isolation",n=t.severity??"hard";return Z({name:e,severity:n,tags:["layer"],check:a(r=>{let o=[...(r.edges??[]).filter(s=>s.kind==="declared"||s.kind==="produces").map(s=>({from:s.from,to:s.to})),...(r.relationships??[]).filter(s=>s.kind==="dependsOn").map(s=>({from:s.from,to:s.to}))],i=[];for(let s of o){let l=nn(s.from,t),c=nn(s.to,t);for(let d of t.rules)!d.allowed&&Qr(l,c,d)&&i.push({policyName:e,severity:n,message:d.message??`Layer violation: ${s.from} (${l}) must not relate to ${s.to} (${c})`})}return i.length>0?i:!0},"check")})}a(_e,"defineLayerPolicy");function Be(t){return t.tags?.includes("layer")??!1}a(Be,"isLayerPolicy");var rn={layerIsolation(){return rn.cleanArchitectureMatrix()},cleanArchitectureMatrix(){return _e({name:"Clean architecture matrix",severity:"hard",rules:[{from:"Domain",to:"Adapter",allowed:!1},{from:"Domain",to:"Application",allowed:!1},{from:"Adapter",to:"Application",allowed:!1},{from:"Adapter",to:"Domain",allowed:!1}]})}};function je(t,e={}){return _e({name:e.name??`${t.name} layer policy`,severity:e.severity??"hard",rules:t.rules,resolveLayer:t.resolveLayer})}a(je,"defineArchitectureProfilePolicy");function Ge(t){return e=>({event:e,relationships:t.intentRegistry?.getAllRelationships(),edges:t.dependencyGraph?.getEdges()})}a(Ge,"buildPublishPolicyContext");function eo(t){return Z(t)}a(eo,"definePublishPolicy");var Q=class extends Error{static{a(this,"UnregisteredIntentError")}intentName;constructor(e){super(`Intent "${e}" is not registered. Register it with IntentRegistry.define() before publish/subscribe, including metadata.source producer intents in strict mode.`),this.name="UnregisteredIntentError",this.intentName=e}},ee=class extends Error{static{a(this,"InvalidIntentNameError")}intentName;reason;constructor(e,n){super(`Invalid intent name "${e}": ${n}`),this.name="InvalidIntentNameError",this.intentName=e,this.reason=n}},te=class extends Error{static{a(this,"LayerPolicyContextError")}constructor(){super("Layer/architecture policies require intentRegistry, dependencyGraph, or a custom getPolicyContext. Without graph/registry context, layer policies cannot inspect relationships."),this.name="LayerPolicyContextError"}},ne=class extends Error{static{a(this,"EventContractViolationError")}intentName;issues;constructor(e,n){super(`Event contract violation for "${e}". Register a matching event contract/version or fix the payload before publishing.`),this.name="EventContractViolationError",this.intentName=e,this.issues=n}},j=class extends Error{static{a(this,"UnknownEventSourceError")}intentName;source;constructor(e,n){super(n?`Event "${e}" metadata.source "${n}" is not registered. Register the producer intent or publish from a known source.`:`Event "${e}" must include metadata.source. Strict Ark uses source to enforce observed layer flow.`),this.name="UnknownEventSourceError",this.intentName=e,this.source=n}},$=class extends Error{static{a(this,"SourceMetadataOverrideError")}boundSource;attemptedSource;constructor(e,n){super(`Source-bound publisher for "${e}" cannot publish with metadata.source "${n}". Create a publisher for the intended source instead.`),this.name="SourceMetadataOverrideError",this.boundSource=e,this.attemptedSource=n}},re=class extends Error{static{a(this,"ObservedLayerFlowViolationError")}source;intentName;fromLayer;toLayer;constructor(e,n,r,o,i){super(i??`Observed layer violation: "${e}" (${r}) must not produce "${n}" (${o}). Route this through an allowed layer or adjust the architecture profile rule.`),this.name="ObservedLayerFlowViolationError",this.source=e,this.intentName=n,this.fromLayer=r,this.toLayer=o}},G=class extends Error{static{a(this,"ArkKernelConfigError")}code;layers;constructor(e){super(`Hard observed-layer-flow enforcement cannot resolve layer(s) ${e.map(n=>`"${n}"`).join(", ")}: they appear in a deny rule but declare no intentPrefixes (and are not canonical 11-layer names), so no intent maps to them and the rule would never fire. Add intentPrefixes to those layers in ark.config.json, or pass enforceObservedLayerFlow: 'soft' | 'off' explicitly.`),this.name="ArkKernelConfigError",this.code="ARKRUN_LAYER_FLOW_UNRESOLVABLE",this.layers=e}};function oe(t,e){if(!(!e.strictRegistry&&!e.validateIntentNaming)){if(e.validateIntentNaming){let n=Fe(t);if(!n.valid)throw new ee(t,n.reason)}if(e.strictRegistry&&e.intentRegistry&&!e.intentRegistry.has(t))throw new Q(t)}}a(oe,"assertIntentAllowed");function on(t,e){if(e.requireKnownSource){if(!t.metadata.source||t.metadata.source==="unknown")throw new j(t.intent);if(e.intentRegistry&&!e.intentRegistry.has(t.metadata.source))throw new j(t.intent,t.metadata.source)}}a(on,"assertSourceAllowed");function ie(t,e){if(!e.eventContracts)return;let n=e.eventContracts.validate(t);if(!n.ok&&(e.strictEventContracts||n.contract))throw new ne(t.intent,n.issues)}a(ie,"assertContractAllowed");function H(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}a(H,"isPlainRecord");function K(t){return Array.isArray(t)?t.map(K):H(t)?Object.fromEntries(Object.entries(t).map(([e,n])=>[e,K(n)])):t}a(K,"clonePatchValue");function He(t,e,n="payload"){let r={...t};for(let[o,i]of Object.entries(e)){let s=`${n}.${o}`;if(!(o in r)||r[o]===void 0){r[o]=K(i);continue}if(H(r[o])&&H(i)){r[o]=He(r[o],i,s);continue}if(Array.isArray(r[o])&&Array.isArray(i)){r[o]=Ke(r[o],i,s);continue}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}return r}a(He,"mergeRecordPatch");function Ke(t,e,n="payload"){let r=[...t];return e.forEach((o,i)=>{let s=`${n}[${i}]`;if(i>=r.length||r[i]===void 0){r[i]=K(o);return}if(H(r[i])&&H(o)){r[i]=He(r[i],o,s);return}if(Array.isArray(r[i])&&Array.isArray(o)){r[i]=Ke(r[i],o,s);return}throw new Error(`Interceptor patch cannot overwrite existing ${s}.`)}),r}a(Ke,"mergeArrayPatch");function sn(t,e){if(Array.isArray(e)){if(t===void 0)return K(e);if(!Array.isArray(t))throw new Error("Array interceptor patch requires an array payload.");return Ke(t,e)}if(t===void 0)return K(e);if(!H(t))throw new Error("Object interceptor patch requires an object payload.");return He(t,e)}a(sn,"applyPayloadPatch");async function an(t,e){if(t.metadata.allowInterception===!1)return t;let n=[...e.interceptorsForIntent(t.intent)],r=t;for(let o of n){let i=[];try{if(await Promise.resolve(o.interceptor({event:r,intercept:a(c=>{i.push(c)},"intercept")})),i.length===0)continue;let s=new Date().toISOString(),l={...r,metadata:{...r.metadata,interceptions:[...r.metadata.interceptions??[],{interceptorId:o.interceptorId,timestamp:s}]}};for(let c of i)l={...l,payload:sn(l.payload,c),metadata:{...l.metadata}};ie(l,{eventContracts:e.eventContracts,strictEventContracts:e.strictEventContracts}),r=l,o.lastInterceptedAt=s,e.appendTrace({type:"event.intercepted",timestamp:s,intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length}}),await e.recordAudit("event.intercepted",r,{registrationId:o.registrationId,interceptorId:o.interceptorId,patchesApplied:i.length})}catch(s){await to(o,r,s,e)}}return r}a(an,"applyInterceptors");async function to(t,e,n,r){let o=n instanceof Error?n.message:String(n);r.appendTrace({type:"interceptor.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o}}),await r.recordAudit("interceptor.error",e,{registrationId:t.registrationId,interceptorId:t.interceptorId,error:o})}a(to,"recordInterceptorError");function Sn(t){if(t==="deny"||t==="deny-cross-parent")return t;if(t!==null&&typeof t=="object"){let e=t.mode;if(e==="deny-cross-parent")return e}}a(Sn,"sharedImportsSliceMode");function bs(t){if(t===null||typeof t!="object")return[];let e=t.stopAt;return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.length>0):[]}a(bs,"sharedImportsSliceStopAt");var ln=new Map;function cn(t){return/[.*+?^${}()|[\]\\]/.test(t)?`\\${t}`:t}a(cn,"escapeLiteral");function ve(t){let e="";for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"&&n+1<t.length){let o=t[n+1];if("*?{}[],".includes(o)||o==="\\"){e+="\\"+o,n+=1;continue}e+="/";continue}e+=r}return e}a(ve,"normalizeGlobSeparators");function no(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t[n];if(r==="\\"){n+=1;continue}if(r==="{")e+=1;else if(r==="}"&&(e-=1,e<0))return!1}return e===0}a(no,"bracesBalanced");function W(t){let e=ln.get(t);if(e)return e;let n=ve(t),r=no(n),o="",i=0;for(let l=0;l<n.length;l+=1){let c=n[l];c==="\\"&&l+1<n.length?(o+=cn(n[l+1]),l+=1):c==="*"?n[l+1]==="*"?n[l+2]==="/"?(o+="(?:.*/)?",l+=2):(o+=".*",l+=1):o+="[^/]*":c==="?"?o+="[^/]":c==="{"&&r?(o+="(?:",i+=1):c==="}"&&r&&i>0?(o+=")",i-=1):c===","&&r&&i>0?o+="|":o+=cn(c)}let s=new RegExp(`^${o}$`);return ln.set(t,s),s}a(W,"globToRegExp");function ro(t){return ve(String(t)).split("/").filter(Boolean).filter(n=>n!=="**"&&n!=="*"&&!n.includes("*")&&!n.includes("?")&&!n.includes("{")&&!n.includes("["))}a(ro,"concreteGlobSegments");function oo(t,e){let n=ve(String(t)),r=ro(n),o=n.replace(/\*/g,"").length,i=r.length*1e4+o;if(e==null||e==="")return i;let s=String(e).split(/[/\\]/).filter(Boolean);if(r.length===0)return o;let l=0,c=-1;for(let d of r){let f=-1;for(let p=l;p<s.length;p+=1)if(s[p]===d){f=p;break}if(f<0)return i;c=f,l=f+1}return(c+1)*1e6+r.length*1e4+o}a(oo,"patternSpecificity");function As(t,e){let n=String(t).split(/[/\\]/).join("/"),r,o=-1;for(let i of e??[])if(!(i.exclude??[]).some(s=>W(s).test(n))){for(let s of i.patterns??[])if(W(s).test(n)){let l=oo(s,n);l>o&&(o=l,r=i.name)}}return r}a(As,"layerForRelativePath");function se(t,e,n){return In(t,e,n==="stars"?"stars":"path")}a(se,"sliceIdForPath");function We(t,e){return In(t,e?[...e]:void 0,wn)}a(We,"legacyStarsSliceIdForPath");var wn="stars-4.8.23";function In(t,e,n){if(!e?.length)return;let r=String(t).split(/[/\\]/).filter(Boolean);if(r.length===0)return;let o=new Set;for(let i of e){if(typeof i!="string"||i.length===0)continue;let s=io(i);if(s.anchored){let l=ao(r,s.anchored,n);if(l)return l;continue}s.bare!==void 0&&o.add(s.bare)}return fo(r,o)}a(In,"sliceIdWithBinding");var ye=new Map;function io(t){let e=ye.get(t);if(e)return e;let n={};return vn(t)?n={anchored:so(t)}:!t.includes("/")&&!t.includes("\\")&&!t.includes("*")&&(n={bare:t.toLowerCase()}),ye.size>=1024&&ye.clear(),ye.set(t,n),n}a(io,"parsedSliceFolder");function vn(t){let e=t.split(/[/\\]/).filter(n=>n.length>0);return e.length<2||e[0]==="*"||e[0]==="**"?!1:e.some(n=>n==="*")}a(vn,"isAnchoredSliceEntry");function so(t){return t.split(/[/\\]/).filter(e=>e.length>0).map(e=>e.toLowerCase())}a(so,"anchoredSlicePattern");function ao(t,e,n){let r=An(t,e[0]??"");for(let o of r){let i=lo(t,e,o,n);if(i)return i}}a(ao,"anchoredSliceIdFromPattern");function lo(t,e,n,r="path"){let o=[],i=[],s=-1,l=n;for(let c=0;c<e.length;c+=1){let d=e[c];if(d==="*"){if(l>=t.length-1){for(let f=c;f<e.length;f+=1)if(e[f]!=="*")return;break}o.push(t[l].toLowerCase()),i.push(!0),l+=1;continue}if(d==="**"||l>=t.length||t[l].toLowerCase()!==d)return;o.push(t[l].toLowerCase()),i.push(!1),s=o.length-1,l+=1}if(o.length!==0)return r===wn?s<0?void 0:o.slice(s).join("/"):r==="stars"?s<0?void 0:o.filter((c,d)=>d>=s||i[d]).join("/"):o.join("/")}a(lo,"bindAnchoredSlice");function bn(t){let e=-1;for(let r=0;r<t.length;r+=1)t[r]!=="*"&&(e=r);if(e<0)return null;let n=[];for(let r=0;r<t.length;r+=1)(r>=e||t[r]==="*")&&n.push(r);return n}a(bn,"starsKeptSegmentIndexes");function ks(t){let e=[];for(let n of t??[]){if(!n||n.sliceIdentity!=="stars")continue;let r=new Map,o=new Map;for(let i of n.sliceFolders??[]){if(typeof i!="string"||i.length===0)continue;let s=co(i);if(!s)continue;let l=i.split(/[/\\]/).filter(f=>f.length>0).join("/").toLowerCase(),c=o.get(s)??new Set;if(c.has(l))continue;c.add(l),o.set(s,c);let d=r.get(s)??[];d.push(i),r.set(s,d)}for(let[i,s]of r)s.length<2||e.push({from:n.from,to:n.to,stem:i,paths:s,message:uo(n.from,n.to,s,i)})}return e}a(ks,"sliceIdentityCollisions");function co(t){if(!vn(t))return;let e=t.split(/[/\\]/).filter(r=>r.length>0).map(r=>r.toLowerCase());if(e.some(r=>r==="**"))return;let n=bn(e);if(n)return n.map(r=>e[r]).join("/")}a(co,"starsIdentityStem");function uo(t,e,n,r){let o=n.length===2?`${n[0]} and ${n[1]}`:`${n.slice(0,-1).join(", ")}, and ${n[n.length-1]}`;return`${t} \u2192 ${e}: sliceIdentity "stars" gives one slice id to ${o}. They bind as ${r}.`}a(uo,"formatSliceIdentityCollision");function fo(t,e){if(e.size!==0){for(let n=0;n<t.length-1;n+=1)if(e.has(t[n].toLowerCase())&&!(n+1>=t.length-1))return`${t[n].toLowerCase()}/${t[n+1].toLowerCase()}`}}a(fo,"bareSliceId");function po(t){let e=new Set;for(let n of t??[]){let o=ve(String(n)).split("/").filter(Boolean);for(let i=0;i<o.length;i+=1){let s=o[i];if((s==="**"||s==="*")&&i>0){let l=o[i-1];l&&!l.includes("*")&&!l.includes("{")&&!l.includes("}")&&e.add(l)}}}return[...e]}a(po,"inferSliceFoldersFromPatterns");function ze(t,e,n){if(Array.isArray(t.sliceFolders)&&t.sliceFolders.length>0)return t.sliceFolders.filter(o=>typeof o=="string"&&o.length>0);let r=(n??[]).find(o=>o.name===e);return po(r?.patterns)}a(ze,"resolveSliceFolders");function dn(t){return String(t).split(/[/\\]/).filter(e=>!!e&&e!==".").map(e=>e.toLowerCase())}a(dn,"normalizeSegments");function ae(t){let e=t.length;for(;e>0&&t[e-1]==="/";)e-=1;return t.slice(0,e)}a(ae,"trimTrailingSlashes");var go=["src","app"];function An(t,e){let n=(t[0]??"").toLowerCase(),r=e.toLowerCase();return go.includes(n)&&r!==n?[0,1]:[0]}a(An,"anchorOffsets");function mo(t){let e=ae(t.replace(/^[./]+/,""));return e==="*"||e==="**"}a(mo,"isBlanketRoot");function Se(t,e){if(!t||!e?.length)return!1;let n=String(t).split(/[/\\]/).join("/"),r=n.toLowerCase(),o=dn(n);for(let i of e){if(typeof i!="string"||i.length===0||mo(i))continue;if(i.includes("*")){let c=ae(i.toLowerCase());if(W(c).test(r)||W(`${c}/**`).test(r))return!0;continue}let s=dn(i);if(s.length===0)continue;let l=An(o,s[0]??"");for(let c of l){if(c+s.length>o.length)continue;let d=!0;for(let f=0;f<s.length;f+=1)if(o[c+f]!==s[f]){d=!1;break}if(d)return!0}}return!1}a(Se,"pathUnderSharedRoot");function un(t,e){let n=String(t).split(/[/\\]/).filter(Boolean).join("/").toLowerCase();if(!n)return!1;let r=e.toLowerCase();return n===r?!0:!n.includes("/")&&r.endsWith(`/${n}`)}a(un,"sliceMatchesDeclaration");function fn(t,e,n){return!t?.length||!e||!n?!1:t.some(r=>r&&typeof r.from=="string"&&typeof r.to=="string"&&un(r.from,e)&&un(r.to,n))}a(fn,"crossSliceEdgeAllowed");function ho(t){if(!t.fromPath)return{denied:!0,reason:"missing-path"};if(t.folderCount<=0)return{denied:!0,reason:"no-slice-folders"};let e=!!t.fromSlice||t.fromShared===!0;if(!t.toPath)return e?t.fromSlice?{denied:!0,reason:"missing-path"}:{denied:!1}:{denied:!0,reason:"unclassifiable-path"};let n=!!t.toSlice||t.toShared===!0;return!e||!n?{denied:!0,reason:"unclassifiable-path"}:t.sharedImportsSlice==="deny"&&t.fromShared===!0&&t.toSlice&&!t.fromSlice?{denied:!0,reason:"shared-imports-slice"}:!t.fromSlice||!t.toSlice?{denied:!1}:t.fromSlice===t.toSlice?{denied:!1}:t.crossSliceAllowed?{denied:!1}:{denied:!0,reason:"cross-slice"}}a(ho,"peerIsolationDecision");function kn(t){return ae(t.trim().replace(/\\/g,"/")).toLowerCase()}a(kn,"aliasGlobPattern");function En(t,e){let n=kn(t);if(!n||n==="*"||n==="**")return!1;let r=String(e).replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),o=qe(r),i=W(n),l=(n.split("/").pop()??"").includes("*")?null:W(`${n}/**`),c=a(d=>i.test(d)||l!==null&&l.test(d),"hit");return c(r)||o!==r&&c(o)}a(En,"aliasGlobMatches");function Es(t,e){return!t||!e?.length?!1:Se(t,[...e])?!0:e.some(n=>typeof n=="string"&&En(n,t))}a(Es,"pathMatchesSharedWalkStop");function Je(t){let e=kn(t).split("/").filter(Boolean);return e.length<2||e.some(n=>n.includes("*")||n==="."||n==="..")?null:{universeId:e.slice(0,-1).join("/"),childId:e.join("/")}}a(Je,"splitAliasTarget");function Rn(t,e){for(let n of e.childSlices?.sliceAliases??[])if(!(!n||typeof n.from!="string"||typeof n.to!="string")&&En(n.from,t))return n;return null}a(Rn,"firstSliceAliasEntry");function yo(t,e){let n=Rn(t,e);return n?Je(n.to):null}a(yo,"firstSliceAlias");function Ue(t,e,n){if(!t)return{};let r=n??e.sliceFolders,o=se(t,r?[...r]:void 0,e.sliceIdentity),i=we(t,o,e.childSlices);if(o||i.childId||i.mismatched)return i.childId?{universeId:o,childId:i.childId}:{universeId:o};let s=yo(t,e);return s?{universeId:s.universeId,childId:s.childId}:{}}a(Ue,"resolveGovernedSlice");function So(t){let e=[];for(let n of t??[]){if(typeof n!="string"||n.length===0)continue;let r=n.split(/[/\\]/).filter(Boolean).map(l=>l.toLowerCase());if(r.length===1&&r[0]&&!r[0].includes("*")){e.push({literals:[r[0],null],legacy:[r[0],null]});continue}if(r.some(l=>l==="**"||l.includes("*")&&l!=="*"))continue;let o=bn(r);if(!o||!r.includes("*"))continue;let i=a(l=>l==="*"?null:l,"star"),s=o.find(l=>r[l]!=="*")??0;e.push({literals:o.map(l=>i(r[l]??"")),legacy:r.slice(s).map(i)})}return e}a(So,"starsUniverseShapes");function pn(t,e){return t.length===e.length&&t.every((n,r)=>n===null||e[r]==="*"||n===e[r])}a(pn,"literalsMatch");function V(t,e){let n=e.split("/").filter(Boolean).map(i=>i.toLowerCase()),r=So(t);if(n.length===0||r.some(i=>pn(i.literals,n)))return[];let o=new Set;for(let i of r)if(i.legacy.length!==i.literals.length&&pn(i.legacy,n)){let s=[...n],l=i.literals.length-i.legacy.length;o.add([...i.literals.slice(0,l).map(()=>"*"),...s].join("/"))}return[...o].sort()}a(V,"legacyStarsIdTargets");function Pn(t,e){if(t.sliceIdentity!=="stars")return;let n=Je(e);if(n)return V(t.sliceFolders,n.universeId).length===1?n.universeId:void 0}a(Pn,"legacyAliasUniverse");function gn(t,e,n){let r=Ue(t,e,n);if(!t||e.sliceIdentity!=="stars")return r;if(r.universeId){let o=Rn(t,e);if(!se(t,[...n],e.sliceIdentity)&&o&&Pn(e,o.to)!==void 0)return{...r,legacyAlias:!0,legacyUniverse:r.universeId,legacyChild:r.childId};let s=We(t,n),l=e.childSlices,c=l?.sliceIdentity==="stars"?We(t,l.sliceFolders):void 0;return{...r,...s?{legacyUniverse:s}:{},...c&&r.childId?{legacyChild:c}:{}}}return r}a(gn,"placeForPair");function wo(t,e,n,r){let o=gn(n,t,e),i=gn(r,t,e),s=o.legacyUniverse,l=i.legacyUniverse,c=a((S,u)=>{if(!S.legacyAlias||u.legacyAlias||!u.universeId||u.legacyUniverse?.toLowerCase()!==S.universeId?.toLowerCase())return S;let y=S.childId?.split("/").pop();return{...S,universeId:u.universeId,...y?{childId:`${u.universeId}/${y}`}:{}}},"adopt"),d=c(o,i),f=c(i,o),p=fn(t.allowedCrossSlice,d.universeId,f.universeId)||t.sliceIdentity==="stars"&&(s!==d.universeId||l!==f.universeId)&&fn(t.allowedCrossSlice,s,l),m=t.childSlices?.sliceIdentity==="stars"&&o.legacyChild!==void 0&&i.legacyChild!==void 0&&o.legacyChild!==i.legacyChild&&Cn(t.childSlices.allowedCrossSlice,o.legacyChild,i.legacyChild),h=a(S=>({...S.universeId?{universeId:S.universeId}:{},...S.childId?{childId:S.childId}:{}}),"strip");return{from:h(d),to:h(f),crossSliceAllowed:p,legacyChildAllowed:m}}a(wo,"resolveGovernedSlicePair");function Io(t,e){switch(t){case"cross-slice":return`cross-slice edge ${e.fromSlice??"?"} \u2192 ${e.toSlice??"?"}. Extract the shared code, use events/ports across slices, or declare the edge in the rule's allowedCrossSlice.`;case"shared-imports-slice":return`shared root imports slice ${e.toSlice??"?"} (${e.fromPath??"?"} \u2192 ${e.toPath??"?"}). The wall is direct-only.`;case"unclassifiable-path":{let n=[e.fromSlice?void 0:e.fromPath,e.toSlice?void 0:e.toPath].filter(o=>!!o);return`unclassifiable path${n.length>0?` (${n.join(", ")})`:""} \u2014 ArkGate cannot place it in a slice, so it cannot prove this is not a cross-slice edge. Move it into a slice, or declare its root in the rule's sharedRoots.`}case"no-slice-folders":return"no slice folders \u2014 peerIsolation is on but no slice folder resolves from the rule or the layer patterns. Set sliceFolders on the rule.";default:return"no path evidence for this edge \u2014 peerIsolation needs the importer and importee paths."}}a(Io,"peerIsolationDenyExplanation");function vo(t,e){return`cross-parent slice ${t??"?"} \u2192 ${e??"?"}. The child wall cannot allow another universe.`}a(vo,"crossParentExplanation");function bo(t,e,n){return`cross-sibling slice ${t} \u2192 ${e} inside ${n}.`}a(bo,"crossSiblingExplanation");function Ao(t){return`universe common imports child ${t}. parentMayImportChild is off.`}a(Ao,"parentImportsChildExplanation");function mn(t){if(!t)return;let e=t.split("/").filter(Boolean);return e.length>0?e[e.length-1]:void 0}a(mn,"universePairLabel");function ko(t,e){if(!t||!e?.length)return!1;let n=t.toLowerCase();return e.some(r=>typeof r=="string"&&r.length>0&&r.toLowerCase()===n)}a(ko,"isCommonFolderName");function we(t,e,n){if(!t||!n?.sliceFolders?.length)return{};let r=se(t,n.sliceFolders,n.sliceIdentity);if(!r||!e)return{};let o=r.toLowerCase(),i=e.toLowerCase();if(o===i)return{};if(!o.startsWith(`${i}/`))return{mismatched:{childId:r,universeId:e}};let s=o.slice(i.length+1).split("/")[0];return ko(s,n.commonFolders)?{}:{childId:r}}a(we,"resolveChildSliceId");function Eo(t){return ae(t.trim().replace(/\\/g,"/")).toLowerCase()}a(Eo,"siblingEntryKey");function qe(t){return t.replace(/^(?:src|app)\//,"")}a(qe,"stripSrcOrApp");function Ro(t,e){let n=t.replace(/\\/g,"/").replace(/^\/+/,"").toLowerCase(),r=qe(e);if(!r)return!1;let o=qe(n);return n===r||n.startsWith(`${r}/`)||o===r||o.startsWith(`${r}/`)}a(Ro,"pathUnderSubtree");function Po(t,e,n){if(!e||!n?.length)return!1;let r=e.toLowerCase();for(let o of n){if(typeof o!="string")continue;let i=Eo(o);if(!(!i||i.includes("*"))&&(r===i||t&&Ro(t,i)))return!0}return!1}a(Po,"importerInEnforcedSubtree");function Co(t,e,n){return t==null||t==="deny"?!1:t==="advisory"?!0:t.default==="deny"?!1:!Po(e,n,t.enforce)}a(Co,"siblingCrossingAdvisory");function Ie(t){if(typeof t!="string")return null;let e=ae(t.trim().replace(/\\/g,"/")).toLowerCase();if(!e.includes("/"))return null;let n=e.split("/");for(let r of n)if(r.length===0||r==="."||r===".."||r.includes("*")&&r!=="*")return null;return n}a(Ie,"childSlicePatternSegments");function hn(t,e){let n=Ie(t),r=Ie(e);if(!n||!r||n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!=="*"&&i!==r[o])return!1}return!0}a(hn,"childSlicePatternMatches");function Cn(t,e,n){if(!t?.length)return!1;for(let r of t)if(!(!r||typeof r.from!="string"||typeof r.to!="string")&&hn(r.from,e)&&hn(r.to,n))return!0;return!1}a(Cn,"childCrossSliceAllowed");function xo(t,e){let n=Ie(t),r=Ie(e);if(!n||!r)return!1;let o=n.slice(0,-1),i=r.slice(0,-1);if(o.length!==i.length)return!0;for(let s=0;s<o.length;s+=1){let l=o[s],c=i[s];if(l==="*"||c==="*"||l!==c)return!0}return!1}a(xo,"childAllowanceSpansUniverses");function Lo(t){let e=ho({fromPath:t.fromPath,toPath:t.toPath,folderCount:t.folderCount,fromSlice:t.fromSlice,toSlice:t.toSlice,fromShared:t.fromShared,toShared:t.toShared,crossSliceAllowed:t.crossSliceAllowed,sharedImportsSlice:Sn(t.rule.sharedImportsSlice)});if(e.denied){let s=!!t.rule.childSlices&&e.reason==="cross-slice";return{crossing:e.reason==="cross-slice"?"cross-parent":"fail-closed",decision:"deny",...s?{reasonId:"CROSS_PARENT_SLICE"}:{},explanation:s?vo(t.fromSlice,t.toSlice):Io(e.reason??"missing-path",{fromPath:t.fromPath,toPath:t.toPath,fromSlice:t.fromSlice,toSlice:t.toSlice}),peerIsolationReason:e.reason,fromUniverse:t.fromSlice,toUniverse:t.toSlice}}let n=t.rule.childSlices;if(!n||!t.fromSlice||!t.toSlice||t.fromSlice!==t.toSlice||!t.toPath)return{crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};let r=t.fromChild??we(t.fromPath,t.fromSlice,n).childId,o=t.toChild??we(t.toPath,t.toSlice,n).childId,i={crossing:"none",decision:"allow",fromUniverse:t.fromSlice,toUniverse:t.toSlice};return r&&o&&r!==o?t.legacyChildAllowed||Cn(n.allowedCrossSlice,r,o)?i:{crossing:"cross-sibling",decision:Co(n.siblings,t.fromPath,r)?"advisory":"deny",reasonId:"CROSS_SIBLING_SLICE",explanation:bo(r,o,t.fromSlice),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:!r&&o&&n.parentMayImportChild!==!0?{crossing:"parent-imports-child",decision:"deny",explanation:Ao(o),fromUniverse:t.fromSlice,toUniverse:t.toSlice}:i}a(Lo,"evaluateNestedSliceWall");function xn(t){return t?.crossing==="cross-sibling"||t?.crossing==="parent-imports-child"}a(xn,"isChildWallCrossing");function Rs(t,e){return xn(e)?t?.childSlices?.message:t?.message}a(Rs,"sliceConsumerMessage");function Ps(t){let e=t.verdict.explanation,n=xn(t.verdict),r=n?t.childMessage:t.ruleMessage;if(t.surface==="intent"){let o=t.defaultMessage??`${t.fromLayer} must not reference ${t.toLayer} intent.`;return n&&e?`${t.childMessage??o} ${e}`:t.verdict.reasonId&&e?`${o} ${e}`:e&&t.verdict.peerIsolationReason!=="cross-slice"?`${o} ${e}`:r?e?`${r} (${e})`:r:o}if(r)return e?`${r} (${e})`:r;if(e){let o=t.kind??"import";return`${t.fromLayer} must not ${o} another slice of ${t.toLayer} (${t.fromPath} \u2192 ${t.toPath}): ${e}`}return`${t.fromLayer} must not ${t.kind??"import"} ${t.toLayer}.`}a(Ps,"composeSliceDenialMessage");function Cs(t){if(!t||t.decision==="allow")return{};let e=mn(t.fromUniverse),n=mn(t.toUniverse);return{...t.reasonId?{reasonId:t.reasonId}:{},...t.reasonId&&e&&n?{universeFrom:e,universeTo:n}:{},...t.decision==="advisory"?{failsStrict:!1,severity:"warning"}:{}}}a(Cs,"sliceFindingExtras");function xs(t,e){let n=[],r=new Set,o=new Set;for(let i of t??[])if(i?.peerIsolation&&i.allowed===!1&&n.push(...Oo(i,e)),!!i?.childSlices){if(!i.peerIsolation||i.allowed!==!1){n.push({ruleId:"CONFIG_CHILD_SLICES_INERT",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`${i.from} \u2192 ${i.to}: childSlices is inert on this rule and enforces nothing. The child wall runs only inside a universe wall. Add "peerIsolation": true and "allowed": false to the same rule, or remove childSlices.`});continue}for(let s of e){let l=se(s,i.sliceFolders,i.sliceIdentity),c=we(s,l,i.childSlices);if(!c.mismatched)continue;let d=`${i.from}\0${i.to}\0${c.mismatched.universeId}\0${c.mismatched.childId}`;r.has(d)||(r.add(d),n.push({ruleId:"CONFIG_CHILD_SLICE_EXTENDS",failsStrict:!1,fromLayer:i.from,toLayer:i.to,path:s,message:`${i.from} \u2192 ${i.to}: child id ${c.mismatched.childId} does not extend universe id ${c.mismatched.universeId} (${s}).`}))}for(let s of i.childSlices.allowedCrossSlice??[]){if(!s||typeof s.from!="string"||typeof s.to!="string"||!xo(s.from,s.to))continue;let l=`${s.from.trim().toLowerCase()}\0${s.to.trim().toLowerCase()}`;o.has(l)||(o.add(l),n.push({ruleId:"CONFIG_CHILD_SLICE_CROSS_UNIVERSE",failsStrict:!1,fromLayer:i.from,toLayer:i.to,message:`childSlices.allowedCrossSlice ${s.from} \u2192 ${s.to} cannot cross the universe wall. The universe wall still denies that edge.`}))}}return n}a(xs,"childSliceConfigFindings");function yn(t,e){let n=new Map;if(!t?.length)return n;for(let r of e){if(typeof r!="string")continue;let o=se(r,[...t],"stars"),i=We(r,t);if(!o||!i||o===i)continue;let s=n.get(i)??new Set;s.add(o),n.set(i,s)}return n}a(yn,"observedIdsByLegacy");function Ve(t,e,n,r){let o=r?`/${r}`:"",i=`${e[0]??t}${o}`,s=[...n.get(t.toLowerCase())??[]].sort().map(l=>`${l}${o}`);return s.length===1?`${s[0]}`:s.length>1?`${i} (one entry per module: ${s.join(", ")})`:i}a(Ve,"newIdHint");function Oo(t,e){let n=[],r=a(i=>n.push({ruleId:"CONFIG_SLICE_LEGACY_STARS_ID",failsStrict:!1,fromLayer:t.from,toLayer:t.to,message:`${t.from} \u2192 ${t.to}: ${i} It keeps its 4.8.23 meaning for this release only.`}),"push"),o=t.childSlices;if(t.sliceIdentity==="stars"){let i=yn(t.sliceFolders,e);for(let s of o?.sliceAliases??[]){if(!s||typeof s.to!="string")continue;let l=Je(s.to);if(!l||Pn(t,s.to)===void 0)continue;let c=V(t.sliceFolders,l.universeId),d=l.childId.split("/").pop();r(`sliceAliases to "${s.to}" is a 4.8.23 stars id (the star before the last literal was dropped). The id is now ${Ve(l.universeId,c,i,d)}; write that instead.`)}for(let s of t.allowedCrossSlice??[]){if(!s||typeof s.from!="string"||typeof s.to!="string")continue;let l=[s.from,s.to].filter(d=>d.includes("/")&&V(t.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?Ve(d,V(t.sliceFolders,d),i):d,"rename");r(`allowedCrossSlice ${s.from} \u2192 ${s.to} names a 4.8.23 stars id. The ids are now ${c(s.from)} \u2192 ${c(s.to)}; write those instead.`)}}if(o?.sliceIdentity==="stars"){let i=yn(o.sliceFolders,e);for(let s of o.allowedCrossSlice??[]){if(!s||typeof s.from!="string"||typeof s.to!="string")continue;let l=[s.from,s.to].filter(d=>V(o.sliceFolders,d).length>0);if(l.length===0)continue;let c=a(d=>l.includes(d)?Ve(d,V(o.sliceFolders,d),i):d,"rename");r(`childSlices.allowedCrossSlice ${s.from} \u2192 ${s.to} names a 4.8.23 stars id. The ids are now ${c(s.from)} \u2192 ${c(s.to)}; write those instead.`)}}return n}a(Oo,"legacyStarsIdFindings");function Ls(t){if(t!==null&&typeof t=="object"){let e=t.ratchet;if(e===!0)return"always";if(e===!1)return"never"}return"auto"}a(Ls,"siblingRatchetMode");function Ln(t,e,n,r){return $o(t,e,n,r)?.rule}a(Ln,"findDeniedEdgeRule");function $o(t,e,n,r){for(let o of t??[])if(!(o.from!==e||o.to!==n)&&o.allowed===!1){if(o.peerIsolation){let i=r?.fromPath,s=r?.toPath,l=ze(o,e,r?.layers),c=wo(o,l,i,s),d=c.from,f=c.to,p=d.universeId,m=f.universeId,h=Lo({rule:o,fromPath:i,toPath:s,folderCount:l.length,fromSlice:p,toSlice:m,fromChild:d.childId,toChild:f.childId,fromShared:!p&&Se(i,o.sharedRoots),toShared:!m&&Se(s,o.sharedRoots),crossSliceAllowed:c.crossSliceAllowed,legacyChildAllowed:c.legacyChildAllowed});if(h.decision!=="allow")return{rule:o,peerIsolationReason:h.peerIsolationReason,fromSlice:p,toSlice:m,sliceVerdict:h};continue}if(e!==n)return{rule:o}}}a($o,"findDeniedEdgeDecision");function Os(t,e,n,r){let o=r?.fromPath,i=r?.toPath;if(!(!o||!i))for(let s of t??[]){if(s.from!==e||s.to!==n||s.allowed!==!1||!s.peerIsolation||Sn(s.sharedImportsSlice)==="deny")continue;let l=ze(s,e,r?.layers),c=Ue(o,s,l).universeId,d=Ue(i,s,l).universeId;if(!(c||!d)&&Se(o,s.sharedRoots))return{fromPath:o,toPath:i,toSlice:d}}}a(Os,"findSharedImportsSliceBridge");function $s(t,e,n){return ze(t,e,n)}a($s,"peerSliceFolders");async function On(t,e){if(e.mode==="off"||!e.architectureProfile)return;let n=t.metadata.source;if(!n||n==="unknown")return;let r=e.architectureProfile,o=r.resolveLayer(n),i=r.resolveLayer(t.intent);if(!o||!i)return;let s=Ln(r.rules.filter(f=>f.peerIsolation!==!0),o,i);if(!s)return;let l=e.mode,c=s.message??`Observed layer violation: "${n}" (${o}) must not produce "${t.intent}" (${i}).`,d={source:n,intent:t.intent,fromLayer:o,toLayer:i,severity:l,message:c,rule:s};if(e.appendTrace({type:"layer.observedViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:d}),await e.recordAudit("layer.observedViolation",t,d),l==="hard")throw new re(n,t.intent,o,i,c)}a(On,"assertObservedLayerFlowAllowed");async function $n(t,e){let n=e.getPolicyContext(t),r;try{r=e.policyEngine.enforce(n)}catch(o){throw o instanceof O&&(e.appendTrace({type:"policy.hardViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:o.violations}}),await e.recordAudit("policy.hardViolation",t,{violations:o.violations})),o}r.softViolations.length>0&&(e.appendTrace({type:"policy.softViolation",timestamp:new Date().toISOString(),intent:t.intent,correlationId:t.metadata.correlationId,traceId:t.metadata.traceId,spanId:t.metadata.spanId,details:{violations:r.softViolations}}),await e.recordAudit("policy.softViolation",t,{violations:r.softViolations}),e.onSoftViolation&&await e.safeHook(()=>e.onSoftViolation(r,t),"onSoftViolation",t))}a($n,"enforcePublishPolicy");function Do(t,e){t.history.push(e),t.maxHistorySize!==void 0&&t.history.length>t.maxHistorySize&&t.history.splice(0,t.history.length-t.maxHistorySize)}a(Do,"appendHistory");function D(t,e){t.trace.push(e),t.maxHistorySize!==void 0&&t.trace.length>t.maxHistorySize&&t.trace.splice(0,t.trace.length-t.maxHistorySize);for(let n of t.traceSinks)try{n(e)}catch{}}a(D,"appendTrace");async function le(t,e,n,r){if(t.auditTrail)try{await t.auditTrail.record({type:e,source:n.metadata.source,intent:n.intent,correlationId:n.metadata.correlationId,causationId:n.metadata.causationId,subject:n.intent,details:r})}catch(o){D(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{hook:"auditTrail",error:o instanceof Error?o.message:String(o)}})}}a(le,"recordAudit");async function Dn(t,e){let n={intent:e.intent,source:e.metadata.source,suggestion:"Publish through a registered intent creator so strict registry, contracts, and agent tooling share one source of truth."};D(t,{type:"event.rawPublish",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:n}),await le(t,"event.rawPublish",e,n)}a(Dn,"recordRawPublishDiagnostic");async function Nn(t,e,n,r){let o={event:e,publishedAt:new Date().toISOString(),subscribersNotified:n};Do(t,o);let i=await t.eventBuffer?.enqueue(e,r);return D(t,{type:"event.published",timestamp:o.publishedAt,intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{subscribersNotified:n}}),await le(t,"event.published",e,{subscribersNotified:n}),{record:o,bufferRecord:i??void 0}}a(Nn,"recordSuccessfulPublish");async function Tn(t,e,n,r){let o=t.eventBuffer;if(o)try{r.ok?await o.markDispatched(n):await o.markFailed(n,r.error)}catch(i){D(t,{type:"hook.error",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:{hook:"eventBuffer",error:i instanceof Error?i.message:String(i)}})}}a(Tn,"settleBufferRecord");async function Mn(t,e,n,r){let o={transport:r,error:n instanceof Error?n.message:String(n)};D(t,{type:"event.handoffFailed",timestamp:new Date().toISOString(),intent:e.intent,correlationId:e.metadata.correlationId,traceId:e.metadata.traceId,spanId:e.metadata.spanId,details:o}),await le(t,"event.handoffFailed",e,o)}a(Mn,"recordHandoffFailure");function Ye(t,e,n){return{...t,...e,occurredAt:e.occurredAt||t.occurredAt||new Date().toISOString(),source:e.source||t.source||"unknown",kernelInstanceId:e.kernelInstanceId??t.kernelInstanceId??n,eventVersion:e.eventVersion??t.eventVersion,schemaVersion:e.schemaVersion??t.schemaVersion,allowInterception:e.allowInterception??t.allowInterception,interceptions:e.interceptions??t.interceptions,correlationId:e.correlationId??t.correlationId,causationId:e.causationId??t.causationId,traceId:e.traceId??t.traceId,spanId:e.spanId??t.spanId,parentSpanId:e.parentSpanId??t.parentSpanId}}a(Ye,"enrichMetadata");function No(){let t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID().replace(/-/g,"").slice(0,10):Math.random().toString(36).slice(2,12).padEnd(10,"0")}a(No,"randomNonce");var To=No(),Fn=new Map;function k(t){let e=(Fn.get(t)??0)+1;return Fn.set(t,e),`${t}-${Date.now()}-${To}-${e}`}a(k,"nextRuntimeId");function Mo(){return k("interceptor")}a(Mo,"nextInterceptorRegistrationId");var U=class{static{a(this,"EventBusImpl")}subscriptions=[];subscriptionsByIntent=new Map;interceptors=[];interceptorsByIntent=new Map;recording;onPublish;onSoftViolation;onHandlerError;eventContracts;strictEventContracts;requireKnownSource;architectureProfile;enforceObservedLayerFlowMode;rethrowHandlerErrors;settleBufferOnLocalDelivery;policyEngine;getPolicyContext;intentRegistry;dependencyGraph;strictRegistry;validateIntentNaming;constructor(e={}){if(this.onPublish=e.onPublish,this.onSoftViolation=e.onSoftViolation,this.onHandlerError=e.onHandlerError,this.eventContracts=e.eventContracts,this.strictEventContracts=e.strictEventContracts??!1,this.requireKnownSource=e.requireKnownSource??!1,this.architectureProfile=e.architectureProfile,this.enforceObservedLayerFlowMode=e.enforceObservedLayerFlow??"off",this.rethrowHandlerErrors=e.rethrowHandlerErrors??!1,this.settleBufferOnLocalDelivery=e.settleBufferOnLocalDelivery??!1,this.intentRegistry=e.intentRegistry,this.dependencyGraph=e.dependencyGraph,this.strictRegistry=e.strictRegistry??e.intentRegistry!==void 0,this.validateIntentNaming=e.validateIntentNaming??this.strictRegistry,this.recording={history:[],trace:[],maxHistorySize:e.maxHistorySize,traceSinks:[...e.traceSinks??[]],auditTrail:e.auditTrail,eventBuffer:e.eventBuffer??e.outbox,instanceId:e.instanceId},e.policyEngine?this.policyEngine=e.policyEngine:e.policies&&e.policies.length>0&&(this.policyEngine=new B(e.policies)),(this.policyEngine?.getPolicies()??e.policies??[]).some(Be)&&!e.intentRegistry&&!e.dependencyGraph&&!e.getPolicyContext)throw new te;e.getPolicyContext?this.getPolicyContext=e.getPolicyContext:e.intentRegistry||e.dependencyGraph?this.getPolicyContext=Ge({intentRegistry:e.intentRegistry,dependencyGraph:e.dependencyGraph}):this.getPolicyContext=r=>({event:r})}async publish(e,n,r,o){await this.dispatch(e,n,r,o)}async dispatch(e,n,r,o={}){let i=o.notifySubscribers!==!1,s=o.awaitHandlers!==!1,l=o.runOnPublish!==!1,c,d=typeof e!="function";if(d){let u=e,y=r??n??{};c={...u,metadata:Ye(u.metadata,y,this.recording.instanceId)}}else{let u=e,y=n,g=r??{},v=u(y);c={...v,metadata:Ye(v.metadata,g,this.recording.instanceId)}}d&&this.strictRegistry&&await Dn(this.recording,c),oe(c.intent,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),on(c,{requireKnownSource:this.requireKnownSource,intentRegistry:this.intentRegistry}),ie(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),c=await an(c,{interceptorsForIntent:a(u=>this.interceptorsByIntent.get(u)??[],"interceptorsForIntent"),eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts,appendTrace:a(u=>this.appendTrace(u),"appendTrace"),recordAudit:a((u,y,g)=>this.recordAudit(u,y,g),"recordAudit")}),ie(c,{eventContracts:this.eventContracts,strictEventContracts:this.strictEventContracts}),await On(c,{mode:this.enforceObservedLayerFlowMode,architectureProfile:this.architectureProfile,appendTrace:a(u=>this.appendTrace(u),"appendTrace"),recordAudit:a((u,y,g)=>this.recordAudit(u,y,g),"recordAudit")}),this.dependencyGraph?.registerEventFlow(c.metadata.source,c.intent);let f=[...this.subscriptionsByIntent.get(c.intent)??[]];this.policyEngine&&await $n(c,{policyEngine:this.policyEngine,getPolicyContext:this.getPolicyContext,appendTrace:a(u=>this.appendTrace(u),"appendTrace"),recordAudit:a((u,y,g)=>this.recordAudit(u,y,g),"recordAudit"),onSoftViolation:this.onSoftViolation,safeHook:a((u,y,g)=>this.safeHook(u,y,g),"safeHook")});let{bufferRecord:p}=await Nn(this.recording,c,i?f.length:0,o.tx);p&&o.onBufferRecord?.(p);let m=p!==void 0&&(o.settleBufferOnLocalDelivery??this.settleBufferOnLocalDelivery),h=(async()=>{i&&await Promise.all(f.map(u=>this.invokeHandler(u,c))),l&&this.onPublish&&await this.safeHook(()=>this.onPublish(c),"onPublish",c)})(),S=m?h.then(()=>this.settleBufferRecord(c,p.id,{ok:!0}),async u=>{throw await this.settleBufferRecord(c,p.id,{ok:!1,error:u}),u}):h;return s?await S:S.then(void 0,()=>{}),c}async settleBufferRecord(e,n,r){await Tn(this.recording,e,n,r)}async recordHandoffFailure(e,n,r){await Mn(this.recording,e,n,r)}createPublisher(e){let n=typeof e=="string"?e:e.name;return oe(n,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry}),{source:n,publish:a(async(r,o,i={},s)=>{if(i.source&&i.source!==n)throw new $(n,i.source);await this.publish(r,o,{...i,source:n},s)},"publish")}}subscribe(e,n){let r=typeof e=="string"?e:e.name;oe(r,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let o={intentName:r,handler:n};this.subscriptions.push(o);let i=this.subscriptionsByIntent.get(r)??[];return i.push(o),this.subscriptionsByIntent.set(r,i),()=>{let s=this.subscriptions.indexOf(o);s>=0&&this.subscriptions.splice(s,1);let l=this.subscriptionsByIntent.get(r);if(!l)return;let c=l.indexOf(o);c>=0&&l.splice(c,1),l.length===0&&this.subscriptionsByIntent.delete(r)}}registerInterceptor(e,n,r){let o=typeof e=="string"?e:e.name;oe(o,{strictRegistry:this.strictRegistry,validateIntentNaming:this.validateIntentNaming,intentRegistry:this.intentRegistry});let i={registrationId:Mo(),interceptorId:r??o,intentName:o,interceptor:n,createdAt:new Date().toISOString()};this.interceptors.push(i);let s=this.interceptorsByIntent.get(o)??[];return s.push(i),this.interceptorsByIntent.set(o,s),i.registrationId}unregisterInterceptor(e){let n=this.interceptors.find(i=>i.registrationId===e);if(!n)return!1;let r=this.interceptors.indexOf(n);r>=0&&this.interceptors.splice(r,1);let o=this.interceptorsByIntent.get(n.intentName);if(o){let i=o.indexOf(n);i>=0&&o.splice(i,1),o.length===0&&this.interceptorsByIntent.delete(n.intentName)}return!0}listInterceptors(e){return this.interceptors.filter(n=>!e||n.intentName===e).map(n=>({registrationId:n.registrationId,interceptorId:n.interceptorId,intent:n.intentName,createdAt:n.createdAt,lastInterceptedAt:n.lastInterceptedAt}))}getHistory(){return[...this.recording.history]}clearHistory(){this.recording.history.length=0}getTrace(){return[...this.recording.trace]}clearTrace(){this.recording.trace.length=0}appendTrace(e){D(this.recording,e)}async recordAudit(e,n,r){await le(this.recording,e,n,r)}async invokeHandler(e,n){try{await Promise.resolve(e.handler(n))}catch(r){if(this.appendTrace({type:"handler.error",timestamp:new Date().toISOString(),intent:n.intent,correlationId:n.metadata.correlationId,traceId:n.metadata.traceId,spanId:n.metadata.spanId,details:{error:r instanceof Error?r.message:String(r)}}),await this.recordAudit("handler.error",n,{handlerIntent:e.intentName,error:r instanceof Error?r.message:String(r)}),this.onHandlerError&&await this.safeHook(()=>this.onHandlerError(r,n,e.intentName),"onHandlerError",n),this.rethrowHandlerErrors)throw r}}async safeHook(e,n,r){try{await Promise.resolve(e())}catch(o){this.appendTrace({type:"hook.error",timestamp:new Date().toISOString(),intent:r.intent,correlationId:r.metadata.correlationId,traceId:r.metadata.traceId,spanId:r.metadata.spanId,details:{hook:n,error:o instanceof Error?o.message:String(o)}}),await this.recordAudit("hook.error",r,{hook:n,error:o instanceof Error?o.message:String(o)})}}};function Fo(t){return new U(t)}a(Fo,"createEventBus");function _o(t){if(!(!t||t.length===0))return t.map(e=>typeof e=="object"&&e!==null&&"key"in e?String(e.key):String(e)).join(".")}a(_o,"formatStandardSchemaPath");function Bo(t){if(Array.isArray(t))return"array";if(t===null)return"object";let e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="object"?e:"unknown"}a(Bo,"actualType");function jo(t,e){return t?`${t}.${e}`:e}a(jo,"formatPath");function _n(t,e,n,r,o){let i=Bo(t);if(e.type!=="unknown"&&i!==e.type){o.push({intent:r.intent,version:r.version,field:n,message:`Expected ${e.type}, received ${i}.`});return}if(e.enum&&!e.enum.some(s=>Object.is(s,t))&&o.push({intent:r.intent,version:r.version,field:n,message:"Value is not allowed by event contract enum."}),e.type==="object"&&e.fields){if(t===null||typeof t!="object"||Array.isArray(t)){o.push({intent:r.intent,version:r.version,field:n,message:"Nested object field must be a non-array object."});return}Bn(t,e.fields,r,o,n)}e.type==="array"&&e.items&&Array.isArray(t)&&t.forEach((s,l)=>{_n(s,e.items,`${n}[${l}]`,r,o)})}a(_n,"validateSchemaField");function Bn(t,e,n,r,o){for(let[i,s]of Object.entries(e)){let l=jo(o,i),c=t[i];if(c===void 0){s.required&&r.push({intent:n.intent,version:n.version,field:l,message:"Required field is missing."});continue}_n(c,s,l,n,r)}}a(Bn,"validateObjectSchema");var be=class{static{a(this,"EventContractRegistryImpl")}contracts=new Map;register(e){let n=this.key(e.intent,e.version);if(this.contracts.has(n))throw new Error(`Event contract "${n}" is already registered.`);this.contracts.set(n,{allowAdditionalFields:!0,...e})}get(e,n){return n?this.contracts.get(this.key(e,n)):this.list(e).at(-1)}list(e){return Array.from(this.contracts.values()).filter(n=>!e||n.intent===e)}validate(e){let n=e.metadata.eventVersion,r=this.get(e.intent,n),o=[];if(!r)return{ok:!1,issues:[{intent:e.intent,version:n,message:n?`No event contract registered for version "${n}".`:"No event contract registered for intent."}]};r.deprecated&&o.push({intent:e.intent,version:r.version,message:typeof r.deprecated=="string"?r.deprecated:"Event contract is deprecated."});let i=e.payload!=null&&typeof e.payload=="object"?e.payload:void 0;if(r.schema){if(!i)o.push({intent:e.intent,version:r.version,message:"Payload must be an object for schema validation."});else if(Bn(i,r.schema,r,o),r.allowAdditionalFields===!1)for(let s of Object.keys(i))r.schema[s]||o.push({intent:e.intent,version:r.version,field:s,message:"Additional field is not allowed by event contract."})}if(r.standardSchema){let s=r.standardSchema["~standard"].validate(e.payload);if(s instanceof Promise)o.push({intent:e.intent,version:r.version,message:"Standard Schema validator returned a Promise; event contract validation is synchronous."});else if(s.issues)for(let l of s.issues)o.push({intent:e.intent,version:r.version,field:_o(l.path),message:l.message})}return{ok:o.length===0,contract:r,issues:o}}clear(){this.contracts.clear()}key(e,n){return`${e}@${n}`}};function Xe(){return new be}a(Xe,"createEventContractRegistry");function Go(){return k("outbox")}a(Go,"nextOutboxId");function jn(t){return{...t,event:{...t.event,metadata:{...t.event.metadata}}}}a(jn,"cloneRecord");var Ho=1e4,q=class{static{a(this,"InMemoryEventBuffer")}records=new Map;maxRecords;evictedPendingIds=new Set;evictedPendingCount=0;constructor(e={}){let n=e.maxRecords;this.maxRecords=typeof n=="number"&&!Number.isNaN(n)&&n>=0?n:1/0}get evictedPending(){return this.evictedPendingCount}trackEvictedPending(e){for(this.evictedPendingCount+=1,this.evictedPendingIds.add(e);this.evictedPendingIds.size>Ho;){let n=this.evictedPendingIds.values().next().value;this.evictedPendingIds.delete(n)}}settleEvicted(e){this.evictedPendingIds.delete(e)&&(this.evictedPendingCount-=1)}evictOverflow(){for(;this.records.size>this.maxRecords;){let e;for(let[n,r]of this.records)if(r.status!=="pending"){e=n;break}e===void 0&&(e=this.records.keys().next().value,this.trackEvictedPending(e)),this.records.delete(e)}}async enqueue(e){let n=new Date().toISOString(),r={id:Go(),event:e,status:"pending",attempts:0,createdAt:n,updatedAt:n};this.records.set(r.id,r);let o=jn(r);return this.evictOverflow(),o}async markDispatched(e){let n=this.records.get(e);if(!n){this.settleEvicted(e);return}n.status="dispatched",n.updatedAt=new Date().toISOString()}async markFailed(e,n){let r=this.records.get(e);if(!r){this.settleEvicted(e);return}r.status="failed",r.attempts+=1,r.error=n instanceof Error?n.message:String(n),r.updatedAt=new Date().toISOString()}async list(e){return Array.from(this.records.values()).filter(n=>!e||n.status===e).map(jn)}async clear(){this.records.clear(),this.evictedPendingIds.clear()}},Ko=q;function Ze(t){return`${t.from}->${t.to}`}a(Ze,"flowKey");function Gn(t){let e=new Set,n=[];for(let r of t){let o=Ze(r);e.has(o)||(e.add(o),n.push(r))}return n}a(Gn,"uniqueFlows");function Hn(t,e){let n=new Set(e.map(Ze));return t.filter(r=>!n.has(Ze(r)))}a(Hn,"difference");function Qe(t){let e=t.registry,n=t.eventBus,r=t.graph;return{report(){let o=e?e.getAllRelationships().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})):[],i=o.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="produces").map(u=>({from:u.from,to:u.to})),s=n?.getHistory().map(u=>({from:u.event.metadata.source,to:u.event.intent}))??[],l=s.length>0||!r?[]:r.getEdges().filter(u=>u.kind==="observed").map(u=>({from:u.from,to:u.to})),c=Gn([...o,...i]),d=Gn([...s,...l]),f=d.filter(u=>!u.from||u.from==="unknown"),p=e?Array.from(new Set(d.map(u=>u.from).filter(u=>u&&u!=="unknown"&&!e.has(u)))):[],m=e?Array.from(new Set(d.map(u=>u.to).filter(u=>!e.has(u)))):[],h=new Set(d.flatMap(u=>[u.from,u.to])),S=e?e.list().map(u=>u.name).filter(u=>!h.has(u)):[];return{generatedAt:new Date().toISOString(),declaredProductions:c,observedProductions:d,declaredButUnobserved:Hn(c,d),observedButUndeclared:Hn(d.filter(u=>u.from!=="unknown"),c),unknownSources:f,unregisteredObservedSources:p,unregisteredObservedIntents:m,registeredButNeverObserved:S}}}}a(Qe,"createObservabilityReporter");function Vo(){return k("audit")}a(Vo,"createAuditId");function Wo(t,e){return!(e.type&&t.type!==e.type||e.intent&&t.intent!==e.intent||e.correlationId&&t.correlationId!==e.correlationId||e.subject&&t.subject!==e.subject||e.since&&t.timestamp<e.since||e.until&&t.timestamp>e.until)}a(Wo,"matchesQuery");var Ae=class{constructor(e){this.maxRecords=e}maxRecords;static{a(this,"InMemoryAuditStore")}records=[];append(e){this.records.push(e),this.maxRecords!==void 0&&this.records.length>this.maxRecords&&this.records.splice(0,this.records.length-this.maxRecords)}query(e={}){let n=this.records.filter(r=>Wo(r,e));return e.limit===void 0?[...n]:n.slice(-e.limit)}clear(){this.records.length=0}},et=class{constructor(e){this.store=e}store;static{a(this,"AuditTrailImpl")}async record(e){let n={id:Vo(),timestamp:e.timestamp??new Date().toISOString(),type:e.type,source:e.source,actor:e.actor,intent:e.intent,correlationId:e.correlationId,causationId:e.causationId,subject:e.subject,details:e.details};return await this.store.append(n),n}async query(e){return this.store.query(e)}async clear(){await this.store.clear()}};function tt(t={}){return new et(t.store??new Ae(t.maxRecords))}a(tt,"createAuditTrail");var nt=class{static{a(this,"DependencyGraphImpl")}nodes=new Map;edges=[];registerDependency(e,n,r="declared"){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:r})}registerEventFlow(e,n){this.ensureNode(e),this.ensureNode(n),this.addEdge({from:e,to:n,kind:"observed"})}getNodes(){return Array.from(this.nodes.values())}getEdges(){return[...this.edges]}toJSON(){return{nodes:this.getNodes(),edges:this.getEdges()}}toMermaid(){let e=`flowchart TD
|
|
6
|
+
`;for(let r of this.edges){let o=r.kind?`|${r.kind}|`:"";e+=` ${this.safeId(r.from)} -->${o} ${this.safeId(r.to)}
|
|
7
|
+
`}let n=new Set(this.edges.flatMap(r=>[r.from,r.to]));for(let r of this.nodes.keys())n.has(r)||(e+=` ${this.safeId(r)}
|
|
8
|
+
`);return e.trim()}toLayerMermaid(e){let n=new Map;for(let i of this.nodes.keys()){let s=e.resolveLayer(i)??"Unclassified",l=n.get(s)??[];l.push(i),n.set(s,l)}let r=`flowchart TD
|
|
9
|
+
`;for(let i of e.layers){let s=n.get(i.name)??[];if(s.length!==0){r+=` subgraph ${this.safeId(i.name)}[${i.name}]
|
|
10
|
+
`;for(let l of s)r+=` ${this.safeId(l)}[${l}]
|
|
11
|
+
`;r+=` end
|
|
12
|
+
`}}let o=n.get("Unclassified")??[];if(o.length>0){r+=` subgraph Unclassified[Unclassified]
|
|
13
|
+
`;for(let i of o)r+=` ${this.safeId(i)}[${i}]
|
|
14
|
+
`;r+=` end
|
|
15
|
+
`}for(let i of this.edges){let s=i.kind?`|${i.kind}|`:"";r+=` ${this.safeId(i.from)} -->${s} ${this.safeId(i.to)}
|
|
16
|
+
`}return r.trim()}detectViolations(e=[]){let n=[],r=this.findSimpleCycles();r.length>0&&n.push(`Cycle detected: ${r.map(o=>o.join("->")).join(", ")}`);for(let o of e)try{let i=o(this.edges);i&&i.length&&n.push(...i)}catch(i){n.push(`Rule error: ${i.message}`)}return n}ensureNode(e){this.nodes.has(e)||this.nodes.set(e,{id:e})}addEdge(e){this.edges.some(r=>r.from===e.from&&r.to===e.to&&r.kind===e.kind)||this.edges.push(e)}findSimpleCycles(){let e=new Map;for(let l of this.edges)e.has(l.from)||e.set(l.from,[]),e.get(l.from).push(l.to);let n=[],r=new Set,o=[],i=a(l=>{r.add(l),o.push(l);for(let c of e.get(l)||[])if(!r.has(c))i(c);else if(o.includes(c)){let d=o.indexOf(c),f=o.slice(d).concat(c);n.push(f)}o.pop()},"dfs");for(let l of e.keys())r.has(l)||i(l);let s=new Set(n.map(l=>l.join("->")));return Array.from(s).map(l=>l.split("->"))}safeId(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}};function rt(){return new nt}a(rt,"createDependencyGraph");function ot(t,e,n={}){let r=n.requireRegisteredTargets??!1;for(let o of t.getAllRelationships())r&&!t.has(o.to)||(o.kind==="dependsOn"?e.registerDependency(o.from,o.to,"declared"):e.registerDependency(o.from,o.to,"produces"))}a(ot,"syncRegistryToGraph");var it=class{static{a(this,"MetadataRegistryImpl")}entities=new Map;entity(e,n,r={}){if(this.entities.has(e)&&!r.allowOverwrite)throw new Error(`Entity metadata "${e}" is already registered.`);let o={name:e,fields:{},...n};return this.entities.set(e,o),o}getEntity(e){return this.entities.get(e)}listEntities(){return Array.from(this.entities.values())}findEntitiesByIntent(e){return this.listEntities().filter(n=>n.emits?.includes(e)||n.consumes?.includes(e))}validate(){let e=[];for(let n of this.entities.values()){n.name.trim()||e.push({entity:n.name,message:"Entity name is required."});for(let[r,o]of Object.entries(n.fields))r.trim()||e.push({entity:n.name,field:r,message:"Field name is required."}),(!o.type||typeof o.type!="string")&&e.push({entity:n.name,field:r,message:"Field type must be a non-empty string."}),o.relation&&!this.entities.has(o.relation.entity)&&e.push({entity:n.name,field:r,message:`Related entity "${o.relation.entity}" is not registered.`})}return{ok:e.length===0,issues:e}}toJSON(){return this.listEntities()}};function st(){return new it}a(st,"createMetadataRegistry");var ke=class{static{a(this,"InMemoryReadModelStore")}states=new Map;load(e){return this.states.get(e)}save(e,n){this.states.set(e,n)}clear(e){e?this.states.delete(e):this.states.clear()}};function Uo(t){return typeof t.initialState=="function"?t.initialState():t.initialState}a(Uo,"initialState");var at=class{static{a(this,"ProjectionRegistryImpl")}definitions=new Map;checkpoints=new Map;store;auditTrail;constructor(e={}){this.store=e.store??new ke,this.auditTrail=e.auditTrail}register(e){if(this.definitions.has(e.name))throw new Error(`Projection "${e.name}" is already registered.`);this.definitions.set(e.name,e),this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}list(){return Array.from(this.definitions.values())}async apply(e){let n=[];for(let r of this.definitions.values()){if(!r.sourceIntents.includes(e.intent))continue;let o=await this.store.load(r.name)??Uo(r),i=await r.project(e,o);await this.store.save(r.name,i);let s=this.checkpoints.get(r.name);this.checkpoints.set(r.name,{projection:r.name,appliedCount:(s?.appliedCount??0)+1,lastIntent:e.intent,lastCorrelationId:e.metadata.correlationId,updatedAt:new Date().toISOString()}),await this.auditTrail?.record({type:"projection.applied",source:"Kernel.ProjectionRegistry",intent:e.intent,correlationId:e.metadata.correlationId,causationId:e.metadata.causationId,subject:r.name,details:{projection:r.name}}),n.push(r.name)}return n}async getState(e){return this.store.load(e)}getCheckpoint(e){return this.checkpoints.get(e)}getCheckpoints(){return Array.from(this.checkpoints.values())}async clear(){await this.store.clear();for(let e of this.definitions.values())this.checkpoints.set(e.name,{projection:e.name,appliedCount:0})}};function lt(t){return new at(t)}a(lt,"createProjectionRegistry");var ct="1.0";function qo(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}a(qo,"policyId");var dt=class{constructor(e){this.data=e}data;static{a(this,"ArkManifestImpl")}toJSON(){return{...this.data}}};function ut(t={}){let e=t.registry,n=t.policyEngine,r=t.metadata,o=t.graph,i=t.profile,s=t.projections,l=t.eventContracts,c=t.observability,d=e?e.list().map(g=>({name:g.name,dependencies:e.getDependencies(g.name),productions:e.getProductions(g.name)})):[],f=e?e.getAllRelationships():[],p=n?n.getPolicies().map(g=>({id:qo(g.name),name:g.name,severity:g.severity,tags:g.tags?[...g.tags]:void 0,owner:g.owner,version:g.version,rationale:g.rationale,enforcementMode:g.enforcementMode,deprecated:g.deprecated,replacedBy:g.replacedBy,description:g.tags?.includes("layer")?"Enforces clean-architecture layer dependency rules on declared relationships.":void 0})):[],m=r?r.toJSON():[],h=o?o.toJSON():{nodes:[],edges:[]},S=m.filter(g=>(g.emits?.length??0)>0||(g.consumes?.length??0)>0).map(g=>({entity:g.name,emits:g.emits,consumes:g.consumes})),u=s?s.list().map(g=>({name:g.name,sourceIntents:g.sourceIntents,checkpoint:s.getCheckpoint(g.name)})):[],y={schemaVersion:"1.0",version:Ct,exportedAt:new Date().toISOString(),intents:d,relationships:f,policies:p,entities:m,graph:h,architecture:i?{profile:i.name,layers:i.layers,rules:i.rules}:void 0,projections:u,eventContracts:l?.list()??[],observability:c?.report(),links:{entityIntents:S}};return new dt(y)}a(ut,"createArkManifest");function Kn(t){return k(t)}a(Kn,"createWorkflowId");function ft(t){return t instanceof Error?t.message:String(t)}a(ft,"errorMessage");function zo(t){return new Promise(e=>{setTimeout(e,t)})}a(zo,"sleep");async function Jo(t,e,n){let r=new AbortController;if(e===void 0)return t(r.signal);let o,i=new Promise((s,l)=>{o=setTimeout(()=>{let c=new Error(`Workflow step "${n}" timed out after ${e}ms.`);r.abort(c),l(c)},e)});try{return await Promise.race([t(r.signal),i])}finally{o&&clearTimeout(o)}}a(Jo,"withTimeout");var Ee=class{static{a(this,"InMemoryWorkflowStore")}snapshots=new Map;save(e,n){let r=this.snapshots.get(e.id);if(r&&r.version!==e.version)throw new Error(`Optimistic concurrency conflict for workflow ${e.id}`);let o=(e.version??0)+1;this.snapshots.set(e.id,{...e,version:o,context:{...e.context}}),e.version=o}get(e,n){let r=this.snapshots.get(e);return r?{...r,context:{...r.context}}:void 0}list(e){return Array.from(this.snapshots.values()).filter(n=>!e||n.workflowName===e).map(n=>({...n,context:{...n.context}}))}claim(e,n,r){let o=Date.now();for(let i of this.snapshots.values()){if(r&&i.workflowName!==r||i.status!=="running"&&i.status!=="compensating")continue;let s=i.expiresAt?new Date(i.expiresAt).getTime()<o:!0;if(!i.ownerId||s){i.ownerId=e,i.expiresAt=new Date(o+n).toISOString();let l=(i.version??0)+1;return i.version=l,this.snapshots.set(i.id,{...i,context:{...i.context}}),{...i,context:{...i.context}}}}}clear(){this.snapshots.clear()}},pt=class{constructor(e,n={}){this.bus=e;this.options=n;this.store=n.store??new Ee}bus;options;static{a(this,"WorkflowEngineImpl")}definitions=new Map;store;register(e){if(this.definitions.has(e.name))throw new Error(`Workflow "${e.name}" is already registered.`);let n=new Set;for(let r of e.steps){if(n.has(r.name))throw new Error(`Workflow "${e.name}" has duplicate step name "${r.name}".`);n.add(r.name)}if(this.definitions.set(e.name,e),e.startOn){let r=e.startOn;this.bus.subscribe(r.intent,async o=>{await this.start(e.name,r.mapEventToPayload(o))})}}async start(e,n,r={}){let o=this.definitions.get(e);if(!o)throw new Error(`Workflow "${e}" is not registered.`);let i=new Date().toISOString(),s={id:r.id??Kn(e),version:0,workflowName:e,status:"running",context:{...n},completedSteps:[],attempts:{},startedAt:i,updatedAt:i};return await this.store.save(s,r.tx),await this.audit("workflow.started",s,{workflowName:e}),this.executeSnapshot(s,o,r.tx)}async resume(e,n={}){let r=await this.get(e,n.tx);if(!r)return;if(r.status!=="running"&&r.status!=="compensating")return r;let o=this.definitions.get(r.workflowName);if(!o)throw new Error(`Workflow "${r.workflowName}" is not registered.`);return this.executeSnapshot(r,o,n.tx)}async executeSnapshot(e,n,r){try{let o=n.steps.filter(i=>!e.completedSteps.includes(i.name));for(let i of o)await this.runStep(e,i,r);return e.status="completed",e.currentStep=void 0,e.completedAt=new Date().toISOString(),e.updatedAt=e.completedAt,await this.store.save(e,r),await this.audit("workflow.completed",e,{workflowName:e.workflowName}),{...e,context:{...e.context}}}catch(o){throw await this.compensate(e,n.steps,o,r),e.status="failed",e.currentStep=void 0,e.error=ft(o),e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.failed",e,{workflowName:e.workflowName,error:e.error,failedStep:e.failedStep}),o}}async get(e,n){return this.store.get(e,n)}async list(e){return this.store.list(e)}async runStep(e,n,r){let o=n.retry??this.options.defaultRetry??{attempts:1},i=Math.max(1,o.attempts);e.currentStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r);for(let s=1;s<=i;s+=1){e.attempts[n.name]=s,await this.store.save(e,r);let l;try{l=await Jo(c=>Promise.resolve(n.execute(e.context,this.bus,c)),n.timeoutMs,n.name)}catch(c){if(s<i){o.delayMs&&await zo(o.delayMs);continue}throw e.failedStep=n.name,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.failed",e,{step:n.name,attempt:s,error:ft(c)}),c}l&&Object.assign(e.context,l),e.completedSteps.push(n.name),e.currentStep=void 0,e.updatedAt=new Date().toISOString(),await this.store.save(e,r),await this.audit("workflow.step.completed",e,{step:n.name,attempt:s});return}throw new Error(`Workflow step "${n.name}" did not complete.`)}async compensate(e,n,r,o){e.status="compensating",e.updatedAt=new Date().toISOString(),await this.store.save(e,o);let i=n.filter(s=>e.completedSteps.includes(s.name));for(let s=i.length-1;s>=0;s-=1){let l=i[s];if(l.compensate)try{await Promise.resolve(l.compensate(e.context,this.bus,r)),await this.audit("workflow.compensation.completed",e,{step:l.name})}catch(c){await this.audit("workflow.step.failed",e,{step:l.name,compensation:!0,error:ft(c)})}}}async audit(e,n,r){await this.options.auditTrail?.record({type:e,source:"Kernel.WorkflowEngine",subject:n.id,details:r})}};function Re(t,e){return new pt(t,e)}a(Re,"createWorkflowEngine");function Yo(t,e,n={}){let r=Re(e,n),o={name:t.name,steps:t.steps};r.register(o);let i=n.id??Kn(t.name),s="idle",l=[];return{id:i,definition:t,get status(){return s},get completedSteps(){return[...l]},async run(c){s="running",l=[];try{let d=await r.start(t.name,c,{id:i});s=d.status==="waiting"?"idle":d.status,l=[...d.completedSteps]}catch(d){let f=await r.get(i);throw s=f?.status==="waiting"?"idle":f?.status??"failed",l=f?.completedSteps??[],d}}}}a(Yo,"createSaga");async function Vn(t,e={}){let n=At({host:e.host,port:e.port,nodeEnv:e.nodeEnv,processNodeEnv:process.env.NODE_ENV}),{listenArkRunInspector:r}=await import("./inspectorListen-6DQVJ4DC.js");return r(t,{bind:n,sseIntervalMs:e.sseIntervalMs})}a(Vn,"startArkRunInspector");var Xo=new Set(["singleton","transient"]);function Wn(t){let e={id:t.id,lifetime:t.lifetime,uses:[...t.uses],reactsTo:[...t.reactsTo],raises:[...t.raises],sends:[...t.sends]};if(t.extendedInfo){let n=t.extendedInfo;e.extendedInfo={...n.label?{label:n.label}:{},...n.architectureKind?{architectureKind:n.architectureKind}:{},...n.tags?{tags:[...n.tags]}:{},...n.group?{group:n.group}:{},...n.metadata?{metadata:{...n.metadata}}:{}}}return e}a(Wn,"cloneComponent");function Zo(t){if(t===void 0)return"singleton";if(typeof t=="string"&&Xo.has(t))return t;throw new Error('ArkRun component lifetime must be "singleton" or "transient".')}a(Zo,"closedLifetime");function Un(){let t=new Map,e=new Map,n=new Set;function r(s){let l=t.get(s);if(!l)throw new Error(`ArkRun component "${s}" is not registered.`);return l}a(r,"mustRecord");function o(s,l){if(!l.factory)throw new Error(`ArkRun component "${s}" has no factory; declarations-only registrations cannot be resolved.`);if(n.has(s))throw new Error(`ArkRun component "${s}" has a circular resolve.`);n.add(s);try{return l.factory()}finally{n.delete(s)}}a(o,"instantiate");function i(s,l){if(e.has(s))return e.get(s);let c=o(s,l);return e.set(s,c),c}return a(i,"singleton"),{register(s){let l=typeof s?.id=="string"?s.id.trim():"";if(!l)throw new Error("ArkRun component id must be a non-empty string.");if(t.has(l))throw new Error(`ArkRun component "${l}" is already registered.`);let c=Zo(s.lifetime),d=St({id:l,lifetime:c,uses:s.uses,reactsTo:s.reactsTo,raises:s.raises,sends:s.sends,extendedInfo:s.extendedInfo});if(!d)throw new Error("ArkRun component id must be a non-empty string.");let f=typeof s.factory=="function"?s.factory:void 0;return t.set(l,{component:d,factory:f}),Wn(d)},resolve(s){let l=r(s);return l.component.lifetime==="transient"?o(s,l):i(s,l)},resolveSingleton(s){let l=r(s);if(l.component.lifetime==="transient")throw new Error(`ArkRun component "${s}" is transient; resolveSingleton requires lifetime "singleton".`);return i(s,l)},snapshotComponents(){return[...t.values()].map(s=>Wn(s.component))}}}a(Un,"createComponentRegistry");function Qo(t){let e={...t.metadata??{}};if(t.source===void 0)return e;if(e.source&&e.source!==t.source)throw new $(t.source,e.source);return e.source=t.source,e}a(Qo,"stampMetadata");async function gt(t,e,n,r={}){let o=bt({transport:r.transport,ephemeral:r.ephemeral??t.defaultEphemeral,brokerBound:typeof t.broker?.send=="function"}),i=Qo(r),s=o.deliveredVia==="broker"&&t.broker!==void 0,l,c=await t.eventBus.dispatch(e,n,i,{notifySubscribers:o.notifySubscribers,awaitHandlers:o.awaitHandlers,...s?{settleBufferOnLocalDelivery:!1}:{},onBufferRecord:a(d=>{l=d.id},"onBufferRecord")});if(s&&t.broker){let d=t.eventBus,f=t.broker,p=(async()=>{try{await f.send(c)}catch(m){throw l!==void 0&&await d.settleBufferRecord(c,l,{ok:!1,error:m}),await d.recordHandoffFailure(c,m,"broker"),m}l!==void 0&&await d.settleBufferRecord(c,l,{ok:!0})})();o.awaitHandoff?await p:p.then(void 0,()=>{})}return o}a(gt,"sendOnArkRunTransport");var ei=1e3;function ti(){return k("ark-kernel")}a(ti,"nextKernelInstanceId");function qn(t,e){let n=t.constructor?.name;return typeof n=="string"&&n.length>0?n:e}a(qn,"portConstructorId");function mt(t={}){let e=t.strict??!0,n=t.instanceId??ti(),r=t.profile??Y,o=t.maxHistorySize??ei,i=Me(),s=rt(),l=t.metadata??st(),c=t.auditTrail===void 0,d=t.auditTrail??tt({maxRecords:o}),f=t.eventContracts??Xe(),p=t.eventBuffer===void 0&&t.outbox===void 0,m=t.eventBuffer??t.outbox??new q({maxRecords:o}),h=t.projections??lt({auditTrail:d}),S=new B([je(r),...t.policies??[]]),u=a(()=>{ot(i,s,{requireRegisteredTargets:!0})},"syncGraph"),y=t.ephemeral??!0,g=t.broker,v=new U({intentRegistry:i,dependencyGraph:s,policyEngine:S,strictRegistry:!0,validateIntentNaming:!0,auditTrail:d,eventContracts:f,strictEventContracts:t.strictEventContracts??e,requireKnownSource:t.requireKnownSource??!0,architectureProfile:r,enforceObservedLayerFlow:t.enforceObservedLayerFlow??(e?"hard":"off"),eventBuffer:m,settleBufferOnLocalDelivery:p,instanceId:n,maxHistorySize:o,onPublish:t.autoApplyProjections===!1?void 0:async w=>{await h.apply(w)}}),yt=Re(v,{auditTrail:d}),Pe=Qe({registry:i,eventBus:v,graph:s}),N=Un(),Jn=typeof g?.send=="function",Yn=p?"InMemoryEventBuffer":qn(m,"EventBufferStore"),Xn=c?"InMemoryAuditStore":qn(d,"AuditTrail"),Zn=kt({stores:[ce(Yn,"outbox"),ce(Xn,"audit"),ce("InMemoryWorkflowStore","workflow")]}),Ce={instanceId:n,profile:r,registry:i,graph:s,metadata:l,auditTrail:d,eventContracts:f,eventBuffer:m,outbox:m,projections:h,policyEngine:S,eventBus:v,workflowEngine:yt,observability:Pe,publisher(w){let T=v.createPublisher(w);return{source:T.source,publish:T.publish,send(E,xe,Qn={}){return gt({eventBus:v,broker:g,defaultEphemeral:y},E,xe,{...Qn,source:T.source})}}},send(w,T,E={}){return gt({eventBus:v,broker:g,defaultEphemeral:y},w,T,E)},register(w){return N.register(w)},resolve(w){return N.resolve(w)},resolveSingleton(w){return N.resolveSingleton(w)},getDependencyInformationPackage(){return wt({kernelInstanceId:n,components:N.snapshotComponents()})},requestGraph(w){return It({kernelInstanceId:n,components:N.snapshotComponents()},w)},getInspectorSnapshot(w){return Pt({kernelInstanceId:n,host:w?.host,port:w?.port,package:{kernelInstanceId:n,components:N.snapshotComponents()},observability:Pe.report(),ephemeralDefault:y,brokerBound:Jn,hardening:Zn})},startInspector(w){return Vn({getInspectorSnapshot:a(E=>Ce.getInspectorSnapshot(E),"getInspectorSnapshot"),requestGraph:a(E=>Ce.requestGraph(E),"requestGraph"),async listInspectorOutbox(){let[E,xe]=await Promise.all([m.list("pending"),m.list("failed")]);return Et([...E,...xe],{sampleLimit:Le})},async listInspectorWorkflows(){return Rt(await yt.list(),{sampleLimit:Le})}},w)},syncGraph:u,manifest(){return u(),ut({registry:i,policyEngine:S,metadata:l,graph:s,profile:r,projections:h,eventContracts:f,observability:Pe})}};return Ce}a(mt,"createArkKernel");function ni(t={}){return mt({...t,strict:!0,strictEventContracts:t.strictEventContracts??!0,requireKnownSource:t.requireKnownSource??!0,enforceObservedLayerFlow:t.enforceObservedLayerFlow??"hard"})}a(ni,"createStrictArkKernel");function ht(t,e,n){let{profileName:r,...o}=e,i=e.enforceObservedLayerFlow,s=(i??n)==="hard"?Qt(t):[];if(i==="hard"&&s.length>0)throw new G(s);return{options:{...o,profile:Te(t,{name:r})},unresolvable:s}}a(ht,"planKernelFromConfig");function zn(t,e){return e.length===0||Promise.resolve().then(()=>t.auditTrail.record({type:"layer.observedFlowUnresolvable",subject:e.join(","),details:{code:"ARKRUN_LAYER_FLOW_UNRESOLVABLE",layers:e,message:new G(e).message}})).catch(()=>{}),t}a(zn,"withUnresolvableNotice");function Gl(t,e={}){let n=e.strict??!0,r=ht(t,e,n?"hard":"off");return zn(mt(r.options),r.unresolvable)}a(Gl,"createArkKernelFromConfig");function Hl(t,e={}){let n=ht(t,e,"hard");return zn(ni(n.options),n.unresolvable)}a(Hl,"createStrictArkKernelFromConfig");function Kl(t,e={}){return ri(ht(t,e,"off").options)}a(Kl,"createLenientArkKernelFromConfig");function ri(t={}){return mt({...t,strict:!1,strictEventContracts:t.strictEventContracts??!1,enforceObservedLayerFlow:t.enforceObservedLayerFlow??"off"})}a(ri,"createLenientArkKernel");export{Ct as a,yi as b,Si as c,Hr as d,wi as e,Kr as f,bi as g,Vr as h,Ai as i,Ne as j,Te as k,Y as l,Jr as m,Sn as n,bs as o,W as p,oo as q,As as r,ks as s,Se as t,fn as u,Es as v,Ue as w,wo as x,mn as y,Rs as z,Ps as A,Cs as B,xs as C,Ls as D,$o as E,Os as F,$s as G,X as H,Yr as I,Me as J,Xr as K,Fe as L,O as M,B as N,Z as O,_e as P,Be as Q,rn as R,je as S,Ge as T,eo as U,Q as V,ee as W,te as X,ne as Y,j as Z,$ as _,re as $,G as aa,Fo as ba,be as ca,Xe as da,q as ea,Ko as fa,Qe as ga,Ae as ha,tt as ia,rt as ja,ot as ka,st as la,ke as ma,lt as na,ct as oa,ut as pa,Ee as qa,Re as ra,Yo as sa,Vn as ta,ei as ua,mt as va,ni as wa,Gl as xa,Hl as ya,Kl as za,ri as Aa};
|